public CityDto GetCity(string name) { string weatherApiUrl = HttpUtility.HtmlDecode(ConfigurationManager.AppSettings["WeatherApiUrl"]); int cityDataTimeout = Convert.ToInt32(ConfigurationManager.AppSettings["CityDataTimeoutHrs"]); CityDto city = _cityRepository.SelectCityByName(name); if (city == null || (city != null && city.LastUpdatedDateTimeUtc.AddHours(cityDataTimeout) <= DateTime.UtcNow)) { string getWeatherDataUri = string.Format(weatherApiUrl, name); GetWeatherDataResponse apiResponse = _apiService.GetRequest <GetWeatherDataResponse>(getWeatherDataUri); if (city == null) { city = new CityDto(); } city.Name = name; city.Latitude = apiResponse.Coord.Lat; city.Longitude = apiResponse.Coord.Lon; city.Temperature = apiResponse.Main.Temp; city.LastUpdatedDateTimeUtc = DateTime.UtcNow; city = _cityRepository.InsertOrUpdateCity(city); } return(city); }
public void GetCity_ShouldReturnCityFromApiIfCityFromRepoIsExpired() { CityDto city = new CityDto(); city.Name = "London"; city.Temperature = 20; city.LastUpdatedDateTimeUtc = DateTime.UtcNow.AddHours(-2); GetWeatherDataResponse getWeatherDataResponse = new GetWeatherDataResponse(); getWeatherDataResponse.Id = 54321; getWeatherDataResponse.City = "London"; getWeatherDataResponse.Coord = new GetWeatherDataResponseCoord { Lat = 50, Lon = -50 }; getWeatherDataResponse.Main = new GetWeatherDataResponseMain { Temp = 26 }; _cityRepository .Setup(x => x.SelectCityByName("London")) .Returns(city); _apiService .Setup(x => x.GetRequest <GetWeatherDataResponse>("http://api.weather.com/weather?city=London")) .Returns(getWeatherDataResponse); _cityRepository .Setup(x => x.InsertOrUpdateCity(It.Is <CityDto>(y => y.Name == "London"))) .Returns(new CityDto { Id = 1, Name = getWeatherDataResponse.City, Latitude = getWeatherDataResponse.Coord.Lat, Longitude = getWeatherDataResponse.Coord.Lon, Temperature = getWeatherDataResponse.Main.Temp }); CityDto actual = _locationService.GetCity("London"); Assert.IsNotNull(actual); Assert.AreEqual(getWeatherDataResponse.Main.Temp, actual.Temperature); }