Exemplo n.º 1
0
        public async Task Fetch_All_Policies_Returns_All()
        {
            //Arrange
            var policies = new List <Policy>
            {
                new Policy
                {
                    PolicyNumber = 123456789
                }
            }.AsQueryable();
            var dbcontext = new Mock <PolicyDatabaseEntities>();
            var dbset     = new Mock <DbSet <Policy> >();

            dbset.As <IDbAsyncEnumerable <Policy> >()
            .Setup(m => m.GetAsyncEnumerator())
            .Returns(new TestDbAsyncEnumerator <Policy>(policies.GetEnumerator()));

            dbset.As <IQueryable <Policy> >()
            .Setup(m => m.Provider)
            .Returns(new TestDbAsyncQueryProvider <Policy>(policies.Provider));

            dbset.As <IQueryable <Policy> >().Setup(m => m.Expression).Returns(policies.Expression);
            dbset.As <IQueryable <Policy> >().Setup(m => m.ElementType).Returns(policies.ElementType);
            dbset.As <IQueryable <Policy> >().Setup(m => m.GetEnumerator()).Returns(policies.GetEnumerator());

            dbcontext.Setup(x => x.Policies).Returns(dbset.Object);

            var primaryInsureds = new List <DAL.PrimaryInsured>
            {
                new DAL.PrimaryInsured
                {
                    PolicyNumber = 123456789
                }
            }.AsQueryable();

            var dbset2 = new Mock <DbSet <DAL.PrimaryInsured> >();

            dbset2.As <IDbAsyncEnumerable <DAL.PrimaryInsured> >()
            .Setup(m => m.GetAsyncEnumerator())
            .Returns(new TestDbAsyncEnumerator <DAL.PrimaryInsured>(primaryInsureds.GetEnumerator()));

            dbset2.As <IQueryable <DAL.PrimaryInsured> >()
            .Setup(m => m.Provider)
            .Returns(new TestDbAsyncQueryProvider <DAL.PrimaryInsured>(primaryInsureds.Provider));

            dbset2.As <IQueryable <DAL.PrimaryInsured> >().Setup(m => m.Expression).Returns(primaryInsureds.Expression);
            dbset2.As <IQueryable <DAL.PrimaryInsured> >().Setup(m => m.ElementType).Returns(primaryInsureds.ElementType);
            dbset2.As <IQueryable <DAL.PrimaryInsured> >().Setup(m => m.GetEnumerator()).Returns(primaryInsureds.GetEnumerator());

            dbcontext.Setup(x => x.PrimaryInsureds).Returns(dbset2.Object);

            var sut = new PolicyRepository(dbcontext.Object);

            //Act
            var results = await sut.FetchAll();

            //Assert
            Assert.IsInstanceOfType(results, typeof(IEnumerable <InsurancePolicy>));
            Assert.AreEqual(policies.First().PolicyNumber.ToString(), results.First().PolicyNumber);
        }
Exemplo n.º 2
0
 public IntegrationTest()
 {
     context                  = GetDbHelper.GetDbContext();
     PolicyRepository         = new PolicyRepository(context);
     CustomerRepository       = new CustomerRepository(context);
     CustomerPolicyRepository = new CustomerPolicyRepository(context);
 }
Exemplo n.º 3
0
        public void CannotAddAPolicyAlreadyExisting()
        {
            // Arrange
            var repository = new PolicyRepository();
            var controller = new PolicyController(repository);
            var newPolicy  = new Policy()
            {
                PolicyNumber = 462946,
                PolicyHolder = new PolicyHolder()
                {
                    Name   = "Peter Parker",
                    Age    = 34,
                    Gender = Gender.Male
                }
            };
            // Act
            var response = controller.Add(newPolicy);

            // Assert
            var policies = ((IList <Policy>)repository.Get());

            Assert.AreEqual(7, policies.Count);
            Assert.IsTrue(policies.IndexOf(newPolicy) == -1);
            Assert.IsInstanceOfType(response.Result, typeof(BadRequestResult));
        }
        private static void AddPolicyRegistry(ServiceCollection services)
        {
            var registry = services.AddPolicyRegistry();

            registry.Add("RetryPolicy", PolicyRepository.RetryPolicy());
            registry.Add("CircuitBreakerPolicy", PolicyRepository.CircuitBreakerPolicy());

            var handlerMock = new Mock <HttpMessageHandler>(MockBehavior.Strict);

            handlerMock
            .Protected()
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>()
                )
            .ReturnsAsync(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent("Nothing"),
            })
            .Verifiable();

            services.AddHttpClient <ISampleTestService, SampleTestService>((serviceCollection, client) =>
            {
                client.BaseAddress = new Uri("http://gonowhere.com");
                client.Timeout     = new TimeSpan(10000);
            })
            .ConfigurePrimaryHttpMessageHandler(sp => handlerMock.Object)
            .AddPolicyHandlerFromRegistry("RetryPolicy")
            .AddPolicyHandlerFromRegistry("CircuitBreakerPolicy");
        }
Exemplo n.º 5
0
        public void CannotUpdateAPolicyThatDoesntExist()
        {
            // Arrange
            var repository   = new PolicyRepository();
            var controller   = new PolicyController(repository);
            var updatePolicy = new Policy()
            {
                PolicyNumber = 1111111,
                PolicyHolder = new PolicyHolder()
                {
                    Name   = "Peter Parker",
                    Age    = 34,
                    Gender = Gender.Male
                }
            };

            // Act
            var response = controller.Update(383002, updatePolicy);

            // Assert
            var policies = ((IList <Policy>)repository.Get());

            Assert.AreEqual(7, policies.Count);
            Assert.IsTrue(policies.IndexOf(updatePolicy) == -1);
            Assert.IsInstanceOfType(response.Result, typeof(NotFoundResult));
        }
Exemplo n.º 6
0
        public void Setup()
        {
            var userPolicies = new PolicyLookup <string, MyUserSecurityContext>
            {
                {
                    "user1",
                    new CustomerPolicy(
                        new CustomerPolicy.CustomerPolicyData(
                            create: false,
                            delete: false,
                            view: true,
                            update: false,
                            viewPersonnel: false,
                            viewVip: true,
                            viewBalanceLimit: 5000,
                            viewRealNames: false
                            ))
                }
            };

            var groupPolicies = new PolicyLookup <string, MyUserSecurityContext>();
            var rolePolicies  = new PolicyLookup <RolesEnum, MyUserSecurityContext>();

            var userPolicyRepo  = new SecurityObjectPolicyRepository <string, MyUserSecurityContext>(userPolicies);
            var groupPolicyRepo = new SecurityObjectPolicyRepository <string, MyUserSecurityContext>(groupPolicies);
            var rolePolicyRepo  = new SecurityObjectPolicyRepository <RolesEnum, MyUserSecurityContext>(rolePolicies);

            var policyRepo = new PolicyRepository(userPolicyRepo, groupPolicyRepo, rolePolicyRepo);

            var userSecurityContext1 = new MyUserSecurityContext("user1", new[] { "g1", "g2" }, new RolesEnum[] { RolesEnum.Cashier });

            UserContexts.User1 = new UserSecuritySchema <MyUserSecurityContext>(policyRepo, userSecurityContext1);
        }
Exemplo n.º 7
0
        public void UpdateAPolicy()
        {
            // Arrange
            var repository   = new PolicyRepository();
            var controller   = new PolicyController(repository);
            var updatePolicy = new Policy()
            {
                PolicyNumber = 383002,
                PolicyHolder = new PolicyHolder()
                {
                    Name   = "Peter Parker",
                    Age    = 34,
                    Gender = Gender.Male
                }
            };

            // Act
            var response = controller.Update(383002, updatePolicy);

            // Assert
            var policies = ((IList <Policy>)repository.Get());

            Assert.AreEqual(7, policies.Count);
            Assert.AreEqual(response.Value, updatePolicy);
            Assert.IsTrue(policies.IndexOf(updatePolicy) > -1);
            Assert.IsInstanceOfType(response.Value, typeof(Policy));
        }
Exemplo n.º 8
0
        public PolicyAPIController()
        {
            var context   = new AppDbContext();
            var policyRep = new PolicyRepository(context);

            _policyService = new PolicyService(policyRep, context);
        }
Exemplo n.º 9
0
        public PoliciesControl()
        {
            repository = new PolicyRepository();

            InitializeComponent();

            refresh();
        }
Exemplo n.º 10
0
        public PolicyService(PolicyRepository pRepository)
        {
            this.policyRepository = pRepository;
            var config = new MapperConfiguration(
                cfg => cfg.CreateMap <PolicyDTO, PolicyEntity>());

            mapper = config.CreateMapper();
        }
 public UnitOfWork(PolicyDbContext policyDbContext)
 {
     _policyDbContext = policyDbContext;
     tx = _policyDbContext.Database.BeginTransaction();
     _offerRepository   = new OfferRepository(policyDbContext);
     _policyRepository  = new PolicyRepository(policyDbContext);
     _messageRepository = new MessageRepository(policyDbContext);
 }
Exemplo n.º 12
0
 public UnitOfWork(GAPTestEntities context)
 {
     _context         = context;
     Users            = new UserRepository(_context);
     Clients          = new ClientRepository(_context);
     Policies         = new PolicyRepository(_context);
     ClienHasPolicies = new ClientHasPolicyRepository(_context);
 }
Exemplo n.º 13
0
        public void TestDeleteWhenPolicyExists()
        {
            // Arrange

            // We configure the in-memory database
            var dbOptions = new DbContextOptionsBuilder <GAPSegurosContext>()
                            .UseInMemoryDatabase(databaseName: "Add_writes_to_database")
                            .Options;

            var toBeDeletedPolicy = new Policy()
            {
                PolicyId = 1, RiskType = new RiskType()
            };
            //toBeDeletedPolicy.RiskType.Policy.Add(toBeDeletedPolicy);

            // We define the initial data that will be in the DB
            var articlesSeeds = new List <Policy>();

            articlesSeeds.Add(toBeDeletedPolicy);
            articlesSeeds.Add(new Policy()
            {
                PolicyId = 2, RiskType = new RiskType()
            });


            // Run the test against one instance of the context
            using (var context = new GAPSegurosContext(dbOptions))
            {
                context.AddRange(articlesSeeds);

                context.SaveChanges();
            }

            // Use a separate instance of the context to verify correct data was saved to database
            using (var context = new GAPSegurosContext(dbOptions))
            {
                var policyRepository = new PolicyRepository(context);

                // Act
                var controller = new PoliciesController(policyRepository, null, null);
                var result     = controller.Delete(id: 1).Result;

                // Assert values

                // We check that the IActionResult received is an instance of ViewResult
                var viewResult = Assert.IsType <ViewResult>(result);

                // We check that the model send to the view is a Policy instance
                var model = Assert.IsAssignableFrom <Policy>(viewResult.ViewData.Model);

                // We check the Policy entity but not the RiskType entity because of circular reference
                model.Should().BeEquivalentTo(toBeDeletedPolicy,
                                              options => options
                                              .Excluding(ctx => ctx.SelectedMemberInfo.MemberType == typeof(RiskType))
                                              );
            }
        }
Exemplo n.º 14
0
 public UnitOfWork(ApplicationDbContext context)
 {
     _context     = context;
     Policies     = new PolicyRepository(context);
     Coverages    = new CoverageRepository(context);
     Risks        = new RiskRepository(context);
     UserPolicies = new UserPolicyRepository(context);
     Users        = new UserRepository(context);
 }
Exemplo n.º 15
0
 public PoliciesDetailsDialog(DialogInterface dialogInterface)
 {
     this.dialogInterface = dialogInterface;
     InitializeComponent();
     FormBorderStyle = FormBorderStyle.FixedSingle;
     repository      = new PolicyRepository();
     initializeCollectionsDropdown();
     initializeUsersDropdown();
 }
Exemplo n.º 16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PolicyServiceTest"/> class.
        /// </summary>
        public PolicyServiceTest()
        {
            var optionsBuilder = new DbContextOptionsBuilder <InsuranceContext>();

            optionsBuilder.UseSqlServer("Server=localhost\\SQLEXPRESS;Database=Insurance;Trusted_Connection=True;MultipleActiveResultSets=true");

            _insuranceContext = new InsuranceContext(optionsBuilder.Options);
            _policyRepository = new PolicyRepository(_insuranceContext);
            _policyService    = new PolicyService(_policyRepository);
        }
Exemplo n.º 17
0
        public ActionResult Policies()
        {
            List <Policy> policies;

            using (PolicyRepository pr = new PolicyRepository())
            {
                policies = pr.GetAllPolicies();
            }
            return(View(policies));
        }
Exemplo n.º 18
0
 public PolicyService(PolicyRepository policyRepository)
 {
     this.policyRepository = policyRepository;
     #region Init Log
     Log.Logger = new LoggerConfiguration()
                  .MinimumLevel.Debug()
                  .WriteTo.File(ConfigurationManager.AppSettings["ErrorLog"].ToString(), fileSizeLimitBytes: 1000)
                  .CreateLogger();
     #endregion
 }
Exemplo n.º 19
0
        public ActionResult Edit(int id)
        {
            var viewModel = new PolicyViewModel();

            using (PolicyRepository pr = new PolicyRepository())
            {
                viewModel.Policy = pr.SearchPolicy(id);
            }
            ViewBag.Operation = "Save";
            return(View(viewModel));
        }
        public void Initialize()
        {
            _fundingStreamId   = NewRandomString();
            _fundingStreamName = NewRandomString();

            _policiesApiClient = Substitute.For <IPoliciesApiClient>();

            _policyRepository = new PolicyRepository(
                _policiesApiClient,
                DatasetsResilienceTestHelper.GenerateTestPolicies());
        }
Exemplo n.º 21
0
 public ContentService(RequestContext c, 
                     HtmlTemplateRepository templates,
                     PolicyRepository policies,
                     CustomUrlRepository customUrls,
                     ContentColumnRepository cols)
 {
     context = c;
     HtmlTemplates = templates;
     this.Policies = policies;
     this.CustomUrls = customUrls;
     this.Columns = cols;
 }
Exemplo n.º 22
0
        public void GetAllPolicies()
        {
            // Arrange
            var repository = new PolicyRepository();
            var controller = new PolicyController(repository);

            // Act
            IList <Policy> response = (IList <Policy>)controller.Get();

            // Assert
            Assert.AreEqual(7, response.Count);
        }
Exemplo n.º 23
0
        public OwnerType(PolicyRepository policyRepository)
        {
            Field(t => t.Id);
            Field(t => t.Name);

            Field <ListGraphType <PolicyType> >(
                "policies",
                resolve: context =>
            {
                return(policyRepository.GetForOwner(context.Source.Id));
            }
                );
        }
Exemplo n.º 24
0
        public void DeleteAPolicy()
        {
            // Arrange
            var repository = new PolicyRepository();
            var controller = new PolicyController(repository);

            // Act
            var response = controller.Remove(383002);

            // Assert
            Assert.IsTrue(response.Value);
            Assert.AreEqual(6, ((IList <Policy>)repository.Get()).Count);
        }
Exemplo n.º 25
0
        public void CannotDeleteAPolicyThatDoesntExist()
        {
            // Arrange
            var repository = new PolicyRepository();
            var controller = new PolicyController(repository);

            // Act
            var response = controller.Remove(1);

            // Assert
            Assert.AreEqual(7, ((IList <Policy>)repository.Get()).Count);
            Assert.IsInstanceOfType(response.Result, typeof(NotFoundResult));
        }
Exemplo n.º 26
0
        public async Task Add_Policy_Call_SaveChanges_Asnyc()
        {
            //Arrange
            AutoMapperConfig.RegisterMappings();

            var insurancePolicy = new InsurancePolicy
            {
                PolicyNumber  = "123456789",
                EffectiveDate = DateTime.Now,
                Expiration    = DateTime.Now,
                InsuredRisk   = new InsuredRisk
                {
                    ConstructionType = new Models.ConstructionType
                    {
                        Id = "1"
                    },
                    YearBuilt = "01-01-1900",
                    Location  = new Models.Address
                    {
                        Street  = "123 Main",
                        City    = "Wales",
                        State   = "WI",
                        ZipCode = "53193"
                    }
                },
                PrimaryInsured = new Models.PrimaryInsured
                {
                    PrimaryInsuredAddress = new Models.Address
                    {
                        Street  = "123 Main",
                        City    = "Wales",
                        State   = "WI",
                        ZipCode = "53193"
                    },
                    PrimaryInsuredFirstName = "Stephan",
                    PrimaryInsuredLastName  = "Frank"
                }
            };
            var dbset     = new Mock <DbSet <Policy> >();
            var dbcontext = new Mock <PolicyDatabaseEntities>();
            var sut       = new PolicyRepository(dbcontext.Object);

            dbcontext.Setup(m => m.Policies).Returns(dbset.Object);

            //Act
            await sut.Add(insurancePolicy);

            //Assert
            dbset.Verify(m => m.Add(It.IsAny <Policy>()), Times.Once());
            dbcontext.Verify(m => m.SaveChangesAsync(), Times.Once());
        }
Exemplo n.º 27
0
 public ActionResult Delete(int id)
 {
     using (PolicyRepository pr = new PolicyRepository())
     {
         try
         {
             pr.DeletePolicy(id);
         }
         catch (Exception)
         {
             return(View("Error"));
         }
     }
     return(RedirectToAction("Policies"));
 }
Exemplo n.º 28
0
 public ActionResult Edit(Policy policy, int id)
 {
     policy.PolicyNumber = id;
     using (PolicyRepository pr = new PolicyRepository())
     {
         try
         {
             pr.EditPolicy(policy);
         }
         catch (Exception)
         {
             return(View("Error"));
         }
     }
     return(RedirectToAction("Policies"));
 }
        private static void AddHttpClient(IServiceCollection services)
        {
            //            var policies = new PolicyRepository();
            //            services.AddSingleton<IPolicyRepository>(policies);

            // Pool HTTP connections with HttpClientFactory to prevent thread pool starvation,
            // Register SampleTestService as a Typed Service Agent to use HttpClient.
            // Ensure that intermittent issues are handled with a retry policy, and spamming prevented with a circuit breaker.
            // Delay recycling clients to every 5 mins (So every 5 mins guaranteed to hit DNS)
            services.AddHttpClient <ISampleTestService, SampleTestService>((serviceCollection, client) =>
            {
                var config         = serviceCollection.GetService <IOptions <Config> >().Value;
                client.BaseAddress = new Uri(config.BaseAddress);
            })
            .AddPolicyHandler(PolicyRepository.RetryPolicy())
            .AddPolicyHandler(PolicyRepository.CircuitBreakerPolicy())
            .SetHandlerLifetime(TimeSpan.FromMinutes(5));
        }
Exemplo n.º 30
0
        protected bool doCheck(long targetId, User user, bool throwException = true)
        {
            if (before(user, targetId))
            {
                return(true);
            }

            var found = new PolicyRepository().query()
                        .where ("user_id", "=", user?.ID ?? 0)
                        .where ("target_id", "=", targetId)
                        .where ("type", "=", type)
                        .first(false);

            if (found == null && throwException)
            {
                throw new UnauthorizedException();
            }

            return(found != null);
        }
Exemplo n.º 31
0
        public void Initialize()
        {
            _policyRepository = new PolicyRepository();

            _client = new ClientModel()
            {
                EMail             = "*****@*****.**",
                Name              = "Иванов Иван Иванович",
                BirthDate         = new DateTime(1990, 01, 01),
                DriverLicenseDate = new DateTime(2011, 05, 07),
                PasswordHash      = "pass123"
            };

            _user = new User(
                "*****@*****.**",
                "Иванов Иван Иванович",
                new DateTime(1990, 01, 01),
                new DateTime(2011, 05, 07),
                "pass123"
                );
        }