Ejemplo n.º 1
0
 private void WritePreamble()
 {
     if (_seal)
     {
         throw SpecFailure.Sealed();
     }
 }
Ejemplo n.º 2
0
        private static Exception _TryParse(string text, out TestTag result)
        {
            if (text == null)
            {
                result = new TestTag();
                return(new ArgumentNullException());
            }

            text = text ?? string.Empty;
            if (text.Length == 0)
            {
                result = new TestTag();
                return(SpecFailure.AllWhitespace(nameof(text)));
            }
            string[] nv = Array.ConvertAll(
                text.Split(new [] { ':' }, 3), t => t.Trim()
                );
            if (nv.Length == 1 && ValidName(nv[0]))
            {
                result = new TestTag(nv[0].Trim());
                return(null);
            }
            if (nv.Length == 2 && ValidName(nv[0]) && ValidName(nv[1]))
            {
                result = new TestTag(nv[0].Trim(), nv[1].Trim());
                return(null);
            }

            result = new TestTag();
            return(new FormatException());
        }
Ejemplo n.º 3
0
 private void ThrowIfReadOnly()
 {
     if (IsReadOnly)
     {
         throw SpecFailure.Sealed();
     }
 }
Ejemplo n.º 4
0
        static Exception _TryParse(string text, out SegmentSequence[] results2)
        {
            results2 = null;
            if (text == null)
            {
                return(new ArgumentNullException("text"));
            }
            if (text.Length == 0)
            {
                return(SpecFailure.EmptyString("text"));
            }

            List <SegmentSequence> results = new List <SegmentSequence>();

            foreach (string sub in text.Split(';'))
            {
                if (Path.IsPathRooted(sub) && NoSpecialChars(sub))
                {
                    RootedSegmentSequence sequence = new RootedSegmentSequence(sub);
                    results.Add(sequence);
                }
                else
                {
                    IteratedSegmentSequence segments;
                    _TryParseList(sub, out segments);
                    results.Add(segments);
                }
            }

            results2 = results.ToArray();
            return(null);
        }
Ejemplo n.º 5
0
 protected void ThrowIfDisposed()
 {
     if (IsDisposed)
     {
         throw SpecFailure.Disposed(GetType().ToString());
     }
 }
Ejemplo n.º 6
0
        private static Exception _TryParse(string text, out TestTagType result)
        {
            result = default(TestTagType);
            if (text == null)
            {
                return(new ArgumentNullException(nameof(text)));
            }

            text = text.Trim();
            if (text.Length == 0)
            {
                return(SpecFailure.AllWhitespace(nameof(text)));
            }

            if (_canonicalNames.TryGetValue(text, out string canonical))
            {
                text = canonical;
            }
            else
            {
                _canonicalNames.Add(text, text);
            }
            result = new TestTagType(text, false);
            return(null);
        }
Ejemplo n.º 7
0
        public DataStreamContext(Uri u)
        {
            string[] parts = u.PathAndQuery.Split(new [] { ',' }, 2);
            if (parts.Length != 2)
            {
                throw SpecFailure.NotValidDataUri();
            }

            var ct = Regex.Replace(parts[0], ";base64", string.Empty);

            byte[] buffer;

            _isBase64 = ct.Length < parts[0].Length; // implied by replacement
            if (_isBase64)
            {
                buffer = Convert.FromBase64String(parts[1]);
            }
            else
            {
                buffer = System.Text.Encoding.ASCII.GetBytes(WebUtility.UrlDecode(parts[1]));
            }

            _baseUri = string.Concat("data:",
                                     _isBase64 ? ";base64" : string.Empty,
                                     ","
                                     );
            _data = new MemoryStream(buffer.Length);
            _data.Write(buffer, 0, buffer.Length);
        }
Ejemplo n.º 8
0
 public void Throw()
 {
     if (Exception == null)
     {
         throw SpecFailure.NoExceptionCaptured();
     }
     ExceptionDispatchInfo.Capture(Exception).Throw();
 }
Ejemplo n.º 9
0
 static bool Parse(string item, out TestTag tag)
 {
     tag = default(TestTag);
     if (string.IsNullOrEmpty(item))
     {
         throw SpecFailure.EmptyString(nameof(item));
     }
     return(TestTag.TryParse(item, out tag));
 }
Ejemplo n.º 10
0
        public static TestFixtureData Parse(string text)
        {
            var items = new FixtureParser(null).Parse(text);

            if (items == null)
            {
                throw SpecFailure.NotParsable("text", typeof(TestFixtureData));
            }
            return(items.Single());
        }
Ejemplo n.º 11
0
            public bool Matches(ITestActualEvaluation <IEnumerable> actualFactory)
            {
                var items = actualFactory.Value;

                if (items == null)
                {
                    throw SpecFailure.SequenceNullConversion();
                }

                Result = ShouldCore(items.Cast <object>(), _real);
                return(Result == null);
            }
Ejemplo n.º 12
0
 public string GetFullPath(string fileName)
 {
     if (fileName == null)
     {
         throw new ArgumentNullException("fileName");
     }
     if (string.IsNullOrEmpty(fileName))
     {
         throw SpecFailure.EmptyString("fileName");
     }
     return(CheckFileName(fileName));
 }
Ejemplo n.º 13
0
        static Exception _TryParseList(string text, out IteratedSegmentSequence segments)
        {
            segments = null;
            string[]       items   = text.Split('/', '\\');
            List <Segment> results = new List <Segment>(items.Length);

            foreach (string s in items)
            {
                Segment sgt;
                if (s.Length == 0)
                {
                    // TODO Only apply at real root; enforce match segment as file or directory
                    sgt = new RootSegment();
                }
                else if (DEVICE.IsMatch(s))
                {
                    sgt = new DeviceSegment(DEVICE.Match(s).Groups["Name"].Value);
                }
                else if (s == "*")
                {
                    sgt = new AnyDirectorySegment();
                }
                else if (s == "**")
                {
                    sgt = new RecursiveSegment();

                    // TODO Support directory navigation
                }
                else if (s == "..")
                {
                    throw new NotImplementedException();
                }
                else if (s == ".")
                {
                    sgt = new CwdSegment();
                }
                else
                {
                    string segment = ExpandSegment(s);
                    if (segment == null)
                    {
                        return(SpecFailure.NotParsable("text", typeof(Glob)));
                    }

                    sgt = new MatchSegment(segment);
                }

                results.Add(sgt);
            }

            segments = new IteratedSegmentSequence(results.ToArray());
            return(null);
        }
Ejemplo n.º 14
0
 public TimeoutAttribute(int timeout)
 {
     if (timeout == 0 || timeout == -1)
     {
         return;
     }
     if (timeout < 0)
     {
         throw SpecFailure.NegativeTimeout(nameof(timeout));
     }
     Timeout = TimeSpan.FromMilliseconds(timeout);
 }
Ejemplo n.º 15
0
 public static TestTag Alias(TestTag from, TestTag to)
 {
     if (from.Type != to.Type)
     {
         throw SpecFailure.CannotAliasDifferentTagTypes();
     }
     if (from != to)
     {
         _aliases[from] = to;
     }
     return(from);
 }
Ejemplo n.º 16
0
        private string CheckFileName(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                fileName = RandomName();
            }

            if (Path.IsPathRooted(fileName) || fileName.StartsWith("../", StringComparison.Ordinal))
            {
                throw SpecFailure.TemporaryDirectoryFileNameRooted("fileName");
            }
            return(Path.Combine(_basePath, fileName));
        }
Ejemplo n.º 17
0
        public static TestFixture Parse(string text)
        {
            var items = new FixtureParser(null).Parse(text);

            if (items == null)
            {
                throw SpecFailure.NotParsable("text", typeof(TestFixture));
            }
            var result = new TestFixture();

            result.Items.AddAll(items);
            return(result);
        }
Ejemplo n.º 18
0
        internal static Exception ApplyFlags(Exception ex, RecordExceptionFlags flags)
        {
            if (flags.HasFlag(RecordExceptionFlags.UnwindTargetExceptions))
            {
                ex = UnwindTargetException(ex);
            }
            if (ex is AssertException && flags.HasFlag(RecordExceptionFlags.StrictVerification))
            {
                throw SpecFailure.CannotAssertAssertExceptions();
            }

            return(ex);
        }
Ejemplo n.º 19
0
            protected override TestFailure ShouldCore(IEnumerable <object> items, ITestMatcher <object> baseMatcher)
            {
                if (ShouldVerify)
                {
                    if (_max < _min)
                    {
                        throw SpecFailure.CardinalityMinGreaterThanMax();
                    }
                    if (_min < 0 || _max < 0)
                    {
                        throw SpecFailure.NegativeCardinality();
                    }
                }
                if (!_min.HasValue && !_max.HasValue)
                {
                    return(null);
                }

                Predicate <Tally> stopper = null;

                if (_max.HasValue)
                {
                    stopper = t => t.Successes > _max;
                }

                var  tally      = Tally.New(items, baseMatcher, stopper);
                bool outOfRange = (_max.HasValue && tally.Successes > _max.Value) ||
                                  (_min.HasValue && tally.Successes < _min.Value);

                if (_outer)
                {
                    outOfRange = !outOfRange;
                }

                if (outOfRange)
                {
                    string message = Message();
                    tally.AFailure = TestMatcherLocalizer.FailurePredicate(baseMatcher);

                    if (tally.AFailure.Message == "")
                    {
                        tally.AFailure = null;
                        message        = message.Replace("to:", "items");
                    }

                    return(tally.Lift("cardinality", message, true));
                }

                return(null);
            }
Ejemplo n.º 20
0
 public TagsAttribute(params string[] tags)
 {
     if (tags == null)
     {
         throw new ArgumentNullException(nameof(tags));
     }
     if (tags.Length == 0)
     {
         throw SpecFailure.EmptyCollection(nameof(tags));
     }
     _tags = new List <TestTag>(
         tags.Select(s => TestTag.Parse(s))
         );
 }
Ejemplo n.º 21
0
                public bool Matches(ITestActualEvaluation <TFrom> actualFactory)
                {
                    var      real  = TestMatcherName.FromType(_real.GetType());
                    Func <T> thunk = () => {
                        try {
                            var actual = actualFactory.Value;
                            return((T)(object)actual);
                        } catch (InvalidCastException e) {
                            throw SpecFailure.CastRequiredByMatcherFailure(e, real);
                        }
                    };

                    return(_real.Matches(TestActual.Of(thunk)));
                }
Ejemplo n.º 22
0
        internal void RunTestWithTimeout(Func <TestExecutionContext, object> testFunc, TimeSpan timeout)
        {
            if (timeout <= TimeSpan.Zero)
            {
                _testReturnValue = testFunc(this);
                return;
            }

            Exception error = null;
            var       cts   = new CancellationTokenSource();

            cts.CancelAfter(timeout);
            _cancellationToken = cts.Token;

            ParameterizedThreadStart thunk = syncObject => {
                try {
                    _testReturnValue = testFunc(this);
                } catch (Exception ex) {
                    error = ex;
                }
                lock (syncObject) {
                    Monitor.Pulse(syncObject);
                }
            };

            object monitorSync = new object();
            bool   timedOut;

            var thread = new Thread(thunk);

            lock (monitorSync) {
                thread.Start(monitorSync);
                timedOut = !Monitor.Wait(monitorSync, timeout);
                cts.Cancel();
            }
            cts.Dispose();

            _cancellationToken = CancellationToken.None;

            if (timedOut)
            {
                thread.Abort();
                throw SpecFailure.TestTimedOut(timeout);
            }
            if (error != null)
            {
                throw error;
            }
        }
Ejemplo n.º 23
0
        IEnumerable <TestData> ITestDataProvider.GetData(TestContext context)
        {
            TestUnit unit = context.TestUnit;
            var      rt   = (TestTheory)unit;
            var      pms  = rt.TestMethod.GetParameters();

            if (pms.Length != 1)
            {
                throw SpecFailure.TestFileDataRequiresOneParameter();
            }
            var pt = pms[0].ParameterType.GetTypeInfo();

            return(_input.ReadInputs(context,
                                     u => ToTestData(context.DownloadFile(u), pt),
                                     f => ToTestData(context.LoadFile(f.FileName), pt)));
        }
Ejemplo n.º 24
0
        IEnumerable <TestData> ITestDataProvider.GetData(TestContext context)
        {
            TestUnit unit          = context.TestUnit;
            var      declaringType = ((TestTheory)unit).TestMethod.DeclaringType;
            var      all           = new List <IMemberAccessor>();

            foreach (var f in _fields)
            {
                var fld = declaringType.GetField(f, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
                if (fld == null)
                {
                    throw SpecFailure.CannotFindDataField(f);
                }
                all.Add(MemberAccessors.Field(fld));
            }
            return(this.WithNames(TestDataProvider.FromMemberAccessors(all).GetData(context), _tags.TestTags));
        }
Ejemplo n.º 25
0
        public static StreamContext FromFile(string fileName)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }
            if (string.IsNullOrEmpty(fileName))
            {
                throw SpecFailure.EmptyString("fileName");
            }
            var uri = new Uri(fileName, UriKind.RelativeOrAbsolute);

            if (Path.IsPathRooted(fileName))
            {
                uri = new Uri("file://" + fileName);
            }
            return(new FileSystemStreamContext(uri));
        }
Ejemplo n.º 26
0
        string FindActualPath(string fileName)
        {
            if (Path.IsPathRooted(fileName) && File.Exists(fileName))
            {
                return(fileName);
            }
            if (File.Exists(fileName))
            {
                return(Path.GetFullPath(fileName));
            }
            var result = _opts.FixturePaths.GetFullPath(fileName);

            if (result != null)
            {
                return(result);
            }

            throw SpecFailure.CannotFindFixture(fileName, TestRunnerOptions.FixturePaths);
        }
Ejemplo n.º 27
0
 internal override void Implies(CommandCondition c)
 {
     if (!ShouldVerify)
     {
         return;
     }
     if (c == CommandCondition.ExactlyOne)
     {
         if (_min.GetValueOrDefault(1) != 1 || _max.GetValueOrDefault(1) != 1)
         {
             throw SpecFailure.ExactlyOnePlural();
         }
     }
     else if (c == CommandCondition.NotOneButZeroOrMore)
     {
         if (_min.GetValueOrDefault(1) == 1 && _max.GetValueOrDefault(1) == 1)
         {
             throw SpecFailure.ExactlyOneSingular();
         }
     }
 }
Ejemplo n.º 28
0
        private KeyValuePair <string, string> ParseHeredoc(Match match)
        {
            string fileName = match.Groups["FileName"].Value;

            (FoldLines fold, FinalFold final) = GetFoldType(match.Groups["Fold"].Value);

            if (!MoveNext())
            {
                return(new KeyValuePair <string, string>(fileName, string.Empty));
            }

            string indentation = Regex.Match(Current, @"^\s*").Value;

            if (indentation.Contains("\t"))
            {
                throw SpecFailure.FixtureParserIllegalTabs(_lex.Line);
            }

            StringBuilder sb = new StringBuilder();

            if (indentation.Length == 0)
            {
                // Encountered an empty here doc, treat as value
                _lex.MovePrevious();
                return(new KeyValuePair <string, string>(fileName, string.Empty));
            }

            string previous = null;

            foreach (var canonical in ReadHeredocLines(indentation))
            {
                fold(sb, canonical, previous);
                previous = canonical;
            }

            var body = final(sb);

            _lex.MovePrevious();
            return(new KeyValuePair <string, string>(fileName, body));
        }
Ejemplo n.º 29
0
        IEnumerable <TestData> ITestDataProvider.GetData(TestContext context)
        {
            TestUnit unit          = context.TestUnit;
            var      declaringType = ((TestTheory)unit).TestMethod.DeclaringType;
            var      all           = new List <IMemberAccessor>();

            foreach (var p in _properties)
            {
                var prop = declaringType.GetProperty(p, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
                if (prop == null)
                {
                    throw SpecFailure.CannotFindDataProperty(p);
                }

                if (prop.GetMethod == null)
                {
                    throw SpecFailure.DataPropertyIncorrectGetter();
                }
                all.Add(MemberAccessors.Property(prop));
            }
            return(this.WithNames(TestDataProvider.FromMemberAccessors(all).GetData(context), _tags.TestTags));
        }
Ejemplo n.º 30
0
        internal static IEnumerable <TestData> Create(MethodInfo testMethod, object testObject, IMemberAccessor[] accessors)
        {
            if (accessors.Length == 1)
            {
                return(Create(testMethod, testObject, accessors[0]));
            }

            if (testMethod.GetParameters().Length != accessors.Length)
            {
                throw SpecFailure.MultiAccessorsTheoryParameterMismatch();
            }

            // TODO It would be better to enforce IEnumerable instead of failing with cast

            var elements = accessors
                           .Select(t => ((IEnumerable)t.GetValue(testObject)).Cast <object>().ToArray())
                           .ToList();

            var actualData = Combinatorial(elements)
                             .Select(t => new TestData(t));

            return(actualData);
        }