Example #1
0
        public void ValidateOutput(List <string> rawFileTypes, List <string> nonRawFileTypes, List <string> videoFileTypes)
        {
            var outputDirectory = new DirectoryInfo(m_OutputDirectory);

            Assert.IsTrue(outputDirectory.Exists);
            foreach (var referenceFile in m_ReferenceFileDescriptions)
            {
                var files = outputDirectory.GetFiles(referenceFile.FileName, SearchOption.AllDirectories);
                Assert.IsNotNull(files);
                Assert.That(files.Count, Is.AtMost(1));
                var requiredFileKind = FileKind.Unrecognized;
                if (rawFileTypes.Contains(referenceFile.Extension.ToLowerInvariant()))
                {
                    requiredFileKind = FileKind.RawImage;
                }
                if (nonRawFileTypes.Contains(referenceFile.Extension.ToLowerInvariant()))
                {
                    requiredFileKind = FileKind.JpegImage;
                }
                if (videoFileTypes.Contains(referenceFile.Extension.ToLowerInvariant()))
                {
                    requiredFileKind = FileKind.Video;
                }
                var expectedPath        = referenceFile.GetExpectedPath(requiredFileKind);
                var expectedPathPresent = files[0].FullName.EndsWith(expectedPath);
                Assert.IsTrue(
                    expectedPathPresent,
                    $"Expected {expectedPath}, got {files[0].FullName}"
                    );
            }
        }
Example #2
0
        public void check_of_returning_statement()
        {
            var sql = @"insert into regions (region_id, region_name) values (6, 'Antarctica') returning ""REGION_ID"", ""REGION_NAME"", ""CREATEDATE"" into :p1, :p2, :p3";

            using (var c = GetCommand(sql))
            {
                var p1 = c.CreateParameter();
                p1.ParameterName = "p1";
                p1.Value         = 1m;
                p1.Direction     = ParameterDirection.Output;
                var p2 = c.CreateParameter();
                p2.ParameterName = "p2";
                p2.Value         = "a";
                p2.Size          = 25;
                p2.Direction     = ParameterDirection.Output;
                var p3 = c.CreateParameter();
                p3.ParameterName = "p3";
                p3.Value         = DateTime.MinValue;
                p3.Direction     = ParameterDirection.Output;
                c.Parameters.Add(p1);
                c.Parameters.Add(p2);
                c.Parameters.Add(p3);
                c.Connection.Open();
                c.ExecuteNonQuery();

                Assert.AreEqual(6, c.Parameters["p1"].Value);
                Assert.AreEqual("Antarctica", c.Parameters["p2"].Value);
                var timeSpan = (DateTime.Now - ((DateTime)c.Parameters["p3"].Value));
                Console.WriteLine(timeSpan.TotalMilliseconds);
                Assert.That(timeSpan.TotalMilliseconds, Is.AtMost(2000));
            }
        }
Example #3
0
        public void ChildrenNumbersMoreOrEqualTo(int moreThen)
        {
            AllureLifecycle.Instance.RunStep("Get children' number", () => { });
            int children = AllureLifecycle.Instance.RunStep <int>("Cointing children", () => City.HowManyBuildings);

            Assert.That(children, Is.AtMost(moreThen), "No, still less");
        }
Example #4
0
        public async Task Should_stop_pumping_messages_after_first_unsuccessful_receive()
        {
            var successfulReceives = 46;
            var queueSize          = 1000;

            var parser = new QueueAddressTranslator("nservicebus", "dbo", null, null);

            var inputQueue = new FakeTableBasedQueue(parser.Parse("input").QualifiedTableName, queueSize, successfulReceives);

            var pump = new MessagePump(
                m => new ProcessWithNoTransaction(sqlConnectionFactory),
                qa => qa == "input" ? (TableBasedQueue)inputQueue : new TableBasedQueue(parser.Parse(qa).QualifiedTableName, qa),
                new QueuePurger(sqlConnectionFactory),
                new ExpiredMessagesPurger(_ => sqlConnectionFactory.OpenNewConnection(), TimeSpan.MaxValue, 0),
                new QueuePeeker(sqlConnectionFactory, new QueuePeekerOptions()),
                new SchemaInspector(_ => sqlConnectionFactory.OpenNewConnection()),
                TimeSpan.MaxValue);

            await pump.Init(
                _ => Task.FromResult(0),
                _ => Task.FromResult(ErrorHandleResult.Handled),
                new CriticalError(_ => Task.FromResult(0)),
                new PushSettings("input", "error", false, TransportTransactionMode.None));

            pump.Start(new PushRuntimeSettings(1));

            await WaitUntil(() => inputQueue.NumberOfPeeks > 1);

            await pump.Stop();

            Assert.That(inputQueue.NumberOfReceives, Is.AtMost(successfulReceives + 2), "Pump should stop receives after first unsuccessful attempt.");
        }
Example #5
0
        public void CreateSubOrder_Success()
        {
            var item = new InventoryItem(Component1Vertical, 60);

            var order = new Order(Guid.NewGuid(), "Test order")
            {
                ItemsOrdered = new HashSet <InventoryItem>
                {
                    new InventoryItem(Product1InteriorDoor, 20),
                    new InventoryItem(Product2InteriorDoor, 10),
                },
                ItemsProduced = new HashSet <InventoryItem>
                {
                    InventoryItem.Empty(Product1InteriorDoor),
                    InventoryItem.Empty(Product2InteriorDoor),
                },
                ShipmentDeadline = new DateTimeOffset(2020, 1, 1, 1, 1, 1, TimeSpan.Zero)
            };
            var now      = DateTimeOffset.Now;
            var subOrder = OrderService.CreateSubOrder(item, order);

            Assert.That(subOrder.ParentOrder, Is.EqualTo(order));
            Assert.That(subOrder.ItemsOrdered.Contains(item), Is.True);
            Assert.That(subOrder.Status, Is.EqualTo(OrderStatus.New));
            Assert.That(subOrder.Type, Is.EqualTo(OrderType.Internal));
            Assert.That(order.SubOrders.Contains(subOrder), Is.True);
            Assert.That(TimberComponentShop.Orders.Contains(subOrder), Is.True);
            Assert.That(subOrder.CreatedAt, Is.AtLeast(now));
            Assert.That(subOrder.CreatedAt, Is.AtMost(DateTimeOffset.Now));
        }
        public async Task ConsumerHeartbeatsWithinTimeLimit(int heartbeatMilliseconds, int totalMilliseconds)
        {
            var protocol = new JoinGroupRequest.GroupProtocol(new ConsumerProtocolMetadata("mine"));
            var router   = Substitute.For <IRouter>();
            var conn     = Substitute.For <IConnection>();

            router.GetGroupConnectionAsync(Arg.Any <string>(), Arg.Any <CancellationToken>())
            .Returns(_ => Task.FromResult(new GroupConnection(_.Arg <string>(), 0, conn)));

            var lastHeartbeat      = DateTimeOffset.UtcNow;
            var heartbeatIntervals = ImmutableArray <TimeSpan> .Empty;

            conn.SendAsync(Arg.Any <HeartbeatRequest>(), Arg.Any <CancellationToken>(), Arg.Any <IRequestContext>())
            .Returns(_ => {
                heartbeatIntervals = heartbeatIntervals.Add(DateTimeOffset.UtcNow - lastHeartbeat);
                lastHeartbeat      = DateTimeOffset.UtcNow;
                return(Task.FromResult(new HeartbeatResponse(ErrorCode.NONE)));
            });
            var request  = new JoinGroupRequest(TestConfig.GroupId(), TimeSpan.FromMilliseconds(heartbeatMilliseconds), "", ConsumerEncoder.Protocol, new [] { protocol });
            var memberId = Guid.NewGuid().ToString("N");
            var response = new JoinGroupResponse(ErrorCode.NONE, 1, protocol.protocol_name, memberId, memberId, new [] { new JoinGroupResponse.Member(memberId, new ConsumerProtocolMetadata("mine")) });

            lastHeartbeat = DateTimeOffset.UtcNow;

            using (new GroupConsumer(router, request.group_id, request.protocol_type, response)) {
                await Task.Delay(totalMilliseconds);
            }

            foreach (var interval in heartbeatIntervals)
            {
                Assert.That((int)interval.TotalMilliseconds, Is.AtMost(heartbeatMilliseconds));
            }
        }
Example #7
0
        public void ComparisonTests()
        {
            // Classic Syntax
            Assert.Greater(7, 3);
            Assert.GreaterOrEqual(7, 3);
            Assert.GreaterOrEqual(7, 7);

            // Constraint Syntax
            Assert.That(7, Is.GreaterThan(3));
            Assert.That(7, Is.GreaterThanOrEqualTo(3));
            Assert.That(7, Is.AtLeast(3));
            Assert.That(7, Is.GreaterThanOrEqualTo(7));
            Assert.That(7, Is.AtLeast(7));

            // Classic syntax
            Assert.Less(3, 7);
            Assert.LessOrEqual(3, 7);
            Assert.LessOrEqual(3, 3);

            // Constraint Syntax
            Assert.That(3, Is.LessThan(7));
            Assert.That(3, Is.LessThanOrEqualTo(7));
            Assert.That(3, Is.AtMost(7));
            Assert.That(3, Is.LessThanOrEqualTo(3));
            Assert.That(3, Is.AtMost(3));
        }
Example #8
0
    public void QuantityIsLessOrEqual()
    {
        int expectedValue = 2;
        int actualValue   = 3;

        // MSTest does not support this case.

        // NUnit
        Assert.That(actualValue, Is.LessThanOrEqualTo(expectedValue), () => "Some context");
        Assert.That(actualValue, Is.AtMost(expectedValue), () => "Some context");
        // Some context
        //  Expected: less than or equal to 2
        //  But was: 3

        // XUnit does not support this case.

        // Fluent
        actualValue.Should().BeLessOrEqualTo(expectedValue, "SOME REASONS");
        // Expected actualValue to be less or equal to 2 because SOME REASONS, but found 3.

        // Shouldly
        actualValue.ShouldBeLessThanOrEqualTo(expectedValue, "Some context");
        // actualValue
        //   should be less than or equal to
        // 2
        //   but was
        // 3
        //
        // Additional Info:
        //  Some context
    }
        public async Task Test_Execute_TestPerformance()
        {
            // Arrange
            var stopWatch = new Stopwatch();
            var ipAddress = "0.0.0.0";

            var oldHostFileContent = await TestHelpers.GetEmbeddedFileAsync("Resources/old-hosts");

            _ = this.fileWrapperMock.Setup(f => f.ReadAllTextAsync(this.pathToHostsFile))
                .ReturnsAsync(() => oldHostFileContent);

            var remoteHostFileUrls = new List <Uri>
            {
                new Uri("https://www.adawayapk.net/downloads/hostfiles/official/1_hosts.txt"),
                new Uri("https://www.adawayapk.net/downloads/hostfiles/official/2_ad_servers.txt"),
                new Uri("https://www.adawayapk.net/downloads/hostfiles/official/3_yoyohost.txt")
            };

            var adAwayHost = new AdAwayHost(this.loggerMock.Object, this.hostFileDownloader, this.hostFileWriter);

            // Act
            stopWatch.Start();
            await adAwayHost.UpdateHosts(remoteHostFileUrls, ipAddress);

            stopWatch.Stop();

            // Assert
            Assert.That(stopWatch.Elapsed, Is.AtMost(TimeSpan.FromSeconds(10)));
        }
        public void BuildShouldReturnBookViewingViewModelWithValidViewingDate()
        {
            // Arrange
            var builder = new BookViewingViewModelBuilder(_context);

            var viewingsProperty1 = new List <Viewing> {
                new Viewing {
                    ViewingDate = DateTime.Now
                },
                new Viewing {
                    ViewingDate = DateTime.Now.AddDays(1)
                }
            };

            var property = new Domain.Models.Property {
                Id = 5000, StreetName = "Smith Street", Description = "", IsListedForSale = true
            };

            _context.Properties.Find(property.Id).Returns(property);

            // Act
            var viewModel = builder.Build(property.Id);

            // Assert
            Assert.That(viewModel.ViewingDate, Is.AtMost(DateTime.Now));
        }
 public void SetUp()
 {
     parseTree       = "<lessthanorequal 7>";
     staticSyntax    = Is.AtMost(7);
     inheritedSyntax = Helper().AtMost(7);
     builderSyntax   = Builder().AtMost(7);
 }
        public void should_return_item_with_last_modified_date_within_a_minute_of_object_creation()
        {
            requestHeaderFields = new Dictionary <RequestHeaderFields, string>
            {
                { RequestHeaderFields.IfModifiedSince, pastDateTime.ToString() }
            };

            using (var testHelper = new TestHelper(authToken, storageUrl))
            {
                ICloudFilesResponse getStorageItemResponse = null;
                try
                {
                    testHelper.PutItemInContainer();
                    var getStorageItem = new GetStorageItem(storageUrl, Constants.CONTAINER_NAME, Constants.StorageItemName, requestHeaderFields);

                    getStorageItemResponse = new GenerateRequestByType().Submit(getStorageItem, authToken);
                    Assert.That(getStorageItemResponse.Status, Is.EqualTo(HttpStatusCode.OK));
                    Assert.That(getStorageItemResponse.LastModified, Is.AtLeast(DateTime.Now.AddMinutes(-1)));
                    Assert.That(getStorageItemResponse.LastModified, Is.AtMost(DateTime.Now.AddMinutes(2)));
                }
                finally
                {
                    if (getStorageItemResponse != null)
                    {
                        getStorageItemResponse.Dispose();
                    }
                    testHelper.DeleteItemFromContainer();
                }
            }
        }
Example #13
0
        public IEnumerator StartAndCountTo100AndPauseAndResumeAt50()
        {
            countPos = 0;
            SmartRoutine testObject = new SmartRoutine(CountToX(100));

            Assert.That(SmartRoutineHelper.Instance.Routines.Count, Is.EqualTo(1), "1 SmartRoutine should be active.");

            while (countPos != 50)
            {
                Assert.That(SmartRoutineHelper.Instance.Routines.Count, Is.EqualTo(1), "1 SmartRoutine should be active.");
                yield return(new WaitForEndOfFrame());
            }

            Assert.That(SmartRoutineHelper.Instance.Routines.Count, Is.EqualTo(1), "1 SmartRoutine should be active.");
            testObject.Stop(false);

            Assert.That(testObject.IsPaused, Is.True, "SmartRoutine failed to pause.");
            Assert.That(testObject.IsRunning, Is.True, "SmartRoutine stopped when it should be paused.");
            Assert.That(SmartRoutineHelper.Instance.Routines.Count, Is.EqualTo(0), "No SmartRoutine should be active while paused.");

            yield return(testObject);

            Assert.That(countPos, Is.EqualTo(100), "Failed to count to 100.");
            Assert.That(testObject.IsRunning, Is.False, "SmartRoutine failed to stop.");
            Assert.That(SmartRoutineHelper.Instance.Routines.Count, Is.AtMost(0), "SmartRoutine did not complete.");
            yield break;
        }
Example #14
0
            /// <summary>
            /// Tests creating a random integer generator with a particular set of lower bounds
            /// and an integer count
            /// </summary>
            /// <param name="lowerBound">The lower bounds (inclusive) of the integers to be generated</param>
            /// <param name="upperBound">The upper bounds (inclusive) of the integers to be generated</param>
            /// <param name="count">The number of integers to be generated</param>
            private void TestRandomIntegerGenerator(int lowerBound, int upperBound, int count)
            {
                Assert.That(count, Is.GreaterThanOrEqualTo(0));
                Assert.That(lowerBound, Is.AtMost(upperBound));

                IRandomIntegerGenerator randomIntGenerator = new RandomIntegerGenerator();

                //Create the random integer generator
                IEnumerable <int> randomIntegers = randomIntGenerator.CreateIntegerGenerator(lowerBound,
                                                                                             upperBound, count);

                //Iterate over the random integers, verifying that there are the correct number of integers
                //and that they all fall within the specified bounds
                int integerCount = 0;

                foreach (int randomInt in randomIntegers)
                {
                    //Verify that the random integer is within the specified bounds
                    Assert.That(randomInt, Is.AtLeast(lowerBound));
                    Assert.That(randomInt, Is.AtMost(upperBound));

                    integerCount++;
                }

                //Verify that the correct number of integers were generated
                Assert.That(integerCount, Is.EqualTo(count));
            }
        public void DefaultTimestampProvider_GetTimestamp_ReturnsValueInRange()
        {
            ITimestampProvider provider = new DefaultTimestampProvider();
            long timestamp = provider.GetCurrentTimestampInMilliseconds();

            Assert.That(timestamp,
                        Is.AtMost(IF_MORE_BASE_YEAR_MAY_BE_WRONG).And.AtLeast(IF_LESS_UNITS_ARE_WRONG));
        }
Example #16
0
 public void PluginAPILevelIsLessThanOrEqualToSDKAPILevel()
 {
     if (!SDKUtility.sdkAvailable)
     {
         Assert.Ignore("Cannot locate Lumin SDK");
     }
     Assert.That(SDKUtility.pluginAPILevel, Is.AtMost(SDKUtility.sdkAPILevel));
 }
        public void CheckMaxLenghth()
        {
            // Create a random unique number
            var number = randomNumberGen.GetUniqueRandomNumber();

            // Check if its length is max 5
            Assert.That(number, Is.AtMost(99999), "Number is greater than max number length of 5");
        }
Example #18
0
        public void Test1()
        {
            var r1   = new RandomUsingOtherRandom();
            var next = r1.Rand7();

            Assert.That(next, Is.AtLeast(0));
            Assert.That(next, Is.AtMost(6));
        }
Example #19
0
        public IEnumerator StartAndRunToCompletionAndWaitFor1SecondWithArgs()
        {
            SmartRoutine testObject = new SmartRoutine(WaitFor);

            yield return(testObject.Start(1f));

            Assert.That(SmartRoutineHelper.Instance.Routines.Count, Is.AtMost(0), "SmartRoutine did not complete.");
            yield break;
        }
Example #20
0
 public void WrapModeLoopWillLoopTheTime()
 {
     animation["Clip1"].wrapMode = WrapMode.Loop;
     for (int i = 0; i < 4; i++)
     {
         animation.UpdateAnimationStates(0.55f);
     }
     Assert.That(animation["Clip1"].time, Is.AtMost(0.21f));
     Assert.That(animation["Clip1"].enabled, Is.True);
 }
        public void should_calculate_the_distance_correctly_between_two_points()
        {
            var london = new LocationCoordinate(51.500288, -0.126269);
            var paris  = new LocationCoordinate(48.856495, 2.350907);

            var result = Resolve <IDistanceCalculatorService>().DistanceBetween(london, paris) / 1000;

            Assert.That(result, Is.AtLeast(342));
            Assert.That(result, Is.AtMost(343));
        }
Example #22
0
        public IEnumerator StartAndRunToCompletionAndSetABoolOnComplete()
        {
            bool         test       = false;
            SmartRoutine testObject = new SmartRoutine(WaitFor(), () => { test = true; });

            yield return(testObject);

            Assert.That(test, Is.True, "Callback did not invoke on completion.");
            Assert.That(SmartRoutineHelper.Instance.Routines.Count, Is.AtMost(0), "SmartRoutine did not complete.");
        }
Example #23
0
        public IEnumerator CreateAndStartAndYieldUntilComplete()
        {
            SmartRoutine testObject = new SmartRoutine(WaitFor());

            yield return(testObject);

            Assert.That(testObject.IsRunning, Is.False, "SmartRoutine did not complete.");
            Assert.That(SmartRoutineHelper.Instance.Routines.Count, Is.AtMost(0), "SmartRoutine did not complete.");
            yield break;
        }
Example #24
0
        public IEnumerator CreateAndStartInline()
        {
            SmartRoutine testObject = new SmartRoutine(WaitFor());

            Assert.That(testObject.IsRunning, Is.True, "SmartRoutine did not start.");
            Assert.That(SmartRoutineHelper.Instance.Routines.Count, Is.EqualTo(1), "SmartRoutine did not start.");
            testObject.Stop();
            Assert.That(SmartRoutineHelper.Instance.Routines.Count, Is.AtMost(0), "SmartRoutine did not stop.");
            yield break;
        }
Example #25
0
        public IEnumerator StartAndRunToCompletionAndSetABoolOnStopForCompletion()
        {
            bool?        test       = null;
            SmartRoutine testObject = new SmartRoutine(WaitFor(.5f), (bool x) => { test = x; });

            yield return(testObject);

            Assert.That(test, Is.True, "OnStop did not return true for completion.");
            Assert.That(SmartRoutineHelper.Instance.Routines.Count, Is.AtMost(0), "SmartRoutine did not complete.");
        }
Example #26
0
 public void WrapModeDefaultWillTakeTheWrapModeFromTheAnimationComponent()
 {
     animation["Clip1"].wrapMode = WrapMode.Default;
     animation.wrapMode          = WrapMode.Loop;
     for (int i = 0; i < 4; i++)
     {
         animation.UpdateAnimationStates(0.55f);
     }
     Assert.That(animation["Clip1"].time, Is.AtMost(0.21f));
     Assert.That(animation["Clip1"].enabled, Is.True);
 }
Example #27
0
        public async Task WhenNoConnectionThrowSocketExceptionAfterMaxRetry()
        {
            var reconnectionAttempt = 0;
            var config     = new ConnectionConfiguration(onConnecting: (endpoint, attempt, elapsed) => Interlocked.Increment(ref reconnectionAttempt));
            var socket     = new TcpSocket(new Endpoint(new Uri("http://not.com"), null), config, TestConfig.InfoLog);
            var resultTask = socket.ReadAsync(4, CancellationToken.None);

            Assert.ThrowsAsync <ConnectionException>(async() => await resultTask);
            Assert.That(reconnectionAttempt, Is.AtLeast(ConnectionConfiguration.Defaults.MaxConnectionAttempts + 1));
            Assert.That(reconnectionAttempt, Is.AtMost(ConnectionConfiguration.Defaults.MaxConnectionAttempts + 2));
        }
Example #28
0
        public void Test(int[] dimensions, int bestSoFar, int targetCases)
        {
            int features = dimensions.Length;

            string[][] sources = new string[features][];

            for (int i = 0; i < features; i++)
            {
                string featureName = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".Substring(i, 1);

                int n = dimensions[i];
                sources[i] = new string[n];
                for (int j = 0; j < n; j++)
                {
                    sources[i][j] = featureName + j.ToString();
                }
            }

            ICombiningStrategy strategy = new PairwiseStrategy();

            PairCounter pairs = new PairCounter();
            int         cases = 0;

            foreach (NUnit.Framework.Internal.TestCaseParameters parms in strategy.GetTestCases(sources))
            {
                for (int i = 1; i < features; i++)
                {
                    for (int j = 0; j < i; j++)
                    {
                        string a = parms.Arguments[i] as string;
                        string b = parms.Arguments[j] as string;
                        pairs[a + b] = null;
                    }
                }

                ++cases;
            }

            int expectedPairs = 0;

            for (int i = 1; i < features; i++)
            {
                for (int j = 0; j < i; j++)
                {
                    expectedPairs += dimensions[i] * dimensions[j];
                }
            }

            Assert.That(pairs.Count, Is.EqualTo(expectedPairs), "Number of pairs is incorrect");
            Assert.That(cases, Is.AtMost(bestSoFar), "Regression: Number of test cases exceeded target previously reached");
#if DEBUG
            //Assert.That(cases, Is.AtMost(targetCases), "Number of test cases exceeded target");
#endif
        }
Example #29
0
        public void it_should_return_the_date_at_the_beginning_of_the_week()
        {
            foreach (var date in _randomDates)
            {
                DateTime expected = date.AtBeginningOfWeek();

                Assert.That(expected.DayOfWeek, Is.EqualTo(DayOfWeek.Sunday));
                Assert.That(expected.TimeOfDay, Is.EqualTo(_midnight));
                Assert.That(date.Day, Is.GreaterThanOrEqualTo(expected.Day));
                Assert.That(date.Day - expected.Day, Is.AtMost(6));
            }
        }
Example #30
0
        public void it_should_return_the_date_at_the_end_of_the_week()
        {
            foreach (var date in _randomDates)
            {
                DateTime expected = date.AtEndOfWeek();

                Assert.That(expected.DayOfWeek, Is.EqualTo(DayOfWeek.Saturday));
                Assert.That(expected.TimeOfDay, Is.EqualTo(_endOfDay));
                Assert.That(date.Day, Is.LessThanOrEqualTo(expected.Day));
                Assert.That(expected.Day - date.Day, Is.AtMost(6));
            }
        }