コード例 #1
0
        internal async Task <RoadCorridor> GetRoadStatus(string roadName)
        {
            client.BaseAddress = new Uri("https://api.tfl.gov.uk");
            //specify to use TLS 1.2 as default connection
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            var path = @"/Road/" + roadName + "?app_id=" + app_id + "&app_key=" + app_key;

            RoadCorridor        road     = null;
            HttpResponseMessage response = client.GetAsync(Uri.EscapeUriString(path)).Result;     //await client.GetAsync(path);

            if (response.IsSuccessStatusCode)
            {
                var resultList = await response.Content.ReadAsAsync <List <RoadCorridor> >();

                road = resultList.FirstOrDefault();
            }
            else
            {
                var apiError = await response.Content.ReadAsAsync <ApiError>();

                var errorMessage = string.Format("{0} is not a valid road", roadName);
                throw new Exception(errorMessage);
            }
            return(road);
        }
コード例 #2
0
        public void When_Run_GivenValidRoadId_ShouldContainStatusSeverityDesc()
        {
            HttpResponseMessage validResponse = CreateValidResponse();

            Mock <IClient> clientWrapper = new Mock <IClient>();

            clientWrapper.Setup(x => x.GetAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()))
            .Returns(Task.FromResult(validResponse));
            Client client = new Client(clientWrapper.Object);

            RoadCorridor roadInfo = client.Run(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()).GetAwaiter().GetResult();

            Assert.IsFalse(string.IsNullOrEmpty(roadInfo.StatusSeverityDescription));
        }
コード例 #3
0
ファイル: RoadTests.cs プロジェクト: MALS19/RoadStatuses
        private List <RoadCorridor> GetResponse()
        {
            var response = new RoadCorridor()
            {
                Id                        = "a2",
                DisplayName               = "A2",
                StatusSeverity            = "Good",
                StatusSeverityDescription = "No Exceptional Delays"
            };

            return(new List <RoadCorridor> {
                response
            });
        }
コード例 #4
0
        public void RoadQueryFeatures(string roadName, RoadCorridor roadCorridor, ApiError apiError)
        {
            $"Road service should not be null"
            .x(() => _roadService.Should().NotBeNull());
            $"And it should be query the road {roadName}"
            .x(async() => { (roadCorridor, apiError) = await _roadService.Get(roadName); });

            $"Than the road {roadName} query should return an api error DTO"
            .x(() => apiError.Should().NotBeNull());

            $"And road query result should be in type ApiError DTO"
            .x(() => apiError.Should().BeOfType(typeof(ApiError)));

            $"And api error result should be equal HTTP status code 404"
            .x(() => apiError.HttpStatusCode.Should().Be(404));

            $"Also api error result string should be contains 'is not a valid road' message and queried road name"
            .x(() => apiError.ToString().Should().ContainAll(new string[] { roadName, "is not a valid road" }));
        }
コード例 #5
0
        public void When_Run_GivenInvalidRoadId_ShouldThrowException()
        {
            HttpResponseMessage invalidResponse = CreateInvalidResponse();

            Mock <IClient> clientWrapper = new Mock <IClient>();

            clientWrapper.Setup(x => x.GetAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()))
            .Returns(Task.FromResult(invalidResponse));
            Client client = new Client(clientWrapper.Object);

            try
            {
                RoadCorridor roadInfo = client.Run(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()).GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                Assert.IsTrue(ex is ApiException);
                Assert.IsTrue(((ApiException)ex).ApiError.ExceptionType == "EntityNotFoundException");
            }
        }
コード例 #6
0
        public void RoadQueryFeatures(string roadName, RoadCorridor roadCorridor, ApiError apiError)
        {
            $"Road service should not be null"
            .x(() => _roadService.Should().NotBeNull());

            $"And it should be query the road {roadName}"
            .x(async() => { (roadCorridor, apiError) = await _roadService.Get(roadName); });

            $"Than the road {roadName} query should not return an api error DTO"
            .x(() => apiError.Should().BeNull());

            $"And road query result should be in type RoadCorridor DTO"
            .x(() => roadCorridor.Should().BeOfType(typeof(RoadCorridor)));

            $"And road query result should be equal queried road name as well"
            .x(() => roadCorridor.DisplayName.ToLower().Should().BeEquivalentTo(roadName.ToLower()));

            $"Also road query result string should be contains 'Road Status' and 'Road Status Description' texts"
            .x(() => roadCorridor.ToString().Should().ContainAll(new string[] { "Road Status", "Road Status Description" }));
        }
コード例 #7
0
ファイル: RoadTests.cs プロジェクト: MALS19/RoadStatuses
        private List <RoadCorridor> GetInvalidResponse()
        {
            var response = new RoadCorridor()
            {
                Id        = "A233",
                ErrorApis = new List <ErrorAPI>()
                {
                    new ErrorAPI()
                    {
                        ExceptionType  = "EntityNotFoundException",
                        HttpStatusCode = 404,
                        HttpStatus     = "NotFound",
                        Message        = "The following road id is not recognised: A233"
                    }
                }
            };

            return(new List <RoadCorridor> {
                response
            });
        }
コード例 #8
0
ファイル: RoadStatusManager.cs プロジェクト: horaciofn/TFL
        public ConsoleResponse RoadStatus(string url)
        {
            // Initialise return object
            ConsoleResponse Result = new ConsoleResponse
            {
                Lines = new List <string>()
            };

            try
            {
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
                req.Method = "GET";

                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();

                ICollection <RoadCorridor> RoadCorridors;

                // convert json response to RoadCorridor object
                using (Stream respStream = resp.GetResponseStream())
                {
                    using (StreamReader streamReader = new StreamReader(respStream, Encoding.UTF8))
                    {
                        RoadCorridors = JsonConvert.DeserializeObject <ICollection <RoadCorridor> >(streamReader.ReadToEnd());
                    }
                }

                // Response is an array, we need to retrieve the first item
                RoadCorridor roadCorridor = RoadCorridors.FirstOrDefault();

                // Fill return object
                Result.Lines.Add($"status of the { roadCorridor.displayName} is as follows");
                Result.Lines.Add($"Road Status is {roadCorridor.statusSeverity}");
                Result.Lines.Add($"Road Status Description is {roadCorridor.statusSeverityDescription}");
                Result.ExitCode = (int)EnumExitCode.OK;
            }
            catch (WebException ex)
            {
                ApiError resultError;

                // validate exception before getting json
                if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null && ((HttpWebResponse)ex.Response).StatusCode != HttpStatusCode.InternalServerError)
                {
                    var resp = (HttpWebResponse)ex.Response;

                    // convert json response to ApiError object
                    using (Stream respStream = resp.GetResponseStream())
                    {
                        using (StreamReader streamReader = new StreamReader(respStream, Encoding.UTF8))
                        {
                            resultError = JsonConvert.DeserializeObject <ApiError>(streamReader.ReadToEnd());
                        }
                    }

                    // Fill return object
                    Result.Lines.Add(resultError.message);
                    Result.ExitCode = (int)EnumExitCode.AppError;
                }
                else
                {
                    // write error log ex.Message
                    Result.ExitCode = (int)EnumExitCode.AppUnkownError;
                }
            }
            catch (Exception ex)
            {
                // write error log ex.Message
                Result.ExitCode = (int)EnumExitCode.AppUnkownError;
            }
            return(Result);
        }