예제 #1
0
        public void TestGetAllCarsForUserWithId_WithUserIdNull_ShouldReturnZeroCarsForTheUserWithIdNull()
        {
            // Arrange
            var contextFactory = new ApplicationDbContextFactory();
            var context        = contextFactory.CreateApplicationDbContext();

            var mapperFactory = new AutoMapperFactory();
            var mapper        = mapperFactory.CreateMapper();

            var carServices = new CarServices(context, mapper);


            SeedDbWithUsers(context);
            SeedDbWithCars(context);
            SeedCarsToTheFirstUser(context);

            // Act
            var count = carServices.GetAllCarsForUserWithId(null).Count();

            var expectedCount = 0;
            var actualCount   = count;

            // Assert
            Assert.Equal(expected: expectedCount, actual: actualCount);
        }
예제 #2
0
        public async Task TestEditCarDataAsync_WithTestData_ShouldEditTheCarData()
        {
            // Arrange
            var contextFactory = new ApplicationDbContextFactory();
            var context        = contextFactory.CreateApplicationDbContext();

            var mapperFactory = new AutoMapperFactory();
            var mapper        = mapperFactory.CreateMapper();

            SeedDbWithCars(context);

            var carServices     = new CarServices(context, mapper);
            var car             = context.Cars.FirstOrDefault();
            var carServiceModel = mapper.Map <CarServiceModel>(car);

            carServiceModel.Brand = "Tesla";
            carServiceModel.Model = "Model S";

            // Act
            await carServices.EditCarDataAsync(carServiceModel);

            var carFormDb = context.Cars.FirstOrDefault(c => c.Id == car.Id);

            var expectedBrand = "Tesla";
            var expectedModel = "Model S";

            var actualBrand = carFormDb.Brand;
            var actualModel = carFormDb.Model;

            // Assert
            Assert.True(expectedBrand == actualBrand &&
                        expectedModel == actualModel,
                        "The method EditCarDataAsnc does not work!");
        }
예제 #3
0
        public void TestGetCarById_WithTestData_ShouldReturnTheCarWithId()
        {
            // Arrange
            var contextFactory = new ApplicationDbContextFactory();
            var context        = contextFactory.CreateApplicationDbContext();

            var mapperFactory = new AutoMapperFactory();
            var mapper        = mapperFactory.CreateMapper();

            var carServices = new CarServices(context, mapper);

            SeedDbWithCars(context);

            var car   = context.Cars.FirstOrDefault();
            var carId = car.Id;

            // Act
            var expetedCar = car;
            var actualCar  = carServices.GetCarById(carId);

            // Assert
            Assert.True(expetedCar.Id == actualCar.Id &&
                        expetedCar.Brand == actualCar.Brand &&
                        expetedCar.Model == actualCar.Model &&
                        expetedCar.Number == actualCar.Number,
                        "The Method: GetCarById() does not work correctly!");
        }
예제 #4
0
        public void TestGetAllCarsForUserWithId_WithTestData_ShouldReturnAllCarsForTheUserWithId()
        {
            // Arrange
            var contextFactory = new ApplicationDbContextFactory();
            var context        = contextFactory.CreateApplicationDbContext();

            var mapperFactory = new AutoMapperFactory();
            var mapper        = mapperFactory.CreateMapper();

            var carServices = new CarServices(context, mapper);


            SeedDbWithUsers(context);
            SeedDbWithCars(context);
            SeedCarsToTheFirstUser(context);

            var firstUser = context.Users.FirstOrDefault();

            // Act
            var count = carServices.GetAllCarsForUserWithId(firstUser.Id).Count();

            var expectedCount = 2;
            var actualCount   = count;

            // Assert
            Assert.Equal(expected: expectedCount, actual: actualCount);
        }
        public AdminServicesTests()
        {
            // DbContext.
            var contextFactory = new ApplicationDbContextFactory();

            this.context = contextFactory.CreateApplicationDbContext();

            if (this.context.Users.Any(x => x.Role == "Admin") == false)
            {
                this.SeedDbWithAdmins(this.context);
            }

            if (this.context.Users.Any(x => x.Role == "User") == false)
            {
                this.SeedDbWithUsers(this.context);
            }
            if (this.context.Users.Any(x => x.Role == "Banned") == false)
            {
                this.SeedDbWithBanned(this.context);
            }
            if (this.context.Cars.Any() == false)
            {
                this.SeedDbWithCars(this.context);
            }

            // AutoMapper.
            var mapperFactory = new AutoMapperFactory();

            this.mapper = mapperFactory.CreateMapper();

            // Services.
            this.adminServices = new AdminServices(this.context, this.mapper);
        }
예제 #6
0
        public async Task TestAddCarAsync_WithTestData_ShouldAddCarToDb()
        {
            // Arrange
            var contextFactory = new ApplicationDbContextFactory();
            var context        = contextFactory.CreateApplicationDbContext();

            var mapperFactory = new AutoMapperFactory();
            var mapper        = mapperFactory.CreateMapper();

            var carServices = new CarServices(context, mapper);

            var car = new Car()
            {
                Brand    = "BMW",
                Model    = "X6",
                Number   = "PB1234K",
                YearFrom = DateTime.Now
            };
            var carServiceModel = mapper.Map <CarServiceModel>(car);

            // Act
            await carServices.AddCarAsync(carServiceModel);

            var expectedCount = 1;
            var actualCount   = context.Cars.Count();

            // Assert
            Assert.Equal(expected: expectedCount, actual: actualCount);
        }
예제 #7
0
        public async Task GetDemo_DemoPlanPresent_DemoPlanReturned()
        {
            //Arrange
            var fakeMediator = Substitute.For <IMediator>();

            fakeMediator
            .Send(Arg.Any <GetDemoPlanQuery>())
            .Returns(new Plan(
                         "some-bundle-id",
                         1337,
                         new Bundle(),
                         Array.Empty <PullDogPlan>()));

            var mapper = AutoMapperFactory.CreateValidMapper();

            var controller = new PlansController(
                mapper,
                fakeMediator);

            //Act
            var demoResponse = await controller.GetDemo();

            //Assert
            Assert.IsNotNull(demoResponse);

            Assert.AreEqual("some-bundle-id", demoResponse.Id);
        }
        public async Task TestEditPersonalityDesctriptionAsync_WithWithDescriptionIdNull_ShouldNotClearThePersonalityDescription()
        {
            // Arrange
            var contextFactory = new ApplicationDbContextFactory();
            var context        = contextFactory.CreateApplicationDbContext();

            var mapperFactory = new AutoMapperFactory();
            var mapper        = mapperFactory.CreateMapper();

            var adminServices = new AdminServices(context, mapper);

            SeedDbWithUsers(context);                                 // Count: 2

            var testApplicationUser = context.Users.FirstOrDefault(); // Take the first user.
            var userId = testApplicationUser.Id;


            // Act
            await adminServices.EditPersonalityDesctriptionAsync(userId, null);

            var actualDescription = context.Users
                                    .FirstOrDefault(user => user.Id == userId)
                                    .PersonalityDesctription;

            // Assert
            Assert.Equal(expected: null, actual: actualDescription);
        }
예제 #9
0
        public async Task ProvisionDemo_DemoAlreadyProvisioned_ReturnsValidationError()
        {
            //Arrange
            var fakeMediator = Substitute.For <IMediator>();

            fakeMediator
            .Send(Arg.Any <GetDemoPlanQuery>())
            .Returns(new Plan(
                         "some-bundle-id",
                         1337,
                         new Bundle(),
                         Array.Empty <PullDogPlan>()));

            fakeMediator
            .Send(Arg.Any <ProvisionDemoInstanceCommand>())
            .Throws(new DemoInstanceAlreadyProvisionedException());

            var mapper = AutoMapperFactory.CreateValidMapper();

            var controller = new PlansController(
                mapper,
                fakeMediator);

            //Act
            var result = await controller.ProvisionDemo();

            //Assert
            var validationProblem = result.GetValidationProblemDetails();

            Assert.AreEqual("ALREADY_PROVISIONED", validationProblem.Type);
        }
예제 #10
0
        public async Task Get_OneSupportedPlanPresent_SupportedPlanReturned()
        {
            //Arrange
            var fakeMediator = Substitute.For <IMediator>();

            fakeMediator
            .Send(Arg.Any <GetSupportedPlansQuery>())
            .Returns(new[]
            {
                new Plan(
                    "some-bundle-id",
                    1337,
                    new Bundle(),
                    Array.Empty <PullDogPlan>())
            });

            var mapper = AutoMapperFactory.CreateValidMapper();

            var controller = new PlansController(
                mapper,
                fakeMediator);

            //Act
            var responses = await controller.Get();

            //Assert
            var responsesArray = responses.ToArray();

            Assert.AreEqual(1, responsesArray.Length);

            Assert.AreEqual("some-bundle-id", responsesArray.Single().Id);
        }
예제 #11
0
        public async Task GetCurrentPaymentMethod_ActivePaymentMethodDoesNotExist_NullReturned()
        {
            //Arrange
            var fakeMediator = Substitute.For <IMediator>();

            fakeMediator
            .Send(Arg.Any <GetActivePaymentMethodForUserQuery>())
            .Returns((PaymentMethod)null);

            var mapper = AutoMapperFactory.CreateValidMapper();

            var controller = new PaymentController(
                fakeMediator,
                mapper);

            controller.FakeAuthentication("some-identity-name");

            //Act
            var paymentMethodResponse = await controller.GetCurrentPaymentMethod();

            //Assert
            var paymentMethod = paymentMethodResponse.ToObject <PaymentMethodResponse>();

            Assert.IsNull(paymentMethod);
        }
예제 #12
0
        public void TestGetUserByCarId_WithoutUser_ShouldReturnNull()
        {
            // Arrange
            var contextFactory = new ApplicationDbContextFactory();
            var context        = contextFactory.CreateApplicationDbContext();

            var mapperFactory = new AutoMapperFactory();
            var mapper        = mapperFactory.CreateMapper();

            var services = new UserServices(context, mapper);

            SeedDbWithCars(context);


            var carId = context.Cars.FirstOrDefault().Id;

            // Act
            var result = services.GetUserByCarId(carId);

            var actualUser = result;

            // Assert
            Assert.True(null == actualUser,
                        "The method: GetUserById(string userId) does not work correctly!");
        }
예제 #13
0
        public void TestGetUserByCarId_WithTestData_ShouldReturnTheUserWithCarId()
        {
            // Arrange
            var contextFactory = new ApplicationDbContextFactory();
            var context        = contextFactory.CreateApplicationDbContext();

            var mapperFactory = new AutoMapperFactory();
            var mapper        = mapperFactory.CreateMapper();


            var services = new UserServices(context, mapper);

            SeedDbWithUsers(context);
            SeedDbWithCars(context);
            SeedCarsToTheFirstUser(context);

            var carId = context.Cars.FirstOrDefault().Id;
            var user  = context.Users.FirstOrDefault(x => x.Cars.Any(car => car.Id == carId));

            // Act
            var result = services.GetUserByCarId(carId);

            var expectedUser = user;
            var actualUser   = result;

            Assert.True(expectedUser.Id == actualUser.Id &&
                        expectedUser.UserName == actualUser.UserName &&
                        expectedUser.Email == actualUser.Email,
                        "The method: GetUserById(string userId) does not work correctly!");
        }
예제 #14
0
        public void TestGetUserByName_WithTestData_ShouldReturnTheUserWithName()
        {
            // Arrange
            var contextFactory = new ApplicationDbContextFactory();
            var context        = contextFactory.CreateApplicationDbContext();

            var mapperFactory = new AutoMapperFactory();
            var mapper        = mapperFactory.CreateMapper();

            var services = new UserServices(context, mapper);


            SeedDbWithUsers(context);

            var testUsername = "******";

            var user = context.Users.FirstOrDefault(x => x.UserName == testUsername);

            // Act
            var resultUser = services.GetUserByName(testUsername);

            var expectedUser = user;
            var actualUser   = resultUser;

            // Assert
            Assert.True(expectedUser.Id == actualUser.Id &&
                        expectedUser.UserName == actualUser.UserName &&
                        expectedUser.Email == actualUser.Email);
        }
예제 #15
0
        public static void Register(HttpConfiguration config, out IApplicationSettings applicationSettings)
        {
            var container = new Container(cfg =>
            {
                cfg.Scan(scanner =>
                {
                    scanner.AssemblyContainingType <CQRSIndex>();
                    scanner.AssemblyContainingType <IMediator>();
                    scanner.WithDefaultConventions();
                    scanner.ConnectImplementationsToTypesClosing(typeof(IRequestHandler <,>));
                    scanner.ConnectImplementationsToTypesClosing(typeof(AbstractValidator <>));
                });
                cfg.For(typeof(IRequestHandler <,>)).DecorateAllWith(typeof(ValidatorHandler <,>));
                cfg.For <SingleInstanceFactory>().Use <SingleInstanceFactory>(ctx => t => ctx.GetInstance(t));
                cfg.For <MultiInstanceFactory>().Use <MultiInstanceFactory>(ctx => t => ctx.GetAllInstances(t));

                cfg.For <IMapper>().Singleton().Use(AutoMapperFactory.Create());

                cfg.For <ISession>().Singleton().Use <InMemorySession>();

                cfg.For <IApplicationSettings>().Singleton().Use <ApplicationSettings>();
                cfg.For <IGuard>().Singleton().Use <Guard>();
            });

#if DEBUG
            // TODO: review the following lines (alternatives?)
            container.GetInstance <MockSessionDataInitializer>().Initialize();
#endif

            applicationSettings = container.GetInstance <IApplicationSettings>();

            config.Services.Replace(typeof(IHttpControllerActivator), new StructureMapHttpControllerActivator(container));
        }
예제 #16
0
        private IMapper CreateMapperInstance()
        {
            var factory = new AutoMapperFactory();
            var mapper  = factory.ProduceMapper();

            return(mapper);
        }
예제 #17
0
 public TripServiceTests()
 {
     _context = InterviewContextFactory.Create();
     _mapper  = AutoMapperFactory.Create();
     _authorizationService = new AuthorizationService();
     _tripService          = new TripService(_context, _mapper, _authorizationService);
 }
예제 #18
0
        protected override void Load(ContainerBuilder builder)
        {
            RegisterMediatr(builder);

            builder.RegisterModule <ApplicationModule>();
            builder.RegisterModule <PersistenceModule>();

            builder.RegisterInstance(AutoMapperFactory.Create());

            builder.Register(c => PublicClientApplicationBuilder
                             .Create(ServiceConstants.MSAL_APPLICATION_ID)
                             .WithRedirectUri($"msal{ServiceConstants.MSAL_APPLICATION_ID}://auth")
                             .WithIosKeychainSecurityGroup("com.microsoft.adalcache")
                             .Build());

            builder.RegisterAssemblyTypes(ThisAssembly)
            .Where(t => t.Name.EndsWith("Service", StringComparison.CurrentCultureIgnoreCase))
            .Where(t => !t.Name.Equals("NavigationService", StringComparison.CurrentCultureIgnoreCase))
            .AsImplementedInterfaces();

            builder.RegisterAssemblyTypes(ThisAssembly)
            .Where(t => !t.Name.StartsWith("DesignTime", StringComparison.CurrentCultureIgnoreCase))
            .Where(t => t.Name.EndsWith("ViewModel", StringComparison.CurrentCultureIgnoreCase))
            .AsImplementedInterfaces();

            builder.RegisterAssemblyTypes(ThisAssembly)
            .Where(t => !t.Name.StartsWith("DesignTime", StringComparison.CurrentCultureIgnoreCase))
            .Where(t => t.Name.EndsWith("ViewModel", StringComparison.CurrentCultureIgnoreCase))
            .AsSelf();

            CultureHelper.CurrentCulture = CultureInfo.CreateSpecificCulture(new SettingsFacade(new SettingsAdapter()).DefaultCulture);
        }
        public TestFixture()
        {
            // Configure services
            var services = new ServiceCollection();

            services.AddEntityFrameworkInMemoryDatabase()
            .AddDbContext <ConduitDbContext>(options => options.UseInMemoryDatabase($"{Guid.NewGuid().ToString()}.db"));
            services.AddIdentity <ConduitUser, IdentityRole>()
            .AddEntityFrameworkStores <ConduitDbContext>();

            // Configure HTTP context for authentication
            var context = new DefaultHttpContext();

            context.Features.Set <IHttpAuthenticationFeature>(new HttpAuthenticationFeature());
            services.AddSingleton <IHttpContextAccessor>(_ => new HttpContextAccessor
            {
                HttpContext = context
            });

            // Configure current user accessor as a provider
            var serviceProvider = services.BuildServiceProvider();

            // Initialize the database with seed data and context accessors services
            var databaseContext = serviceProvider.GetRequiredService <ConduitDbContext>();

            ConduitDbInitializer.Initialize(databaseContext);

            // Create the services from configured providers
            Mapper             = AutoMapperFactory.Create();
            MachineDateTime    = new DateTimeTest();
            TokenService       = new TokenServiceTest();
            Context            = databaseContext;
            UserManager        = serviceProvider.GetRequiredService <UserManager <ConduitUser> >();
            CurrentUserContext = new CurrentUserContextTest(UserManager);
        }
예제 #20
0
        public async Task Logs_InstanceNotAvailable_NotFoundReturned()
        {
            //Arrange
            var fakeMediator = Substitute.For <IMediator>();

            fakeMediator
            .Send(
                Arg.Any <GetInstanceByNameQuery>(),
                default)
            .Returns((Dogger.Domain.Models.Instance)null);

            var mapper = AutoMapperFactory.CreateValidMapper();

            var controller = new ClustersController(
                fakeMediator,
                mapper);

            //Act
            var result = await controller.Logs("some-instance-name");

            //Assert
            var response = result as NotFoundObjectResult;

            Assert.IsNotNull(response);
        }
예제 #21
0
        public async Task DemoConnectionDetails_DemoInstanceAvailable_DemoInstanceConnectionDetailsReturned()
        {
            //Arrange
            var fakeMediator = Substitute.For <IMediator>();

            fakeMediator
            .Send(
                Arg.Is <GetConnectionDetailsQuery>(arg =>
                                                   arg.ClusterId == "demo"),
                default)
            .Returns(new Dogger.Domain.Queries.Clusters.GetConnectionDetails.ConnectionDetailsResponse(
                         "some-ip-address",
                         "some-host-name",
                         Array.Empty <ExposedPort>()));

            var mapper = AutoMapperFactory.CreateValidMapper();

            var controller = new ClustersController(
                fakeMediator,
                mapper);

            //Act
            var result = await controller.DemoConnectionDetails();

            //Assert
            var response = result.ToObject <ConnectionDetailsResponse>();

            Assert.IsNotNull(response);
        }
예제 #22
0
        public async Task ConnectionDetails_InstanceNotAvailable_NotFoundReturned()
        {
            //Arrange
            var fakeMediator = Substitute.For <IMediator>();

            fakeMediator
            .Send(
                Arg.Is <GetLightsailInstanceByNameQuery>(arg =>
                                                         arg.Name == "some-instance-name"),
                default)
            .Returns((Instance)null);

            var mapper = AutoMapperFactory.CreateValidMapper();

            var controller = new ClustersController(
                fakeMediator,
                mapper);

            controller.FakeAuthentication("some-identity-name");

            //Act
            var result = await controller.ConnectionDetails("some-instance-name");

            //Assert
            var response = result as NotFoundObjectResult;

            Assert.IsNotNull(response);
        }
예제 #23
0
        public async Task Destroy_ClusterNotFound_ClusterNotFoundValidationErrorReturned()
        {
            //Arrange
            var fakeClusterId = Guid.NewGuid();

            var fakeMediator = Substitute.For <IMediator>();

            fakeMediator
            .Send(Arg.Is <GetClusterForUserQuery>(args =>
                                                  args.ClusterId == fakeClusterId))
            .Returns((Cluster)null);

            fakeMediator
            .Send(Arg.Any <EnsureUserForIdentityCommand>())
            .Returns(new User());

            var mapper = AutoMapperFactory.CreateValidMapper();

            var controller = new ClustersController(
                fakeMediator,
                mapper);

            controller.FakeAuthentication("some-identity-name");

            //Act
            var result = await controller.Destroy(fakeClusterId);

            //Assert
            var response = result.GetValidationProblemDetails();

            Assert.IsNotNull(response);

            Assert.AreEqual("CLUSTER_NOT_FOUND", response.Type);
        }
예제 #24
0
        public GivenCustomerController()
        {
            var fixture = new Fixture();

            var mapperFactory      = new AutoMapperFactory();
            var customerRepository = Substitute.For <ICustomerRepository>(); //maybe forse a dictionary implementation instead of an inline mock


            _notExistingId = Guid.Empty;
            var customer = DomainGenerator.CustomerGenerator().Generate();

            _existingId = customer.Id;

            Dictionary <Guid, Customer> repo = new Dictionary <Guid, Customer>();

            repo.Add(_notExistingId, null);
            repo.Add(_existingId, customer);


            customerRepository.Get(Guid.Empty).Returns(null as Customer);
            customerRepository.Get(customer.Id).Returns(repo[customer.Id]);
            customerRepository
            .When(cr => cr.UpdateAsync(Arg.Any <Customer>()))
            .Do(callInfo =>
            {
                var callInfoCustomer = callInfo.Arg <Customer>();
                if (callInfoCustomer.Id == Guid.Empty)
                {
                    while (!repo.TryAdd(callInfoCustomer.Id, callInfoCustomer))
                    {
                        callInfoCustomer.Id = new Faker().Random.Guid();
                    }
                }
                else
                {
                    if (repo.ContainsKey(callInfoCustomer.Id))
                    {
                        repo[callInfoCustomer.Id] = callInfoCustomer;
                    }
                    else
                    {
                        throw new ArgumentException("Couldnt update repo, wasn't added");
                    }
                }
            });

            IErrorService errorService = new ErrorService();

            fixture.Inject(customerRepository);
            fixture.Inject(errorService);
            fixture.Customize(new AutoNSubstituteCustomization()
            {
                ConfigureMembers = true, GenerateDelegates = true
            });
            fixture.Inject(mapperFactory.CreateMapper <CustomerItem, Customer>()); //Is tested in other class, so used for easyness at the moment
            fixture.Inject(mapperFactory.CreateMapper <ContactInfoItem, ContactInfo>());
            fixture.Inject(new ControllerContext());
            _sut = fixture.Create <CustomerController>();
        }
예제 #25
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddTransient <IMapper>(_ => AutoMapperFactory.CreateMapper());
            services.AddTransient <IBoardFactory, StandardBoardFactory>();
            services.AddDbContext <GameContext>(options => options.UseInMemoryDatabase("5dafbe98-2b52-48c4-994e-9845751d5919"));
        }
예제 #26
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
     services.AddDefaultAWSOptions(Configuration.GetAWSOptions());
     services.AddServices();
     services.AddSingleton(AutoMapperFactory.CreateAndConfigure());
     services.AddDbContext <ApplicationDbContext>();
 }
예제 #27
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddMvc();
     services.AddServices();
     services.AddSingleton(AutoMapperFactory.CreateAndConfigure());
     services.AddDbContext <ApplicationDbContext>();
     services.AddScoped <DbContext>(sp => sp.GetService <ApplicationDbContext>());
 }
예제 #28
0
        public void Details_ReturnsNoModelInViewResult_IfContractorNotExists()
        {
            var controller = new ContractorController(_service, AutoMapperFactory.Create());

            var result = controller.Details(Guid.NewGuid()) as ViewResult;

            Assert.Null(result.Model);
        }
예제 #29
0
        public void Details_ReturnsModelInViewResult_IfContractorExists()
        {
            var controller = new ContractorController(_service, AutoMapperFactory.Create());

            var id     = _service.GetContractors().FirstOrDefault().Id;
            var result = controller.Details(id) as ViewResult;

            Assert.NotNull(result.Model);
        }
예제 #30
0
 public static void BindServices(IServiceCollection serviceCollection)
 {
     serviceCollection.AddTransient <Logger>();
     serviceCollection.AddTransient <Client>();
     serviceCollection.AddTransient <Driver>();
     serviceCollection.AddTransient <InfrastuctureLayer.Gds.Ctrip.Client>();
     serviceCollection.AddTransient <InfrastuctureLayer.Gds.Ctrip.Driver>();
     serviceCollection.AddTransient(c => AutoMapperFactory.Create());
     serviceCollection.AddTransient <GdsFactory>();
 }