public async Task GetCurrentWeather_Lisbon()
        {
            var service = new OpenWeatherMapService("948f7c5035a11f66bf2347f57aa3fe4d");
            var weather = await service.GetCurrentWeather("Lisbon");

            Assert.NotNull(weather);
        }
Ejemplo n.º 2
0
        public async Task Given2GoodWeatherSources_Handle_UseTheTopPriorityOne()
        {
            GetCurrentWeatherQuery query = new GetCurrentWeatherQuery("AU", "Melbourne");

            IOptions <WeatherStackConfig> weatherStackconfig = Options.Create(new WeatherStackConfig
            {
                Units         = UnitsEnum.Metric,
                PriorityOrder = 1
            });
            var weatherStackService = new Mock <WeatherStackService>(weatherStackconfig);

            weatherStackService.Setup(w => w.GetCurrentWeather("AU", "Melbourne"))
            .ReturnsAsync((new WeatherOutputModel(5, 23), string.Empty));
            IOptions <OpenWeatherMapConfig> config = Options.Create(new OpenWeatherMapConfig
            {
                Units         = UnitsEnum.Metric,
                PriorityOrder = 2
            });
            OpenWeatherMapService openWeatherMapService = new OpenWeatherMapService(config);

            List <IWeatherService> weatherServices = new List <IWeatherService>
            {
                weatherStackService.Object, openWeatherMapService
            };

            var memoryCache = new Mock <IMemoryCacheService>();

            memoryCache.Setup(m => m.SetCache(It.IsAny <string>(), It.IsAny <object>()));

            GetCurrentWeatherQueryHandler queryHandler = new GetCurrentWeatherQueryHandler(weatherServices, memoryCache.Object);
            await queryHandler.Handle(query, CancellationToken.None);

            //assert
            weatherStackService.Verify(w => w.GetCurrentWeather("AU", "Melbourne"));
        }
        public void GetWeatherDataTest()
        {
            OpenWeatherMapService openWeatherMapService = OpenWeatherMapService.Instance;

            WeatherData exeptedWeatherData = new WeatherData();
            City        city = new City();

            city.ID                 = "2643743";
            city.Country            = "GB";
            city.Name               = "London";
            city.Lon                = -0.13;
            city.Lat                = 51.51;
            exeptedWeatherData.City = city;

            Location loction = new Location();

            loction.Name = "London";
            WeatherData actualWeatherData = openWeatherMapService.GetWeatherData(loction);

            Assert.IsNotNull(actualWeatherData);
            Assert.AreEqual(exeptedWeatherData.City.ID, actualWeatherData.City.ID);
            Assert.AreEqual(exeptedWeatherData.City.Country, actualWeatherData.City.Country);
            Assert.AreEqual(exeptedWeatherData.City.Name, actualWeatherData.City.Name);
            Assert.AreEqual(exeptedWeatherData.City.Lat, actualWeatherData.City.Lat);
            Assert.AreEqual(exeptedWeatherData.City.Lon, actualWeatherData.City.Lon);
        }
Ejemplo n.º 4
0
        public void AcceptancePolandWarsawTest()
        {
            var service  = new OpenWeatherMapService();
            var response = service.GetWeatherForecastAsync(new Services.Models.WeatherForecastRequest
            {
                Configuration = new Services.Models.ApiConfiguration
                {
                    ApiKey = "ffa42a7152fe42b4afb5139e65b3c6d7"
                },
                Location = new Services.Models.Location
                {
                    City    = "Warsaw",
                    Country = "Poland"
                }
            }).Result;

            Assert.NotNull(response);
            Assert.NotNull(response.Location);
            Assert.NotNull(response.Tempreature);
            Assert.Equal("warsaw", response.Location.City.ToLower());
            Assert.Equal("poland", response.Location.Country.ToLower());
            Assert.Equal("celsius", response.Tempreature.Format.ToLower());
            Assert.NotEqual(0, response.Tempreature.Value);
            Assert.NotEqual(0, response.Humidity);
        }
Ejemplo n.º 5
0
        public async void GetWeather()
        {
            WeatherConditions weather;

            var melbourneLocation = new Location()
            {
                Latitude  = "-37.8136",
                Longitude = "144.9631"
            };
            var serializedMelbourne = JsonConvert.SerializeObject(melbourneLocation);

            var cacheRepository = new CacheRepository <WeatherConditions>(_TomataboardContext);

            var openWeatherMapService = new OpenWeatherMapService(new StubLogger <OpenWeatherMapService>(), _openWeatherMapKeys);

            weather = await openWeatherMapService.Execute(serializedMelbourne);

            Assert.NotNull(weather);

            var forecastService = new ForecastService(new StubLogger <ForecastService>(), _forecastKeys);

            weather = await forecastService.Execute(serializedMelbourne);

            Assert.NotNull(weather);

            //var yahooWeatherService = new YahooWeatherService(new StubLogger<YahooWeatherService>(), _yahooWeatherKeys);

            //var provider = new WeatherProvider(new StubLogger<WeatherProvider>(), cacheRepository, forecastService,openWeatherMapService, yahooWeatherService);
            //weather = await provider.Execute(serializedMelbourne);
            Assert.NotNull(weather);
        }
 public WeatherForecastViewModel()
 {
     model          = new WeatherForecast();
     owms           = new OpenWeatherMapService();
     City           = "Lugano";
     WeatherCommand = new DelegateCommand(OnWeather);
 }
Ejemplo n.º 7
0
        public void TempratreAndHumidityTest()
        {
            var service  = new OpenWeatherMapService();
            var response = service.GetWeatherForecastAsync(new Services.Models.WeatherForecastRequest
            {
                Configuration = new Services.Models.ApiConfiguration
                {
                    ApiKey = "ffa42a7152fe42b4afb5139e65b3c6d7"
                },
                Location = new Services.Models.Location
                {
                    City    = "London",
                    Country = "United Kingdom"
                }
            }).Result;

            Assert.NotNull(response);
            Assert.NotNull(response.Location);
            Assert.NotNull(response.Tempreature);
            Assert.Equal("london", response.Location.City.ToLower());
            Assert.Equal("united kingdom", response.Location.Country.ToLower());
            Assert.Equal("celsius", response.Tempreature.Format.ToLower());
            Assert.NotEqual(0, response.Tempreature.Value);
            Assert.NotEqual(0, response.Humidity);
        }
Ejemplo n.º 8
0
        private void button1_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
            var location = new Location(textBox1.Text);

            OpenWeatherMapService.SetKey("7a27417787c2bea7d429df742eaf139d");
            var service =
                WeatherDataServiceFactory.GetWeatherDataService(WeatherDataServiceFactory.OPEN_WEATHER_MAP);
            var history  = textBox1.Text;
            var data     = service.GetWeatherData(location);
            var dataText = data;

            //Convert.ToString(dataText);
            richTextBox1.AppendText(Convert.ToString(dataText));
            richTextBox2.AppendText("\n" + history);
            //richTextBox1.AppendText = data.ToString();
            Console.Write(data.ToString());

            /*
             * var c = Console.ReadKey();
             * Console.Clear();
             * if (c.KeyChar == 'n')
             * {
             *   Console.WriteLine("Bye Bye!");
             *   break;
             * }*/
        }
Ejemplo n.º 9
0
    // Use this for initialization
    void Start()
    {
        _myText = GameObject.Find("DebugText").GetComponent <Text>();

#if WINDOWS_UWP
        owms = new OpenWeatherMapService();
#endif
    }
Ejemplo n.º 10
0
        public MainPage()
        {
            InitializeComponent();
            On<Xamarin.Forms.PlatformConfiguration.iOS>().SetUseSafeArea(true);
            _openWeatherMapService = new OpenWeatherMapService();

            _brightnessService = DependencyService.Get<IBrightnessService>();
        }
Ejemplo n.º 11
0
        public void GetWeatherDataTest()
        {
            var location = new Location("Tel aviv");

            OpenWeatherMapService.SetKey("7ee2765dd79071b177532e10e1118cff");
            var service = WeatherDataServiceFactory.GetWeatherDataService(ServiceName.OpenWeatherMap);
            var data    = service.GetWeatherData(location);

            Assert.IsNotNull(data);
        }
Ejemplo n.º 12
0
        public MapsModule()
        {
            InitializeComponent();

            TilesLayer.DataProvider = MapUtils.CreateBingDataProvider(BingMapKind.Area);
            mapControl1.SetMapItemFactory(new DemoWeatherItemFactory());

            this._openWeatherMapService          = new OpenWeatherMapService(LoadCapitalsFromXML());
            OpenWeatherMapService.ReadCompleted += OpenWeatherMapService_ReadCompleted;
            _openWeatherMapService.GetWeatherAsync();
        }
Ejemplo n.º 13
0
        private async Task LoadWeatherAsync(IEnumerable <City> cities)
        {
            var service = new OpenWeatherMapService();
            List <WeatherForecast> forecast = new List <WeatherForecast>();

            foreach (var cityFollowed in cities)
            {
                var weather = await service.GetCurrentWeatherByCityAsync(cityFollowed);

                forecast.Add(weather);
            }
            Forecast.ItemsSource = forecast;
        }
Ejemplo n.º 14
0
        public override async Task OnInitializing()
        {
            await base.OnInitializing();

            var weather = await OpenWeatherMapService.GetDemoWeatherInfoAsync();

            if (weather is WeatherInfo)
            {
                var weatherInfo = weather as WeatherInfo;
                LocationText.Text = weatherInfo.LocationName;
                TempText.Text     = $"{Math.Round(weatherInfo.Temp)}˚{weatherInfo.TempUnitShort}";
                DateText.Text     = LocalTime.Now.ToString("dddd, MMMM dd");
            }
        }
        public async void GetOpenWeatherForecast_ShouldReturnTheWeatherForecast()
        {
            var openWeatherMapService = new OpenWeatherMapService(new HttpClient());

            var location = new Position {
                Latitude = 41.890969, Longitude = -87.676392
            };

            var resultTask = openWeatherMapService.Get7DayForecastAsync(location);

            resultTask.Wait();

            Assert.IsNotNull(resultTask.Result);
        }
        static async Task <bool> GetPressure(TelemetryItem inputTable)
        {
            OpenWeatherMapService client = new OpenWeatherMapService(owmKey);
            var result = await client.GetWeatherAsync("Sydney, AU", LanguageCode.EN, Unit.Metric);

            if (result.IsSuccess)
            {
                inputTable.hPa      = result.Response.MainWeather.Pressure;
                inputTable.Humidity = result.Response.MainWeather.Humidity;

                return(true);
            }
            return(false);
        }
        public MainPage()
        {
            InitializeComponent();

            // Initialize OpenWeatherMap service
            service = new OpenWeatherMapService();

            // Initialize weather data list
            forecastData = new List <WeatherForecast>();

            weathers = new List <Weather>();

            this.BindingContext = this;
        }
Ejemplo n.º 18
0
        public void GetForecast_ShouldReturnA7DayForecast()
        {
            //TODO supply mock instance
            var openWeatherMapService = new OpenWeatherMapService(new HttpClient());
            var forecastService       = new ForecastService(openWeatherMapService);
            var location = new Position {
                Latitude = 41.890969, Longitude = -87.676392
            };

            var resultTask = forecastService.GetForecastAsync(location);

            resultTask.Wait();

            Assert.IsNotNull(resultTask.Result);
            Assert.AreEqual(resultTask.Result.WeatherList.Count, 7);
        }
Ejemplo n.º 19
0
        }//OnNavigatedTo

        //Ref https://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage(v=vs.110).aspx
        //    https://stackoverflow.com/questions/32314799/uwp-image-uri-in-application-folder
        public async void CurrentWeather()
        {
            try
            {
                var currentPosition = await GeoLocationService.GetPosition();
                RootObject myWeather = await OpenWeatherMapService.GetWeather(currentPosition.Coordinate.Point.Position.Latitude, currentPosition.Coordinate.Point.Position.Longitude);

                //Set labels
                Label0.Text = "Location";
                Label1.Text = "Description";
                Label2.Text = "Temperature";
                Label3.Text = "Wind Speed";
                Label4.Text = "Sun Rise";
                Label5.Text = "Sun Set";

                //Display weather image
                string icon = String.Format("ms-appx:///Assets/Weather/{0}.png", myWeather.weather[0].icon);
                WeatherImage.Source = new BitmapImage(new Uri(icon, UriKind.Absolute));

                //Display location
                LocationBlock.Text = myWeather.name;

                //Display weather description
                DescriptionBlock.Text = FirstCharToUpper(myWeather.weather[0].description);

                //Display temperature
                TemperatureBlock.Text = string.Format("{0}°C", myWeather.main.temp);

                //Display wind speed
                WindBlock.Text = string.Format("{0} m/s", myWeather.wind.speed);

                //Display time of sunrise and sunset
                var srTime = myMethods.getDate(myWeather.sys.sunrise);
                var ssTime = myMethods.getDate(myWeather.sys.sunset);
                var sunRise = srTime.ToString("H:mm");
                var sunSet = ssTime.ToString("H:mm");
                SunRiseBlock.Text = string.Format("{0}", sunRise);
                SunSetBlock.Text = string.Format("{0}", sunSet);
            }
            catch
            {
                WorldTidesStation.Text = "Error retrieving data";
                myMethods.EnableGPSDialog();
            }
        }//CurrentWeather
Ejemplo n.º 20
0
        public void GivenMockResponse_OpenWeatherMap_TransformResponse_ShouldReturnValidData()
        {
            using (StreamReader r = new StreamReader("openWeatherMapResponse.json"))
            {
                string mockResponse = r.ReadToEnd();

                IOptions <OpenWeatherMapConfig> config = Options.Create(new OpenWeatherMapConfig
                {
                    Units = UnitsEnum.Metric
                });
                OpenWeatherMapService weatherMapService = new OpenWeatherMapService(config);
                var(weatherOutput, error) = weatherMapService.TransformResponse(mockResponse);

                Assert.Empty(error);
                Assert.Equal((decimal)14.79, weatherOutput.temperature_degrees);
                Assert.Equal((decimal)(9.8 * 3.6), weatherOutput.wind_speed);
            }
        }
        public MainPage(string location)
        {
            // Set city
            city = location;

            // Initialize OpenWeatherMap service
            service = new OpenWeatherMapService();

            // Initialize weather data list
            forecastData = new List <WeatherForecast>();

            weathers = new List <Weather>();

            GetWeather(location);

            InitializeComponent();

            this.BindingContext = this;
        }
Ejemplo n.º 22
0
        public async Task VerifyServiceWorks()
        {
            var locationProvider = new Mock <ILocationProvider>();

            locationProvider.Setup(m => m.GetPositionAsync())
            .ReturnsAsync(new GeoLocation
            {
                Latitude  = 44.55d,
                Longitude = 23,
            });

            var weatherService = new OpenWeatherMapService(locationProvider.Object, new RequestProvider());

            for (var i = 0; i < 15; i++)
            {
                var weather = await weatherService.GetWeatherInfoAsync();

                Assert.IsInstanceOf(typeof(WeatherInfo), weather);
            }
        }
Ejemplo n.º 23
0
        protected override async Task ConfigureAsync(IDeviceService deviceService)
        {
            var pi2PortController = new Pi2GpioService();

            var openWeatherMapService = new OpenWeatherMapService(
                ServiceLocator.GetService <IDateTimeService>(),
                ServiceLocator.GetService <ISchedulerService>(),
                ServiceLocator.GetService <ISystemInformationService>());

            ServiceLocator.RegisterService(typeof(IOutdoorTemperatureService), new OutdoorTemperatureService(openWeatherMapService, ServiceLocator.GetService <IDateTimeService>()));
            ServiceLocator.RegisterService(typeof(IOutdoorHumidityService), new OutdootHumidityService(openWeatherMapService, ServiceLocator.GetService <IDateTimeService>()));
            ServiceLocator.RegisterService(typeof(IDaylightService), new DaylightService(openWeatherMapService, ServiceLocator.GetService <IDateTimeService>()));
            ServiceLocator.RegisterService(typeof(IWeatherService), new WeatherService(openWeatherMapService, ServiceLocator.GetService <IDateTimeService>()));
            ServiceLocator.RegisterService(typeof(OpenWeatherMapService), openWeatherMapService);

            var ccToolsFactory = new CCToolsBoardService(this, GetDevice <II2CBusService>());
            var hsrt16         = ccToolsFactory.CreateHSRT16(Device.CellarHSRT16, new I2CSlaveAddress(32));

            var garden = this.CreateArea(RoomId.Garden)
                         .WithLamp(Garden.LampTerrace, hsrt16[HSRT16Pin.Relay15])
                         .WithLamp(Garden.LampGarage, hsrt16[HSRT16Pin.Relay14])
                         .WithLamp(Garden.LampTap, hsrt16[HSRT16Pin.Relay13])
                         .WithLamp(Garden.SpotlightRoof, hsrt16[HSRT16Pin.Relay12])
                         .WithLamp(Garden.LampRearArea, hsrt16[HSRT16Pin.Relay11])
                         .WithSocket(Garden.SocketPavillion, hsrt16[HSRT16Pin.Relay10])
                         // 9 = free
                         .WithLamp(Garden.LampParkingLot, new LogicalBinaryOutput().WithOutput(hsrt16[HSRT16Pin.Relay8]).WithOutput(hsrt16[HSRT16Pin.Relay6]).WithOutput(hsrt16[HSRT16Pin.Relay7]))
                         .WithButton(Garden.Button, pi2PortController.GetInput(4).WithInvertedState())
                         .WithStateMachine(Garden.StateMachine, SetupStateMachine);

            garden.GetStateMachine(Garden.StateMachine).ConnectMoveNextAndToggleOffWith(garden.GetButton(Garden.Button));

            garden.SetupConditionalOnAutomation()
            .WithActuator(garden.GetLamp(Garden.LampParkingLot))
            .WithOnAtNightRange()
            .WithOffBetweenRange(TimeSpan.Parse("22:30:00"), TimeSpan.Parse("05:00:00"));

            TimerService.Tick += (s, e) => { pi2PortController.PollOpenInputPorts(); };

            await base.ConfigureAsync();
        }
Ejemplo n.º 24
0
        // GET: Note
        public ViewResult Index(string sortOrder, string searchString)
        {
            // Sort function using viewbag
            ViewBag.NameSort = String.IsNullOrEmpty(sortOrder) ? "message_desc" : "";
            ViewBag.DateSort = sortOrder == "Date" ? "date_desc" : "Date";
            var notes = from n in _context.Notes
                        select n;

            if (!String.IsNullOrEmpty(searchString))
            {
                notes = notes.Where(n => n.Message.Contains(searchString));
            }
            switch (sortOrder)
            {
            case "message_desc":
                notes = notes.OrderByDescending(n => n.Message);
                break;

            case "Date":
                notes = notes.OrderBy(n => n.Date);
                break;

            case "date_desc":
                notes = notes.OrderByDescending(n => n.Date);
                break;

            default:
                notes = notes.OrderBy(n => n.Message);
                break;
            }

            var weatherService = new OpenWeatherMapService();
            var notelist       = notes.ToList();

            foreach (var note in notelist)
            {
                weatherService.FindMaxTemp(note);
            }

            return(View(notes.ToList()));
        }
Ejemplo n.º 25
0
        public void Setup()
        {
            var httpMessageResponse = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(@"{""Name"": ""Bothell""}")
            };

            mockHandler
            .Protected()
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>())
            .ReturnsAsync(httpMessageResponse);



            mockConfig.SetupGet(x => x[It.Is <string>(s => s == "values:OpenWeatherMapAppId")]).Returns("FakeAppId");
            _service = new OpenWeatherMapService(new HttpClient(mockHandler.Object), mockLogger.Object, mockConfig.Object);
        }
        public static async Task Run([TimerTrigger("0 */15 * * * *")] TimerInfo myTimer, TraceWriter log, ExecutionContext context, [Blob("cache/weatherData.json", System.IO.FileAccess.Write)] CloudBlockBlob blob)
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();

            string apiKey = config["ApiKey"]; //Robert Schlaeger API Key for OpenWeatherMap
            OpenWeatherMapService weatherService = new OpenWeatherMapService(apiKey);

            OpenWeatherMapServiceResponse <WeatherRoot> res = await weatherService.GetWeatherAsync("München", LanguageCode.DE);

            log.Info(res.Response.CityId.ToString());

            var outputJson = JsonConvert.SerializeObject(res.Response);

            blob.Properties.ContentType = "application/json";
            await blob.UploadTextAsync(outputJson);

            //TODO: Implement Parsing
        }
Ejemplo n.º 27
0
 private static void Main(string[] args)
 {
     while (true)
     {
         Console.WriteLine("Welcom to the Weather App!");
         Console.WriteLine("Please enter location: ");
         var location = new Location(Console.ReadLine());
         OpenWeatherMapService.SetKey("7ee2765dd79071b177532e10e1118cff");
         var service =
             WeatherDataServiceFactory.GetWeatherDataService(WeatherDataServiceFactory.OPEN_WEATHER_MAP);
         var data = service.GetWeatherData(location);
         Console.WriteLine(data);
         Console.WriteLine("press n to exit or any key to try again");
         var c = Console.ReadKey();
         Console.Clear();
         if (c.KeyChar == 'n')
         {
             Console.WriteLine("Bye Bye!");
             break;
         }
     }
 }
        /// <summary>
        /// This method will retrieve an array of forecasts from the OpenWeatherMap service,
        /// pick a forecast for the day, determine which contact method should be used for that
        /// day, and return an IEnumerable that contains all of the days and the associated
        /// contact method.
        ///
        /// The temperature boundaries for high and low temperatures are configurable, as are
        /// the codes that specify whether a weather condition specifies rain. Yes, this means
        /// that some yo-yo can put in the code for sand storm and have it mean "rain" but you
        /// can't have everything in life. And this is just an example...
        /// </summary>
        /// <param name="location">The name of the city for which we are returning contact methods. Example: "Minneapolis".</param>
        /// <returns></returns>
        public async Task <IEnumerable <ContactMethod> > GetContactMethodsForCity(string location)
        {
            var url = $"{_apiConfig.BaseForecastUrl}q={location.ToLower()},us&units=imperial&APPID={_apiConfig.AppId}";

            // TODO: talk to architect about what should be logged, if anything. I have found it helpful for debugging to log things at various points of during a process.
            _logger.LogInformation($"About to get data from \"{url}\"");

            OpenWeatherMapResponse response = await OpenWeatherMapService.GetForecastsForLocation(url);

            IEnumerable <ContactMethod> contactMethods = null;

            // If there is an object, we got data back from the call to the API. So figure out what the contact method should be for each day returned.
            if (response.OpenWeatherMapData != null)
            {
                // TODO: talk to team about whether we should consider picking a different time of day. I picked 3:00pm because that time is mostly likely to be the highest temperature for the day.

                // Get all forecasts for 3:00pm
                contactMethods = from f in response.OpenWeatherMapData.Forecasts
                                 where f.ForecastDateTime.TimeOfDay == new TimeSpan(15, 0, 0)
                                 select new ContactMethod {
                    ContactDate = f.ForecastDateTime, ContactType = MethodOfContact(f)
                };
            }
            else
            {
                // TODO: talk with team about what should be logged. I included the HTTP response the the OpenWeatherMapResponse class in case we wanted to save anything from that for debugging purposes.
                if (response.Excp != null)
                {
                    _logger.LogError(response.Excp, "Something really bad happened!");
                }
                else
                {
                    _logger.LogInformation($"Probably used a city name that OpenWeatherMap doesn't know about. HTTP response code: {response.HttpResponseMessage.StatusCode.ToString()} : {response.HttpResponseMessage.ReasonPhrase}");
                }
            }

            return(contactMethods);
        }
Ejemplo n.º 29
0
        public async Task GivenAllBadWeatherSources_Handle_ShouldGetFromMemoryCache()
        {
            GetCurrentWeatherQuery query = new GetCurrentWeatherQuery("AU", "Melbourne");

            IOptions <OpenWeatherMapConfig> config = Options.Create(new OpenWeatherMapConfig
            {
                BaseURL       = "WillFailURL",
                Units         = UnitsEnum.Metric,
                PriorityOrder = 1
            });
            OpenWeatherMapService openWeatherMapService = new OpenWeatherMapService(config);

            IOptions <WeatherStackConfig> weatherStackConfig = Options.Create(new WeatherStackConfig
            {
                BaseURL       = "WillFailURL",
                Units         = UnitsEnum.Metric,
                PriorityOrder = 2
            });
            var weatherStackService = new WeatherStackService(weatherStackConfig);

            List <IWeatherService> weatherServices = new List <IWeatherService>
            {
                weatherStackService, openWeatherMapService
            };

            var memoryCache = new Mock <IMemoryCacheService>();

            memoryCache.Setup(m => m.GetValueFromCache <WeatherOutputModel>(It.IsAny <string>())).Returns(new WeatherOutputModel(5, 23));

            GetCurrentWeatherQueryHandler queryHandler = new GetCurrentWeatherQueryHandler(weatherServices, memoryCache.Object);

            var(weatherOutput, error) = await queryHandler.Handle(query, CancellationToken.None);

            //assert
            Assert.Empty(error);
            Assert.Equal(5, weatherOutput.wind_speed);
            Assert.Equal(23, weatherOutput.temperature_degrees);
        }
Ejemplo n.º 30
0
        public async Task TestGetWeatherData_HttpClientFailure_Should_Return_Null()
        {
            var httpMessageResponse = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.BadRequest,
            };

            var mockHandler = new Mock <HttpMessageHandler>();

            mockHandler
            .Protected()
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.IsAny <HttpRequestMessage>(),
                ItExpr.IsAny <CancellationToken>())
            .ReturnsAsync(httpMessageResponse);

            var service = new OpenWeatherMapService(new HttpClient(mockHandler.Object), mockLogger.Object, mockConfig.Object);

            var result = await service.GetWeatherData("98012");

            result.Should().Be(null);
        }