コード例 #1
0
        public async Task OnSuccessShouldReturnValidObject()
        {
            // Arrange
            //
            var faceSettings = TestHelper.GetFaceSettings();
            var lat          = (decimal)38.855652;
            var lon          = (decimal) - 94.799712;

            var handler             = new Mock <HttpMessageHandler>();
            var openWeatherResponse =
                "{\"coord\":{\"lon\":-94.8,\"lat\":38.88},\"weather\":[{\"id\":800,\"main\":\"Clear\",\"description\":\"clear sky\",\"icon\":\"01d\"}],\"base\":\"stations\",\"main\":{\"temp\":4.28,\"feels_like\":0.13,\"temp_min\":3,\"temp_max\":5.56,\"pressure\":1034,\"humidity\":51},\"visibility\":16093,\"wind\":{\"speed\":2.21,\"deg\":169},\"clouds\":{\"all\":1},\"dt\":1584811457,\"sys\":{\"type\":1,\"id\":5188,\"country\":\"US\",\"sunrise\":1584793213,\"sunset\":1584837126},\"timezone\":-18000,\"id\":4276614,\"name\":\"Olathe\",\"cod\":200}";

            handler.SetupRequest(HttpMethod.Get, faceSettings.BuildOpenWeatherUrl(lat, lon))
            .ReturnsResponse(openWeatherResponse, "application/json");

            var client = new OpenWeatherClient(
                TestHelper.GetLoggerMock <OpenWeatherClient>().Object,
                handler.CreateClient(),
                faceSettings,
                TestHelper.GetMetricsMock().Object,
                MapperConfig.CreateMapper());

            // Act
            //
            var result = await client.RequestOpenWeather(lat, lon);

            // Assert
            //
            Assert.Equal(RequestStatusCode.Ok, result.RequestStatus.StatusCode);
            Assert.Equal("clear-day", result.Icon);
            Assert.Equal((decimal)0.51, result.Humidity);
            Assert.Equal((decimal)4.28, result.Temperature);
        }
コード例 #2
0
        public async Task OnErrorShouldReturnErrorObject()
        {
            // Arrange
            //
            var faceSettings = TestHelper.GetFaceSettings();
            var lat          = (decimal)38.855652;
            var lon          = (decimal) - 94.799712;

            var handler = new Mock <HttpMessageHandler>();

            handler.SetupAnyRequest()
            .ReturnsResponse(HttpStatusCode.BadRequest);

            var client = new OpenWeatherClient(
                TestHelper.GetLoggerMock <OpenWeatherClient>().Object,
                handler.CreateClient(),
                faceSettings,
                TestHelper.GetMetricsMock().Object,
                MapperConfig.CreateMapper());

            // Act
            //
            var result = await client.RequestOpenWeather(lat, lon);

            // Assert
            //
            Assert.Equal(RequestStatusCode.Error, result.RequestStatus.StatusCode);
            Assert.Equal(400, result.RequestStatus.ErrorCode);
        }
コード例 #3
0
        // This method gets called by the runtime. Use this method to add services to the container
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <DatabaseSettings>(Configuration.GetSection("DatabaseSettings"));
            services.AddOptions();
            // Add framework services.
            services.AddApplicationInsightsTelemetry(Configuration);

            services.AddSingleton <IMapper>(sp => MapperConfig.CreateMapper());

            services.AddDbContext <CallCenterContext>();

            services.AddScoped <ICustomerRepository, CustomerRepository>();
            services.AddScoped <ICampaignRepository, CampaignRepository>();
            services.AddScoped <ICallRepository, CallRepository>();

            services.AddTransient <CallCenterContextSeedData>();

            services.AddMvc();



            services.AddSwaggerGen();
            services.ConfigureSwaggerGen(options =>
            {
                options.SingleApiVersion(new Info
                {
                    Version        = "v1",
                    Title          = "Call Center Api",
                    Description    = "Call Center Api for the application",
                    TermsOfService = "None"
                });
                //options.IncludeXmlComments(pathToDoc);
                options.DescribeAllEnumsAsStrings();
            });
        }
コード例 #4
0
        public async Task SaveDbShouldCorrectlyGetDataFromQuery()
        {
            // Arrange
            //

            var connectionSettings = _factory.Services.GetRequiredService <IConnectionSettings>();
            var dbConnection       = new DataConnectionFactory(connectionSettings.GetDataProvider(), connectionSettings.BuildConnectionString())
                                     .Create();

            var dataProvider = new PostgresDataProvider(
                TestHelper.GetLoggerMock <PostgresDataProvider>().Object,
                new DataConnectionFactory(connectionSettings),
                MapperConfig.CreateMapper(), null);

            var watchRequest = new WatchRequest
            {
                DeviceId        = "device-id",
                DeviceName      = "device-name",
                Version         = "version",
                CiqVersion      = "ciq-version",
                Framework       = "framework",
                WeatherProvider = "weather-provider",
                DarkskyKey      = "dark-key",
                Lat             = (decimal)1.1,
                Lon             = (decimal)2.2,
                BaseCurrency    = "USD",
                TargetCurrency  = "EUR"
            };

            // Act
            //
            await dataProvider.SaveRequestInfo(watchRequest,
                                               new WeatherInfo { WindSpeed = (decimal)5.5, Temperature = (decimal)4.4 },
                                               new LocationInfo { CityName = "city-name" },
                                               new ExchangeRateInfo { ExchangeRate = (decimal)3.3 });

            // Assert
            //
            var actualDevice = await dbConnection.GetTable <DeviceData>().SingleAsync(d => d.DeviceId == watchRequest.DeviceId);

            var actualRequest = await dbConnection.GetTable <RequestData>().SingleAsync(r => r.DeviceDataId == actualDevice.Id);


            Assert.Equal("device-name", actualDevice.DeviceName);
            Assert.Equal("device-id", actualDevice.DeviceId);


            Assert.Equal(watchRequest.Framework, actualRequest.Framework);
            Assert.Equal(watchRequest.CiqVersion, actualRequest.CiqVersion);
            Assert.Equal(watchRequest.Version, actualRequest.Version);
            Assert.Equal(watchRequest.Lon, actualRequest.Lon);
            Assert.Equal(watchRequest.Lat, actualRequest.Lat);
            Assert.Equal(watchRequest.BaseCurrency, actualRequest.BaseCurrency);
            Assert.Equal(watchRequest.TargetCurrency, actualRequest.TargetCurrency);

            Assert.Equal((decimal)4.4, actualRequest.Temperature);
            Assert.Equal("city-name", actualRequest.CityName);
            Assert.Equal((decimal)3.3, actualRequest.ExchangeRate);
        }
コード例 #5
0
        /// <summary>
        /// Use mapper for conver our Accounts to AccountDTo
        /// </summary>
        /// <returns> List AccountDTO</returns>
        public IEnumerable <AccountDTO> GetAllAccounts()
        {
            //var mapper = new MapperConfiguration(cfg => cfg.CreateMap<Account, AccountDTO>()).CreateMapper();
            //return mapper.Map<IEnumerable<Account>, List<AccountDTO>>(unitOfWork.Accounts.GetAllAccounts());
            MapperConfig mapperConfiguration = new MapperConfig(unitOfWork);

            return(mapperConfiguration.CreateMapper());
        }
コード例 #6
0
        public UserControllerTests()
        {
            _userServiceMock = new Mock <IUserService>();

            var mapper = MapperConfig.CreateMapper();

            _controller = new UserController(mapper, _userServiceMock.Object);
        }
コード例 #7
0
        public ContactControllerTests()
        {
            _contactServiceMock = new Mock <IContactService>();

            var mapper = MapperConfig.CreateMapper();

            _controller = new ContactController(mapper, _contactServiceMock.Object);
        }
コード例 #8
0
        public SplitControllerTests()
        {
            _splitServiceMock = new Mock <ISplitService>();

            var mapper = MapperConfig.CreateMapper();

            _controller = new SplitController(mapper, _splitServiceMock.Object);

            var claims = new List <Claim> {
                new Claim(ClaimTypes.NameIdentifier, "1")
            };
            var httpContext = new DefaultHttpContext();

            httpContext.User = new ClaimsPrincipal(new ClaimsIdentity(claims));
            _controller.ActionContext.HttpContext = httpContext;
        }
コード例 #9
0
        public static void RegisterComponents()
        {
            var container = new UnityContainer();

            // register all your components with the container here
            // it is NOT necessary to register your controllers

            // e.g. container.RegisterType<ITestService, TestService>();

            GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);


            var mapperConfig = new MapperConfig();

            container.RegisterInstance(mapperConfig.CreateMapper());

            container.RegisterType <IToDoListService, ToDoListService>();
            container.RegisterType <IAppDbContext, AppDbContext>();
        }
コード例 #10
0
        public async Task SameDeviceWithTheSameCoordinatesShouldReturnCity()
        {
            // Arrange
            //
            var connectionSettings = _factory.Services.GetRequiredService <IConnectionSettings>();

            var dataProvider = new PostgresDataProvider(
                TestHelper.GetLoggerMock <PostgresDataProvider>().Object,
                new DataConnectionFactory(connectionSettings),
                MapperConfig.CreateMapper(),
                TestHelper.GetMetricsMock().Object);

            var watchRequest = new WatchRequest
            {
                DeviceId        = "device-id",
                DeviceName      = "device-name",
                Version         = "version",
                CiqVersion      = "ciq-version",
                Framework       = "framework",
                WeatherProvider = "weather-provider",
                DarkskyKey      = "dark-key",
                Lat             = (decimal)1.1,
                Lon             = (decimal)2.2,
                BaseCurrency    = "USD",
                TargetCurrency  = "EUR"
            };


            await dataProvider.SaveRequestInfo(watchRequest,
                                               new WeatherInfo { WindSpeed = (decimal)5.5, Temperature = (decimal)4.4 },
                                               new LocationInfo { CityName = "city-name2" },
                                               new ExchangeRateInfo { ExchangeRate = (decimal)3.3 });


            // Act
            //
            var actualLocationInfo = await dataProvider.LoadLastLocation("device-id", (decimal)1.1, (decimal)2.2);

            // Assert
            //
            Assert.Equal("city-name2", actualLocationInfo.CityName);
            Assert.Equal(RequestStatusCode.Ok, actualLocationInfo.RequestStatus.StatusCode);
        }
コード例 #11
0
        public async Task NoLocationShouldReturnNull()
        {
            // Arrange
            //
            var connectionSettings = _factory.Services.GetRequiredService <IConnectionSettings>();

            var dataProvider = new PostgresDataProvider(
                TestHelper.GetLoggerMock <PostgresDataProvider>().Object,
                new DataConnectionFactory(connectionSettings),
                MapperConfig.CreateMapper(),
                TestHelper.GetMetricsMock().Object);

            // Act
            //
            var actualLocationInfo = await dataProvider.LoadLastLocation("device-id", (decimal)1.1, (decimal)2.2);

            // Assert
            //
            Assert.Null(actualLocationInfo);
        }
コード例 #12
0
        public async Task OnAuthErrorShouldLogAuthIssue()
        {
            // Arrange
            //
            var faceSettings = TestHelper.GetFaceSettings();
            var lat          = (decimal)38.855652;
            var lon          = (decimal) - 94.799712;

            var loggerMock = TestHelper.GetLoggerMock <OpenWeatherClient>();

            var handler = new Mock <HttpMessageHandler>();

            handler.SetupAnyRequest()
            .ReturnsResponse(HttpStatusCode.Unauthorized);

            var client = new OpenWeatherClient(
                loggerMock.Object,
                handler.CreateClient(),
                faceSettings,
                TestHelper.GetMetricsMock().Object,
                MapperConfig.CreateMapper());

            // Act
            //
            var result = await client.RequestOpenWeather(lat, lon);

            // Assert
            //
            Assert.Equal(RequestStatusCode.Error, result.RequestStatus.StatusCode);
            Assert.Equal(401, result.RequestStatus.ErrorCode);

            loggerMock.Verify(
                x => x.Log(
                    It.IsAny <LogLevel>(),
                    It.IsAny <EventId>(),
                    It.Is <It.IsAnyType>((o, t) => string.Equals("Unauthorized access to OpenWeather", o.ToString(), StringComparison.InvariantCultureIgnoreCase)),
                    It.IsAny <Exception>(),
                    (Func <It.IsAnyType, Exception, string>)It.IsAny <object>()),
                Times.Once);
        }
コード例 #13
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //var mappingConfig = new MapperConfiguration(mc =>
            //{
            //    mc.AddProfile(new MappingProfile());
            //});
            //IMapper mapper = mappingConfig.CreateMapper();
            //services.AddSingleton(mapper);

            services.AddSingleton(MapperConfig.CreateMapper());

            services.AddDbContext <VegaDbContext>(options =>
                                                  options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));



            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
        }
コード例 #14
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // configuration
            //
            var faceSettings = Configuration.LoadVerifiedConfiguration <FaceSettings>();
            var pgSettings   = Configuration.LoadVerifiedConfiguration <IConnectionSettings, PostgresProviderSettings>();

            services.AddSingleton(Configuration.LoadVerifiedConfiguration <KafkaSettings>());
            services.AddSingleton(faceSettings);
            services.AddSingleton(pgSettings);

            // services
            //
            services.AddSingleton <DataConnectionFactory>();
            services.AddSingleton <KafkaProvider>();
            services.AddScoped <PostgresDataProvider>();
            services.AddScoped <ExchangeRateCacheStrategy>();
            services.AddScoped <RequestRateLimit>();

            services.AddControllers();

            services.AddHostedService <StartupHostedService>();

            services.AddApplicationInsightsTelemetry(Configuration);

            // metrics
            //
            var metrics = AppMetrics.CreateDefaultBuilder()
                          .Configuration.Configure(
                options => options.GlobalTags.Add("version", SolutionInfo.Version))
                          .Configuration.ReadFrom(Configuration)
                          .OutputMetrics.AsPrometheusPlainText()
                          .Build();

            services.AddMetrics(metrics);

            services.AddMetricsTrackingMiddleware();
            services.AddMetricsReportingHostedService();
            services.AddMetricsEndpoints(
                options => options.MetricsEndpointOutputFormatter = metrics.OutputMetricsFormatters
                                                                    .OfType <MetricsPrometheusTextOutputFormatter>().First());

            // Authentication
            //
            services
            .AddAuthentication(faceSettings.AuthSettings.Scheme)
            .AddScheme <TokenAuthOptions, TokenAuthenticationHandler>(
                faceSettings.AuthSettings.Scheme,
                options =>
            {
                options.ApiTokenName = faceSettings.AuthSettings.TokenName;
                options.Scheme       = faceSettings.AuthSettings.Scheme;
                options.ApiToken     = faceSettings.AuthSettings.Token;
            });
            services.AddAuthorization();

            // HttpClients
            //
            services.AddHttpClient <VirtualearthClient>().AddRetryPolicyWithCb(4, TimeSpan.FromMinutes(10));
            services.AddHttpClient <CurrencyConverterClient>().AddRetryPolicyWithCb(4, TimeSpan.FromMinutes(10));
            services.AddHttpClient <ExchangeRateApiClient>().AddRetryPolicyWithCb(4, TimeSpan.FromMinutes(10));
            services.AddHttpClient <DarkSkyClient>().AddRetryPolicyWithCb(4, TimeSpan.FromMinutes(10));
            services.AddHttpClient <OpenWeatherClient>().AddRetryPolicyWithCb(4, TimeSpan.FromMinutes(10));

            // AutoMapper Configuration
            //
            services.AddSingleton(MapperConfig.CreateMapper());

            // for AppMetric prometheus endpoint
            //
            services.Configure <KestrelServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });

            // Add telegram bot
            //
            var proxy = (faceSettings.ProxySettings != null)
                ? new HttpToSocks5Proxy(faceSettings.ProxySettings.Host, faceSettings.ProxySettings.Port)
                : null;

            services.AddSingleton <ITelegramBotClient>(new TelegramBotClient(faceSettings.TelegramKey, proxy));
            services.AddSingleton <TelegramService>();

            // Add the health check
            //
            services.AddHealthChecks()
            .AddNpgSql(pgSettings.BuildConnectionString(), name: "database")
            .AddUrlGroup(faceSettings.BuildLocationUrl(0, 0), "location")
            .AddUrlGroup(new Uri("https://api.darksky.net/v1/status.txt"), "darkSky")
            .AddUrlGroup(faceSettings.BuildOpenWeatherUrl(0, 0), "openWeather");

            services.AddApiVersioning(options =>
            {
                options.AssumeDefaultVersionWhenUnspecified = true;
                options.DefaultApiVersion = new ApiVersion(1, 0);
                options.ReportApiVersions = true;
                options.ErrorResponses    = new VersioningErrorProvider();
            });
        }