Example #1
0
        public void PopulateEntitiesListViewWhenThereAreListItems()
        {
            var items = new List <System.Windows.Forms.ListViewItem>
            {
                new System.Windows.Forms.ListViewItem("Item1"),
                new System.Windows.Forms.ListViewItem("Item2")
            };
            Exception exception = null;

            NotificationServiceMock.Setup(x => x.DisplayErrorFeedback(It.IsAny <System.Windows.Forms.IWin32Window>(), It.IsAny <string>()))
            .Verifiable();

            using (var listView = new System.Windows.Forms.ListView())
            {
                FluentActions.Invoking(() => systemUnderTest.PopulateEntitiesListView(items, exception, null, listView, NotificationServiceMock.Object))
                .Should()
                .NotThrow();
            }

            NotificationServiceMock.Verify(x => x.DisplayErrorFeedback(It.IsAny <System.Windows.Forms.IWin32Window>(), It.IsAny <string>()), Times.Never);
            NotificationServiceMock.Verify(x => x.DisplayWarningFeedback(It.IsAny <System.Windows.Forms.IWin32Window>(), It.IsAny <string>()), Times.Never);
        }
Example #2
0
        public async Task InvokeMethodAsync_CanInvokeMethodWithNoReturnTypeAndData()
        {
            // Configure Client
            var httpClient = new TestHttpClient();
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient
            })
                             .Build();

            Request request = new Request()
            {
                RequestParameter = "Hello "
            };
            var task = daprClient.InvokeMethodAsync <Request>("test", "test", request);

            // Get Request and validate
            httpClient.Requests.TryDequeue(out var entry).Should().BeTrue();
            var envelope = await GrpcUtils.GetRequestFromRequestMessageAsync <InvokeServiceRequest>(entry.Request);

            envelope.Id.Should().Be("test");
            envelope.Message.Method.Should().Be("test");
            envelope.Message.ContentType.Should().Be(Constants.ContentTypeApplicationJson);

            var json            = envelope.Message.Data.Value.ToStringUtf8();
            var typeFromRequest = JsonSerializer.Deserialize <Request>(json);

            typeFromRequest.RequestParameter.Should().Be("Hello ");

            // Create Response & Respond
            var response = new Response()
            {
                Name = "Look, I was invoked!"
            };

            await SendResponse(response, entry);

            FluentActions.Awaiting(async() => await task).Should().NotThrow();
        }
Example #3
0
        public void IsDefined()
        {
            FastEnum.IsDefined <TEnum>(TEnum.MinValue).Should().BeTrue();
            FastEnum.IsDefined <TEnum>(TEnum.MaxValue).Should().BeTrue();
            FastEnum.IsDefined <TEnum>((TEnum)123).Should().BeFalse();

            TEnum.MinValue.IsDefined().Should().BeTrue();
            TEnum.MaxValue.IsDefined().Should().BeTrue();

            FastEnum.IsDefined <TEnum>(nameof(TEnum.MinValue)).Should().BeTrue();
            FastEnum.IsDefined <TEnum>(nameof(TEnum.MaxValue)).Should().BeTrue();
            FastEnum.IsDefined <TEnum>("123").Should().BeFalse();
            FastEnum.IsDefined <TEnum>("minvalue").Should().BeFalse();

            FastEnum.IsDefined <TEnum>(TUnderlying.MinValue).Should().BeTrue();
            FastEnum.IsDefined <TEnum>(TUnderlying.MaxValue).Should().BeTrue();
            FastEnum.IsDefined <TEnum>((TUnderlying)123).Should().BeFalse();
            FluentActions
            .Invoking(() => FastEnum.IsDefined <TEnum>((sbyte)123))
            .Should()
            .Throw <ArgumentException>();
        }
Example #4
0
        public async Task ShouldThrowRestExceptionWhenPostIsAlreadyUnpinned()
        {
            //arrange
            var loggedUser = await RunAsUserAsync("scott101@localhost", "Pa$$w0rd!");

            var discussionToAdd = new Faker <Discussion>("en")
                                  .RuleFor(p => p.Id, f => f.Random.Guid())
                                  .RuleFor(p => p.Title, f => f.Lorem.Sentence(wordCount: 3))
                                  .RuleFor(p => p.Description, f => f.Lorem.Sentences(sentenceCount: 2)).Generate();

            await AddAsync(discussionToAdd);

            var postToAdd = new Faker <Post>("en")
                            .RuleFor(p => p.Id, f => f.Random.Guid())
                            .RuleFor(p => p.Body, f => f.Lorem.Sentences(5))
                            .RuleFor(p => p.DiscussionId, f => discussionToAdd.Id).Generate();

            await AddAsync(postToAdd);

            var pinCommand = new PinPostCommand()
            {
                Id = postToAdd.Id
            };

            await SendAsync(pinCommand);

            var unpinCommand = new UnpinPostCommand()
            {
                Id = postToAdd.Id
            };

            await SendAsync(unpinCommand);

            //act

            //assert
            FluentActions.Invoking(() =>
                                   SendAsync(unpinCommand)).Should().Throw <RestException>();
        }
        public async Task ShouldThrowRestExceptionWhenDiscussionIsAlreadyOpened()
        {
            //arrange
            var loggedUser = await RunAsUserAsync("scott101@localhost", "Pa$$w0rd!");

            var createdDiscussionId = await SendAsync(new Faker <CreateDiscussionCommand>("en")
                                                      .RuleFor(d => d.Id, f => f.Random.Guid())
                                                      .RuleFor(d => d.Title, f => f.Lorem.Sentence(wordCount: 3))
                                                      .RuleFor(d => d.Description, f => f.Lorem.Sentences(sentenceCount: 2))
                                                      .RuleFor(d => d.PostBody, f => f.Lorem.Paragraph()).Generate());

            var openCommand = new OpenDiscussionCommand()
            {
                Id = createdDiscussionId
            };

            //act

            //assert
            FluentActions.Invoking(() =>
                                   SendAsync(openCommand)).Should().ThrowAsync <RestException>();
        }
        public void GetOperationMessageWithExecuteMultipleResponseItemHavingInnerFault()
        {
            var    testMessage  = "Random Test message!";
            Entity entity       = new Entity("contact", Guid.NewGuid());
            var    responseItem = new ExecuteMultipleResponseItem
            {
                Fault = new OrganizationServiceFault()
                {
                    InnerFault = new OrganizationServiceFault()
                    {
                        Message = testMessage
                    }
                }
            };
            string actual = null;

            FluentActions.Invoking(() => actual = responseItem.GetOperationMessage(entity))
            .Should()
            .NotThrow();

            actual.Should().Contain(testMessage);
        }
Example #7
0
        public async Task ShouldRequireUniqueTitle()
        {
            var  user    = ReturnUser();
            var  testId  = Guid.NewGuid();
            Guid groupId = await SetUpUserGroup();

            await SendAsync(new Create.Command
            {
                Title       = "[Peru] Machu Pichu is bugged",
                Id          = testId,
                Description = "e",
                BugType     = "Localization",
                Device      = "Iphone 2",
                Priority    = "High",
                Date        = DateTime.Now,
                GroupId     = groupId,
                Status      = "Open",
                Version     = "1337"
            });

            // Create new Ticket with the same ticket.
            testId = Guid.NewGuid();
            var command = new Create.Command
            {
                Title       = "[Peru] Machu Pichu is bugged",
                Id          = testId,
                Description = "Even though this is a perfectly valid Description, this title already exists.",
                BugType     = "UI",
                Device      = "Iphone 2",
                Priority    = "High",
                Date        = DateTime.Now,
                GroupId     = groupId,
                Status      = "Open",
                Version     = "1337"
            };

            FluentActions.Invoking(() => SendAsync(command)).Should().Throw <Microsoft.EntityFrameworkCore.DbUpdateException>();
        }
        public void SaveSchemaEntityAttributeSelected()
        {
            NotificationServiceMock.Setup(x => x.DisplayFeedback("Please select at least one attribute for each selected entity!"))
            .Verifiable();
            var entityLogicalName = "contact";
            var entityMetadata    = InstantiateEntityMetaData(entityLogicalName);

            InsertAttributeList(entityMetadata, new List <string> {
                "contactId", "firstname", "lastname"
            });

            inputCheckedEntity.Add(entityLogicalName);

            var attributeSet = new HashSet <string>()
            {
                "contactId", "firstname", "lastname"
            };

            inputEntityAttributes.Add(entityLogicalName, attributeSet);
            var inputAttributeMapping = new AttributeTypeMapping();
            var serviceParameters     = GenerateMigratorParameters();

            MetadataServiceMock.Setup(x => x.RetrieveEntities(It.IsAny <string>(), It.IsAny <IOrganizationService>(), It.IsAny <IExceptionService>()))
            .Returns(entityMetadata)
            .Verifiable();

            using (var schemaPathTextBox = new System.Windows.Forms.TextBox())
            {
                var inputCrmSchemaConfiguration = new DataMigration.Config.CrmSchemaConfiguration();

                FluentActions.Invoking(() => systemUnderTest.SaveSchema(serviceParameters, inputCheckedEntity, inputEntityRelationships, inputEntityAttributes, inputAttributeMapping, inputCrmSchemaConfiguration, schemaPathTextBox))
                .Should()
                .NotThrow();
            }

            MetadataServiceMock.VerifyAll();
            NotificationServiceMock.Verify(x => x.DisplayFeedback("Please select at least one attribute for each selected entity!"), Times.Never);
        }
Example #9
0
        public void ExportDataAsCsv()
        {
            var dataFormat     = DataFormat.Csv;
            var exportSettings = new ExportSettings
            {
                // this is not really unit test but it is the quckest way to get this tested as CrmSchemaConfiguration.ReadFromFile actually looks for the file!
                SchemaPath       = "TestData/BusinessUnitSchema.xml",
                DataFormat       = dataFormat,
                ExportConfigPath = "TestData",
                BatchSize        = 5000,
                SavePath         = "TestData"
            };

            var storeReader = new Mock <IDataStoreReader <Entity, EntityWrapper> >().Object;
            var storeWriter = new Mock <IDataStoreWriter <Entity, EntityWrapper> >().Object;

            var genericCrmDataMigrator = new GenericCrmDataMigrator(loggerMock.Object, storeReader, storeWriter);

            var factoryMock = new Mock <ICrmGenericMigratorFactory>();

            factoryMock.Setup(x => x.GetCrmDataMigrator(
                                  dataFormat,
                                  It.IsAny <ILogger>(),
                                  It.IsAny <EntityRepository>(),
                                  It.IsAny <CrmExporterConfig>(),
                                  It.IsAny <CancellationToken>(),
                                  It.IsAny <CrmSchemaConfiguration>()))
            .Returns(genericCrmDataMigrator)
            .Verifiable();

            var localSystemUnderTest = new DataMigrationService(loggerMock.Object, factoryMock.Object);

            FluentActions.Invoking(() => localSystemUnderTest.ExportData(exportSettings))
            .Should()
            .Throw <NullReferenceException>();

            factoryMock.Verify(x => x.GetCrmDataMigrator(dataFormat, It.IsAny <ILogger>(), It.IsAny <EntityRepository>(), It.IsAny <CrmExporterConfig>(), It.IsAny <CancellationToken>(), It.IsAny <CrmSchemaConfiguration>()), Times.Once);
        }
Example #10
0
        public void ProcessEntityManyToManyEnity()
        {
            var id1    = Guid.NewGuid();
            var id2    = Guid.NewGuid();
            var entity = new Entity()
            {
                LogicalName = "accountcontact"
            };

            entity.Attributes["accountid"] = id1;
            entity.Attributes["contactid"] = id2;
            var entityWrapper = new EntityWrapper(entity, true);

            var entityMetadata = new EntityMetadata();

            MockEntityRepo.SetupGet(a => a.GetEntityMetadataCache).Returns(MockEntityMetadataCache.Object);
            MockEntityRepo.Setup(a => a.GetParentBuId()).Returns(Guid.NewGuid());
            MockEntityRepo.Setup(a => a.GetOrganizationId()).Returns(Guid.NewGuid());

            MockEntityMetadataCache.Setup(a => a.GetEntityMetadata(It.IsAny <string>())).Returns(entityMetadata);

            var values = new Dictionary <Guid, Guid>
            {
                { id1, Guid.NewGuid() },
                { id2, Guid.NewGuid() }
            };

            mappingConfig.Mappings.Add("accountcontact", values);

            systemUnderTest = new MapEntityProcessor(mappingConfig, MockLogger.Object, MockEntityRepo.Object, passOneReferences);

            FluentActions.Invoking(() => systemUnderTest.ProcessEntity(entityWrapper, passNumber, maxPassNumber))
            .Should()
            .NotThrow();

            MockEntityRepo.VerifyAll();
            MockEntityMetadataCache.Verify(a => a.GetEntityMetadata(It.IsAny <string>()));
        }
            public void DependentEntityContainsPrincipalEntityIdAsTheShadowProperty()
            {
                var dbConnectionString = DbConnectionString.Create(nameof(ConfiguringNonrelationalProperties), GetCallerName());

                using var context =
                          dbConnectionString
                          .AsSqlConnectionString <PrincipalDependentContext>()
                          .EnsureDb()
                          .BuildDbContext()
                          .StartLogging(_testOutput.AsLineWriter());

                Func <object> func = () =>
                                     context
                                     .Entry(new Dependent())
                                     .Property($"{nameof(Dependent.NavigationProp)}{nameof(Principal.PrincipalId)}")
                                     .CurrentValue;

                FluentActions
                .Invoking(func)
                .Should()
                .NotThrow($"because EF Core should have created the shadow property representing {nameof(Principal.PrincipalId)} " +
                          $"to be able to link {nameof(Dependent)} to {nameof(Principal)}");
            }
        public void WithoutExpressionExpandingTest()
        {
            var builder = new DbContextOptionsBuilder <TestContext>();

            builder
            .UseSqlite("DataSource=testdb;mode=memory");

            using (var context = new TestContext(builder.Options))
            {
                context.Database.OpenConnection();
                context.Database.EnsureCreated();

                context.TestEntities.Add(new TestEntity {
                    Id = 1, Value = "One"
                });
                context.SaveChanges();

                FluentActions.Invoking(() => context.TestEntities.Where(e => FilterTrue(e)).ToArray()).Should()
                .Throw <InvalidOperationException>();
                FluentActions.Invoking(() => context.TestEntities.Where(e => FilterFalse(e)).ToArray()).Should()
                .Throw <InvalidOperationException>();
            }
        }
        public async Task GetBankAccountByIdForCurrentUser_UserDoesNotOwnAccount_ThrowsException()
        {
            // Arrange
            var bankAccountEntity = new BankAccountEntity
            {
                AccountType    = BankAccountType.Checking,
                Disabled       = true,
                CurrentBalance = 100,
                StartBalance   = 100,
                Name           = "BankAccount",
                UserId         = _defaultUserId + 1
            };

            InsertEntity(bankAccountEntity);

            var bankAccountService = _mocker.CreateInstance <BankAccountService>();

            // Act
            var result = FluentActions.Awaiting(async() => await bankAccountService.GetBankAccountByIdForCurrentUser(bankAccountEntity.Id));

            // Arrange
            await result.Should().ThrowAsync <NotFoundException>();
        }
Example #14
0
        public async Task ShouldRequireUniqueTitle()
        {
            var categoryId = await SendAsync(new CreateTodoCategoryCommand
            {
                CategoryTitle = "New List"
            });

            await SendAsync(new CreateTodoCategoryCommand
            {
                CategoryTitle = "Other List"
            });

            var command = new UpdateTodoCategoryCommand
            {
                Id            = categoryId,
                CategoryTitle = "Other List"
            };

            FluentActions.Invoking(() =>
                                   SendAsync(command))
            .Should().Throw <ValidationException>().Where(ex => ex.Errors.ContainsKey("CategoryTitle"))
            .And.Errors["CategoryTitle"].Should().Contain("The specified title already exists.");
        }
Example #15
0
        public async Task InvokeRawMethodAsync_WithCancelledToken()
        {
            // Configure Client
            var httpClient = new TestHttpClient();
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient, ThrowOperationCanceledOnCancellation = true
            })
                             .Build();

            var ctSource         = new CancellationTokenSource();
            CancellationToken ct = ctSource.Token;

            ctSource.Cancel();

            var body = new Request()
            {
                RequestParameter = "Hello "
            };
            var bytes = JsonSerializer.SerializeToUtf8Bytes(body);
            await FluentActions.Awaiting(async() => await daprClient.InvokeMethodRawAsync("test", "testMethod", bytes, cancellationToken: ct))
            .Should().ThrowAsync <OperationCanceledException>();
        }
Example #16
0
        public async Task ShouldAllowAdministrator()
        {
            await RunAsAdministratorAsync();

            var city = await SendAsync(new CreateCityCommand
            {
                Name = "Çanakkale"
            });

            var result = await SendAsync(new CreateDistrictCommand
            {
                Name   = "Çan",
                CityId = city.Data.Id
            });

            var query = new ExportDistrictsQuery
            {
                CityId = result.Data.Id
            };

            FluentActions.Invoking(() => SendAsync(query))
            .Should().NotThrow <ForbiddenAccessException>();
        }
Example #17
0
        public async Task ShouldThrowNotFoundWhenInvalidDiscussionId()
        {
            //arrange
            var loggedUser = await RunAsUserAsync("scott101@localhost", "Pa$$w0rd!");

            var discussionToAdd = new Faker <Discussion>("en")
                                  .RuleFor(d => d.Id, f => f.Random.Guid())
                                  .RuleFor(d => d.Title, f => f.Lorem.Sentence(wordCount: 3))
                                  .RuleFor(d => d.Description, f => f.Lorem.Sentences(sentenceCount: 2)).Generate();

            await AddAsync(discussionToAdd);

            var createPostCommand = new Faker <CreatePostCommand>("en")
                                    .RuleFor(p => p.Id, f => f.Random.Guid())
                                    .RuleFor(p => p.Body, f => f.Lorem.Sentences(5))
                                    .RuleFor(p => p.DiscussionId, f => f.Random.Guid()).Generate();

            //act

            //assert
            FluentActions.Invoking(() =>
                                   SendAsync(createPostCommand)).Should().ThrowAsync <NotFoundException>();
        }
Example #18
0
        public async Task ShouldRequireUniqueTitle()
        {
            var listId = await SendAsync(new CreateTodoList.Command
            {
                Title = "New List"
            });

            await SendAsync(new CreateTodoList.Command
            {
                Title = "Other List"
            });

            var command = new Command
            {
                Id    = listId,
                Title = "Other List"
            };

            FluentActions.Invoking(async() => await
                                   GetService <Handler>().Handle(command))
            .Should().Throw <ValidationException>().Where(ex => ex.Errors.ContainsKey("Title"))
            .And.Errors["Title"].Should().Contain("The specified title already exists.");
        }
Example #19
0
        public void how_SqlHelper_RemoveSensitiveInformations_works()
        {
            // This is what is done: Password and User ID are removed.
            var s = "Server=.;Database=test;User ID=toto;Password=pwd";
            var c = new SqlConnectionStringBuilder(s);

            c["Password"] = null;
            c["User ID"]  = null;
            c.ToString().Should().Be("Data Source=.;Initial Catalog=test");

            // The SqlHelper.RemoveSensitiveInformations( string connectionString ) must be protected.
            FluentActions.Invoking(() => new SqlConnectionStringBuilder("something totally f****d.")).Should().Throw <ArgumentException>();


            SqlHelper.RemoveSensitiveInformations("Server=14.247.78.98; Pwd=pouf; uid=user; database=mydb")
            .Should().Be("Data Source=14.247.78.98;Initial Catalog=mydb");

            SqlHelper.RemoveSensitiveInformations(null)
            .Should().StartWith("ArgumentException: ");

            SqlHelper.RemoveSensitiveInformations("something totally f****d")
            .Should().StartWith("ArgumentException: ");
        }
        public void GenerateImportConfigFile()
        {
            var inputMapper = new Dictionary <string, Dictionary <Guid, Guid> >();
            var value       = new Dictionary <Guid, Guid> {
                { Guid.NewGuid(), Guid.NewGuid() }
            };

            inputMapper.Add("contact", value);

            NotificationServiceMock.Setup(x => x.DisplayFeedback(It.IsAny <string>()))
            .Verifiable();

            using (var importConfig = new System.Windows.Forms.TextBox())
            {
                importConfig.Text = $"TestData//{Guid.NewGuid()}.json";

                FluentActions.Invoking(() => systemUnderTest.GenerateImportConfigFile(NotificationServiceMock.Object, importConfig, inputMapper))
                .Should()
                .NotThrow();
            }

            NotificationServiceMock.Verify(x => x.DisplayFeedback(It.IsAny <string>()), Times.Never);
        }
        public async Task Handle_WrongUser_ShouldThrowNotFoundException()
        {
            var projectId = await CreateFinancialProject();

            var transaction = new CreateTransactionCommand
            {
                FinancialProjectId = projectId,
                Amount             = 100,
                ToUserId           = SecondUser.Id,
                TransactionType    = TransactionType.FinancialReceipts
            };

            var id = await SendAsync(transaction);

            var deleteTransaction = new DeleteTransactionCommand
            {
                Id = id
            };

            await RunAsUserAsync("*****@*****.**", "nah");

            FluentActions.Invoking(async() => await SendAsync(deleteTransaction)).Should().Throw <NotFoundException>();
        }
Example #22
0
        public async Task ShouldRequireUniqueTitle()
        {
            var paymentId = await SendAsync(new CreatePaymentCommand
            {
                Name = "New List"
            });

            await SendAsync(new CreatePaymentCommand
            {
                Name = "This thing is also done"
            });

            var command = new UpdatePaymentCommand
            {
                Id   = paymentId,
                Name = "This thing is also done"
            };

            FluentActions.Invoking(() =>
                                   SendAsync(command))
            .Should().Throw <ValidationException>().Where(ex => ex.Errors.ContainsKey("Name"))
            .And.Errors["Name"].Should().Contain("The specified name is already exists.");
        }
Example #23
0
        public async Task CmdHandler_CriarContrato_Ja_Existente()
        {
            var fixture = new Fixture();

            var repository = Substitute.For <IContratoDeEmprestimoRepository>();

            repository.LoadAsync(Arg.Any <Guid>())
            .ReturnsForAnyArgs(fixture.Create <ContratoDeEmprestimoAggregate>());

            IRequestHandler <CriarContratoCmd> handler = new CriarContratoHandler(repository);

            await FluentActions
            .Invoking(async() =>
                      await handler.Handle(fixture.Create <CriarContratoCmd>(), CancellationToken.None))
            .Should()
            .ThrowAsync <ResourceAlreadyExistsException>();

            await repository.Received(1)
            .LoadAsync(Arg.Any <Guid>());

            await repository.Received(0)
            .SaveAsync(Arg.Any <ContratoDeEmprestimoAggregate>());
        }
Example #24
0
        public async Task ExecuteStateTransactionAsync_WithCancelledToken()
        {
            // Configure Client
            var httpClient = new TestHttpClient();
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient, ThrowOperationCanceledOnCancellation = true
            })
                             .Build();

            var ctSource         = new CancellationTokenSource();
            CancellationToken ct = ctSource.Token;

            ctSource.Cancel();

            var operation  = new StateTransactionRequest("test", null, StateOperationType.Delete);
            var operations = new List <StateTransactionRequest>
            {
                operation
            };
            await FluentActions.Awaiting(async() => await daprClient.ExecuteStateTransactionAsync("testStore", operations, new Dictionary <string, string>(), cancellationToken: ct))
            .Should().ThrowAsync <OperationCanceledException>();
        }
Example #25
0
        public async Task ShouldHaveErrorWhenEmailNotCorrect()
        {
            //arrange
            var command = new RegisterUserCommand()
            {
                Username = "******",
                Email    = "scott@localhost",
                Password = "******"
            };
            var registeredUser = await SendAsync(command);

            var query = new LoginUserQuery()
            {
                Email    = "scottnotagoodemail@localhost",
                Password = "******"
            };

            //act

            //assert
            FluentActions.Invoking(() =>
                                   SendAsync(query)).Should().ThrowAsync <RestException>();
        }
        public void ItemNotExists()
        {
            var item = new Item(
                ItemId.From("1"),
                ItemName.From("acoustic guitar"),
                CatalogueStatus.NOT_FOR_SALE,
                Source.CRAFTING,
                Image.From("https://acnhcdn.com/latest/FtrIcon/FtrAcorsticguitar_Remake_0_0.png"),
                new ItemVariant(
                    ItemVariantId.From("1_0"),
                    ItemVariantName.From("Natural")
                    )
                );
            var items = new List <Item> {
                item
            };
            var service = new InMemoryItemService(items);


            FluentActions
            .Invoking(() => service.Get(ItemId.From("1234"), null))
            .Should().Throw <InvalidOperationException>();
        }
        public async System.Threading.Tasks.Task ShouldRequireUniqueName()
        {
            var employeeId = await SendAsync(new CreateEmployeeCommand
            {
                Name = "John Smith"
            });

            await SendAsync(new CreateEmployeeCommand
            {
                Name = "Jane"
            });

            var command = new UpdateEmployeeCommand
            {
                Id   = employeeId,
                Name = "Jane"
            };

            FluentActions.Invoking(() =>
                                   SendAsync(command))
            .Should().Throw <ValidationException>().Where(ex => ex.Errors.ContainsKey("Name"))
            .And.Errors["Name"].Should().Contain("The specified name already exists.");
        }
Example #28
0
        public async Task ShouldThrowBrandNotFoundException()
        {
            // Arrange


            // Create product category
            var productCategory = await CreateAsync <ProductCategory, ProductCatalogContext>(new ProductCategory("Test ProductCategory"));

            var createProductCommand = new CreateProductCommand
            {
                AvailableToSell = true,
                // created brand id
                BrandId = Guid.NewGuid().ToString(),
                // created product category id
                ProductCategoryId = productCategory.Id.ToString(),
                Name     = "Test Product",
                PhotoUrl = "Test Product",
                Barcode  = "Test Product"
            };

            // Act
            FluentActions.Invoking(() => SendAsync(createProductCommand)).Should().Throw <BrandNotFoundException>();
        }
Example #29
0
        public async Task ShouldRequireUniqueName()
        {
            var city = await SendAsync(new CreateCityCommand
            {
                Name = "Malatya"
            });

            await SendAsync(new CreateCityCommand
            {
                Name = "Denizli"
            });

            var command = new UpdateCityCommand
            {
                Id   = city.Data.Id,
                Name = "Denizli"
            };

            FluentActions.Invoking(() =>
                                   SendAsync(command))
            .Should().Throw <ValidationException>().Where(ex => ex.Errors.ContainsKey("Name"))
            .And.Errors["Name"].Should().Contain("The specified city already exists. If you just want to activate the city leave the name field blank!");
        }
Example #30
0
        public async Task GetSecretAsync_WithCancelledToken()
        {
            // Configure Client
            var httpClient = new TestHttpClient();
            var daprClient = new DaprClientBuilder()
                             .UseGrpcChannelOptions(new GrpcChannelOptions {
                HttpClient = httpClient, ThrowOperationCanceledOnCancellation = true
            })
                             .Build();

            var metadata = new Dictionary <string, string>
            {
                { "key1", "value1" },
                { "key2", "value2" }
            };

            var ctSource         = new CancellationTokenSource();
            CancellationToken ct = ctSource.Token;

            ctSource.Cancel();
            await FluentActions.Awaiting(async() => await daprClient.GetSecretAsync("testStore", "test_key", metadata, cancellationToken: ct))
            .Should().ThrowAsync <OperationCanceledException>();
        }