public Mock<IAsyncCloudGateway> InitializeGetChildItemsAsyncWithFilter(RootName rootName, string path, string filter, params IEnumerable<FileSystemInfoContract>[] pathChildItems)
        {
            var gatewayMock = new Mock<IAsyncCloudGateway>(MockBehavior.Strict);
            gatewayMock.SetupSequence(g => g.GetRootAsync(rootName, FileSystemFixture.ApiKey))
                .ReturnsAsync(FileSystemFixture.Root)
                .ThrowsAsync(new InvalidOperationException("Redundant call to GetRoot()"));
            gatewayMock.SetupSequence(g => g.GetDriveAsync(rootName, FileSystemFixture.ApiKey))
                .ReturnsAsync(FileSystemFixture.Drive)
                .Throws(new InvalidOperationException("Redundant call to GetDrive()"));

            if (path != null) {
                path = path + Path.DirectorySeparatorChar;
                for (int i = 0, j = 0; i >= 0; i = path.IndexOf(Path.DirectorySeparatorChar, Math.Min(path.Length, i + 2)), ++j) {
                    var currentPath = new DirectoryId(path.Substring(0, Math.Max(1, i)));

                    bool applyFilter = j == pathChildItems.Length - 1;
                    var effectiveFilter = applyFilter && filter != null ? new Regex("^" + filter.Replace("*", ".*") + "$") : null;
                    gatewayMock.SetupSequence(g => g.GetChildItemAsync(rootName, currentPath))
                        .ReturnsAsync(applyFilter ? pathChildItems[j].Where(f => effectiveFilter == null || effectiveFilter.IsMatch(f.Name)) : pathChildItems[j])
                        .ThrowsAsync(new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Redundant access to {0}", currentPath)));
                }
            }

            return gatewayMock;
        }
示例#2
0
        public void setUpBeforeEachTest()
        {
            litle = new litleRequest();

            mockXmlReader = new Mock<XmlReader>();
            mockXmlReader.SetupSequence(XmlReader => XmlReader.ReadToFollowing(It.IsAny<String>())).Returns(true).Returns(true).Returns(false);
            mockXmlReader.SetupSequence(XmlReader => XmlReader.ReadState).Returns(ReadState.Initial).Returns(ReadState.Interactive).Returns(ReadState.Closed);
        }
示例#3
0
		public void GetEngineReturnsAllAvailableEngines()
		{
			var engines = new[]
			{
				new Mock<IJsEngine>().Object,
				new Mock<IJsEngine>().Object,
				new Mock<IJsEngine>().Object,
			};
			var factory = new Mock<IEngineFactoryForMock>();
			factory.SetupSequence(x => x.EngineFactory())
				// Initial call to factory is to determine engine type, we don't care
				// about that here.
				.Returns(new Mock<IJsEngine>().Object)
				.Returns(engines[0])
				.Returns(engines[1])
				.Returns(engines[2]);
			var config = new JsPoolConfig
			{
				StartEngines = 3,
				EngineFactory = factory.Object.EngineFactory
			};

			var pool = new JsPool(config);
			var resultEngines = new[]
			{
				pool.GetEngine(),
				pool.GetEngine(),
				pool.GetEngine(),
			};

			CollectionAssert.AreEquivalent(engines, resultEngines);
		}
        public void SetUp()
        {
            _archetype = ContentHelpers.Archetype;

            var content = ContentHelpers.FakeContent(123, "Fake Node 1", properties: new Collection<IPublishedProperty>
            {
                new FakePublishedProperty("myArchetypeProperty", _archetype, true)
            });

            _content = new FakeModel(content);
            _propertyDescriptor = TypeDescriptor.GetProperties(_content)["TextString"];

            _context = new FakeDittoValueResolverContext(_content, _propertyDescriptor);

            var mockedPropertyService = new Mock<PropertyValueService>();

            mockedPropertyService.SetupSequence(
                i =>
                    i.Set(It.IsAny<IPublishedContent>(), It.IsAny<CultureInfo>(), It.IsAny<PropertyInfo>(),
                        It.IsAny<object>(), It.IsAny<object>(), It.IsAny<DittoValueResolverContext>()))
                        .Returns(new HtmlString("<p>This is the <strong>summary</strong> text.</p>"))
                        .Returns("Ready to Enroll?")
                        .Returns("{}");

            _sut = new ArchetypeBindingService(mockedPropertyService.Object, new DittoAliasLocator());
        }
        public void ThenIfOneResourceFailsToUploadThenAllAreReloaded()
        {
            // Arrange: unsuccessful resource upload followed by two successful uploads
            var ckanApi = new Mock<ICkanApi>(MockBehavior.Strict);
            ckanApi.Setup(x => x.CreateResource(resource1)).Returns(resource1);
            ckanApi.SetupSequence(x => x.CreateResource(resource2))
                .Throws<CkanTimeoutException>()
                .Throws<CkanInternalServerException>()
                .Returns(resource2);

            // Arrange: package update after failed resource upload
            package.Resources.Add(resource1);
            ckanApi.Setup(x => x.GetPackage(packageId)).Returns(package);
            ckanApi.Setup(x => x.UpdatePackage(package)).Returns(package);

            // Act: upload resources
            var resources = UploadResources(ckanApi);

            // Assert: expected number of resources
            Assert.AreEqual(2, resources.Count);

            // Assert: package resources have been cleared
            Assert.AreEqual(0, package.Resources.Count);
            ckanApi.VerifyAll();
        }
		public void GetControllersMetaData_LocalControllers_GetWithoutIgnoredAndSortedCorrectly()
		{
			// Assign

			SimplifyWebTypesFinder.ExcludedAssembliesPrefixes.Remove("Simplify");
			SimplifyWebTypesFinder.ExcludedAssembliesPrefixes.Add("DynamicProxyGenAssembly2");
			SimplifyWebTypesFinder.CleanLoadedTypesAndAssembliesInfo();

			var factory = new Mock<IControllerMetaDataFactory>();
			var store = new ControllersMetaStore(factory.Object);

			factory.SetupSequence(x => x.CreateControllerMetaData(It.IsAny<Type>()))
				.Returns(new ControllerMetaData(typeof(TestController1), new ControllerExecParameters(null, 2)))
				.Returns(new ControllerMetaData(typeof(TestController2), new ControllerExecParameters(null, 1)))
				.Returns(new ControllerMetaData(typeof(TestController4)))
				.Returns(new ControllerMetaData(typeof(TestController5)));

			// Act
			var metaData = store.ControllersMetaData;

			Assert.AreEqual(4, metaData.Count);
			Assert.AreEqual("TestController4", metaData[0].ControllerType.Name);
			Assert.AreEqual("TestController5", metaData[1].ControllerType.Name);
			Assert.AreEqual("TestController2", metaData[2].ControllerType.Name);
			Assert.AreEqual("TestController1", metaData[3].ControllerType.Name);

			factory.Verify(x => x.CreateControllerMetaData(It.Is<Type>(t => t == typeof(TestController1))));
			factory.Verify(x => x.CreateControllerMetaData(It.Is<Type>(t => t == typeof(TestController2))));
			factory.Verify(x => x.CreateControllerMetaData(It.Is<Type>(t => t == typeof(TestController4))));
			factory.Verify(x => x.CreateControllerMetaData(It.Is<Type>(t => t == typeof(TestController5))));
		}
示例#7
0
        public void DisposeDisposesAllEngines()
        {
            var engines = new[]
            {
                new Mock<IJsEngine>(),
                new Mock<IJsEngine>(),
                new Mock<IJsEngine>(),
                new Mock<IJsEngine>(),
            };
            var factory = new Mock<IEngineFactoryForMock>();
            factory.SetupSequence(x => x.EngineFactory())
                .Returns(engines[0].Object)
                .Returns(engines[1].Object)
                .Returns(engines[2].Object)
                .Returns(engines[3].Object);
            var config = new JsPoolConfig
            {
                StartEngines = 3,
                EngineFactory = factory.Object.EngineFactory
            };

            var pool = new JsPool(config);
            pool.Dispose();

            foreach (var engine in engines)
            {
                engine.Verify(x => x.Dispose());
            }
        }
        public async void GetWeatherAsync_2ClientsWithOneClientWrong()
        {
            var mockHttpClient = new Mock<IHttpClient>();

            //Arrange 
            mockHttpClient.SetupSequence(x => x.GetStringAsync(It.IsAny<string>()))
            //BBC
            .Returns(Task.Run<HttpClientResponse>(() => DataTest.HttpClientResponse["BBCWeatherOK"]))
            //AccuWeather
            .Returns(Task.Run<HttpClientResponse>(() => DataTest.HttpClientResponse["Wrong"]));


            var moclHttpClientFactory = new Mock<IHttpClientFactory>();
            moclHttpClientFactory.Setup(x => x.GetHttpClient<HttpClientWrapper>()).Returns(mockHttpClient.Object);

            _container.RegisterInstance<IHttpClientFactory>(moclHttpClientFactory.Object);

            var manager = _container.Resolve<ApiWeatherManager>();

            //Act
            var result = await manager.GetWeatherAsync("anylocation", Api.Weather.TemperatureUnits.Farenheits, Api.Weather.WindUnits.MPHs);

            //Assert
            result.WindUnit.Should().Be(WindUnits.MPHs);
            result.TemperatureUnit.Should().Be(TemperatureUnits.Farenheits);
            result.Wind.Should().Be(0.62f);
            result.Temperature.Should().Be(77);
        }
        public void SerializeError_serializes_httperror()
        {
            using (var stream = new MemoryStream())
            {
                var textWriter = new StreamWriter(stream);
                var writer = new JsonTextWriter(textWriter);

                var mockInnerException = new Mock<Exception>(MockBehavior.Strict);
                mockInnerException.Setup(m => m.Message).Returns("Inner exception message");
                mockInnerException.Setup(m => m.StackTrace).Returns("Inner stack trace");

                var outerException = new Exception("Outer exception message", mockInnerException.Object);

                var error = new HttpError(outerException, true)
                {
                    StackTrace = "Outer stack trace"
                };
                var jsonSerializer = new JsonSerializer();

                var mockIdProvider = new Mock<IErrorIdProvider>(MockBehavior.Strict);
                mockIdProvider.SetupSequence(p => p.GenerateId(It.IsAny<HttpError>())).Returns("OUTER-ID").Returns("INNER-ID");

                var serializer = new ErrorSerializer(mockIdProvider.Object);
                serializer.SerializeError(error, stream, writer, jsonSerializer);

                writer.Flush();

                var expectedJson = File.ReadAllText("ErrorSerializerTest.json");
                var minifiedExpectedJson = JsonHelpers.MinifyJson(expectedJson);
                var output = System.Text.Encoding.ASCII.GetString(stream.ToArray());
                output.Should().Be(minifiedExpectedJson);
            }
        }
        public async Task CallAsync_MethodWithReturnValue()
        {
            var mockService = new Mock<ITestService>();
            mockService
                .SetupSequence(m => m.TestMethod("good"))
                .Returns("BAD")
                .Returns("OK");

            mockService.Setup(m => m.TestMethod("second", "two")).Returns("2");

            var serviceHost = InProcTestFactory.CreateHost<ITestService>(new TestServiceImpl(mockService));

            var proxy = WcfClientProxy.CreateAsyncProxy<ITestService>(c =>
            {
                c.MaximumRetries(1);
                c.SetEndpoint(serviceHost.Binding, serviceHost.EndpointAddress);
                c.RetryOnResponse<string>(s => s == "BAD");
            });

            Console.WriteLine("Caller thread: " + Thread.CurrentThread.ManagedThreadId);

            string result = await proxy.CallAsync(m => m.TestMethod("good"));
            string result2 = await proxy.CallAsync(m => m.TestMethod("second", "two"));

            Console.WriteLine("Continuation thread: " + Thread.CurrentThread.ManagedThreadId);

            Assert.That(result, Is.EqualTo("OK"));
            Assert.That(result2, Is.EqualTo("2"));
        }
        public void Main_WithTwoValidCommands_ExitsProgramWhenEmptyStringIsEntered()
        {
            // Arrange
            Mock<IStringCalculator> mockCalculator = new Mock<IStringCalculator>();
            Mock<IConsole> mockConsole = new Mock<IConsole>();
            mockCalculator.Setup(c => c.Add("1,2,3")).Returns(6);
            mockCalculator.Setup(c => c.Add("3")).Returns(3);
            mockCalculator.Setup(c => c.Add("5")).Returns(5);

            mockConsole.SetupSequence(c => c.ReadLine())
                .Returns("3")
                .Returns("5")
                .Returns("");

            StringCalculatorConsole stringCalculatorConsole = CreateCalcConsole(mockCalculator, mockConsole);

            // Act
            stringCalculatorConsole.Main(new string[] { "scalc '1,2,3'" });

            // Assert
            mockConsole.Verify(c => c.WriteLine("The result is 6"));
            mockConsole.Verify(c => c.WriteLine("another input please"), Times.Exactly(3));
            mockConsole.Verify(c => c.WriteLine("The result is 3"));
            mockConsole.Verify(c => c.WriteLine("The result is 5"));
            mockConsole.Verify(c => c.ReadLine(), Times.Exactly(3));
        }
示例#12
0
        public async Task WriteFileAsync_WritesResponse_InChunksOfFourKilobytes()
        {
            // Arrange
            var mockReadStream = new Mock<Stream>();
            mockReadStream.SetupSequence(s => s.ReadAsync(It.IsAny<byte[]>(), 0, 0x1000, CancellationToken.None))
                .Returns(Task.FromResult(0x1000))
                .Returns(Task.FromResult(0x500))
                .Returns(Task.FromResult(0));

            var mockBodyStream = new Mock<Stream>();
            mockBodyStream
                .Setup(s => s.WriteAsync(It.IsAny<byte[]>(), 0, 0x1000, CancellationToken.None))
                .Returns(Task.FromResult(0));

            mockBodyStream
                .Setup(s => s.WriteAsync(It.IsAny<byte[]>(), 0, 0x500, CancellationToken.None))
                .Returns(Task.FromResult(0));

            var result = new FileStreamResult(mockReadStream.Object, "text/plain");

            var httpContext = GetHttpContext();
            httpContext.Response.Body = mockBodyStream.Object;

            var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            mockReadStream.Verify();
            mockBodyStream.Verify();
        }
        public void SwagOMeterViewModelShouldAwardSwagAndCanSwagSetToFalseWhenSwagAndAttendeesAreAllUsedUpAfterAward()
        {
            // Arrange
            var mockAttendee = new Mock<IAttendee>();
            mockAttendee.SetupGet(a => a.Name).Returns("Bob");

            var mockSwag = new Mock<ISwag>();
            mockSwag.SetupGet(s => s.Company).Returns("Company");
            mockSwag.SetupGet(s => s.Thing).Returns("Thing");

            var stubAttendeeSource = new Mock<IAttendeeSource>();

            var stubSwagSource = new Mock<ISwagSource>();

            var stubWinnersSource = new Mock<IWinnersSource>();

            var stubSwagOMeterEngine = new Mock<ISwagOMeterAwardEngine>();
            stubSwagOMeterEngine.Setup(e => e.CheckCanSwag()).Returns(true);
            stubSwagOMeterEngine.SetupSequence(e => e.CanSwag).Returns(true).Returns(false);
            stubSwagOMeterEngine.SetupGet(e => e.AwardedSwag).Returns(mockSwag.Object);
            stubSwagOMeterEngine.SetupGet(e => e.WinningAttendee).Returns(mockAttendee.Object);

            // Act
            var viewModel = new SwagOMeterViewModel(stubAttendeeSource.Object, stubSwagSource.Object, stubWinnersSource.Object, stubSwagOMeterEngine.Object);
            viewModel.ViewReady();
            viewModel.AwardSwagCommand.Execute(null);

            // Assert
            StringAssert.Matches(viewModel.WinningAttendee, new Regex("Bob"));
            StringAssert.Matches(viewModel.WonSwag, new Regex("Company Thing"));
            Assert.IsFalse(viewModel.CanSwag);
        }
示例#14
0
        public void setUpBeforeEachTest()
        {
            _mockConfig = new Dictionary<string, string>();
            _mockConfig["url"] = "https://www.mockurl.com";
            _mockConfig["reportGroup"] = "Mock Report Group";
            _mockConfig["username"] = "******";
            _mockConfig["printxml"] = "false";
            _mockConfig["timeout"] = "35";
            _mockConfig["proxyHost"] = "www.mockproxy.com";
            _mockConfig["merchantId"] = "MOCKID";
            _mockConfig["password"] = "******";
            _mockConfig["proxyPort"] = "3000";
            _mockConfig["sftpUrl"] = "www.mockftp.com";
            _mockConfig["sftpUsername"] = "******";
            _mockConfig["sftpPassword"] = "******";
            _mockConfig["knownHostsFile"] = "C:\\MockKnownHostsFile";
            _mockConfig["onlineBatchUrl"] = "www.mockbatch.com";
            _mockConfig["onlineBatchPort"] = "4000";
            _mockConfig["requestDirectory"] = "C:\\MockRequests";
            _mockConfig["responseDirectory"] = "C:\\MockResponses";

            _mockCache.Setup(x => x[_mockConfig["responseDirectory"] + "\\Responses\\" + mockFileName])
                .Returns(new StringBuilder());
            litle = new litleRequest(_mockCache.Object, _mockConfig);

            mockXmlReader = new Mock<XmlReader>();
            mockXmlReader.SetupSequence(XmlReader => XmlReader.ReadToFollowing(It.IsAny<string>()))
                .Returns(true)
                .Returns(true)
                .Returns(false);
            mockXmlReader.SetupSequence(XmlReader => XmlReader.ReadState)
                .Returns(ReadState.Initial)
                .Returns(ReadState.Interactive)
                .Returns(ReadState.Closed);
        }
        public void IntegrationTestProcessBatch()
        {
            var orders = new List<IDummyOrderObject>();
            for (var i = 0; i < 6; i++)
            {
                var order = new Mock<IDummyOrderObject>();
                order.Setup(s => s.OrderNumber).Returns(i.ToString(CultureInfo.InvariantCulture));
                orders.Add(order.Object);
            }

            var repo = new Mock<IFraudRepository>();
            var mockRuleFailing = RuleGenerators.FetchMockedRule(true);
            var mockRulePassing = RuleGenerators.FetchMockedRule(false);
            repo
                .SetupSequence(m => m.FetchAllRules())
                .Returns(new List<IFraudRule> { mockRuleFailing.Object })
                .Returns(new List<IFraudRule> { mockRulePassing.Object })
                .Returns(new List<IFraudRule> { mockRuleFailing.Object })
                .Returns(new List<IFraudRule> { mockRulePassing.Object })
                .Returns(new List<IFraudRule> { mockRuleFailing.Object })
                .Returns(new List<IFraudRule> { mockRulePassing.Object });

            var bulkProcessor = new FraudCheckerBulkProcessor(repo.Object);
            var report = bulkProcessor.ProcessBatch(orders);

            Assert.AreEqual(6, report.Count);
            Assert.IsFalse(report["0"].OverallResult);
            Assert.IsTrue(report["1"].OverallResult);
            Assert.IsFalse(report["2"].OverallResult);
            Assert.IsTrue(report["3"].OverallResult);
            Assert.IsFalse(report["4"].OverallResult);
            Assert.IsTrue(report["5"].OverallResult);
        }
示例#16
0
 public void Setup()
 {
     _display = new Mock<IGameDisplay>();
     _display.SetupSequence<IGameDisplay, bool>(x => x.PlayAgainMessage()).Returns(true).Returns(true).Returns(false);
     _board = new Mock<IBoard>();
     _playGameHandler = new Mock<PlayGameHandler>();
     _gameEngine = new GameEngine(_display.Object, _board.Object, _playGameHandler.Object);
 }
示例#17
0
        public void Setup()
        {
            Mock<ILoggerService> loggerService = new Mock<ILoggerService>();
            loggerService.SetupSequence(o => o.Log(It.IsAny<Log>())).Returns(true);

            FileService Service = new FileService(loggerService.Object);
            Service.SaveMedia(StoredMedia, data);
        }
示例#18
0
        public void SetUp()
        {
            adapter = new Mock<IShaderAdapter>();
            adapter.SetupSequence(a => a.CreateProgram())
                   .Returns(1)
                   .Returns(2);
            adapter.SetupSequence(a => a.CreateShader(It.IsAny<ShaderType>()))
                   .Returns(1)
                   .Returns(2);
            adapter.Setup(a => a.GetShaderProgramStatus(
                    It.IsAny<int>(), GetProgramParameterName.LinkStatus))
                   .Returns(true);

            vertexShader = new Shader(adapter.Object, ShaderType.VertexShader);
            fragmentShader = new Shader(adapter.Object, ShaderType.FragmentShader);

            program = new ShaderProgram(adapter.Object, vertexShader, fragmentShader);
        }
示例#19
0
        public void DeleteMedia_NormalCase_Deleted()
        {
            Mock<ILoggerService> loggerService = new Mock<ILoggerService>();
            loggerService.SetupSequence(o => o.Log(It.IsAny<Log>())).Returns(true);

            FileService Service = new FileService(loggerService.Object);
            bool flag = Service.DeleteMedia(this.StoredMedia);
            Assert.IsTrue(flag);
        }
示例#20
0
        public void GetLogs_LogsNotExist_ReturnsNullList()
        {
            Mock<IRepository<Log>> repository = new Mock<IRepository<Log>>();
            repository.SetupSequence(o => o.GetAll()).Returns(null);

            LoggerService service = new LoggerService(repository.Object);
            IList<Log> logs = service.GetLogs();
            Assert.IsNull(logs);
        }
示例#21
0
        public void SendMailsTest()
        {
            //Arrange
            var emailBuilder1 = new Mock<IEmailBuilder>();
            var emailBuilder2 = new Mock<IEmailBuilder>();
            var mailClient1 = new Mock<IMailClient>();
            var mailClient2 = new Mock<IMailClient>();
            var mailFactory = new Mock<IEmailFactory>();
            var mailIntialezer = new Mock<IEmailInitializer>();

            mailFactory.SetupSequence(m => m.CreateEmailBuilder())
                       .Returns(emailBuilder1.Object)
                       .Returns(emailBuilder2.Object);

            mailFactory.SetupSequence(m => m.CreateMailClient())
                       .Returns(mailClient1.Object)
                       .Returns(mailClient2.Object);
            
            var emailList = new List<EmailBase>() { new Mock<EmailBase>().Object, new Mock<EmailBase>().Object };
            var repository = new MailerRepository(mailFactory.Object, mailIntialezer.Object);

            mailClient1.Setup(m => m.Send(It.IsAny<IEmailBuilder>())).Returns(() =>
                {
                    var tcs = new TaskCompletionSource<object>();
                    tcs.SetResult(null);
                    return tcs.Task;
                });
            mailClient2.Setup(m => m.Send(It.IsAny<IEmailBuilder>())).Returns(() =>
                {
                    var tcs = new TaskCompletionSource<object>();
                    tcs.SetResult(null);
                    return tcs.Task;
                });
            
            //Act
            var task = repository.SendMails(emailList);
            task.Wait();

            //Assert
            mailIntialezer.Verify(m => m.Initialize(emailBuilder1.Object, emailList[0]), Times.Once());
            mailIntialezer.Verify(m => m.Initialize(emailBuilder2.Object, emailList[1]), Times.Once());
            mailClient1.Verify(m => m.Send(emailBuilder1.Object), Times.Once());
            mailClient2.Verify(m => m.Send(emailBuilder2.Object), Times.Once());
        }
示例#22
0
        public void GetMedia_NormalCase_Saved()
        {
            Mock<ILoggerService> loggerService = new Mock<ILoggerService>();
            loggerService.SetupSequence(o => o.Log(It.IsAny<Log>())).Returns(true);

            FileService Service = new FileService(loggerService.Object);

            byte[] retrieved = Service.GetMedia(this.StoredMedia);
            Assert.AreEqual("System.Byte[]", retrieved.ToString());
        }
        public void Setup()
        {
            generator = new ConfigurableIterationGenerator(2);
            mockDice = new Mock<Dice>();
            mockDice.SetupSequence(d => d.Roll(3).d(6).AsSum())
                .Returns(min).Returns(max).Returns(middle)
                .Returns(min - 1).Returns(max + 1).Returns(middle);

            randomizer = new PoorStatsRandomizer(mockDice.Object, generator);
        }
示例#24
0
        public void SaveMedia_NormalCase_Saved()
        {
            Mock<ILoggerService> loggerService = new Mock<ILoggerService>();
            loggerService.SetupSequence(o => o.Log(It.IsAny<Log>())).Returns(true);

            FileService Service = new FileService(loggerService.Object);
            string path = "/test.txt";
            bool flag = Service.SaveMedia(path, new byte[1]);
            Assert.IsTrue(flag);
        }
        public void WhenTextReaderReturnsEmptyStringThenCreateEmptyDictionary()
        {
            var mockedTextReader = new Mock<TextReader>();
            mockedTextReader.SetupSequence(p => p.ReadLine())
                .Returns("");

            ISentenceProcessor sentenceProvider = new SentenceProcessor(_standardDelimiters);
            var result = sentenceProvider.Process(mockedTextReader.Object);

            Assert.That(result.Count, Is.EqualTo(0));            
        }
示例#26
0
        public int TestTakeTurn(int initialPosition, int die1, int die2)
        {
            Mock<IRandomNumberGenerator> randMock = new Mock<IRandomNumberGenerator>();
            randMock.SetupSequence(s => s.Generate(1, MonopolyGame.NUMBER_OF_SIDES)).Returns(die1).Returns(die2);

            Player player = new Player("Car", randMock.Object) { CurrentPosition = initialPosition };

            player.TakeTurn();

            return player.CurrentPosition;
        }
		public void PerformSequenceWithThrowsFirst()
		{
			var mock = new Mock<IFoo>();

			mock.SetupSequence(x => x.Do())
				.Throws<Exception>()
				.Returns(1);

			Assert.Throws<Exception>(() => mock.Object.Do());
			Assert.Equal(1, mock.Object.Do());
		}
        public void TestGetAllBatches()
        {
            var dateTime1 = DateTime.Now.AddDays(1);
            var dateTime2 = DateTime.Now.AddDays(2);

            var dataReader = new Mock<IDataReader>();
            dataReader.SetupSequence(mocked => mocked.Read()).Returns(true).Returns(true).Returns(false);
            dataReader.SetupSequence(mocked => mocked[0]).Returns(1).Returns(2);
            dataReader.SetupSequence(mocked => mocked[1]).Returns("name1").Returns("name2");
            dataReader.SetupSequence(mocked => mocked[2]).Returns(dateTime1).Returns(dateTime2);
            dataReader.Setup(mocked => mocked.IsDBNull(3)).Returns(false);
            dataReader.SetupSequence(mocked => mocked.GetInt16(3)).Returns(0).Returns(1);

            var dbCommand = new Mock<IDbCommand>();
            dbCommand.Setup(mocked => mocked.Dispose());
            dbCommand.SetupSet(mocked => mocked.CommandType = CommandType.Text).Verifiable();
            dbCommand.SetupSet(mocked => mocked.CommandText = "SELECT ID, IDBatch, DateProcess, Exported FROM Batches  ORDER BY DateProcess DESC").Verifiable();
            dbCommand.Setup(mocked => mocked.ExecuteReader()).Returns(dataReader.Object);

            _dbConnection.Setup(mocked => mocked.Open());
            _dbConnection.Setup(mocked => mocked.CreateCommand()).Returns(dbCommand.Object);
            _dbConnection.Setup(mocked => mocked.Close());

            var result = _fixture.GetBatches(false);
            _dbConnection.VerifyAll();
            dataReader.VerifyAll();
            dbCommand.VerifyAll();

            Assert.IsNotNull(result);
            Assert.AreEqual(2, result.Count);

            Assert.AreEqual(1, result[0].Id);
            Assert.AreEqual("name1", result[0].Name);
            Assert.AreEqual(dateTime1, result[0].ScanDate);
            Assert.AreEqual(BatchStatus.NotExported, result[0].Status);

            Assert.AreEqual(2, result[1].Id);
            Assert.AreEqual("name2", result[1].Name);
            Assert.AreEqual(dateTime2, result[1].ScanDate);
            Assert.AreEqual(BatchStatus.Exported, result[1].Status);
        }
        public void DataReaderPopulatedTableData2x2Reader()
        {
            reader = new Mock<IDataReader>();
            reader.Setup(x => x.FieldCount).Returns(2);
            reader.Setup(x => x.GetName(0)).Returns("a");
            reader.Setup(x => x.GetName(1)).Returns("b");
            reader.SetupSequence(x => x.Read()).Returns(true).Returns(true).Returns(false);
            reader.SetupSequence(x => x.GetValue(0)).Returns(1).Returns(3);
            reader.SetupSequence(x => x.GetValue(1)).Returns(2).Returns(4);

            TableData tableData = new DataReaderPopulatedTableData(reader.Object);

            Assert.AreEqual(2, tableData.ColumnNames.Count);
            Assert.AreEqual("a", tableData.ColumnNames[0]);
            Assert.AreEqual("b", tableData.ColumnNames[1]);
            Assert.AreEqual(2, tableData.Rows.Count);
            Assert.AreEqual(1, tableData.Rows[0][0]);
            Assert.AreEqual(2, tableData.Rows[0][1]);
            Assert.AreEqual(3, tableData.Rows[1][0]);
            Assert.AreEqual(4, tableData.Rows[1][1]);
        }
        public void WhenInputPassedThenCountWithoutCaseSensitivity()
        {
            var mockedTextReader = new Mock<TextReader>();
            mockedTextReader.SetupSequence(p => p.ReadLine())
                .Returns("test")
                .Returns("Test");

            ISentenceProcessor sentenceProvider = new SentenceProcessor(_standardDelimiters);
            var result = sentenceProvider.Process(mockedTextReader.Object);

            Assert.That(result["test"], Is.EqualTo(2));            
        }
示例#31
0
        public void CreatePathAlternating()
        {
            string[] inGrid =
            {
                "0.0.0.0",
                ". . . .",
                "0.0.0.0",
                ". . . .",
                "0.0.0.0",
            };

            string[] outGrid =
            {
                "A#C.C#B",
                "# . . .",
                "D#F.F#E",
                ". . . #",
                "G#I.I#H",
            };

            Mock <IRandom> testRand = new Mock <IRandom>(MockBehavior.Strict);

            Moq.Language.ISetupSequentialResult <int> seq = testRand.SetupSequence(p => p.Next(2));
            seq = seq.Returns(0);
            seq = seq.Returns(1);

            var pathGen = new Mock <GridPathTwoSides <IGridPathTestContext> > {
                CallBase = true
            };

            pathGen.Object.GapAxis = Axis4.Horiz;

            Moq.Language.ISetupSequentialResult <RoomGen <IGridPathTestContext> > defaultSeq = pathGen.SetupSequence(p => p.GetDefaultGen());
            defaultSeq = defaultSeq.Returns(new TestGridRoomGen('C'));
            defaultSeq = defaultSeq.Returns(new TestGridRoomGen('F'));
            defaultSeq = defaultSeq.Returns(new TestGridRoomGen('I'));

            Mock <IRandPicker <PermissiveRoomGen <IGridPathTestContext> > > mockHalls = new Mock <IRandPicker <PermissiveRoomGen <IGridPathTestContext> > >(MockBehavior.Strict);

            mockHalls.Setup(p => p.Pick(testRand.Object)).Returns(new TestGridRoomGen());
            pathGen.Object.GenericHalls = mockHalls.Object;
            Mock <IRandPicker <RoomGen <IGridPathTestContext> > > mockRooms = new Mock <IRandPicker <RoomGen <IGridPathTestContext> > >(MockBehavior.Strict);

            Moq.Language.ISetupSequentialResult <RoomGen <IGridPathTestContext> > roomSeq = mockRooms.SetupSequence(p => p.Pick(testRand.Object));
            roomSeq = roomSeq.Returns(new TestGridRoomGen('A'));
            roomSeq = roomSeq.Returns(new TestGridRoomGen('B'));
            roomSeq = roomSeq.Returns(new TestGridRoomGen('D'));
            roomSeq = roomSeq.Returns(new TestGridRoomGen('E'));
            roomSeq = roomSeq.Returns(new TestGridRoomGen('G'));
            roomSeq = roomSeq.Returns(new TestGridRoomGen('H'));
            pathGen.Object.GenericRooms = mockRooms.Object;

            TestGridFloorPlan floorPlan        = TestGridFloorPlan.InitGridToContext(inGrid);
            TestGridFloorPlan compareFloorPlan = TestGridFloorPlan.InitGridToContext(outGrid);

            pathGen.Object.ApplyToPath(testRand.Object, floorPlan);

            TestGridFloorPlan.CompareFloorPlans(floorPlan, compareFloorPlan);

            testRand.Verify(p => p.Next(2), Times.Exactly(2));
            mockHalls.Verify(p => p.Pick(testRand.Object), Times.Exactly(8));
            mockRooms.Verify(p => p.Pick(testRand.Object), Times.Exactly(6));
            pathGen.Verify(p => p.GetDefaultGen(), Times.Exactly(3));
        }
        public void GetApiKeysTest_TwoPages()
        {
            var request = InstantiateClassGenerator.Execute <GetApiKeysRequest>();

            var firstResponse  = InstantiateClassGenerator.Execute <GetApiKeysResponse>();
            var secondResponse = InstantiateClassGenerator.Execute <GetApiKeysResponse>();

            secondResponse.Position = null;

            _mockClient.SetupSequence(x => x.GetApiKeys(request)).Returns(firstResponse).Returns(secondResponse);
            var paginator = _mockClient.Object.Paginators.GetApiKeys(request);

            Assert.AreEqual(2, paginator.Responses.ToList().Count);
        }
示例#33
0
        public void UpdateAchievements()
        {
            long facebookUserId = _users.First().FacebookUserId;

            ICollection <UserAchievement> achievements =
                new[]
            {
                new UserAchievement
                {
                    FacebookUserId = facebookUserId,
                    AchievementId  = 1,
                    Achievement    = new Achievement
                    {
                        Id          = 1,
                        GameId      = 1,
                        Name        = "Achievement 1 for Game 1",
                        Description = ""
                    }
                },
                new UserAchievement
                {
                    FacebookUserId = facebookUserId,
                    AchievementId  = 2,
                    Achievement    = new Achievement
                    {
                        Id          = 2,
                        GameId      = 1,
                        Name        = "Achievement 2 for Game 1",
                        Description = ""
                    }
                },
                new UserAchievement
                {
                    FacebookUserId = facebookUserId,
                    AchievementId  = 3,
                    Achievement    = new Achievement
                    {
                        Id          = 3,
                        GameId      = 1,
                        Name        = "Achievement 3 for Game 1",
                        Description = ""
                    }
                },
                new UserAchievement
                {
                    FacebookUserId = facebookUserId,
                    AchievementId  = 4,
                    Achievement    = new Achievement
                    {
                        Id          = 4,
                        GameId      = 2,
                        Name        = "Achievement 1 for Game 2",
                        Description = ""
                    }
                },
                new UserAchievement
                {
                    FacebookUserId = facebookUserId,
                    AchievementId  = 5,
                    Achievement    = new Achievement
                    {
                        Id          = 5,
                        GameId      = 2,
                        Name        = "Achievement 2 for Game 2",
                        Description = ""
                    }
                },
                new UserAchievement
                {
                    FacebookUserId = facebookUserId,
                    AchievementId  = 6,
                    Achievement    = new Achievement
                    {
                        Id          = 6,
                        GameId      = 3,
                        Name        = "Achievement for Game",
                        Description = "Game 3 Achievement 1"
                    }
                },
                new UserAchievement
                {
                    FacebookUserId = facebookUserId,
                    AchievementId  = 7,
                    Achievement    = new Achievement
                    {
                        Id          = 7,
                        GameId      = 3,
                        Name        = "Achievement for Game",
                        Description = "Game 3 Achievement 2"
                    }
                },
                new UserAchievement
                {
                    FacebookUserId = facebookUserId,
                    AchievementId  = 8,
                    Achievement    = new Achievement
                    {
                        Id          = 8,
                        GameId      = 4,
                        Name        = "Achievement for Game",
                        Description = "Game 4 Achievement 1"
                    }
                }
            };

            _repositoryMock.SetupSequence(rep => rep.Achievements)
            .Returns(new Achievement[0].AsQueryable())
            .Returns(achievements.Select(a => a.Achievement).AsQueryable());
            _repositoryMock.SetupProperty(rep => rep.UserAchievements, new UserAchievement[0].AsQueryable());

            _manager.UpdateAchievements(achievements);

            _repositoryMock.VerifyGet(rep => rep.Achievements);
            _repositoryMock.VerifyGet(rep => rep.UserAchievements);
            _repositoryMock.Verify(rep => rep.InsertOnSubmit(It.IsAny <Achievement>()), Times.Exactly(achievements.Count));
            _repositoryMock.Verify(rep => rep.InsertAllOnSubmit(It.IsAny <IEnumerable <UserAchievement> >()));
            _repositoryMock.Verify(rep => rep.SubmitChanges(), Times.Exactly(2));
        }
示例#34
0
        private TransportClient GetMockTransportClientForGlobalStrongReads(AddressInformation[] addressInformation, ReadQuorumResultKind result)
        {
            // create objects for all the dependencies of the StoreReader
            Mock <TransportClient> mockTransportClient = new Mock <TransportClient>();

            // create mock store response object
            StoreResponse mockStoreResponse1 = new StoreResponse();
            StoreResponse mockStoreResponse2 = new StoreResponse();
            StoreResponse mockStoreResponse3 = new StoreResponse();
            StoreResponse mockStoreResponse4 = new StoreResponse();
            StoreResponse mockStoreResponse5 = new StoreResponse();

            // set lsn and activityid on the store response.
            mockStoreResponse1.Headers = new StoreRequestNameValueCollection
            {
                { WFConstants.BackendHeaders.LSN, "100" },
                { WFConstants.BackendHeaders.ActivityId, "ACTIVITYID1_1" },
                { WFConstants.BackendHeaders.GlobalCommittedLSN, "90" },
                { WFConstants.BackendHeaders.NumberOfReadRegions, "1" },
            };

            mockStoreResponse2.Headers = new StoreRequestNameValueCollection
            {
                { WFConstants.BackendHeaders.LSN, "90" },
                { WFConstants.BackendHeaders.ActivityId, "ACTIVITYID1_2" },
                { WFConstants.BackendHeaders.GlobalCommittedLSN, "90" },
                { WFConstants.BackendHeaders.NumberOfReadRegions, "1" },
            };

            mockStoreResponse3.Headers = new StoreRequestNameValueCollection
            {
                { WFConstants.BackendHeaders.LSN, "92" },
                { WFConstants.BackendHeaders.ActivityId, "ACTIVITYID1_3" },
                { WFConstants.BackendHeaders.GlobalCommittedLSN, "90" },
                { WFConstants.BackendHeaders.NumberOfReadRegions, "1" },
            };

            mockStoreResponse4.Headers = new StoreRequestNameValueCollection
            {
                { WFConstants.BackendHeaders.LSN, "100" },
                { WFConstants.BackendHeaders.ActivityId, "ACTIVITYID1_3" },
                { WFConstants.BackendHeaders.GlobalCommittedLSN, "92" },
                { WFConstants.BackendHeaders.NumberOfReadRegions, "1" },
            };

            mockStoreResponse5.Headers = new StoreRequestNameValueCollection
            {
                { WFConstants.BackendHeaders.LSN, "100" },
                { WFConstants.BackendHeaders.ActivityId, "ACTIVITYID1_3" },
                { WFConstants.BackendHeaders.GlobalCommittedLSN, "100" },
                { WFConstants.BackendHeaders.NumberOfReadRegions, "1" },
                { WFConstants.BackendHeaders.CurrentReplicaSetSize, "1" },
                { WFConstants.BackendHeaders.QuorumAckedLSN, "100" },
            };

            if (result == ReadQuorumResultKind.QuorumMet)
            {
                // setup mock transport client for the first replica
                mockTransportClient.Setup(
                    client => client.InvokeResourceOperationAsync(
                        new Uri(addressInformation[0].PhysicalUri), It.IsAny <DocumentServiceRequest>()))
                .ReturnsAsync(mockStoreResponse5);

                mockTransportClient.SetupSequence(
                    client => client.InvokeResourceOperationAsync(
                        new Uri(addressInformation[1].PhysicalUri), It.IsAny <DocumentServiceRequest>()))
                .Returns(Task.FromResult <StoreResponse>(mockStoreResponse1))
                .Returns(Task.FromResult <StoreResponse>(mockStoreResponse1))
                .Returns(Task.FromResult <StoreResponse>(mockStoreResponse1))
                .Returns(Task.FromResult <StoreResponse>(mockStoreResponse1))
                .Returns(Task.FromResult <StoreResponse>(mockStoreResponse1))
                .Returns(Task.FromResult <StoreResponse>(mockStoreResponse5));

                mockTransportClient.SetupSequence(
                    client => client.InvokeResourceOperationAsync(
                        new Uri(addressInformation[2].PhysicalUri), It.IsAny <DocumentServiceRequest>()))
                .Returns(Task.FromResult <StoreResponse>(mockStoreResponse2))
                .Returns(Task.FromResult <StoreResponse>(mockStoreResponse2))
                .Returns(Task.FromResult <StoreResponse>(mockStoreResponse2))
                .Returns(Task.FromResult <StoreResponse>(mockStoreResponse1))
                .Returns(Task.FromResult <StoreResponse>(mockStoreResponse4))
                .Returns(Task.FromResult <StoreResponse>(mockStoreResponse5));
            }
            if (result == ReadQuorumResultKind.QuorumSelected)
            {
                // setup mock transport client for the first replica
                mockTransportClient.Setup(
                    client => client.InvokeResourceOperationAsync(
                        new Uri(addressInformation[0].PhysicalUri), It.IsAny <DocumentServiceRequest>()))
                .ReturnsAsync(mockStoreResponse2);

                // setup mock transport client with a sequence of outputs
                mockTransportClient.Setup(
                    client => client.InvokeResourceOperationAsync(
                        new Uri(addressInformation[1].PhysicalUri), It.IsAny <DocumentServiceRequest>()))
                .ReturnsAsync(mockStoreResponse1);

                // setup mock transport client with a sequence of outputs
                mockTransportClient.Setup(
                    client => client.InvokeResourceOperationAsync(
                        new Uri(addressInformation[2].PhysicalUri), It.IsAny <DocumentServiceRequest>()))
                .ReturnsAsync(mockStoreResponse2);
            }
            else if (result == ReadQuorumResultKind.QuorumNotSelected)
            {
                // setup mock transport client for the first replica
                mockTransportClient.Setup(
                    client => client.InvokeResourceOperationAsync(
                        new Uri(addressInformation[0].PhysicalUri), It.IsAny <DocumentServiceRequest>()))
                .ReturnsAsync(mockStoreResponse5);

                mockTransportClient.Setup(
                    client => client.InvokeResourceOperationAsync(
                        new Uri(addressInformation[1].PhysicalUri), It.IsAny <DocumentServiceRequest>()))
                .ReturnsAsync(mockStoreResponse5);

                mockTransportClient.Setup(
                    client => client.InvokeResourceOperationAsync(
                        new Uri(addressInformation[2].PhysicalUri), It.IsAny <DocumentServiceRequest>()))
                .Throws(new GoneException("test"));
            }

            TransportClient mockTransportClientObject = mockTransportClient.Object;

            return(mockTransportClientObject);
        }
示例#35
0
        public async Task RefreshCacheTest()
        {
            // Arrange
            var store = new EntityStore <string, string>(new InMemoryDbStore(), "cache");
            var serviceAuthentication  = new ServiceAuthentication(ServiceAuthenticationType.None);
            Func <ServiceIdentity> si1 = () => new ServiceIdentity("d1", "1234", Enumerable.Empty <string>(), serviceAuthentication, ServiceIdentityStatus.Enabled);
            Func <ServiceIdentity> si2 = () => new ServiceIdentity("d2", "m1", "2345", Enumerable.Empty <string>(), serviceAuthentication, ServiceIdentityStatus.Enabled);
            Func <ServiceIdentity> si3 = () => new ServiceIdentity("d3", "5678", Enumerable.Empty <string>(), serviceAuthentication, ServiceIdentityStatus.Enabled);
            Func <ServiceIdentity> si4 = () => new ServiceIdentity("d2", "m4", "9898", Enumerable.Empty <string>(), serviceAuthentication, ServiceIdentityStatus.Enabled);

            var iterator1 = new Mock <IServiceIdentitiesIterator>();

            iterator1.SetupSequence(i => i.HasNext)
            .Returns(true)
            .Returns(true)
            .Returns(false);
            iterator1.SetupSequence(i => i.GetNext())
            .ReturnsAsync(
                new List <ServiceIdentity>
            {
                si1(),
                si2()
            })
            .ReturnsAsync(
                new List <ServiceIdentity>
            {
                si3(),
                si4()
            });

            var iterator2 = new Mock <IServiceIdentitiesIterator>();

            iterator2.SetupSequence(i => i.HasNext)
            .Returns(true)
            .Returns(false);
            iterator2.SetupSequence(i => i.GetNext())
            .ReturnsAsync(
                new List <ServiceIdentity>
            {
                si1(),
                si2(),
                si3()
            });

            var serviceProxy = new Mock <IServiceProxy>();

            serviceProxy.SetupSequence(s => s.GetServiceIdentitiesIterator())
            .Returns(iterator1.Object)
            .Returns(iterator2.Object);
            var updatedIdentities = new List <ServiceIdentity>();
            var removedIdentities = new List <string>();

            // Act
            IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache = await DeviceScopeIdentitiesCache.Create(serviceProxy.Object, store, TimeSpan.FromSeconds(8));

            deviceScopeIdentitiesCache.ServiceIdentityUpdated += (sender, identity) => updatedIdentities.Add(identity);
            deviceScopeIdentitiesCache.ServiceIdentityRemoved += (sender, s) => removedIdentities.Add(s);

            // Wait for refresh to complete
            await Task.Delay(TimeSpan.FromSeconds(3));

            Option <ServiceIdentity> receivedServiceIdentity1 = await deviceScopeIdentitiesCache.GetServiceIdentity("d1");

            Option <ServiceIdentity> receivedServiceIdentity2 = await deviceScopeIdentitiesCache.GetServiceIdentity("d2/m1");

            Option <ServiceIdentity> receivedServiceIdentity3 = await deviceScopeIdentitiesCache.GetServiceIdentity("d3");

            Option <ServiceIdentity> receivedServiceIdentity4 = await deviceScopeIdentitiesCache.GetServiceIdentity("d2/m4");

            // Assert
            Assert.True(si1().Equals(receivedServiceIdentity1.OrDefault()));
            Assert.True(si2().Equals(receivedServiceIdentity2.OrDefault()));
            Assert.True(si3().Equals(receivedServiceIdentity3.OrDefault()));
            Assert.True(si4().Equals(receivedServiceIdentity4.OrDefault()));

            Assert.Equal(0, updatedIdentities.Count);
            Assert.Equal(0, removedIdentities.Count);

            // Wait for another refresh cycle to complete
            await Task.Delay(TimeSpan.FromSeconds(8));

            receivedServiceIdentity1 = await deviceScopeIdentitiesCache.GetServiceIdentity("d1");

            receivedServiceIdentity2 = await deviceScopeIdentitiesCache.GetServiceIdentity("d2/m1");

            receivedServiceIdentity3 = await deviceScopeIdentitiesCache.GetServiceIdentity("d3");

            receivedServiceIdentity4 = await deviceScopeIdentitiesCache.GetServiceIdentity("d2/m4");

            // Assert
            Assert.True(si1().Equals(receivedServiceIdentity1.OrDefault()));
            Assert.True(si2().Equals(receivedServiceIdentity2.OrDefault()));
            Assert.True(si3().Equals(receivedServiceIdentity3.OrDefault()));
            Assert.False(receivedServiceIdentity4.HasValue);

            Assert.Equal(0, updatedIdentities.Count);
            Assert.Equal(1, removedIdentities.Count);
            Assert.True(removedIdentities.Contains("d2/m4"));
        }
示例#36
0
        public void WebSocketProcessFeed_ShouldReturnFeed()
        {
            //Arrange
            HttpClient      httpClient      = new HttpClient();
            ClientWebSocket clientWebSocket = new ClientWebSocket();
            List <Product>  products        = new List <Product> {
                new Product {
                    ID = "BTC-EUR"
                }
            };
            Mock <ConnectionAdapter> connectionFactoryMock = new Mock <ConnectionAdapter>(MockBehavior.Strict, httpClient);

            connectionFactoryMock.Object.Authentication = new Authentication("api_key", "passphrase",
                                                                             "NiWaGaqmhB3lgI/tQmm/gQ==", "https://api.pro.coinbase.com", "wss://ws-feed.gdax.com");
            connectionFactoryMock.Setup(x => x.WebSocketSendAsync(products.ToSubscribeString()))
            .ReturnsAsync(@"{""type"":""subscriptions"",""channels"":[{""name"":""ticker"",""product_ids"":[""BTC-EUR"",""ETH-EUR""]}]}");
            connectionFactoryMock
            .Setup(x => x.ConnectAsync(connectionFactoryMock.Object.Authentication.WebSocketUri.ToString()))
            .Returns(Task.CompletedTask);
            connectionFactoryMock.Setup(x => x.IsWebSocketConnected()).Returns(true);
            connectionFactoryMock.SetupSequence(f => f.WebSocketReceiveAsync())
            .Returns(Task.FromResult(@"{
                                            ""type"":""ticker"",
                                            ""sequence"":7000000000,
                                            ""product_id"":""BTC-EUR"",
                                            ""price"":""6693.2"",
                                            ""open_24h"":""6785.59000000"",
                                            ""volume_24h"":""1778.78223836"",
                                            ""low_24h"":""6566.00000000"",
                                            ""high_24h"":""6813.00000000"",
                                            ""volume_30d"":""152160.22176000"",
                                            ""best_bid"":""6693.20"",
                                            ""best_ask"":""6698.12"",
                                            ""side"":""sell"",
                                            ""time"":""2020-04-09T23:09:28.709968Z"",
                                            ""trade_id"":25684401,
                                            ""last_size"":""0.0027496""
                                            }"))  // will be returned on 1st invocation
            .Returns(Task.FromResult(@"{
                                            ""type"":""ticker"",
                                            ""sequence"":7000000001,
                                            ""product_id"":""BTC-EUR"",
                                            ""price"":""6700.34"",
                                            ""open_24h"":""6785.59000000"",
                                            ""volume_24h"":""1778.79785469"",
                                            ""low_24h"":""6566.00000000"",
                                            ""high_24h"":""6813.00000000"",
                                            ""volume_30d"":""152160.22176000"",
                                            ""best_bid"":""6695.20"",
                                            ""best_ask"":""6700.12"",
                                            ""side"":""buy"",
                                            ""time"":""2020-04-09T23:09:57.499045Z"",
                                            ""trade_id"":25684402,
                                            ""last_size"":""0.01428046""
                                            }"))  // will be returned on 2nd invocation
            .Returns(Task.FromResult(@"{
                                            ""type"":""ticker"",
                                            ""sequence"":7000000002,
                                            ""product_id"":""BTC-EUR"",
                                            ""price"":""6695.64"",
                                            ""open_24h"":""6785.59000000"",
                                            ""volume_24h"":""1778.79785469"",
                                            ""low_24h"":""6566.00000000"",
                                            ""high_24h"":""6813.00000000"",
                                            ""volume_30d"":""152160.22176000"",
                                            ""best_bid"":""6695.64"",
                                            ""best_ask"":""6699.80"",
                                            ""side"":""sell"",
                                            ""time"":""2020-04-09T23:10:01.022034Z"",
                                            ""trade_id"":25684403,
                                            ""last_size"":""0.00133587""
                                            }")); // will be returned on 3rd invocation

            Coinbase subjectUnderTest = new Coinbase {
                ConnectionAdapter = connectionFactoryMock.Object
            };
            bool           eventRaised      = false;
            int            eventRaisedCount = 0;
            AutoResetEvent autoEvent        = new AutoResetEvent(false);

            subjectUnderTest.ClientWebSocket      = clientWebSocket;
            subjectUnderTest.NotifyCurrentPrices += delegate(string applicationName, Dictionary <string, decimal> subscribedPrices) {
                eventRaised = true;
                TaskCompletionSource <bool> taskCompletionSource = new TaskCompletionSource <bool>();
                taskCompletionSource.SetResult(false);
                if (applicationName != "Coinbase Exchange")
                {
                    return(taskCompletionSource.Task);
                }
                eventRaisedCount++;
                if (eventRaisedCount < 3)
                {
                    return(taskCompletionSource.Task);
                }
                autoEvent.Set();
                taskCompletionSource.SetResult(true);
                return(taskCompletionSource.Task);
            };
            //Act
            subjectUnderTest.ChangeFeed(products);
            autoEvent.WaitOne();
            Assert.IsTrue(eventRaised);
        }
示例#37
0
        public async Task GetServiceIdentityTest_Module()
        {
            // Arrange
            var store = new EntityStore <string, string>(new InMemoryDbStore(), "cache");
            var serviceAuthenticationNone = new ServiceAuthentication(ServiceAuthenticationType.None);
            var serviceAuthenticationSas  = new ServiceAuthentication(new SymmetricKeyAuthentication(GetKey(), GetKey()));

            var si1_initial = new ServiceIdentity("d1", "m1", "1234", Enumerable.Empty <string>(), serviceAuthenticationNone, ServiceIdentityStatus.Enabled);
            var si1_updated = new ServiceIdentity("d1", "m1", "1234", Enumerable.Empty <string>(), serviceAuthenticationSas, ServiceIdentityStatus.Disabled);
            var si2         = new ServiceIdentity("d2", "m2", "5678", Enumerable.Empty <string>(), serviceAuthenticationSas, ServiceIdentityStatus.Enabled);
            var si3         = new ServiceIdentity("d3", "m3", "0987", Enumerable.Empty <string>(), serviceAuthenticationSas, ServiceIdentityStatus.Enabled);

            var iterator1 = new Mock <IServiceIdentitiesIterator>();

            iterator1.SetupSequence(i => i.HasNext)
            .Returns(true)
            .Returns(false);
            iterator1.SetupSequence(i => i.GetNext())
            .ReturnsAsync(
                new List <ServiceIdentity>
            {
                si1_initial,
                si2
            });

            var serviceProxy = new Mock <IServiceProxy>();

            serviceProxy.Setup(s => s.GetServiceIdentitiesIterator())
            .Returns(iterator1.Object);
            serviceProxy.Setup(s => s.GetServiceIdentity("d1", "m1")).ReturnsAsync(Option.Some(si1_updated));
            serviceProxy.Setup(s => s.GetServiceIdentity("d2", "m2")).ReturnsAsync(Option.None <ServiceIdentity>());
            serviceProxy.Setup(s => s.GetServiceIdentity("d3", "m3")).ReturnsAsync(Option.Some(si3));

            var updatedIdentities = new List <ServiceIdentity>();
            var removedIdentities = new List <string>();

            // Act
            IDeviceScopeIdentitiesCache deviceScopeIdentitiesCache = await DeviceScopeIdentitiesCache.Create(serviceProxy.Object, store, TimeSpan.FromHours(1));

            deviceScopeIdentitiesCache.ServiceIdentityUpdated += (sender, identity) => updatedIdentities.Add(identity);
            deviceScopeIdentitiesCache.ServiceIdentityRemoved += (sender, s) => removedIdentities.Add(s);

            // Wait for refresh to complete
            await Task.Delay(TimeSpan.FromSeconds(3));

            Option <ServiceIdentity> receivedServiceIdentity1 = await deviceScopeIdentitiesCache.GetServiceIdentity("d1/m1");

            Option <ServiceIdentity> receivedServiceIdentity2 = await deviceScopeIdentitiesCache.GetServiceIdentity("d2/m2");

            Option <ServiceIdentity> receivedServiceIdentity3 = await deviceScopeIdentitiesCache.GetServiceIdentity("d3/m3");

            // Assert
            Assert.True(si1_initial.Equals(receivedServiceIdentity1.OrDefault()));
            Assert.True(si2.Equals(receivedServiceIdentity2.OrDefault()));
            Assert.False(receivedServiceIdentity3.HasValue);

            // Get the identities with refresh
            receivedServiceIdentity1 = await deviceScopeIdentitiesCache.GetServiceIdentity("d1/m1", true);

            receivedServiceIdentity2 = await deviceScopeIdentitiesCache.GetServiceIdentity("d2/m2", true);

            receivedServiceIdentity3 = await deviceScopeIdentitiesCache.GetServiceIdentity("d3/m3", true);

            // Assert
            Assert.True(si1_initial.Equals(receivedServiceIdentity1.OrDefault()));
            Assert.True(si2.Equals(receivedServiceIdentity2.OrDefault()));
            Assert.True(si3.Equals(receivedServiceIdentity3.OrDefault()));
            Assert.Equal(0, removedIdentities.Count);
            Assert.Equal(0, updatedIdentities.Count);
        }
示例#38
0
        private TransportClient GetMockTransportClientForGlobalStrongWrites(
            AddressInformation[] addressInformation,
            int indexOfCaughtUpReplica,
            bool undershootGlobalCommittedLsnDuringBarrier,
            bool overshootLsnDuringBarrier,
            bool overshootGlobalCommittedLsnDuringBarrier)
        {
            Mock <TransportClient> mockTransportClient = new Mock <TransportClient>();

            // create mock store response object
            StoreResponse mockStoreResponse1 = new StoreResponse();
            StoreResponse mockStoreResponse2 = new StoreResponse();
            StoreResponse mockStoreResponse3 = new StoreResponse();
            StoreResponse mockStoreResponse4 = new StoreResponse();
            StoreResponse mockStoreResponse5 = new StoreResponse();


            // set lsn and activityid on the store response.
            mockStoreResponse1.Headers = new StoreRequestNameValueCollection
            {
                { WFConstants.BackendHeaders.LSN, "100" },
                { WFConstants.BackendHeaders.ActivityId, "ACTIVITYID1_1" },
                { WFConstants.BackendHeaders.GlobalCommittedLSN, "90" },
                { WFConstants.BackendHeaders.NumberOfReadRegions, "1" },
            };

            mockStoreResponse2.Headers = new StoreRequestNameValueCollection
            {
                { WFConstants.BackendHeaders.LSN, "100" },
                { WFConstants.BackendHeaders.ActivityId, "ACTIVITYID1_2" },
                { WFConstants.BackendHeaders.GlobalCommittedLSN, "100" },
                { WFConstants.BackendHeaders.NumberOfReadRegions, "1" },
            };

            mockStoreResponse3.Headers = new StoreRequestNameValueCollection
            {
                { WFConstants.BackendHeaders.LSN, "103" },
                { WFConstants.BackendHeaders.ActivityId, "ACTIVITYID1_3" },
                { WFConstants.BackendHeaders.GlobalCommittedLSN, "100" },
                { WFConstants.BackendHeaders.NumberOfReadRegions, "1" },
            };

            mockStoreResponse4.Headers = new StoreRequestNameValueCollection
            {
                { WFConstants.BackendHeaders.LSN, "103" },
                { WFConstants.BackendHeaders.ActivityId, "ACTIVITYID1_3" },
                { WFConstants.BackendHeaders.GlobalCommittedLSN, "103" },
                { WFConstants.BackendHeaders.NumberOfReadRegions, "1" },
            };

            mockStoreResponse5.Headers = new StoreRequestNameValueCollection
            {
                { WFConstants.BackendHeaders.LSN, "106" },
                { WFConstants.BackendHeaders.ActivityId, "ACTIVITYID1_3" },
                { WFConstants.BackendHeaders.GlobalCommittedLSN, "103" },
                { WFConstants.BackendHeaders.NumberOfReadRegions, "1" },
            };
            StoreResponse finalResponse = null;

            if (undershootGlobalCommittedLsnDuringBarrier)
            {
                finalResponse = mockStoreResponse1;
            }
            else
            {
                if (overshootLsnDuringBarrier)
                {
                    if (overshootGlobalCommittedLsnDuringBarrier)
                    {
                        finalResponse = mockStoreResponse5;
                    }
                    else
                    {
                        finalResponse = mockStoreResponse3;
                    }
                }
                else
                {
                    if (overshootGlobalCommittedLsnDuringBarrier)
                    {
                        finalResponse = mockStoreResponse4;
                    }
                    else
                    {
                        finalResponse = mockStoreResponse2;
                    }
                }
            }

            for (int i = 0; i < addressInformation.Length; i++)
            {
                if (i == indexOfCaughtUpReplica)
                {
                    mockTransportClient.SetupSequence(
                        client => client.InvokeResourceOperationAsync(new Uri(addressInformation[i].PhysicalUri), It.IsAny <DocumentServiceRequest>()))
                    .Returns(Task.FromResult <StoreResponse>(finalResponse));
                }
                else
                {
                    mockTransportClient.Setup(
                        client => client.InvokeResourceOperationAsync(new Uri(addressInformation[i].PhysicalUri), It.IsAny <DocumentServiceRequest>()))
                    .Returns(Task.FromResult <StoreResponse>(mockStoreResponse1));
                }
            }

            return(mockTransportClient.Object);
        }
示例#39
0
        public void CreatePathMinSize()
        {
            string[] inGrid =
            {
                "0.0",
            };

            string[] outGrid =
            {
                "A#B",
            };

            Mock <IRandom> testRand = new Mock <IRandom>(MockBehavior.Strict);

            var pathGen = new GridPathTwoSides <IGridPathTestContext> {
                GapAxis = Axis4.Horiz
            };

            Mock <IRandPicker <PermissiveRoomGen <IGridPathTestContext> > > mockHalls = new Mock <IRandPicker <PermissiveRoomGen <IGridPathTestContext> > >(MockBehavior.Strict);

            mockHalls.Setup(p => p.Pick(testRand.Object)).Returns(new TestGridRoomGen());
            pathGen.GenericHalls = mockHalls.Object;
            Mock <IRandPicker <RoomGen <IGridPathTestContext> > > mockRooms = new Mock <IRandPicker <RoomGen <IGridPathTestContext> > >(MockBehavior.Strict);

            Moq.Language.ISetupSequentialResult <RoomGen <IGridPathTestContext> > roomSeq = mockRooms.SetupSequence(p => p.Pick(testRand.Object));
            roomSeq = roomSeq.Returns(new TestGridRoomGen('A'));
            roomSeq = roomSeq.Returns(new TestGridRoomGen('B'));
            pathGen.GenericRooms = mockRooms.Object;

            TestGridFloorPlan floorPlan        = TestGridFloorPlan.InitGridToContext(inGrid);
            TestGridFloorPlan compareFloorPlan = TestGridFloorPlan.InitGridToContext(outGrid);

            pathGen.ApplyToPath(testRand.Object, floorPlan);

            TestGridFloorPlan.CompareFloorPlans(floorPlan, compareFloorPlan);

            mockHalls.Verify(p => p.Pick(testRand.Object), Times.Exactly(1));
            mockRooms.Verify(p => p.Pick(testRand.Object), Times.Exactly(2));
        }
        public async Task NextReadHasUpdatedContinuation()
        {
            int      itemCount = 5;
            string   pkRangeId = "0";
            string   etag      = Guid.NewGuid().ToString();
            DateTime startTime = DateTime.UtcNow;
            DocumentServiceLeaseCore documentServiceLeaseCore = new DocumentServiceLeaseCore()
            {
                LeaseToken = pkRangeId
            };

            ResponseMessage firstResponse = new ResponseMessage(System.Net.HttpStatusCode.OK);

            firstResponse.Headers.ETag = etag;
            ResponseMessage secondResponse = new ResponseMessage(System.Net.HttpStatusCode.OK);

            int responseCount = 0;
            Func <Action <RequestMessage>, bool> validateEnricher = (Action <RequestMessage> enricher) =>
            {
                RequestMessage requestMessage = new RequestMessage();
                enricher(requestMessage);
                return(responseCount++ == 0 || requestMessage.Headers.IfNoneMatch == etag);
            };

            Mock <ContainerInternal>   containerMock = new Mock <ContainerInternal>();
            Mock <CosmosClientContext> mockContext   = new Mock <CosmosClientContext>();

            mockContext.Setup(x => x.OperationHelperAsync <ResponseMessage>(
                                  It.Is <string>(str => str.Contains("Change Feed Processor")),
                                  It.IsAny <RequestOptions>(),
                                  It.IsAny <Func <ITrace, Task <ResponseMessage> > >(),
                                  It.IsAny <Func <ResponseMessage, OpenTelemetryAttributes> >(),
                                  It.Is <TraceComponent>(tc => tc == TraceComponent.ChangeFeed),
                                  It.IsAny <TraceLevel>()))
            .Returns <string, RequestOptions, Func <ITrace, Task <ResponseMessage> >, Func <ResponseMessage, OpenTelemetryAttributes>, TraceComponent, TraceLevel>(
                (operationName, requestOptions, func, oTelFunc, comp, level) =>
            {
                using (ITrace trace = Trace.GetRootTrace(operationName, comp, level))
                {
                    return(func(trace));
                }
            });

            mockContext.SetupSequence(c => c.ProcessResourceOperationStreamAsync(
                                          It.IsAny <string>(),
                                          It.Is <Documents.ResourceType>(rt => rt == Documents.ResourceType.Document),
                                          It.Is <Documents.OperationType>(rt => rt == Documents.OperationType.ReadFeed),
                                          It.Is <ChangeFeedRequestOptions>(cfo => cfo.PageSizeHint == itemCount),
                                          It.Is <ContainerInternal>(o => o == containerMock.Object),
                                          It.IsAny <FeedRange>(),
                                          It.IsAny <Stream>(),
                                          It.Is <Action <RequestMessage> >(enricher => validateEnricher(enricher)),
                                          It.Is <ITrace>(t => !(t is NoOpTrace)),
                                          It.IsAny <CancellationToken>()
                                          )
                                      )
            .ReturnsAsync(firstResponse)
            .ReturnsAsync(secondResponse);
            containerMock.Setup(c => c.ClientContext).Returns(mockContext.Object);
            containerMock.Setup(c => c.LinkUri).Returns("http://localhot");

            ChangeFeedPartitionKeyResultSetIteratorCore iterator = ChangeFeedPartitionKeyResultSetIteratorCore.Create(
                lease: documentServiceLeaseCore,
                continuationToken: null,
                maxItemCount: itemCount,
                container: containerMock.Object,
                startTime: startTime,
                startFromBeginning: false);

            await iterator.ReadNextAsync();

            await iterator.ReadNextAsync();

            Assert.AreEqual(2, responseCount);
        }
        public void DescribeCacheClustersTest_TwoPages()
        {
            var request = InstantiateClassGenerator.Execute <DescribeCacheClustersRequest>();

            var firstResponse  = InstantiateClassGenerator.Execute <DescribeCacheClustersResponse>();
            var secondResponse = InstantiateClassGenerator.Execute <DescribeCacheClustersResponse>();

            secondResponse.Marker = null;

            _mockClient.SetupSequence(x => x.DescribeCacheClusters(request)).Returns(firstResponse).Returns(secondResponse);
            var paginator = _mockClient.Object.Paginators.DescribeCacheClusters(request);

            Assert.AreEqual(2, paginator.Responses.ToList().Count);
        }
示例#42
0
        public void ListBatchInferenceJobsTest_TwoPages()
        {
            var request = InstantiateClassGenerator.Execute <ListBatchInferenceJobsRequest>();

            var firstResponse  = InstantiateClassGenerator.Execute <ListBatchInferenceJobsResponse>();
            var secondResponse = InstantiateClassGenerator.Execute <ListBatchInferenceJobsResponse>();

            secondResponse.NextToken = null;

            _mockClient.SetupSequence(x => x.ListBatchInferenceJobs(request)).Returns(firstResponse).Returns(secondResponse);
            var paginator = _mockClient.Object.Paginators.ListBatchInferenceJobs(request);

            Assert.AreEqual(2, paginator.Responses.ToList().Count);
        }
示例#43
0
        public void Initialize()
        {
            var pilotServiceMock = new Mock <IPilotService>();

            pilotServiceMock.Setup(x => x.GetById(It.Is <int>(i => i != 1 && i != 99)))
            .ReturnsAsync((int id) => new PilotDto
            {
                BirthDate  = new DateTime(2001, 12, 12),
                Experience = 5,
                FirstName  = "Pilot",
                SecondName = "Tester",
                Id         = id
            });

            pilotServiceMock.Setup(x => x.GetById(99)).ReturnsAsync(() => null);

            pilotServiceMock.SetupSequence(x => x.GetById(1))
            .Returns(() => Task.Run(() => new PilotDto
            {
                BirthDate  = new DateTime(2001, 12, 12),
                Experience = 5,
                FirstName  = "Pilot",
                SecondName = "Tester",
                Id         = 5
            }))
            .Returns(() => Task.Run(() => new PilotDto
            {
                BirthDate  = new DateTime(2018, 12, 12),
                Experience = 1,
                FirstName  = "PilotUpdated",
                SecondName = "TesterUpdated",
                Id         = 5
            }));

            pilotServiceMock.Setup(x => x.Insert(It.IsAny <EditablePilotFields>()))
            .ReturnsAsync(() => 1);

            pilotServiceMock.Setup(x => x.Update(1, It.IsAny <EditablePilotFields>())).ReturnsAsync(
                (int id, EditablePilotFields pilotEditableFields) => { return(true); });

            _pilotsController =
                new PilotsController(pilotServiceMock.Object)
            {
                ControllerContext = { HttpContext = new DefaultHttpContext() }
            };

            var mockUrlHelper = new Mock <IUrlHelper>();

            mockUrlHelper
            .Setup(
                x => x.Action(
                    It.IsAny <UrlActionContext>()
                    )
                )
            .Returns("callbackUrl")
            .Verifiable();
            mockUrlHelper.Setup(x => x.Link(It.IsAny <string>(), It.IsAny <object>())).Returns((string url, object obj) =>
            {
                return(url);
            });

            _pilotsController.Url = mockUrlHelper.Object;
        }
示例#44
0
        private TransportClient GetMockTransportClientDuringUpgrade(AddressInformation[] addressInformation)
        {
            // create objects for all the dependencies of the StoreReader
            Mock <TransportClient> mockTransportClient = new Mock <TransportClient>();

            // create mock store response object
            StoreResponse mockStoreResponseFast = new StoreResponse();
            StoreResponse mockStoreResponseSlow = new StoreResponse();

            // set lsn and activityid on the store response.
            mockStoreResponseFast.Headers = new StoreRequestNameValueCollection
            {
                { WFConstants.BackendHeaders.LSN, "50" },
                { WFConstants.BackendHeaders.ActivityId, "ACTIVITYID1_1" }
            };

            // set lsn and activityid on the store response.
            mockStoreResponseSlow.Headers = new StoreRequestNameValueCollection
            {
                { WFConstants.BackendHeaders.LSN, "30" },
                { WFConstants.BackendHeaders.ActivityId, "ACTIVITYID1_1" }
            };

            // setup mock transport client for the first replica
            mockTransportClient.Setup(
                client => client.InvokeResourceOperationAsync(
                    new Uri(addressInformation[0].PhysicalUri), It.IsAny <DocumentServiceRequest>()))
            .ReturnsAsync(mockStoreResponseFast);

            // setup mock transport client with a sequence of outputs
            mockTransportClient.SetupSequence(
                client => client.InvokeResourceOperationAsync(
                    new Uri(addressInformation[1].PhysicalUri), It.IsAny <DocumentServiceRequest>()))
            .Returns(Task.FromResult <StoreResponse>(mockStoreResponseFast))          // initial read response
            .Returns(Task.FromResult <StoreResponse>(mockStoreResponseFast))          // barrier retry, count 1
            .Returns(Task.FromResult <StoreResponse>(mockStoreResponseFast))          // barrier retry, count 2
            .Throws(new InvalidPartitionException())                                  // throw invalid partition exception to simulate collection recreate with same name
            .Returns(Task.FromResult <StoreResponse>(mockStoreResponseFast))          // new read
            .Returns(Task.FromResult <StoreResponse>(mockStoreResponseFast))          // subsequent barriers
            .Returns(Task.FromResult <StoreResponse>(mockStoreResponseFast))
            .Returns(Task.FromResult <StoreResponse>(mockStoreResponseFast))
            .Returns(Task.FromResult <StoreResponse>(mockStoreResponseFast))
            .Returns(Task.FromResult <StoreResponse>(mockStoreResponseFast))
            .Returns(Task.FromResult <StoreResponse>(mockStoreResponseFast));

            // After this, the product code should reset target identity, and lsn response

            Queue <StoreResponse> queueOfResponses = new Queue <StoreResponse>();

            // let the first 10 responses be slow, and then fast
            for (int i = 0; i < 20; i++)
            {
                queueOfResponses.Enqueue(i <= 2 ? mockStoreResponseSlow : mockStoreResponseFast);
            }

            // setup mock transport client with a sequence of outputs, for the second replica
            // This replica behaves in the following manner:
            // calling InvokeResourceOperationAsync
            // 1st time: returns valid LSN
            // 2nd time: returns InvalidPartitionException
            mockTransportClient.Setup(
                client => client.InvokeResourceOperationAsync(
                    new Uri(addressInformation[2].PhysicalUri), It.IsAny <DocumentServiceRequest>()))
            .ReturnsAsync(queueOfResponses.Dequeue());

            TransportClient mockTransportClientObject = mockTransportClient.Object;

            return(mockTransportClientObject);
        }
        public void GetNumberOfBonusLanguagesEqualToIntelligenceModifier()
        {
            var attributes = new[] { "Speech" };

            mockPercentileSelector.Setup(s => s.SelectFrom(TableNameConstants.Percentiles.Set.IntelligenceStrongStats)).Returns("14");
            mockCollectionsSelector.Setup(s => s.SelectFrom(TableNameConstants.Collections.Set.IntelligenceCommunication, "14")).Returns(attributes);
            mockPercentileSelector.SetupSequence(s => s.SelectFrom(TableNameConstants.Percentiles.Set.Languages)).Returns("english").Returns("german");

            var intelligence = intelligenceGenerator.GenerateFor(item);

            Assert.That(intelligence.Languages, Has.Count.EqualTo(3)
                        .And.Contains("Common")
                        .And.Contains("english")
                        .And.Contains("german"));
        }