Пример #1
0
 public async Task Plain_text_footer_values_that_are_web_urls_are_replaced(string footerText, string expectedUrl)
 {
     // ARRANGE
     var testData  = new TestDataFactory();
     var changeLog = new ApplicationChangeLog()
     {
         testData.GetSingleVersionChangeLog("1.2.3", entries: new[]
Пример #2
0
        public void Should_clear_all_cache_strategies_for_policy()
        {
            var controllerName   = NameHelper.Controller <AdminController>();
            var policyContainers = new List <PolicyContainer>
            {
                TestDataFactory.CreateValidPolicyContainer(controllerName, "Index"),
                TestDataFactory.CreateValidPolicyContainer(controllerName, "ListPosts"),
                TestDataFactory.CreateValidPolicyContainer(controllerName, "AddPost")
            };

            var conventionPolicyContainer = new ConventionPolicyContainer(policyContainers.Cast <IPolicyContainerConfiguration>().ToList());

            conventionPolicyContainer.Cache <RequireAnyRolePolicy>(Cache.PerHttpRequest);
            conventionPolicyContainer.Cache <RequireAllRolesPolicy>(Cache.PerHttpRequest);

            // Act
            conventionPolicyContainer.ClearCacheStrategyFor <RequireAnyRolePolicy>();

            // Assert
            var containers = policyContainers.ToList();

            Assert.That(containers[0].CacheStrategies.Single().PolicyType, Is.EqualTo(typeof(RequireAllRolesPolicy)));
            Assert.That(containers[1].CacheStrategies.Single().PolicyType, Is.EqualTo(typeof(RequireAllRolesPolicy)));
            Assert.That(containers[2].CacheStrategies.Single().PolicyType, Is.EqualTo(typeof(RequireAllRolesPolicy)));
        }
Пример #3
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseSwagger();

            //Swagger JSON endponint
            app.UseSwaggerUI(s =>
            {
                s.SwaggerEndpoint("/swagger/v1/swagger.json", "Webbet API");
            });

            app.UseCors(options => options.WithOrigins(Configuration["ApplicationSettings:ClientUrl"].ToString())
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowAnyOrigin());
            app.UseAuthentication();

            app.UseMvc();

            //Create database if not exist
            using (var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetRequiredService <WebBetDbContext>();
                //context.Database.EnsureCreated();
                context.Database.Migrate();

                //Fill with test data
                TestDataFactory.Fill(context);
            }
        }
Пример #4
0
        public async Task Update_should_modify_video()
        {
            //Arrange
            EditVideoRequest request = TestDataFactory.CreateEditVideoRequest();

            request.KindId  = new Guid("2fd37626-0b1d-4d51-a243-0bc4266a7a99");
            request.GenreId = new Guid("9dc0d6f2-a3d8-41a9-8393-d832c0b7a6e9");
            Guid Id = new Guid("eaa0B9d4-4A2d-496e-8a68-a36cd0758abb");

            HttpClient    client      = Factory.CreateClient();
            StringContent httpContent = new StringContent(JsonConvert.SerializeObject(request),
                                                          Encoding.UTF8, "application/json");

            //Act
            HttpResponseMessage response = await client.PutAsync($"{Url}/{Id}", httpContent);

            //Assert
            response.EnsureSuccessStatusCode();
            string responseContent = await response.Content.ReadAsStringAsync();

            Video responseEntity = JsonConvert.DeserializeObject <Video>(responseContent);

            responseEntity.Should().BeEquivalentTo(request, o => o.Excluding(x => x.Id));
            Assert.Equal(Id, responseEntity.Id);
        }
        public void CreateNewEmployee_1000NewEmployeesCreated_ShouldBeExecutedInLessThan10Sec()
        {
            //---------------------------------- ARRANGE -------------------------------------

            //expected loading time is 10 seconds
            TimeSpan EXPECTED_EXECUTION_DURATION = TimeSpan.FromSeconds(10);

            Stopwatch stopwatch = new Stopwatch();

            //string the stopwatch
            stopwatch.Start();

            //---------------------------------- ACT -------------------------------------

            //test method goes here
            for (int i = 0; i < 1000; i++)
            {
                EmployeeBLL.CreateNewEmployee(TestDataFactory.CreateNewObjectWithValidNewEmployeeData());
            }

            //---------------------------------- ASSERT -------------------------------------

            //stopping the stopwatch
            stopwatch.Stop();

            TimeSpan ACTUAL_EXECUTION_DURATION = stopwatch.Elapsed;

            Console.WriteLine("Method executed in toal seconds : " + ACTUAL_EXECUTION_DURATION.TotalSeconds);

            Assert.IsTrue(stopwatch.Elapsed < EXPECTED_EXECUTION_DURATION,
                          string.Format(System.Globalization.CultureInfo.CurrentCulture,
                                        "Loading time ({0:#,##0.0} seconds) exceed the expected time ({1:#,##0.0} seconds).",
                                        ACTUAL_EXECUTION_DURATION.TotalSeconds, EXPECTED_EXECUTION_DURATION.TotalSeconds));
        }
Пример #6
0
        public void Should_return_results()
        {
            // Arrange
            var roles = new List <object> {
                UserRole.Owner
            }.ToArray();
            const bool   isAuthenticated = true;
            const string failureOccured  = "Failure occured";
            var          context         = TestDataFactory.CreateSecurityContext(isAuthenticated, roles);

            var policy = new Mock <ISecurityPolicy>();

            policy.Setup(x => x.Enforce(It.IsAny <ISecurityContext>())).Returns(PolicyResult.CreateFailureResult(policy.Object, failureOccured));

            var policyContainer = new PolicyContainer(TestDataFactory.ValidControllerName, TestDataFactory.ValidActionName, TestDataFactory.CreateValidPolicyAppender());

            policyContainer.AddPolicy(policy.Object);

            // Act
            var results = policyContainer.EnforcePolicies(context);

            // Assert
            Assert.That(results.Count(), Is.EqualTo(1));
            Assert.That(results.Single().ViolationOccured, Is.True);
            Assert.That(results.Single().Message, Is.EqualTo(failureOccured));
        }
        public void Should_create_security_context_from_external_ioc()
        {
            // Arrange
            const bool status = true;
            var        roles  = new object[4];

            var iocContext = TestDataFactory.CreateSecurityContext(status, roles);

            FakeIoC.GetAllInstancesProvider = () => new List <ISecurityContext>
            {
                iocContext
            };

            SecurityConfigurator.Configure(c =>
            {
                c.ResolveServicesUsing(FakeIoC.GetAllInstances);
            });

            // Act
            var context = SecurityContext.Current;

            // Assert
            Assert.That(context.Data, Is.TypeOf(typeof(ExpandoObject)));
            Assert.That(context.CurrentUserIsAuthenticated(), Is.EqualTo(status));
            Assert.That(context.CurrentUserRoles(), Is.EqualTo(roles));
            Assert.That(context.Runtime, Is.Not.Null);
            Assert.AreSame(context, iocContext);
        }
        public void MeasureAvailabilityNoDataFirstDates()
        {
            var(_, product, _, feature) = TestDataFactory.BuildCustomerProductJourneyFeature();
            var source = TestDataFactory.BuildSource(product);

            var indicator = IndicatorEntity.Factory.Create(feature, source, DateTime.Now, "test");

            var sourceItemA = SourceEntity.Factory.CreateItem(source,
                                                              OwlveyCalendar.January201905, 900, 1200, DateTime.Now, "test", SourceGroupEnum.Availability);
            var sourceItemB = SourceEntity.Factory.CreateItem(source,
                                                              OwlveyCalendar.EndJanuary2019,
                                                              900, 1200, DateTime.Now, "test", SourceGroupEnum.Availability);

            source.SourceItems.Add(sourceItemA);
            source.SourceItems.Add(sourceItemB);

            var aggregate = new SourceDailyAggregate(indicator.Source,
                                                     new Core.Values.DatePeriodValue(
                                                         OwlveyCalendar.StartJanuary2019,
                                                         OwlveyCalendar.EndJanuary2019));

            var availabilities = aggregate.MeasureAvailability();

            Assert.Equal(2, availabilities.Count());
            Assert.Equal(0.75m, availabilities.ElementAt(0).Measure.Availability);
            Assert.Equal(0.75m, availabilities.ElementAt(1).Measure.Availability);
        }
Пример #9
0
        public void Create_WhenInputDataCorrect_ShouldReturnCorrectFunction()
        {
            //arrange
            ExpressionTreeGenerator <Source, Destination> underTest = new ExpressionTreeGenerator <Source, Destination>();
            var    valueToTest = TestDataFactory.CreatePropertyList();
            Source parameter   = new Source()
            {
                EqualValueTypeProperty = 12,
                CastValueTypeProperty  = 13.5F,
                NotCastTypeProperty    = 48,

                EqualRefTypeProperty     = new List <int>(),
                BaseRefTypeProperty      = new List <int>(),
                DifferentRefTypeProperty = new DateTime()
            };
            Expression <Func <Source, Destination> > expectedBehavior = source => new Destination()
            {
                EqualValueTypeProperty = source.EqualValueTypeProperty,
                CastValueTypeProperty  = source.CastValueTypeProperty,

                EqualRefTypeProperty = source.EqualRefTypeProperty,
                BaseRefTypeProperty  = source.BaseRefTypeProperty
            };

            //act
            var actualBehavior = underTest.Create(valueToTest);

            //assert
            var actual = actualBehavior.Compile().Invoke(parameter);
            var expect = expectedBehavior.Compile().Invoke(parameter);

            Assert.Equal(actual, expect, Destination.DestinationComparer);
        }
Пример #10
0
 public void SetUp()
 {
     _convention = new FindByPolicyNameConvention
     {
         PolicyViolationHandlerProvider = () => TestDataFactory.CreatePolicyViolationHandlers()
     };
 }
Пример #11
0
        public void Constructor_SetsMethodCall()
        {
            var methodCall = TestDataFactory.CreateMethodCallInfo(() => Console.WriteLine());
            var subject    = new Setup(methodCall);

            Assert.AreSame(methodCall, subject.MethodCall);
        }
Пример #12
0
        public void CreateNewEmployee_SupervisorsCountryIsNotSame_ShouldThrowException()
        {
            //---------------------------------- ARRANGE -------------------------------------

            const string SUPERVISOR_COUNTRY = "USA";
            const string EMPLOYEE_COUNTRY   = "UK";

            //creating sample data for other employee, that would contain the different COUNTRY of the new employee
            Employee supervisorEmployee = TestDataFactory.CreateNewObjectWithValidExistingEmployeeData();

            supervisorEmployee.Country = SUPERVISOR_COUNTRY;

            //populating sample data to ObjectSet container that would be considered as the data source in mock database for employee entities
            employeeObjectSet = new FakeObjectSet <Employee>();
            employeeObjectSet.AddObject(supervisorEmployee);

            //setting up the mock database with sample object
            mockDatabaseConext.Setup(db => db.Employees).Returns(employeeObjectSet);

            //creating sample data for new employee, that would contain the different COUNTRY of another employee loaded in mock database
            Employee newEmployee = TestDataFactory.CreateNewObjectWithValidNewEmployeeData();

            newEmployee.Country    = EMPLOYEE_COUNTRY;
            newEmployee.Supervisor = supervisorEmployee;

            //---------------------------------- ACT -------------------------------------

            //perform the operation that is under test
            employeeBLL.CreateNewEmployee(newEmployee);
        }
Пример #13
0
        public async Task Execute_does_not_replace_commit_references_if_no_entry_can_be_found()
        {
            // ARRANGE
            var testData = new TestDataFactory();

            var sut = new ResolveEntryReferencesTask(m_Logger);

            var footer = new ChangeLogEntryFooter(
                new CommitMessageFooterName("footer-name"),
                new CommitReferenceTextElement("some-text", TestGitIds.Id3)
                );
            var changelog = new ApplicationChangeLog()
            {
                testData.GetSingleVersionChangeLog("1.0", entries: new[]
                {
                    testData.GetChangeLogEntry(commit: TestGitIds.Id1),
                    testData.GetChangeLogEntry(commit: TestGitIds.Id2, footers: new[] { footer })
                })
            };

            // ACT
            var result = await sut.RunAsync(changelog);

            // ASSERT
            Assert.Equal(ChangeLogTaskResult.Success, result);
            var commitReference = Assert.IsType <CommitReferenceTextElement>(footer.Value);

            Assert.Equal("some-text", commitReference.Text);
            Assert.Equal(TestGitIds.Id3, commitReference.CommitId);
        }
Пример #14
0
        public async Task Execute_replaces_commit_references_if_commit_refers_to_a_change_log_entry_in_a_different_version()
        {
            // ARRANGE
            var testData = new TestDataFactory();

            var sut = new ResolveEntryReferencesTask(m_Logger);

            var footer = new ChangeLogEntryFooter(
                new CommitMessageFooterName("footer-name"),
                new CommitReferenceTextElement("some-text", TestGitIds.Id1)
                );
            var entry1 = testData.GetChangeLogEntry(commit: TestGitIds.Id1);
            var entry2 = testData.GetChangeLogEntry(commit: TestGitIds.Id2, footers: new[] { footer });

            var changelog = new ApplicationChangeLog()
            {
                testData.GetSingleVersionChangeLog("2.0", entries: new[] { entry1 }),
                testData.GetSingleVersionChangeLog("1.0", entries: new[] { entry2 })
            };

            // ACT
            var result = await sut.RunAsync(changelog);

            // ASSERT
            Assert.Equal(ChangeLogTaskResult.Success, result);
            var entryReference = Assert.IsType <ChangeLogEntryReferenceTextElement>(footer.Value);

            Assert.Equal("some-text", entryReference.Text);
            Assert.Same(entry1, entryReference.Entry);
        }
Пример #15
0
        public async Task Executes_does_not_add_a_commit_link_if_a_link_is_already_set(string footerValue)
        {
            // ARRANGE
            var uri            = new Uri("https://example.com");
            var footer         = new ChangeLogEntryFooter(new CommitMessageFooterName("some-footer"), new WebLinkTextElement(footerValue, uri));
            var expectedCommit = new TestDataFactory().GetGitCommit();

            m_GitRepositoryMock
            .Setup(x => x.TryGetCommit(footerValue))
            .Returns(expectedCommit);

            var sut = new ParseCommitReferencesTask(m_Logger, m_GitRepositoryMock.Object);

            // ACT
            var result = await sut.RunAsync(GetChangeLogFromFooter(footer));

            // ASSERT
            Assert.Equal(ChangeLogTaskResult.Success, result);

            Assert.NotNull(footer.Value);
            var webLink = Assert.IsType <WebLinkTextElement>(footer.Value);

            Assert.Equal(uri, webLink.Uri);
            Assert.Equal(footerValue, webLink.Text);

            m_GitRepositoryMock.Verify(x => x.TryGetCommit(It.IsAny <string>()), Times.Once);
            m_GitRepositoryMock.Verify(x => x.TryGetCommit(footerValue), Times.Once);
        }
        public void Should_resolve_all_instances_from_services_locator_and_resolve_single_instance_from_single_service_locator()
        {
            // Arrange
            var concreteTypesInServiceLocator1 = new List <object> {
                new ConcreteType1(), new ConcreteType1(), new ConcreteType1()
            };
            var concreteTypesInServiceLocator2 = new List <object> {
                new ConcreteType1(), new ConcreteType2()
            };

            FakeIoC.GetAllInstancesProvider = () => concreteTypesInServiceLocator1;
            FakeIoC.GetInstanceProvider     = () => concreteTypesInServiceLocator2;

            Func <Type, IEnumerable <object> > servicesLocator = FakeIoC.GetAllInstances;
            Func <Type, object> singleServiceLocator           = FakeIoC.GetInstance;

            var configurationExpression = TestDataFactory.CreateValidConfigurationExpression();

            // Act
            configurationExpression.ResolveServicesUsing(servicesLocator, singleServiceLocator);

            // Assert
            var externalServiceLocator = GetExternalServiceLocator(configurationExpression);

            Assert.That(externalServiceLocator.ResolveAll(typeof(ConcreteType1)), Is.EqualTo(concreteTypesInServiceLocator1));
            Assert.That(externalServiceLocator.Resolve(typeof(ConcreteType2)), Is.EqualTo(concreteTypesInServiceLocator2.Last()));
        }
Пример #17
0
        public async Task Executes_ignores_leading_and_trailing_whitespace_in_footer_values(string commitId, string footerValue)
        {
            // ARRANGE
            var footer         = new ChangeLogEntryFooter(new CommitMessageFooterName("some-footer"), new PlainTextElement(footerValue));
            var expectedCommit = new TestDataFactory().GetGitCommit();

            m_GitRepositoryMock
            .Setup(x => x.TryGetCommit(commitId))
            .Returns(expectedCommit);

            var sut = new ParseCommitReferencesTask(m_Logger, m_GitRepositoryMock.Object);

            // ACT
            var result = await sut.RunAsync(GetChangeLogFromFooter(footer));

            // ASSERT
            Assert.Equal(ChangeLogTaskResult.Success, result);

            var commitLink = Assert.IsType <CommitReferenceTextElement>(footer.Value);

            Assert.Equal(expectedCommit.Id, commitLink.CommitId);
            Assert.Equal(footerValue, commitLink.Text);

            m_GitRepositoryMock.Verify(x => x.TryGetCommit(It.IsAny <string>()), Times.Once);
            m_GitRepositoryMock.Verify(x => x.TryGetCommit(commitId), Times.Once);
        }
        public void Should_resolve_everything_from_implementation_of_ISecurityServiceLocator()
        {
            // Arrange
            IEnumerable <object> expectedTypes = new List <object> {
                new ConcreteType1(), new ConcreteType1(), new ConcreteType1()
            };
            object expectedType = new ConcreteType2();

            var securityServiceLocator = new Mock <ISecurityServiceLocator>();

            securityServiceLocator.Setup(x => x.ResolveAll(typeof(ConcreteType1))).Returns(expectedTypes);
            securityServiceLocator.Setup(x => x.Resolve(typeof(ConcreteType2))).Returns(expectedType);

            var configurationExpression = TestDataFactory.CreateValidConfigurationExpression();

            // Act
            configurationExpression.ResolveServicesUsing(securityServiceLocator.Object);

            // Assert
            var externalServiceLocator = GetExternalServiceLocator(configurationExpression);

            Assert.That(externalServiceLocator.ResolveAll(typeof(ConcreteType1)), Is.EqualTo(expectedTypes));
            Assert.That(externalServiceLocator.Resolve(typeof(ConcreteType2)), Is.EqualTo(expectedType));
            securityServiceLocator.VerifyAll();
        }
Пример #19
0
        public void Should_not_stop_on_first_violation_and_return_2_results()
        {
            // Arrange
            PolicyExecutionMode.StopOnFirstViolation(false);

            var context = TestDataFactory.CreateSecurityContext(false);

            var firstPolicy = new Mock <ISecurityPolicy>();

            firstPolicy.Setup(x => x.Enforce(It.IsAny <ISecurityContext>())).Returns(PolicyResult.CreateFailureResult(firstPolicy.Object, "Failure occured"));

            var secondPolicy = new Mock <ISecurityPolicy>();

            secondPolicy.Setup(x => x.Enforce(It.IsAny <ISecurityContext>())).Returns(PolicyResult.CreateSuccessResult(secondPolicy.Object));

            var policyContainer = new PolicyContainer(TestDataFactory.ValidControllerName, TestDataFactory.ValidActionName, TestDataFactory.CreateValidPolicyAppender());

            policyContainer.AddPolicy(firstPolicy.Object).AddPolicy(secondPolicy.Object);

            // Act
            var results = policyContainer.EnforcePolicies(context);

            // Assert
            Assert.That(results.Count(), Is.EqualTo(2));
            Assert.That(results.First().ViolationOccured, Is.True);
            Assert.That(results.Last().ViolationOccured, Is.False);
        }
        public void Should_have_a_simple_DelegatePolicy()
        {
            // Arrange
            const string policyName     = "Name1";
            const string failureMessage = "Some error message";
            Func <DelegateSecurityContext, bool>          policyDelegate           = context => false;
            Func <PolicyViolationException, ActionResult> violationHandlerDelegate = exception => new EmptyResult();
            var policyContainer = TestDataFactory.CreateValidPolicyContainer();
            var securityContext = new DelegateSecurityContext(new Mock <ISecurityPolicy>().Object, new Mock <ISecurityContext>().Object);

            // Act
            policyContainer.DelegatePolicy(policyName, policyDelegate, violationHandlerDelegate, failureMessage);

            // Assert
            var securityPolicy = policyContainer.GetPolicies().Where(x => x.GetType().Equals(typeof(DelegatePolicy))).Single() as DelegatePolicy;

            Assert.That(securityPolicy, Is.Not.Null);
            Assert.That(securityPolicy.Name, Is.EqualTo(policyName));

            var policyResult = securityPolicy.Policy.Invoke(securityContext);

            Assert.That(policyResult.Message, Is.EqualTo(failureMessage));
            Assert.That(policyResult.ViolationOccured, Is.True);

            Assert.That(securityPolicy.ViolationHandler, Is.EqualTo(violationHandlerDelegate));
        }
Пример #21
0
        public void Should_produce_runtime_policy_event_with_timing_when_event_listener_is_registered()
        {
            // Arrange
            const int    expectedMilliseconds = 9;
            var          expectedResult       = new { };
            const string expectedMessage      = "Message";

            var events = new List <ISecurityEvent>();

            SecurityDoctor.Register(events.Add);
            var context = TestDataFactory.CreateSecurityContext(false);

            // Act
            var result = Publish.RuntimePolicyEvent(() =>
            {
                Thread.Sleep(expectedMilliseconds + 5);
                return(expectedResult);
            }, r => expectedMessage, context);

            // Assert
            Assert.That(result, Is.EqualTo(expectedResult));

            var @event = events.Single();

            Assert.That(@event.CorrelationId, Is.EqualTo(context.Id));
            Assert.That(@event.Message, Is.EqualTo(expectedMessage));
            Assert.That(@event.CompletedInMilliseconds, Is.GreaterThanOrEqualTo(expectedMilliseconds));
        }
Пример #22
0
        public void Should_add_policyresult_cache_strategy_to_policycontainers()
        {
            // Arrange
            var controllerName   = NameHelper.Controller <AdminController>();
            var policyContainers = new List <PolicyContainer>
            {
                TestDataFactory.CreateValidPolicyContainer(controllerName, "Index"),
                TestDataFactory.CreateValidPolicyContainer(controllerName, "ListPosts"),
                TestDataFactory.CreateValidPolicyContainer(controllerName, "AddPost")
            };

            var         conventionPolicyContainer = new ConventionPolicyContainer(policyContainers.Cast <IPolicyContainerConfiguration>().ToList());
            const Cache expectedLifecycle         = Cache.PerHttpRequest;
            const By    expectedLevel             = By.ControllerAction;
            var         expectedType = typeof(DenyAnonymousAccessPolicy);

            // Act
            conventionPolicyContainer.Cache <DenyAnonymousAccessPolicy>(expectedLifecycle, expectedLevel);

            // Assert
            var containers = policyContainers.ToList();

            Assert.That(containers[0].CacheStrategies.Single().PolicyType, Is.EqualTo(expectedType));
            Assert.That(containers[0].CacheStrategies.Single().CacheLifecycle, Is.EqualTo(expectedLifecycle));
            Assert.That(containers[0].CacheStrategies.Single().CacheLevel, Is.EqualTo(expectedLevel));
            Assert.That(containers[1].CacheStrategies.Single().PolicyType, Is.EqualTo(expectedType));
            Assert.That(containers[1].CacheStrategies.Single().CacheLifecycle, Is.EqualTo(expectedLifecycle));
            Assert.That(containers[1].CacheStrategies.Single().CacheLevel, Is.EqualTo(expectedLevel));
            Assert.That(containers[2].CacheStrategies.Single().PolicyType, Is.EqualTo(expectedType));
            Assert.That(containers[2].CacheStrategies.Single().CacheLifecycle, Is.EqualTo(expectedLifecycle));
            Assert.That(containers[2].CacheStrategies.Single().CacheLevel, Is.EqualTo(expectedLevel));
        }
        public void Init()
        {
            var config = new ConfigurationBuilder()
                         .AddJsonFile("appsettings.json")
                         .Build();
            var connectionString = config["ConnectionStrings:DwapiConnection"];

            _serviceProvider = new ServiceCollection()
                               .AddDbContext <HtsContext>(o => o.UseSqlServer(connectionString))
                               .AddTransient <IManifestRepository, ManifestRepository>()
                               .BuildServiceProvider();

            _facilities = TestDataFactory.TestFacilityWithPatients(2);
            _manifests  = TestDataFactory.TestManifests(2);

            _manifests[0].FacilityId = _facilities[0].Id;
            _manifests[1].FacilityId = _facilities[1].Id;

            _context = _serviceProvider.GetService <HtsContext>();
            _context.Database.EnsureDeleted();
            _context.Database.EnsureCreated();
            _context.MasterFacilities.AddRange(TestDataFactory.TestMasterFacilities());
            _context.Facilities.AddRange(_facilities);
            _context.Manifests.AddRange(_manifests);
            _context.SaveChanges();
        }
Пример #24
0
        public void Init()
        {
            var config = new ConfigurationBuilder()
                         .AddJsonFile("appsettings.json")
                         .Build();
            var connectionString = config["ConnectionStrings:DwapiConnectionDev"];


            _serviceProvider = new ServiceCollection()
                               .AddDbContext <CbsContext>(o => o.UseSqlServer(connectionString))
                               .AddScoped <IFacilityRepository, FacilityRepository>()
                               .AddScoped <IMasterFacilityRepository, MasterFacilityRepository>()
                               .AddScoped <IMasterPatientIndexRepository, MasterPatientIndexRepository>()
                               .AddScoped <IManifestRepository, ManifestRepository>()
                               .AddScoped <IMpiService, MpiService>()
                               .AddScoped <IManifestService, ManifestService>()
                               .AddMediatR(typeof(ValidateFacilityHandler))
                               .BuildServiceProvider();


            _context = _serviceProvider.GetService <CbsContext>();
            _context.Database.EnsureDeleted();
            _context.Database.Migrate();
            _context.MasterFacilities.AddRange(TestDataFactory.TestMasterFacilities());
            var facilities = TestDataFactory.TestFacilities();

            _context.Facilities.AddRange(facilities);
            _context.SaveChanges();
            _patientIndices      = TestDataFactory.TestMasterPatientIndices(1, facilities.First(x => x.SiteCode == 1).Id);
            _patientIndicesSiteB = TestDataFactory.TestMasterPatientIndices(2, facilities.First(x => x.SiteCode == 2).Id);
        }
Пример #25
0
        public void ReturnValue_NoReturnValueConfigured_ThrowsException()
        {
            var methodCall = TestDataFactory.CreateMethodCallInfo(() => Console.ReadLine());
            var subject    = new Setup <string>(methodCall);

            Assert.Throws <InvalidOperationException>(() => subject.GetReturnValue(null));
        }
Пример #26
0
        public void Init()
        {
            var config = new ConfigurationBuilder()
                         .AddJsonFile("appsettings.json")
                         .Build();
            var        connectionString = config["ConnectionStrings:DwapiConnectionDev"];
            var        liveSync         = config["LiveSync"];
            Uri        endPointA        = new Uri(liveSync); // this is the endpoint HttpClient will hit
            HttpClient httpClient       = new HttpClient()
            {
                BaseAddress = endPointA,
            };

            DapperPlusManager.AddLicense("1755;700-ThePalladiumGroup", "2073303b-0cfc-fbb9-d45f-1723bb282a3c");
            if (!Z.Dapper.Plus.DapperPlusManager.ValidateLicense(out var licenseErrorMessage))
            {
                throw new Exception(licenseErrorMessage);
            }

            _serviceProvider = new ServiceCollection()
                               .AddDbContext <MnchContext>(o => o.UseSqlServer(connectionString))

                               .AddScoped <IDocketRepository, DocketRepository>()
                               .AddScoped <IMasterFacilityRepository, MasterFacilityRepository>()

                               .AddScoped <IFacilityRepository, FacilityRepository>()
                               .AddScoped <IManifestRepository, ManifestRepository>()
                               .AddScoped <IPatientMnchRepository, PatientMnchRepository>()
                               .AddScoped <IAncVisitRepository, AncVisitRepository>()

                               .AddScoped <IFacilityRepository, FacilityRepository>()
                               .AddScoped <IMasterFacilityRepository, MasterFacilityRepository>()
                               .AddScoped <IPatientMnchRepository, PatientMnchRepository>()
                               .AddScoped <IManifestRepository, ManifestRepository>()


                               .AddScoped <IAncVisitRepository, AncVisitRepository>()


                               .AddScoped <IMnchService, MnchService>()
                               .AddScoped <ILiveSyncService, LiveSyncService>()
                               .AddScoped <IManifestService, ManifestService>()
                               .AddSingleton <HttpClient>(httpClient)
                               .AddMediatR(typeof(ValidateFacilityHandler))
                               .BuildServiceProvider();
            _context = _serviceProvider.GetService <MnchContext>();
            _context.Database.EnsureDeleted();
            _context.Database.Migrate();
            _context.MasterFacilities.AddRange(TestDataFactory.TestMasterFacilities());
            var facilities = TestDataFactory.TestFacilities();

            _context.Facilities.AddRange(facilities);
            _context.SaveChanges();
            _context.MnchPatients.AddRange(TestDataFactory.TestClients(1, facilities.First(x => x.SiteCode == 1).Id));
            _context.MnchPatients.AddRange(TestDataFactory.TestClients(2, facilities.First(x => x.SiteCode == 2).Id));
            _context.SaveChanges();

            //1,
        }
Пример #27
0
        public void management_purges_queue()
        {
            address = TestDataFactory.GetAddress();

            new PurgeImpl(true, address)
            .Purge()
            .Wait();
        }
Пример #28
0
        public void Should_not_have_error_when_Duration_is_null()
        {
            AddVideoRequest addVideoRequest = TestDataFactory.CreateAddVideoRequest();

            addVideoRequest.Duration = null;

            Validator.ShouldNotHaveValidationErrorFor(x => x.Duration, addVideoRequest);
        }
Пример #29
0
        public void Should_have_error_when_Duration_is_lower_than_0()
        {
            AddVideoRequest addVideoRequest = TestDataFactory.CreateAddVideoRequest();

            addVideoRequest.Duration = -1;

            Validator.ShouldHaveValidationErrorFor(x => x.Duration, addVideoRequest);
        }
Пример #30
0
        public void Should_have_error_when_GenreId_is_empty()
        {
            AddVideoRequest addVideoRequest = TestDataFactory.CreateAddVideoRequest();

            addVideoRequest.GenreId = Guid.Empty;

            Validator.ShouldHaveValidationErrorFor(x => x.GenreId, addVideoRequest);
        }