Example #1
0
 public Device(MyMqttClient mqttClient, string serialNo, string deviceName)
 {
     _serialNo      = serialNo;
     _deviceName    = deviceName;
     _mqttClient    = mqttClient;
     _weatherClient = new WeatherApiClient();
 }
Example #2
0
        public async void ReturnsAnEmptyListIfApiRequestFails()
        {
            // Arrange
            var mockHandler = GetMockMessageHandler(HttpStatusCode.GatewayTimeout, null);
            var mockFactory = GetMockHttpClientFactory(mockHandler.Object);
            var mockLogger  = new Mock <ILogger <WeatherApiClient> >();
            var apiClient   = new WeatherApiClient(mockFactory.Object, mockLogger.Object);

            // Act
            var result = await apiClient.LocationSearch("London");

            // Assert
            Assert.NotNull(result);
            Assert.Empty(result);

            // also check the 'http' call was like we expected it
            var expectedUri = new Uri($"{_defaultBaseUrl}/api/location/search?query=London");

            mockHandler.Protected().Verify(
                "SendAsync",
                Times.Exactly(1), // we expected a single external request
                ItExpr.Is <HttpRequestMessage>(req =>
                                               req.Method == HttpMethod.Get && // we expected a GET request
                                               req.RequestUri == expectedUri // to this uri
                                               ),
                ItExpr.IsAny <CancellationToken>()
                );
        }
        public async Task GetWeatherDto_WhenInvalidData_ThrowsException()
        {
            var response = new HttpResponseMessage
            {
                StatusCode   = HttpStatusCode.BadRequest,
                ReasonPhrase = It.IsAny <string>(),
                Content      = new StringContent(
                    "{\"error\": {\"message\": \"error\"}}")
            };

            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

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

            handlerMock.Protected()
            .Setup <Task <HttpResponseMessage> >
            (
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>()
            )
            .ReturnsAsync(response)
            .Verifiable();

            var httpClient = new HttpClient(handlerMock.Object)
            {
                BaseAddress = new Uri("http://something.com/")
            };

            var weatherApiClient = new WeatherApiClient(httpClient);
            var result           = weatherApiClient.GetWeatherDto(It.IsAny <string>());

            await Assert.ThrowsAsync <CityNotFoundException>(() => result);
        }
Example #4
0
 public DistributedCacheController(WeatherApiClient weatherApiClient, ILogger <ResponseCacheController> logger,
                                   IDistributedCache cache)
 {
     _weatherApiClient = weatherApiClient;
     _logger           = logger;
     _cache            = cache;
 }
        public async Task GetForecastDto_ByDefault_ReturnsCorrectType()
        {
            var response = new HttpResponseMessage
            {
                StatusCode   = HttpStatusCode.OK,
                ReasonPhrase = It.IsAny <string>(),
                Content      = new StringContent(
                    "{\"location\": {\"name\": \"city\"}}"
                    )
            };

            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

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

            handlerMock.Protected()
            .Setup <Task <HttpResponseMessage> >
            (
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>()
            )
            .ReturnsAsync(response)
            .Verifiable();

            var httpClient = new HttpClient(handlerMock.Object)
            {
                BaseAddress = new Uri("http://something.com/")
            };

            var weatherApiClient = new WeatherApiClient(httpClient);
            var result           = await weatherApiClient.GetForecastDto(It.IsAny <string>());

            Assert.IsType <WeatherDto>(result);
        }
Example #6
0
        public async void CallsTheMetaWeatherApiUrlWithQueryParam()
        {
            // Arrange
            var searchResult = "[{\"title\":\"Leeds\",\"location_type\":\"City\",\"woeid\":26042,\"latt_long\":\"53.794491,-1.546580\"}]";

            var mockHandler = GetMockMessageHandler(HttpStatusCode.OK, new StringContent(searchResult));
            var mockFactory = GetMockHttpClientFactory(mockHandler.Object);
            var mockLogger  = new Mock <ILogger <WeatherApiClient> >();
            var apiClient   = new WeatherApiClient(mockFactory.Object, mockLogger.Object);

            // Act
            var result = await apiClient.LocationSearch("Leeds");

            // Assert
            Assert.NotNull(result);
            Assert.Single(result);
            var firstResult = result[0];

            Assert.Equal(26042, firstResult.WoeId);

            // also check the 'http' call was like we expected it
            var expectedUri = new Uri($"{_defaultBaseUrl}/api/location/search?query=Leeds");

            mockHandler.Protected().Verify(
                "SendAsync",
                Times.Exactly(1), // we expected a single external request
                ItExpr.Is <HttpRequestMessage>(req =>
                                               req.Method == HttpMethod.Get && // we expected a GET request
                                               req.RequestUri == expectedUri // to this uri
                                               ),
                ItExpr.IsAny <CancellationToken>()
                );
        }
        public async Task GetCurrentWeatherConditionInShouldReturnWeather()
        {
            // ARRANGE
            _configurationMock.Setup(p => p.GetSection("WeatherApiBaseUrl").Value).Returns(weatherApiUrl);
            
            var httpClient = new Mock<HttpClient>();

            var mockHttpMessageHandler = new Mock<HttpMessageHandler>();
            mockHttpMessageHandler.Protected()
                .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
                .ReturnsAsync(new HttpResponseMessage
                {
                    StatusCode = HttpStatusCode.OK,
                    Content = new StringContent(GetresponseContent()),
                });
            var client = new HttpClient(mockHttpMessageHandler.Object);
            _httpClientFactoryMock.Setup(_ => _.CreateClient(It.IsAny<string>())).Returns(client);

            var weatherApiClient = new WeatherApiClient(_loggerMock.Object, _httpClientFactoryMock.Object, _configurationMock.Object);

            //  ACT
            var result = await weatherApiClient.GetCurrentWeatherConditionIn("London");

            //  ASSERT
            Assert.AreEqual(name, result.Location.Name);
            Assert.AreEqual(region, result.Location.Region);
            Assert.AreEqual(country, result.Location.Country);
        }
Example #8
0
 public LazyCacheController(
     IAppCache cache,
     WeatherApiClient weatherApiClient,
     ILogger <MemoryCacheController> logger)
 {
     _cache            = cache;
     _weatherApiClient = weatherApiClient;
     _logger           = logger;
 }
Example #9
0
 public MemoryCacheController(
     IMemoryCache memoryCache,
     WeatherApiClient weatherApiClient,
     ILogger <MemoryCacheController> logger)
 {
     _cache            = memoryCache;
     _weatherApiClient = weatherApiClient;
     _logger           = logger;
 }
        public async void ReturnsNullIfApiCallFails()
        {
            var mockHandler = GetMockMessageHandler(HttpStatusCode.GatewayTimeout, null);
            var mockFactory = GetMockHttpClientFactory(mockHandler.Object);
            var mockLogger  = new Mock <ILogger <WeatherApiClient> >();
            var apiClient   = new WeatherApiClient(mockFactory.Object, mockLogger.Object);
            // Act
            var result = await apiClient.GetLocation(1234);

            // Assert
            Assert.Null(result);
        }
        public async Task <IEnumerable <WeatherForecastResource> > Get()
        {
            var httpClient = new HttpClient();
            var client     = new WeatherApiClient("https://localhost:5003", httpClient);
            var forecast   = await client.WeatherForecastAsync();

            return(forecast.Select(x => new WeatherForecastResource
            {
                Date = x.Date.LocalDateTime,
                TemperatureC = x.TemperatureC,
                Summary = x.Summary
            })
                   .ToArray());
        }
        public async void ReturnsARedWarningWhenWindSpeedIsOverSeventy()
        {
            string locationData = File.ReadAllText("../../../Fixtures/red-warning.json");
            var    mockHandler  = GetMockMessageHandler(HttpStatusCode.OK, new StringContent(locationData));
            var    mockFactory  = GetMockHttpClientFactory(mockHandler.Object);
            var    mockLogger   = new Mock <ILogger <WeatherApiClient> >();
            var    apiClient    = new WeatherApiClient(mockFactory.Object, mockLogger.Object);

            // Act
            var result = await apiClient.GetLocation(1234);

            // Assert
            Assert.Equal("red", result.ConsolidatedWeather[0].Warning);
        }
Example #13
0
        /// <summary>
        /// Intializes the client and sets the request header user-agent to the consumingApplicationName
        /// </summary>
        /// <param name="consumingApplicationName">The name of the application that is consuming the SDK</param>
        /// <param name="metriksApiBaseAddress">The base address of the API</param>
        internal Client(string consumingApplicationName, string metriksApiBaseAddress, IApiClient client = null)
        {
            if (client == null)
            {
                apiClient = InitializeClient(consumingApplicationName, metriksApiBaseAddress);
            }
            else
            {
                apiClient = client;
            }

            Weather = new WeatherApiClient(apiClient);
            Weight  = new WeightApiClient(apiClient);
        }
Example #14
0
        public void UpdateWeather(string city)
        {
            string            url = String.Format("http://api.openweathermap.org/data/2.5/forecast/daily?q={0}&cnt={1}&units=metric&mode=json&APPID={2}", city, CNT, WeatherApiClient.GetAPIKey());
            Task <RootObject> t   = Task.Run(() => WeatherApiClient.GetWeatherForecast(url));

            t.Wait();
            RootObject r = t.Result;

            if (r != null)
            {
                WeatherList = new ObservableCollection <DayElem>(r.list);
                SelectedDay = WeatherList[0];
                Root        = r;
            }
        }
        public async void ReturnsSixDaysWeather()
        {
            string locationData = File.ReadAllText("../../../Fixtures/london.json");
            var    mockHandler  = GetMockMessageHandler(HttpStatusCode.OK, new StringContent(locationData));
            var    mockFactory  = GetMockHttpClientFactory(mockHandler.Object);
            var    mockLogger   = new Mock <ILogger <WeatherApiClient> >();
            var    apiClient    = new WeatherApiClient(mockFactory.Object, mockLogger.Object);

            // Act
            var result = await apiClient.GetLocation(31253);

            // Assert
            Assert.NotNull(result);
            Assert.Equal(6, result.ConsolidatedWeather.Count);
        }
Example #16
0
        public GameSimulator(
            string gameId,
            string weatherApiUri,
            GameMapModel map)
        {
            _gameId = gameId;

            Logger  = new Logger(gameId);
            _random = new Random();

            _tanks = new List <Tank>();
            _map   = new GameMap(map);

            _weatherApiClient = new WeatherApiClient(weatherApiUri);
        }
Example #17
0
        public async Task GetWeatherForecastAsync_ReturnsNull_WhenAnExceptionOccurs()
        {
            var config = new ExternalServicesConfig {
                Url = "http://www.example.com", MinsToCache = 0
            };

            var mockOptions = new Mock <IOptionsMonitor <ExternalServicesConfig> >();

            mockOptions.Setup(x => x.Get(It.IsAny <string>())).Returns(config);

            var client = new HttpClient(new ExceptionHandler());

            var sut = new WeatherApiClient(client, mockOptions.Object, NullLogger <WeatherApiClient> .Instance);

            var result = await sut.GetWeatherForecastAsync();

            Assert.Null(result);
        }
Example #18
0
        public async Task GetWeatherForecastAsync_ReturnsWeatherApiResult_WhenHttpRequestSucceeds()
        {
            var config = new ExternalServicesConfig {
                Url = "http://www.example.com", MinsToCache = 0
            };

            var mockOptions = new Mock <IOptionsMonitor <ExternalServicesConfig> >();

            mockOptions.Setup(x => x.Get(It.IsAny <string>())).Returns(config);

            var client = new HttpClient(new SuccessHandler());

            var sut = new WeatherApiClient(client, mockOptions.Object, NullLogger <WeatherApiClient> .Instance);

            var result = await sut.GetWeatherForecastAsync();

            Assert.IsType <WeatherApiResult>(result);
            Assert.Equal("London", result.City);
        }
Example #19
0
        private void InitializeItemsViewModel()
        {
            Title              = "Your Locations List";
            LocationInfos      = new ObservableCollection <LocationInfo>();
            LoadItemsCommand   = new Command(async() => await ExecuteLoadItemsCommand());
            DeleteItemsCommand = new Command(async location => await ExecuteDeleteLocationCommand(location));

            MessagingCenter.Subscribe <SearchPage, LocationInfo>(this, "AddItem", async(obj, item) =>
            {
                if (LocationInfos.Any(element => element.Key.Equals(item.Key)))
                {
                    return;
                }
                var weather      = await WeatherApiClient.GetCurrentWeather(item.Key);
                item.WeatherInfo = weather;
                LocationInfos.Add(item);
                await LocationService.AddItemAsync(item);
            });
        }
Example #20
0
        public async Task SearchForLocation(string searchValue)
        {
            await ExecuteCommand(async() =>
            {
                LocationInfos.Clear();

                var items         = await WeatherApiClient.SearchLocation(searchValue);
                var locationInfos = items.ToList();

                if (items.ToList().Count == 0)
                {
                    return;
                }

                foreach (var locationInfo in locationInfos)
                {
                    LocationInfos.Add(locationInfo);
                }
            });
        }
Example #21
0
        public async void ReturnsAnEmptyListAndNoApiCallIfNoQueryIsPassed()
        {
            // Arrange
            var mockHandler = GetMockMessageHandler(HttpStatusCode.OK, null);
            var mockFactory = GetMockHttpClientFactory(mockHandler.Object);
            var mockLogger  = new Mock <ILogger <WeatherApiClient> >();
            var apiClient   = new WeatherApiClient(mockFactory.Object, mockLogger.Object);

            // Act
            var result = await apiClient.LocationSearch(null);

            // Assert
            Assert.NotNull(result);
            Assert.Empty(result);

            mockHandler.Protected().Verify(
                "SendAsync",
                Times.Exactly(0), // we don't expect the api to be called
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>()
                );
        }
Example #22
0
 async Task ExecuteLoadItemsCommand()
 {
     await ExecuteCommand(async() =>
     {
         var items = await LocationService.GetItemsAsync();
         foreach (var locationInfo in items)
         {
             var weather = await WeatherApiClient.GetCurrentWeather(locationInfo.Key);
             if (weather != null)
             {
                 locationInfo.WeatherInfo = weather;
             }
         }
         if (items != null)
         {
             LocationInfos.Clear();
             foreach (var item in items)
             {
                 LocationInfos.Add(item);
             }
         }
     }
                          );
 }
        public async void ReturnsNullIfZeroIsPassed()
        {
            var mockHandler = GetMockMessageHandler(HttpStatusCode.GatewayTimeout, null);
            var mockFactory = GetMockHttpClientFactory(mockHandler.Object);
            var mockLogger  = new Mock <ILogger <WeatherApiClient> >();
            var apiClient   = new WeatherApiClient(mockFactory.Object, mockLogger.Object);

            // Act
            var result = await apiClient.GetLocation(0);

            // Assert
            Assert.Null(result);
            var expectedUri = new Uri($"{_defaultBaseUrl}/api/location/");

            mockHandler.Protected().Verify(
                "SendAsync",
                Times.Exactly(0), // we expected a single external request
                ItExpr.Is <HttpRequestMessage>(req =>
                                               req.Method == HttpMethod.Get && // we expected a GET request
                                               req.RequestUri == expectedUri // to this uri
                                               ),
                ItExpr.IsAny <CancellationToken>()
                );
        }
 public ResponseCacheController(WeatherApiClient weatherApiClient, ILogger <ResponseCacheController> logger)
 {
     _weatherApiClient = weatherApiClient;
     _logger           = logger;
 }
Example #25
0
 public WeatherService(WeatherApiClient client)
 {
     _weatherClient = client;
 }
Example #26
0
 public WeatherForecastService(IConfiguration configuration, ICacheService cache)
 {
     _configuration = configuration;
     _cache         = cache;
     apiClient      = new Client.WeatherApiClient(configuration, cache);
 }
Example #27
0
 public void Start()
 {
     weatherClient = GameObject.Find("WeatherApiClient").GetComponent <WeatherApiClient>();
 }