public void Install_should_install_if_a_package_has_not_been_installed_yet()
        {
            // Arrange
            var fixture = new Fixture().Customize(new AutoMoqCustomization());

            var proj = fixture.Freeze<Project>();
            var pwPkg = new ProjectWidePackage("Prig", "2.0.0", proj);
            var mocks = new MockRepository(MockBehavior.Strict);
            {
                var m = mocks.Create<IVsPackageInstallerServices>();
                m.Setup(_ => _.IsPackageInstalledEx(proj, "Prig", "2.0.0")).Returns(false);
                m.Setup(_ => _.IsPackageInstalled(proj, "Prig")).Returns(false);
                fixture.Inject(m);
            }
            {
                var m = mocks.Create<IVsPackageUninstaller>();
                fixture.Inject(m);
            }
            {
                var m = mocks.Create<IVsPackageInstaller>();
                m.Setup(_ => _.InstallPackage(default(string), proj, "Prig", "2.0.0", false));
                fixture.Inject(m);
            }

            var pwInstllr = fixture.NewProjectWideInstaller();


            // Act
            pwInstllr.Install(pwPkg);


            // Assert
            mocks.VerifyAll();
        }
        public void MessageShouldBeSameAfterSerializationAndDeserialization()
        {
            var writer = new BinaryWriter(new MemoryStream());
            IMessageFactory msgFactory = new MessageFactory(new Message[]
                {
                    new ISomeServiceComplexRequest()
                });

            var fixture = new Fixture();
            fixture.Customize<ISomeServiceComplexRequest>(ob =>
                ob.With(x => x.datas,
                    fixture.CreateMany<SubData>().ToList()));
            fixture.Customize<ComplexData>(ob => ob
                .With(x => x.SomeArrString, fixture.CreateMany<string>().ToList())
                .With(x => x.SomeArrRec, fixture.CreateMany<SubData>().ToList()));

            var msg = fixture.CreateAnonymous<ISomeServiceComplexRequest>();

            //serialize and deserialize msg1
            msg.Serialize(writer);
            writer.Seek(0, SeekOrigin.Begin);
            var reader = new BinaryReader(writer.BaseStream);
            Message retMsg = msgFactory.Deserialize(reader);

            retMsg.Should().BeOfType<ISomeServiceComplexRequest>();
            msg.ShouldBeEqualTo((ISomeServiceComplexRequest)retMsg);
        }
        public async Task Save_should_update_an_existing_product()
        {
            using (var store = NewDocumentStore())
            {
                using (var session = store.OpenAsyncSession())
                {
                    // Arrange
                    var fixture = new Fixture();
                    var product = fixture.Build<Product>()
                        .With(c => c.Id, "Products-1")
                        .With(c => c.Name, "Mediums")
                        .Create();
                    await SaveEntity(product, session);

                    // Act
                    var dto = new ProductDto {Id = "Products-1", Name = "Updated name"};
                    var service = GetProductsService(session);
                    var model = await service.Save(dto);
                    model.Message.Should().Be("Atualizou tipo Updated name");
                }

                using (var session = store.OpenAsyncSession())
                {
                    var actual = await session.LoadAsync<Product>("Products-1");
                    actual.Name.Should().Be("Updated name");
                }
            }
        }
        public void HasImage_Should_Add_ImageNameAttribute()
        {
            var imageName = new Fixture().Create<string>();
            _Builder.HasImage(imageName);

            A.CallTo(() => _TypeInfo.AddAttribute(A<ImageNameAttribute>.That.Matches(t => t.ImageName == imageName))).MustHaveHappened();
        }
        public void TestEvaluateCancel()
        {
            // Arrange
              var aFixture = new Fixture();

              var expressionContent = aFixture.Create<string>();
              var expression = new Expression("not", expressionContent);

              var evaluator = new Mock<IExpressionEvaluator>();
              var registry = Mock.Of<IEvaluatorSelector>(x => x.GetEvaluator(It.IsAny<Expression>()) == evaluator.Object);
              evaluator
            .Setup(x => x.Evaluate(It.Is<Expression>(e => e.ToString() == expressionContent),
                               It.IsAny<RenderingContext>(),
                               It.IsAny<TalesModel>()))
            .Returns(new ExpressionResult(ZptConstants.CancellationToken));

              var model = new TalesModel(registry);

              var sut = new NotExpressionEvaluator();

              // Act
              var result = sut.Evaluate(expression, Mock.Of<RenderingContext>(), model);

              // Assert
              Assert.NotNull(result, "Result nullability");
              Assert.AreEqual(true, result.Value, "Correct result");
        }
Example #6
0
            public void Execute(Fixture fixture, Action next)
            {
                foreach (var injectionMethod in fixtures.Keys)
                    injectionMethod.Invoke(fixture.Instance, new[] { fixtures[injectionMethod] });

                next();
            }
Example #7
0
        public bool Read(XmlReader reader)
        {
            if(reader.IsStartElement() && reader.Name == "Fixture") {
                Fixture fixture = new Fixture();

                //...Any attributes go here...
                fixture.AllowFrameSkip = bool.Parse(reader.GetAttribute("allowFrameSkip"));
                fixture.Name = reader.GetAttribute("name");
                // This needs to hold off until after channels are loaded.
                string fixtureDefinitionName = reader.GetAttribute("fixtureDefinitionName");

                if(reader.ElementsExistWithin("Fixture")) { // Entity element
                    // Channels
                    if(reader.ElementsExistWithin("Channels")) { // Container element for child entity
                        ChannelReader<OutputChannel> channelReader = new ChannelReader<OutputChannel>();
                        while(channelReader.Read(reader)) {
                            fixture.InsertChannel(channelReader.Channel);
                        }
                        reader.ReadEndElement(); // Channels
                    }

                    // With channels loaded, the fixture template reference can be set.
                    fixture.FixtureDefinitionName = fixtureDefinitionName;

                    reader.ReadEndElement(); // Fixture

                    this.Fixture = fixture;
                }
                return true;
            }
            return false;
        }
Example #8
0
        public void StartPacking_should_create_nupkg()
        {
            // Arrange
            var fixture = new Fixture().Customize(new AutoMoqCustomization());
            {
                var m = new Mock<IEnvironmentRepository>(MockBehavior.Strict);
                m.Setup(_ => _.GetNuGetPath()).Returns(AppDomain.CurrentDomain.GetPathInBaseDirectory(@"tools\NuGet.exe"));
                fixture.Inject(m);
            }

            var nugetExecutor = fixture.NewNuGetExecutor();


            // Act
            var result = nugetExecutor.StartPacking(AppDomain.CurrentDomain.GetPathInBaseDirectory(@"tools\NuGet\Prig.nuspec"), AppDomain.CurrentDomain.BaseDirectory);


            // Assert
            var lines = result.Split(new[] { "\r\n" }, StringSplitOptions.None);
            Assert.LessOrEqual(2, lines.Length);
            var match = Regex.Match(lines[1], "'([^']+)'");
            Assert.IsTrue(match.Success);
            var nupkgPath = match.Groups[1].Value;
            Assert.IsTrue(File.Exists(nupkgPath));
            Assert.GreaterOrEqual(TimeSpan.FromSeconds(1), DateTime.Now - File.GetLastWriteTime(nupkgPath));
        }
				public static TestData Create(int projectCount=5)
				{
					var fixture = new Fixture();
					var returnValue = new TestData
					{
						Fixture = fixture,
						UserName = fixture.Create<string>("UserName"),
						ProjectList = fixture.CreateMany<DeployProject>(projectCount).ToList(),
						ProjectRoleManager = new Mock<IProjectRoleManager>(),
                        SystemRoleManager = new Mock<ISystemRoleManager>(),
						UserIdentity = new Mock<IUserIdentity>()
					};
					returnValue.DeployProjectRoleList = 
						(from i in returnValue.ProjectList
						 select new DeployProjectRole
							{
								ProjectId = i.Id,
								RoleName = fixture.Create<string>("RoleName")
							}
						).ToList();
                    returnValue.ProjectRoleManager.Setup(i => i.GetProjectRoleListForUser(It.IsAny<string>())).Returns(new List<DeployProjectRole>());
                    returnValue.ProjectRoleManager.Setup(i => i.GetProjectRoleListForUser(returnValue.UserName)).Returns(returnValue.DeployProjectRoleList);

                    returnValue.SystemRoleManager.Setup(i=>i.GetSystemRoleListForUser(It.IsAny<string>())).Returns(new List<SystemRole>());

					returnValue.UserIdentity.Setup(i=>i.UserName).Returns(returnValue.UserName);

					returnValue.Sut = new PermissionValidator(returnValue.ProjectRoleManager.Object, returnValue.SystemRoleManager.Object, returnValue.UserIdentity.Object);

					return returnValue;
				}
        public Cell CompileCell(CellHandling cellHandling, Fixture fixture)
        {
            _cell = Cell.For(cellHandling, _property, fixture);
            _cell.output = true;

            return _cell;
        }
 public void Initialize()
 {
     fixture = new Fixture();
     fixture.Customize<usr_CUSTOMERS>(
         customer =>
         customer.With(x => x.password, Tests.SAMPLE_PASSWORD).With(x => x.email, Tests.SAMPLE_EMAIL_ADDRESS));
 }
Example #12
0
        public FileSyncTests()
        {
            _client = new DropNetClient(TestVariables.ApiKey, TestVariables.ApiSecret);
            _client.UserLogin = new Models.UserLogin { Token = TestVariables.Token, Secret = TestVariables.Secret };

            _fixture = new Fixture();
        }
        public void WriteMappingFragment_should_write_store_entity_set_name()
        {
            var fixture = new Fixture();

            var entityType = new EntityType("E", "N", DataSpace.CSpace);
            var entitySet = new EntitySet("ES", "S", null, null, entityType);
            var entityContainer = new EntityContainer("EC", DataSpace.SSpace);

            entityContainer.AddEntitySetBase(entitySet);

            var storageEntitySetMapping
                = new EntitySetMapping(
                    entitySet,
                    new EntityContainerMapping(entityContainer));

            TypeMapping typeMapping = new EntityTypeMapping(storageEntitySetMapping);

            var mappingFragment = new MappingFragment(entitySet, typeMapping, false);

            fixture.Writer.WriteMappingFragmentElement(mappingFragment);

            Assert.Equal(
                @"<MappingFragment StoreEntitySet=""ES"" />",
                fixture.ToString());
        }
        public async Task GetById_should_retrieve_a_product_from_the_db()
        {
            using (var store = NewDocumentStore())
            {
                using (var session = store.OpenAsyncSession())
                {
                    // Arrange
                    var fixture = new Fixture();
                    var product = fixture.Build<Product>()
                        .With(c => c.Id, "Products-1")
                        .With(c => c.Name, "Mediums")
                        .Create();
                    await SaveEntity(product, session);

                    // Act
                    var service = GetProductsService(session);
                    var actual = await service.GetById("Products-1");

                    // Assert
                    actual.Id.Should().Be("Products-1");
                    actual.Name.Should().Be("Mediums");
                    actual.Count.Should().Be(product.Count);
                    actual.Type.Should().Be(product.Type);
                }
            }
        }
Example #15
0
		public void TestInitialize()
		{
			_context = new DbTestContext(Settings.Default.MainConnectionString);
			_fixture = new Fixture();

			_repository = new SenderRepository(new PasswordConverter(), new SqlProcedureExecutor(Settings.Default.MainConnectionString));
		}
Example #16
0
        public void SetUp()
        {
            processor = Builder.CellProcessor();
            processor.Memory.GetItem<Context>().TestPagePath = new FilePath(@"\some\path.html");

            fixture = new Fixture { Processor = processor };
        }
            public async Task CanStoreComplexClient(NpgsqlClientStore store, Fixture fixture, string clientId)
            {
                // Given
                var client = new Client
                {
                    ClientId = clientId,
                    ClientSecrets = fixture.Create<List<ClientSecret>>(),
                    Flow = Flows.AuthorizationCode,
                    Claims = new List<Claim> { new Claim(fixture.Create("type"), fixture.Create("value"))},
                    AccessTokenType = AccessTokenType.Jwt,
                    ClientUri = fixture.Create<string>(),
                    ClientName = fixture.Create<string>(),
                    RequireConsent = false,
                    ScopeRestrictions = fixture.Create<List<string>>(),
                    LogoUri = fixture.Create<string>(),
                    Enabled = true,
                };

                // When
                await store.AddClientAsync(client);

                // Then
                var fromDb = await store.FindClientByIdAsync(clientId);
                fromDb.ShouldNotBe(null);

                fromDb.ClientId.ShouldBe(clientId);
                fromDb.ClientSecrets.Count.ShouldBe(client.ClientSecrets.Count);
                fromDb.Flow.ShouldBe(client.Flow);
                
            }
        public void Setup()
        {
            _fixture = new Fixture();
            _pmGateway = new Mock<IProjectManagerGateway>();
            _projectRepository = new Mock<IProjectRepository>();
            _vcsGateway = new Mock<IVersionControlSystemGateway>();
            _eventSinkMock = new Mock<IEventSink>();
            _userRepository = new Mock<IUserRepository>();
            var paginationSettings = new ProjectManagement.Domain.PaginationSettings(10);

            _pmGateway
                .Setup(pm => pm.CreateProject(It.IsAny<CreateProjectRequest>()))
                .Returns(_fixture.Create<RedmineProjectInfo>());
            _vcsGateway
                .Setup(vcs => vcs.CreateRepositoryForProject(It.IsAny<CreateProjectRequest>()))
                .Returns(_fixture.Create<VersionControlSystemInfo>());
            _projectRepository
                .Setup(repo => repo.SaveProject(It.IsAny<Project>()))
                .Returns(1);
            _userRepository.Setup(repo => repo.GetUserRedmineId(It.IsAny<int>())).Returns(1);
            _userRepository.Setup(repo => repo.GetUserGitlabId(It.IsAny<int>())).Returns(1);
            _projectProvider = new ProjectProvider(
                _pmGateway.Object,
                _vcsGateway.Object,
                _projectRepository.Object,
                _eventSinkMock.Object,
                _userRepository.Object,
                paginationSettings,
                new IssuePaginationSettings(25));
        }
Example #19
0
        public void DoTable(Fixture fixture, Parse tables, object[] businessObjects, int right, int wrong, int ignores, int exceptions)
        {
            BusinessObjectRowFixture.objects = businessObjects;
            RunTest(fixture, tables);

            TestUtils.CheckCounts(resultCounts, right, wrong, ignores, exceptions);
        }
        public void WriteFunctionElementHeader_should_not_write_return_type_attribute_for_non_primitive_return_type()
        {
            var fixture = new Fixture();

            var returnParameterType = TypeUsage.CreateDefaultTypeUsage(new RowType());

            var function = new EdmFunction(
                "Foo",
                "Bar",
                DataSpace.SSpace,
                new EdmFunctionPayload
                    {
                        Schema = "dbo",
                        ReturnParameters =
                            new[]
                                {
                                    new FunctionParameter(
                                        "r",
                                        returnParameterType,
                                        ParameterMode.ReturnValue)
                                }
                    });

            fixture.Writer.WriteFunctionElementHeader(function);

            Assert.Equal(
                "<Function Name=\"Foo\" Aggregate=\"false\" BuiltIn=\"false\" NiladicFunction=\"false\" IsComposable=\"true\" ParameterTypeSemantics=\"AllowImplicitConversion\" Schema=\"dbo\"",
                fixture.ToString());
        }
Example #21
0
        public void Equals_DifferentMovies_ReturnsFalse()
        {
            var fixture = new Fixture();

            var id1 = fixture.Create<int>();
            var dateUploadedUnix1 = fixture.Create<int>();

            var id2 = fixture.Create<int>();
            var dateUploadedUnix2 = fixture.Create<int>();

            var movie1 = new MovieFull
            {
                Id = id1,
                DateUploadedUnix = dateUploadedUnix1
            };

            var movie2 = new MovieFull
            {
                Id = id2,
                DateUploadedUnix = dateUploadedUnix2
            };

            Assert.AreEqual(
                _comparer.Equals(movie1, movie2), false);

            Assert.AreEqual(
                _comparer.Equals(movie1, null), false);

            Assert.AreEqual(
                _comparer.Equals(movie2, null), false);
        }
Example #22
0
        public void Given_WhenWhen_ShouldExpectedResult()
        {
            var documentStore = new DocumentStore { Url = "http://mamluka-pc:4253" };
            documentStore.Initialize();

            var fixture = new Fixture();

            using (var session = documentStore.OpenSession())
            {
                var theList = fixture.CreateMany<Contact>(1000).ToList();

                theList.Take(500).ToList().ForEach(x => x.DomainGroup = "a");
                theList.Skip(500).Take(500).ToList().ForEach(x => x.DomainGroup = "b");

                var bigDoc = new Holder
                                 {
                                     TheList = theList
                                 };

                session.Store(bigDoc);
                session.SaveChanges();
            }

            documentStore.DatabaseCommands.PutIndex("Count_Contacts", new IndexDefinitionBuilder<Holder, SummeryOfDomains>
            {
                Map = contacts => contacts.SelectMany(x => x.TheList).Select(x => new { x.DomainGroup, Count = 1 }),
                Reduce = results => results.GroupBy(x => x.DomainGroup).Select(x => new { DomainGroup = x.Key, Count = x.Sum(m => m.Count) })

            }, true);

            using (var session = documentStore.OpenSession())
            {
                Trace.WriteLine(session.Query<List<int>>("Count_Contacts").First());
            }
        }
Example #23
0
		public void TestInitialize()
		{
			_context = new DbTestContext(Settings.Default.FilesConnectionString);
			_fixture = new Fixture();

			_repository = new AwbFileRepository(new SqlProcedureExecutor(Settings.Default.FilesConnectionString));
		}
Example #24
0
        public void Execute(Type testClass, Convention convention, Case[] cases)
        {
            foreach (var @case in cases)
            {
                var exceptions = @case.Exceptions;

                try
                {
                    var instance = construct(testClass);

                    var fixture = new Fixture(testClass, instance, convention.CaseExecution.Behavior, new[] { @case });
                    convention.InstanceExecution.Behavior.Execute(fixture);

                    Lifecycle.Dispose(instance);
                }
                catch (PreservedException preservedException)
                {
                    var constructionException = preservedException.OriginalException;
                    exceptions.Add(constructionException);
                }
                catch (Exception constructionException)
                {
                    exceptions.Add(constructionException);
                }
            }
        }
            public static TestData Create(bool existingUser = false)
            {
                var fixture = new Fixture();
                var testData = new TestData
                {
                    Fixture = fixture,
                    UserManager = new Mock<IUserManager>(),
                    SystemRoleManager = new Mock<ISystemRoleManager>(),
                    SystemSettings = new Mock<ISystemSettings>(),
                    AdministratorUserName = fixture.Create<string>("UserName"),
                    AdministratorPassword = fixture.Create<string>("Password"),
                    AdministratorEmailAddress = fixture.Create<string>("EmailAddress"),
                    AdministratorRole = fixture.Build<SystemRole>()
                                                .With(i => i.RoleType, EnumSystemRoleType.Administrator)
                                                .Create()
                };
                if (existingUser)
                {
                    testData.ExistingUser = fixture.Build<SrirachaUser>()
                                                    .With(i => i.UserName, testData.AdministratorUserName)
                                                    .Create();
                    testData.UserManager.Setup(i => i.GetUser(testData.ExistingUser.Id)).Returns(testData.ExistingUser);
                    testData.UserManager.Setup(i => i.TryGetUserByUserName(testData.ExistingUser.UserName)).Returns(testData.ExistingUser);
                    testData.UserManager.Setup(i => i.GetUserByUserName(testData.ExistingUser.UserName)).Returns(testData.ExistingUser);
                }
                testData.SystemRoleManager.Setup(i => i.GetBuiltInRole(EnumSystemRoleType.Administrator)).Returns(testData.AdministratorRole);

                testData.Sut = new SystemSetterUpper(testData.UserManager.Object, testData.SystemRoleManager.Object, testData.SystemSettings.Object);

                return testData;
            }
Example #26
0
 public void MarksDifferentStringCellAsWrong()
 {
     var cell = new Parse("td", "something else", null, null);
     var fixture = new Fixture {Processor = new Service.Service()};
     fixture.CellOperation.Check(new TypedValue("something"), cell);
     Assert.AreEqual("\n<td class=\"fail\">something else <span class=\"fit_label\">expected</span><hr />something <span class=\"fit_label\">actual</span></td>", cell.ToString());
 }
        public void HasCaption_Should_Add_ModelDefaultAttribute_With_CaptionPropertyName_And_ValueMyCaption()
        {
            var caption = new Fixture().Create<string>();
            _Builder.HasCaption(caption);

            A.CallTo(() => _TypeInfo.AddAttribute(A<ModelDefaultAttribute>.That.Matches(t => t.PropertyName == ModelDefaultKeys.Caption && t.PropertyValue == caption))).MustHaveHappened();
        }
Example #28
0
 public void MarksSameStringCellAsRight()
 {
     var cell = new Parse("td", "something", null, null);
     var fixture = new Fixture {Processor = new Service.Service()};
     fixture.CellOperation.Check(new TypedValue("something"), cell);
     Assert.AreEqual("\n<td class=\"pass\">something</td>", cell.ToString());
 }
Example #29
0
        public void SetUp()
        {
            processor = new CellProcessorBase();
            processor.Memory.GetItem<Context>().TestPagePath = @"\some\path.html";

            fixture = new Fixture { Processor = processor };
        }
        public void AddCreatures_WhenValidIdentifierIsPassed_WritelineShoulbeCalled()
        {
            var mockedFactory = new Mock<ICreaturesFactory>();
            var mockedLogger = new Mock<ILogger>();

            var battleManager = new BattleManager(mockedFactory.Object, mockedLogger.Object);

            var fixture = new Fixture();

            fixture.Customizations.Add(new TypeRelay(typeof(Creature), typeof(Angel)));

            var creature = fixture.Create<Creature>();

            // var creature = new Angel();
            mockedFactory.Setup(x => x.CreateCreature(It.IsAny<string>())).Returns(creature);

            mockedLogger.Setup(x => x.WriteLine(It.IsAny<string>()));

            // The code itself should be refactored. Think about sealed class to be changed or the static method itself
            // You could use an unconstrained Mocking framework
            var identifier = CreatureIdentifier.CreatureIdentifierFromString("Angel(1)");

            // Act
            battleManager.AddCreatures(identifier, 1);

            // Assert
            mockedLogger.Verify(x => x.WriteLine(It.IsAny<string>()), Times.Once);
        }