Esempio n. 1
0
        //[Theory]
        //[InlineData("/api/Employee/All")]
        public async Task GetAllEmployees(string url)
        {
            //Given a running server with employees allocated in his database
            DalService.CreateUnitOfWork().Employees.GetAllAsync(PageRequest.Of(0, int.MaxValue)).Result.Should().HaveCountGreaterThan(0);

            //When a client ask for URL /api/Employee/All
            var client   = TestServer.CreateClient();
            var response = await client.GetAsync(url);

            //Then the response will be successful
            response.EnsureSuccessStatusCode(); // Status Code 200-299

            //and the result body should not be null
            var json = await response.Content.ReadAsStringAsync();

            IEnumerable <EmployeeDto> reaultObjects = JsonConvert.DeserializeObject <IEnumerable <EmployeeDto> >(json);

            reaultObjects.Should().NotBeNull();

            //and the result body should match the employees in the database
            var allEmployeesFromDb = DalService.CreateUnitOfWork().Employees.GetAllAsync(PageRequest.Of(0, int.MaxValue)).Result
                                     .Select(e => Mapper.Map <EmployeeDto>(e));;

            reaultObjects.Should().BeEquivalentTo(allEmployeesFromDb, options => options.IncludingNestedObjects());
        }
Esempio n. 2
0
        public async Task GetBusinessPartnersPaging(string url)
        {
            //Given a running server with businessPartners allocated in his database
            DalService.CreateUnitOfWork().BusinessPartners.GetAllAsync(PageRequest.Of(0, 1)).Result.Should().HaveCountGreaterThan(0);

            //When a client ask for URL /api/BusinessPartner&page=x&size=y
            var client   = TestServer.CreateClient();
            var response = await client.GetAsync(url);

            //Then the response will be successful
            response.EnsureSuccessStatusCode(); // Status Code 200-299

            //and the result body should not be null
            var json = await response.Content.ReadAsStringAsync();

            var resultObjects       = JsonConvert.DeserializeObject <IEnumerable <BusinessPartnerDto> >(json);
            var businessPartnersDto = resultObjects as BusinessPartnerDto[] ?? resultObjects.ToArray();

            businessPartnersDto.Should().NotBeNull();

            //and the result body should contain size or less elements
            var size = Convert.ToInt32(url.Split("size=")[1]);

            //var page = Convert.ToInt32(url.Split("page=")[1].Split("&")[0]);
            businessPartnersDto.Should().HaveCountLessOrEqualTo(size);
            var bpsKeys = businessPartnersDto.Select(x => x.Key);
            //and the result body should match the businessPartners in the database
            var allBusinessPartnersFromDb = DalService.CreateUnitOfWork()
                                            .BusinessPartners.FindAllAsync(x => bpsKeys.Contains(x.Key), PageRequest.Of(0, int.MaxValue)).Result
                                            .Select(e => Mapper.Map <BusinessPartnerDto>(e)).ToList();

            allBusinessPartnersFromDb.Count.Should().BeLessOrEqualTo(size);
            businessPartnersDto.Should().BeEquivalentTo(allBusinessPartnersFromDb, options => options.IncludingNestedObjects());
        }
Esempio n. 3
0
        public void AddNewValidQuotationShouldSucceed()
        {
            var numOfQuotationBefore = DalService.CreateUnitOfWork().Quotations.CountAsync().Result;

            //Given a valid new quotation
            var validQuotation = CreateValidQuotation();

            //When adding the new quotation
            var unitOfWork = DalService.CreateUnitOfWork();
            {
                var addedQuotations = unitOfWork.Quotations.AddAsync(validQuotation).Result;
                _addedQuotationsToCancelAtDispose.Add(addedQuotations);

                //Then the result should not be null
                addedQuotations.Should().NotBeNull();
                //and the result's document sum should be close to quantity*pricePerQuantity*(100-discountPrecent)/100 + VAT
                var calculatedTotal = validQuotation.Items.Sum(i => i.PricePerQuantity * i.Quantity * (100 - i.DiscountPercent) / 100);
                Debug.Assert(addedQuotations.VatPercent != null, "addedQuotations.VatPercent != null");
                calculatedTotal += (calculatedTotal * addedQuotations.VatPercent.Value) / 100;
                addedQuotations.DocTotal.Should().BeInRange(calculatedTotal - 1, calculatedTotal + 1);
                //and the transaction should succeed
                unitOfWork.CompleteAsync().Wait();
                //and the repository should contain the new quotation
                Debug.Assert(addedQuotations.Key != null, "addedQuotations.Key != null");
                var quotationAfterCommit = DalService.CreateUnitOfWork().Quotations.FindByIdAsync(addedQuotations.Key.Value).Result;
                quotationAfterCommit.Should().NotBeNull();
                quotationAfterCommit.ValidUntil.Should().Be(validQuotation.ValidUntil);

                var numOfQuotationAfter = DalService.CreateUnitOfWork().Quotations.CountAsync().Result;
                numOfQuotationAfter.Should().Be(numOfQuotationBefore + 1);
            }
        }
Esempio n. 4
0
        public void AddingCustomerWithCidShouldFailAndThrowException()
        {
            //Given a BusinessPartner repository
            var numberOfCustomerBefore = DalService.CreateUnitOfWork().BusinessPartners.CountAsync().Result;
            //When Adding a BusinessPartner with a Cid (not null)
            var businessPartner = new BusinessPartner
            {
                Key  = "000",
                Name = "testName"
            };
            //Than the adding function will throw an exception
            BusinessPartner addedBusinessPartner = null;
            Action          comparison           = () =>
            {
                using var uow        = DalService.CreateUnitOfWork();
                addedBusinessPartner = uow.BusinessPartners.AddAsync(businessPartner).Result;
                uow.CompleteAsync().Wait();
            };

            comparison.Should().Throw <Exception>();

            //and the database will not affected
            DalService.CreateUnitOfWork().BusinessPartners.CountAsync().Result.Should().Be(numberOfCustomerBefore);

            //and the returned BusinessPartner need to be null
            (addedBusinessPartner == null).Should().BeTrue();
        }
Esempio n. 5
0
        public async Task GetEmployeeBySn(string url)
        {
            //Given a running server with employees allocated in his database
            var employeeId     = Convert.ToInt32(url.Split("GetBySN/")[1]);
            var employeeFromDb = DalService.CreateUnitOfWork().Employees.FindByIdAsync(employeeId).Result;

            employeeFromDb.Should().NotBeNull();

            //When a client ask for URL /api/Employee/GetByID/5
            var client   = TestServer.CreateClient();
            var response = await client.GetAsync(url);


            //Then the response will be successful
            response.EnsureSuccessStatusCode(); // Status Code 200-299

            //and the result body should not be null
            var json = await response.Content.ReadAsStringAsync();

            EmployeeDto reaultObject = JsonConvert.DeserializeObject <EmployeeDto>(json);

            reaultObject.Should().NotBeNull();

            //and the result body should match the employees in the database
            reaultObject.Should().BeEquivalentTo(Mapper.Map <EmployeeDto>(employeeFromDb)
                                                 , options => options.IncludingNestedObjects());
        }
Esempio n. 6
0
        public async Task GetEmployeesPageing(string url)
        {
            //Given a running server with employees allocated in his database
            DalService.CreateUnitOfWork().Employees.GetAllAsync(PageRequest.Of(0, int.MaxValue)).Result.Should().HaveCountGreaterThan(0);

            //When a client ask for URL /api/Employee&page=x&size=y
            var client   = TestServer.CreateClient();
            var response = await client.GetAsync(url);

            //Then the response will be successful
            response.EnsureSuccessStatusCode(); // Status Code 200-299

            //and the result body should not be null
            var json = await response.Content.ReadAsStringAsync();

            IEnumerable <EmployeeDto> reaultObjects = JsonConvert.DeserializeObject <IEnumerable <EmployeeDto> >(json);

            reaultObjects.Should().NotBeNull();


            //and the result body should contain size or less elements
            var size = Convert.ToInt32(url.Split("size=")[1]);
            var page = Convert.ToInt32(url.Split("page=")[1].Split("&")[0]);

            reaultObjects.Should().HaveCountLessOrEqualTo(size);

            //and the result body should match the employees in the database
            var allEmployeesFromDb = DalService.CreateUnitOfWork()
                                     .Employees.GetAllAsync(PageRequest.Of(page, size, Sort <EmployeeEntity> .By(x => x.Sn))).Result
                                     .Select(e => Mapper.Map <EmployeeDto>(e));

            reaultObjects.Should().BeEquivalentTo(allEmployeesFromDb, options => options.IncludingNestedObjects());
        }
        public async Task GetCompany(string url)
        {
            //Given a running server with company allocated in his database
            var companyFromDb = DalService.CreateUnitOfWork().Company.GetAsync().Result;

            companyFromDb.Should().NotBeNull();

            //When a client ask for URL /api/Company
            var client   = TestServer.CreateClient();
            var response = await client.GetAsync(url);


            //Then the response will be successful
            response.EnsureSuccessStatusCode(); // Status Code 200-299

            //and the result body should not be null
            var json = await response.Content.ReadAsStringAsync();

            CompanyDto reaultObject = JsonConvert.DeserializeObject <CompanyDto>(json);

            reaultObject.Should().NotBeNull();

            //and the result body should match the company in the database
            reaultObject.Should().BeEquivalentTo(Mapper.Map <CompanyDto>(companyFromDb),
                                                 options => options.IncludingNestedObjects());
        }
Esempio n. 8
0
        public void AddCustomerListWithOneCustomerThatFailWillThrowExceptionAndRollback()
        {
            //Given a BusinessPartner repository
            var numberOfCustomerBefore = DalService.CreateUnitOfWork().BusinessPartners.CountAsync().Result;

            //When Adding a BusinessPartner list with one or more BusinessPartner that have a Cid (not null)
            var customerList = Enumerable.Range(1, 5)
                               .Select(i => new BusinessPartner {
                Name = "TESTAddCustomerListWithOneCustomerThatFailWillRollback " + i
            })
                               .ToList();

            customerList.ElementAt(3).Key = "000";
            customerList.ElementAt(4).Key = "000";
            Action comparison = () =>
            {
                using var uow = DalService.CreateUnitOfWork();
                uow.BusinessPartners.AddAsync(customerList).Wait();
                uow.CompleteAsync().Wait();
            };


            //Then action will throw an exception
            comparison.Should().Throw <Exception>();

            //and the number of elements in the repository will not affected - transaction will rollback
            var numberOfCustomerAfterTransaction = DalService.CreateUnitOfWork().BusinessPartners.CountAsync().Result;

            numberOfCustomerAfterTransaction.Should().Be(numberOfCustomerBefore);
        }
Esempio n. 9
0
        public async Task PostBusinessPartner(string url)
        {
            //Given a running server with CardGroup and Salesman
            DbContext.Salesmen.Add(new SalesmanEntity
            {
                Sn           = -1,
                Name         = "TEST_S",
                ActiveStatus = SalesmanEntity.Status.Active
            });
            DbContext.CardGroups.Add(new CardGroup {
                Sn = 100, Name = "TEST_S"
            });
            DbContext.SaveChanges();

            var validGroupCodes = DalService.CreateUnitOfWork().BusinessPartners.GetAllGroupsAsync().Result;
            var validSalesmen   = DalService.CreateUnitOfWork().Salesmen.GetAllAsync(PageRequest.Of(0, int.MaxValue)).Result;

            var businessPartnersToPost = Enumerable.Range(1, 3).ToList()
                                         .Select(i => new BusinessPartner {
                Name         = "TestWebBusinessPartner" + i,
                GroupSn      = validGroupCodes.FirstOrDefault()?.Sn,
                SalesmanCode = validSalesmen.FirstOrDefault()?.Sn,
                PartnerType  = BusinessPartner.PartnerTypes.Customer,
                Type         = BusinessPartner.CardType.Private
            }).ToList();

            foreach (var businessPartnerToPost in businessPartnersToPost)
            {
                var jsonSend = JsonConvert.SerializeObject(Mapper.Map <BusinessPartnerDto>(businessPartnerToPost));
                //When a client ask for URL /api/BusinessPartner} with a valid BusinessPartner in the request body
                var client   = TestServer.CreateClient();
                var response = await client.PostAsync(url, new StringContent(jsonSend, Encoding.UTF8, "application/json"));


                //Then the response will be successful
                response.EnsureSuccessStatusCode(); // Status Code 200-299

                //and the result body should be null and the name need to match
                var json = await response.Content.ReadAsStringAsync();

                var resultObject = JsonConvert.DeserializeObject <BusinessPartnerDto>(json);
                resultObject.Should().NotBeNull();
                resultObject.Name.Should().Be(businessPartnerToPost.Name);
                resultObject.Should().BeEquivalentTo(businessPartnerToPost, opt => opt
                                                     .Excluding(x => x.CreationDateTime)
                                                     .Excluding(x => x.LastUpdateDateTime)
                                                     .Excluding(x => x.Key)
                                                     .IncludingNestedObjects()
                                                     );

                //and the businessPartners should be added to the database
                DalService.CreateUnitOfWork().BusinessPartners.FindByIdAsync(resultObject.Key).Result
                .Should().NotBeNull();
            }
        }
Esempio n. 10
0
 public void Dispose()
 {
     //clear added BusinessPartner if any test failed
     using var uow = DalService.CreateUnitOfWork();
     uow.BusinessPartners.RemoveAsync(
         uow.BusinessPartners.GetAllAsync(
             PageRequest.Of(0, int.MaxValue, Sort <BusinessPartner> .By(x => x.Name))).Result
         .Select(c => c.Key)
         .Except(_customerBeforeTesting).ToList()).Wait();
     uow.CompleteAsync().Wait();
 }
        public void GetCompanyShouldSucceed()
        {
            //Given allocated company repository

            //When call to Get Company
            var company = DalService.CreateUnitOfWork().Company.GetAsync().Result;

            //Then the company should not be null
            company.Should().NotBeNull();
            //and the company should contain a name
            company.Name.Should().NotBeNullOrWhiteSpace();
        }
Esempio n. 12
0
        public async void MultiThreadedAddingCustomersShouldSucceed()
        {
            //Given a BusinessPartner Repository
            var readonlyUow            = DalService.CreateUnitOfWork();
            var numberOfCustomerBefore = readonlyUow.BusinessPartners.CountAsync().Result;
            //when a number of different threads want to add some BusinessPartner to the repository at the same time
            const int numOfThreads           = 5;
            const int nymOfCustomerPerThread = 5;


            var taskList = Enumerable.Range(1, numOfThreads).ToList().Select(i =>
            {
                return(Task <List <BusinessPartner> > .Factory.StartNew(() =>
                {
                    var cc = Enumerable.Range(1, nymOfCustomerPerThread)
                             .Select(j => new BusinessPartner {
                        Name = $"TESTAddCustomerList thread={i}:index={j}"
                    })
                             .ToList();
                    using var u = DalService.CreateUnitOfWork();
                    var customerListAfter = u.BusinessPartners.AddAsync(cc).Result.ToList();
                    u.CompleteAsync().Wait();
                    return customerListAfter;
                }));
            }).ToArray();
            var r = (await Task.WhenAll(taskList)).ToList();

            //Then the BusinessPartner Repository will contain all of the BusinessPartner from the different threads
            var numberOfCustomerAfter = readonlyUow.BusinessPartners.CountAsync().Result;

            numberOfCustomerAfter.Should().Be(numberOfCustomerBefore + numOfThreads * nymOfCustomerPerThread);

            r.ForEach(bps =>
            {
                var keys          = bps.Select(cf => cf.Key);
                var addedCustomer = readonlyUow.BusinessPartners
                                    .FindAllAsync(c => keys.Contains(c.Key),
                                                  PageRequest.Of(0, nymOfCustomerPerThread + 1)).Result;
                addedCustomer.Select(c => new[] { c.Key, c.Name })
                .Should().BeEquivalentTo(bps.Select(c => new[] { c.Key, c.Name }),
                                         options => options.IncludingNestedObjects());
            });

            //clear test
            var customersToRemove = r.Aggregate((x1, x2) => x1.Union(x2).ToList());

            using var uow = DalService.CreateUnitOfWork();
            uow.BusinessPartners.RemoveAsync(customersToRemove.Select(c => c.Key).ToList()).Wait();
            uow.CompleteAsync().Wait();
        }
Esempio n. 13
0
 public void Dispose()
 {
     _addedQuotationsToCancelAtDispose.Where(q => q?.Key != null).ToList()
     .ForEach(q =>
     {
         using (var u = DalService.CreateUnitOfWork())
         {
             if (q.Key != null)
             {
                 u.Quotations.CancelAsync(q.Key.Value).Wait();
             }
             u.CompleteAsync().Wait();
         }
     });
 }
Esempio n. 14
0
        public async Task <OrderEntity> CloseDocument(int key, CancellationToken cancellationToken)
        {
            using (var transaction = DalService.CreateUnitOfWork())
            {
                var doc = await transaction.Quotations.FindByIdAsync(key);


                var closedDoc = await GetRepository(transaction).CloseAsync(key);

                cancellationToken.ThrowIfCancellationRequested();
                await transaction.CompleteAsync();

                return(closedDoc);
            }
        }
Esempio n. 15
0
        public void FindBySnWithInValidSnShouldReturnNull()
        {
            var unitOfWork = DalService.CreateUnitOfWork();

            //Given allocated Quotation repository
            unitOfWork.Quotations.CountAsync().Result.Should().BeGreaterThan(0);
            //and a invalid SN that match an existing entry
            const short invalidSn = short.MinValue;

            //When call to FIndBySN with the invalid SN
            var gainQuotation = unitOfWork.Quotations.FindByIdAsync(invalidSn).Result;

            //Then the returned quotation should be null
            gainQuotation.Should().BeNull();
        }
Esempio n. 16
0
        public void GetAllEmployeesShouldSucceed()
        {
            var unitOfWork = DalService.CreateUnitOfWork();

            //Given allocated employee's repository
            unitOfWork.Employees.CountAsync().Result.Should().BeGreaterThan(0);

            //When GetAll Employees
            var allEmployees = unitOfWork.Employees.GetAllAsync(PageRequest.Of(0, int.MaxValue)).Result.ToList();

            //Then the number of gain employees should match the number of  allocated employees
            allEmployees.Count().Should().Be(unitOfWork.Employees.CountAsync().Result);

            //and each employee should have an unique SN
            allEmployees.Select(e => e.Sn).Distinct().Count().Should().Be(allEmployees.Count());
        }
Esempio n. 17
0
        public async Task UpdateBusinessPartner(string url)
        {
            //Given a running server with businessPartners allocated in his database
            using var unitOfWork = DalService.CreateUnitOfWork();
            var bpsInDb = DbContext.BusinessPartners.Take(3).ToList();
            await unitOfWork.CompleteAsync();

            foreach (var businessPartnerFromDb in bpsInDb)
            {
                //When a client update the name of a valid BusinessPartner and ask for URL /api/BusinessPartner with the updated BusinessPartner
                var updateName = businessPartnerFromDb.Name + " UPDATENAME";
                businessPartnerFromDb.Name = updateName;
                var bpDtoToSend = Mapper.Map <BusinessPartnerDto>(businessPartnerFromDb);
                var jsonSend    = JsonConvert.SerializeObject(bpDtoToSend);
                var client      = TestServer.CreateClient();
                var response    = await client.PutAsync($"{url}/{businessPartnerFromDb.Key}", new StringContent(jsonSend, Encoding.UTF8, "application/json"));

                //Then the response will be successful
                response.EnsureSuccessStatusCode(); // Status Code 200-299

                //and the result body should be null
                var json = await response.Content.ReadAsStringAsync();

                var resultBpDto = JsonConvert.DeserializeObject <BusinessPartnerDto>(json);
                resultBpDto.Should().NotBeNull();

                //and the result should contain the updated name

                resultBpDto.Name.Should().Be(updateName);
                resultBpDto.Should().BeEquivalentTo(bpDtoToSend, config => config.Excluding(x => x.LastUpdateDateTime));
                var resultBp = Mapper.Map <BusinessPartner>(resultBpDto);

                Debug.Assert(businessPartnerFromDb.CreationDateTime != null, "businessPartnerFromDb.CreationDateTime != null");
                resultBp.LastUpdateDateTime.Should()
                .BeAfter(businessPartnerFromDb.LastUpdateDateTime ?? businessPartnerFromDb.CreationDateTime.Value);


                //and the BusinessPartner should be updated in database
                var updatedBusinessPartner = DalService.CreateUnitOfWork().BusinessPartners
                                             .FindAllAsync(c => c.Key == resultBpDto.Key,
                                                           PageRequest.Of(0, 10, Sort <BusinessPartner> .By(x => x.Key))).Result.ElementAt(0);
                updatedBusinessPartner.Name.Should().Be(updateName);
            }
        }
Esempio n. 18
0
        public void FindBySnWithValidSnShouldSucceed()
        {
            var unitOfWork = DalService.CreateUnitOfWork();

            //Given allocated Quotation repository
            unitOfWork.Quotations.CountAsync().Result.Should().BeGreaterThan(0);
            //and a valid SN that match an existing entry
            var validKey = unitOfWork.Quotations.GetAllAsync(PageRequest.Of(0, Int32.MaxValue)).Result
                           .ElementAt(new Random().Next(unitOfWork.Quotations.CountAsync().Result)).Key.Value;

            //When call to FIndBySN with the valid SN
            var gainQuotation = unitOfWork.Quotations.FindByIdAsync(validKey).Result;

            //Then the returned quotation should not be null
            gainQuotation.Should().NotBeNull();

            //and contain a SN that match the searched SN
            gainQuotation.Key.Value.Should().Be(validKey);
        }
Esempio n. 19
0
        public void FindByIdEmployeesShouldSucceed()
        {
            var unitOfWork = DalService.CreateUnitOfWork();

            //Given allocated employee's repository
            unitOfWork.Employees.CountAsync().Result.Should().BeGreaterThan(0);

            var allEmployees = unitOfWork.Employees.GetAllAsync(PageRequest.Of(0, int.MaxValue)).Result.ToList();
            var validSn      = unitOfWork.Employees.GetAllAsync(PageRequest.Of(0, int.MaxValue)).Result
                               .ElementAt(new Random().Next(allEmployees.Count() - 1)).Sn;
            //When call to FindByID  with a valid SN
            var employee = unitOfWork.Employees.FindByIdAsync(validSn).Result;

            //Then the employee should not be null
            employee.Should().NotBeNull();

            //and have the searched SN
            employee.Sn.Should().Be(validSn);
        }
Esempio n. 20
0
        public void CustomerWithBalanceMustHaveAccountFinanceRecordsToMatchIt()
        {
            //Given a BusinessPartner Repository with BusinessPartner that have a non zero balance
            var customersWithBalance = DalService.CreateUnitOfWork().BusinessPartners
                                       .FindAllAsync(c => c.Balance != 0,
                                                     PageRequest.Of(0, 100, Sort <BusinessPartner> .By(x => x.Key))).Result;

            customersWithBalance.Should().HaveCountGreaterThan(0);

            //When query BusinessPartner's account finance
            var customersAccountRecords = customersWithBalance.Select(c =>
                                                                      DalService.CreateUnitOfWork().BusinessPartners
                                                                      .GetAccountBalanceRecordsAsync(c.Key).Result).ToList();


            //Then he must have more then zero records
            customersAccountRecords.ForEach(rList => rList.Should().HaveCountGreaterThan(0));
            //and the sum of his record must match the total balance
            customersWithBalance.Zip(customersAccountRecords, (c, r) => new { BusinessPartner = c, RecordsList = r })
            .ToList().ForEach(a =>
                              a.RecordsList.Select(r => r.BalanceDebt).Sum().Should().Be(a.BusinessPartner.Balance));
        }
Esempio n. 21
0
        public void AddValidCustomerListShouldSucceed()
        {
            //Given a repository
            var numOfElementsBeforeAdding = DalService.CreateUnitOfWork().BusinessPartners.CountAsync().Result;

            //When add 10 diffident customers
            var customerList = Enumerable.Range(1, 10)
                               .Select(i => new BusinessPartner {
                Name = "TESTAddCustomerListToRepository " + i
            }).ToList();

            using var uow = DalService.CreateUnitOfWork();
            var customerListAfter = uow.BusinessPartners.AddAsync(customerList).Result.ToList();

            uow.CompleteAsync().Wait();


            //Then
            //the repository must be 10 elements bigger Customers.GetAllAsync().Result
            var numOfElementsAfterAdding = DalService.CreateUnitOfWork().BusinessPartners.CountAsync().Result;

            numOfElementsAfterAdding.Should().Be(numOfElementsBeforeAdding + 10);
            //and the added list must be of size 10
            customerListAfter.Should().HaveCount(10);
            //and the added list must contain a BusinessPartner id
            customerListAfter.TrueForAll(c => c.Key != null).Should().BeTrue();
            //and the repository must contain the added customers
            var customerAtRepository = DalService.CreateUnitOfWork().BusinessPartners
                                       .FindAllAsync(c => customerListAfter.Select(c2 => c2.Key).Contains(c.Key),
                                                     PageRequest.Of(0, 100, Sort <BusinessPartner> .By(x => x.Key))).Result;

            customerAtRepository.Select(c => c.Name).Should().BeEquivalentTo(customerList.Select(c => c.Name));

            //Clear Test
            using var uow2 = DalService.CreateUnitOfWork();
            uow2.BusinessPartners.RemoveAsync(customerListAfter.Select(c => c.Key).ToList()).Wait();
            uow2.CompleteAsync().Wait();
        }
Esempio n. 22
0
        public async Task UpdateOneValidBusinessPartnerShouldSucceed()
        {
            //Given a repository
            //with at least 10 diffident customers
            var bp = new BusinessPartner {
                Name = "TEST_UpdateBpRepository"
            };

            using var uow = DalService.CreateUnitOfWork();
            bp            = await uow.BusinessPartners.AddAsync(bp);

            await uow.CompleteAsync();

            //When update business partner with valid attrs
            using var uow1 = DalService.CreateUnitOfWork();
            (await uow1.BusinessPartners.FindByIdAsync(bp.Key)).Should().NotBeNull();
            bp.Phone2 = "053-555555";
            await uow1.BusinessPartners.UpdateAsync(bp);

            await uow1.CompleteAsync();


            //Then
            using var uow2 = DalService.CreateUnitOfWork();
            var result = await uow2.BusinessPartners.FindByIdAsync(bp.Key);

            result.Key.Should().Be(bp.Key);
            result.Should().BeEquivalentTo(bp, opt => opt
                                           .Excluding(x => x.LastUpdateDateTime)
                                           .Excluding(x => x.CreationDateTime)//TODO
                                           .IncludingNestedObjects()
                                           );

            //Clear Test
            using var uow3 = DalService.CreateUnitOfWork();
            uow3.BusinessPartners.RemoveAsync(bp.Key).Wait();
            await uow3.CompleteAsync();
        }
Esempio n. 23
0
        public void GetCustomerPagingTest()
        {
            //Given a linq to a database with at least 100 customers
            DalService.CreateUnitOfWork().BusinessPartners.CountAsync().Result.Should().BeGreaterOrEqualTo(100);
            //When activating a paging request
            const int page = 10;
            const int size = 6;
            var       customerPagingList = DalService.CreateUnitOfWork()
                                           .BusinessPartners.GetAllAsync(PageRequest.Of(page, size, Sort <BusinessPartner> .By(x => x.Key))).Result
                                           .ToList();

            //Then the result will be at the same size
            customerPagingList.Count().Should().Be(size);

            //and the result page must be at the correct position
            var allCustomers = DalService.CreateUnitOfWork().BusinessPartners
                               .GetAllAsync(PageRequest.Of(0, int.MaxValue, Sort <BusinessPartner> .By(x => x.Key))).Result
                               .ToList();

            allCustomers.GetRange(page * size, size).ToList()
            .Should().BeEquivalentTo(customerPagingList,
                                     options => options.WithoutStrictOrdering().IncludingNestedObjects());
        }
Esempio n. 24
0
        private QuotationEntity CreateValidQuotation()
        {
            var quotationCustomer = DalService.CreateUnitOfWork().BusinessPartners
                                    .FirstOrDefaultAsync(c => c.IsActive == true).Result;

            var quotationOwner = DalService.CreateUnitOfWork().Employees
                                 .FirstOrDefaultAsync(e => e.IsActive).Result;
            var quotationSalesman = DalService.CreateUnitOfWork().Salesmen
                                    .FirstOrDefaultAsync(s => s.ActiveStatus == SalesmanEntity.Status.Active).Result;

            return(new QuotationEntity
            {
                ExternalSn = "testQuotationSN",
                CustomerSn = quotationCustomer.Key,
                CustomerName = quotationCustomer.Name,
                Comments = "this is a test quotation",

                OwnerEmployeeSn = quotationOwner.Sn,
                SalesmanSn = quotationSalesman.Sn,
                Items = new List <DocItemEntity>()
                {
                    new DocItemEntity()
                    {
                        Code = "999999",
                        Description = "testDescription3",
                        PricePerQuantity = 100,
                        Quantity = 1.5M,
                        Details = "testDetails",
                        Comments = "testComments",
                        DiscountPercent = 10,
                        Properties = new Dictionary <string, object>()
                    }
                },

                ValidUntil = DateTime.Now.Date.AddDays(1)
            });
        }
Esempio n. 25
0
        public void AddNewInvalidQuotationShouldFail()
        {
            var numOfQuotationBefore = DalService.CreateUnitOfWork().Quotations.CountAsync().Result;
            //Given an invalid new quotation
            var invalidQuotation = CreateValidQuotation();

            invalidQuotation.Items = new List <DocItemEntity>(); //quotation without items is invalid
                                                                 //When adding the new quotation
            using (var unitOfWork = DalService.CreateUnitOfWork())
            {
                QuotationEntity addedQuotation = null;
                var             transaction    = 0;
                Exception       exception      = null;
                try
                {
                    addedQuotation = unitOfWork.Quotations.AddAsync(invalidQuotation).Result;
                    _addedQuotationsToCancelAtDispose.Add(addedQuotation);
                    transaction = unitOfWork.CompleteAsync().Result;
                }
                catch (Exception e)
                {
                    exception = e;
                }
                finally
                {
                    //Then the result should be null
                    addedQuotation.Should().BeNull();
                    //and the transaction should fail
                    transaction.Should().Be(0);
                    //and throw exception
                    exception.Should().NotBeNull();
                    //and the repository should not affected
                    var numOfQuotationAfter = DalService.CreateUnitOfWork().Quotations.CountAsync().Result;
                    numOfQuotationAfter.Should().Be(numOfQuotationBefore);
                }
            }
        }
Esempio n. 26
0
 public BusinessPartnerRepositoryTests(DatabaseFixture fixture) : base(fixture)
 {
     _customerBeforeTesting = DalService.CreateUnitOfWork().BusinessPartners.GetAllAsync(
         PageRequest.Of(0, int.MaxValue, Sort <BusinessPartner> .By(x => x.Name)))
                              .Result.Select(c => c.Key).ToList();
 }