public static async Task Execute(AhkResult ahkResult)
        {
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("###### Feladat 1 ###### Exercise 1 ######");

            try
            {
                await testGetWithNotFound(ahkResult);
                await testGetWithSuccess(ahkResult);

                // screenshot is mandatory
                if (!ScreenshotValidator.IsScreenshotPresent("screenshot.png", "screenshot.png", ahkResult))
                {
                    ahkResult.ResetPointToZero();
                }
            }
            catch (MissingMethodException ex) // expected problem, violates contract, solution evaluation ignored
            {
                ahkResult.AddProblem(ex, "Nem megengedett kodot valtoztattal. Changed code that you should not have.");
            }
            catch (TypeLoadException ex) // expected problem, violates contract, solution evaluation ignored
            {
                ahkResult.AddProblem(ex, "Nem megengedett kodot valtoztattal. Changed code that you should not have.");
            }
        }
        public static async Task StartWebApp(AhkResult result)
        {
            // Workaround for WebApplicationFactory, otherwise it does not start
            // https://github.com/aspnet/Hosting/blob/release/2.1/src/Microsoft.AspNetCore.TestHost/WebHostBuilderExtensions.cs#L61
            System.IO.File.CreateText(@"/app/dummy.sln").Close();

            Console.WriteLine("Starting web application...");

            try
            {
                appFactory = new WebApplicationFactory <homework.Startup>()
                             .WithWebHostBuilder(builder =>
                {
                    // override the web host startup with custom settings
                    builder.UseContentRoot(@"/app");
                    builder.UseUrls(WebAppBaseUrl);

                    builder.ConfigureServices(services =>
                    {
                        // e.g. you can replace DI services or change their configuration
                        // the sample below removes an Entity Framework DbContext and replaces it with custom data source
                        // services.RemoveAll(typeof(MyDbContext));
                        // services.AddDbContext<MyDbContext>(options => options.UseSqlite("Data Source=temp.db"));
                    });
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine("Cannot start web application. This might be a bug in the solution.");
                Console.WriteLine("Nem indithato el a webalkalmazas. Ez egy bug lehet a megoldasban.");

                throw new Exception("Cannot start web application. This might be a bug in the solution.", ex);
            }

            Console.WriteLine("Web application started.");

            // verifies connection to the web application
            using (var scope = GetRequestScope())
            {
                try
                {
                    var pingResult = await scope.HttpClient.GetAsync("/api/ping");

                    pingResult.EnsureSuccessStatusCode();

                    Console.WriteLine("Web app responding to PING.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Web app not responding to ping. This might be a bug in the solution.");
                    Console.WriteLine("Webalkalmazas nem valaszol a ping keresre. Ez egy bug lehet a megoldasban.");

                    throw new Exception("Web app not responding to ping. This might be a bug in the solution.", ex);
                }
            }
        }
        /// <summary>
        /// GET /api/sample 404
        /// </summary>
        private static async Task testGetWithNotFound(AhkResult ahkResult)
        {
            using (var scope = WebAppInit.GetRequestScope())
            {
                var restGetNoResult = await scope.HttpClient.TryGet <homework.Model.SampleData>("/api/sample?input=no", ahkResult, allowNotFound : true);

                if (restGetNoResult.Success)
                {
                    ahkResult.AddPoints(1);
                    ahkResult.Log("GET /api/sample with notfound");
                }
            }
        }
Exemple #4
0
        /// <summary>
        /// DELETE /api/sample
        /// </summary>
        private static async Task testDelete(AhkResult ahkResult)
        {
            using (var scope = WebAppInit.GetRequestScope())
            {
                var deleteOkResponse = await scope.HttpClient.TryDelete($"/api/sample?input=apple", ahkResult);

                if (deleteOkResponse.Success)
                {
                    ahkResult.AddPoints(2);
                    ahkResult.Log("DELETE /api/sample ok");
                }
                else
                {
                    ahkResult.AddProblem("DELETE /api/sample valasz tartalma hibas. DELETE /api/sample yields invalid reponse.");
                }
            }
        }
Exemple #5
0
        public static async Task Execute(AhkResult ahkResult)
        {
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("###### Feladat 2 ###### Exercise 2 ######");

            try
            {
                await testDelete(ahkResult);
            }
            catch (MissingMethodException ex) // expected problem, violates contract, solution evaluation ignored
            {
                ahkResult.AddProblem(ex, "Nem megengedett kodot valtoztattal. Changed code that you should not have.");
            }
            catch (TypeLoadException ex) // expected problem, violates contract, solution evaluation ignored
            {
                ahkResult.AddProblem(ex, "Nem megengedett kodot valtoztattal. Changed code that you should not have.");
            }
        }
        /// <summary>
        /// GET /api/sample 200
        /// </summary>
        private static async Task testGetWithSuccess(AhkResult ahkResult)
        {
            using (var scope = WebAppInit.GetRequestScope())
            {
                var restGetResult = await scope.HttpClient.TryGet <homework.Model.SampleData>("/api/sample?input=apple", ahkResult);

                if (restGetResult.Success)
                {
                    if (restGetResult.Value != null && restGetResult.Value.Name.Equals("apple", StringComparison.OrdinalIgnoreCase))
                    {
                        ahkResult.AddPoints(1);
                        ahkResult.Log("GET /api/sample with success");
                    }
                    else
                    {
                        ahkResult.Log("Returned item does not match expected data.");
                    }
                }
            }
        }
        public static async Task <TryResult <T> > TryExecuteAndReadResponse <T>(this Task <HttpResponseMessage> send, string httpMethod, string url, AhkResult ahkResult,
                                                                                bool allowNotFound = false, Predicate <HttpResponseMessage> responseAdditionalCheck = null)
        {
            var requestMethodAndUrl = $"{httpMethod.ToUpperInvariant()} {url}";
            HttpResponseMessage responseMessage;

            try
            {
                responseMessage = await send;
            }
            catch (Exception ex)
            {
                ahkResult.AddProblem(ex, $"{requestMethodAndUrl} keres sikertelen. {requestMethodAndUrl} request unsuccessful.");
                return(TryResult <T> .Failed());
            }

            if (responseAdditionalCheck != null)
            {
                if (!responseAdditionalCheck(responseMessage))
                {
                    return(TryResult <T> .Failed());
                }
            }

            if (allowNotFound && responseMessage.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                return(TryResult <T> .Ok(default(T)));
            }

            return(await responseMessage.TryReadResponse <T>(ahkResult));
        }
 public static async Task <TryResult <TResult> > TryGet <TResult>(this HttpClient httpClient, string url, AhkResult ahkResult, bool allowNotFound = false)
 {
     return(await httpClient.GetAsync(url).TryExecuteAndReadResponse <TResult>("GET", url, ahkResult, allowNotFound: allowNotFound));
 }
        public static async Task <TryResult <bool> > TryDelete(this HttpClient httpClient, string url, AhkResult ahkResult)
        {
            var requestMethodAndUrl = $"DELETE {url}";

            try
            {
                var responseMessage = await httpClient.DeleteAsync(url);

                if (responseMessage.StatusCode == System.Net.HttpStatusCode.OK || responseMessage.StatusCode == System.Net.HttpStatusCode.NoContent)
                {
                    return(TryResult <bool> .Ok(true));
                }
                else
                {
                    return(TryResult <bool> .Ok(false));
                }
            }
            catch (Exception ex)
            {
                ahkResult.AddProblem(ex, $"{requestMethodAndUrl} keres sikertelen. {requestMethodAndUrl} request unsuccessful.");
                return(TryResult <bool> .Failed());
            }
        }
        public static async Task <TryResult <TResult> > TryPostWithReturnValue <TResult>(this HttpClient httpClient, string url, object value, AhkResult ahkResult, bool requireLocationHeader = false)
        {
            return(await httpClient.PostAsJsonAsync(url, value).TryExecuteAndReadResponse <TResult>("POST", url, ahkResult,
                                                                                                    responseAdditionalCheck: httpResponse =>
            {
                if (requireLocationHeader)
                {
                    if (!httpResponse.Headers.Contains(Microsoft.Net.Http.Headers.HeaderNames.Location) || httpResponse.Headers.Location == null)
                    {
                        ahkResult.AddProblem($"POST {url} valaszban hianyzo header. POST {url} reponse missing header.");
                        return false;
                    }
                }

                return true;
            }));
        }
        public static async Task <TryResult <TResult> > TryReadResponse <TResult>(this HttpResponseMessage httpResponse, AhkResult ahkResult)
        {
            var requestMethodAndUrl = $"{httpResponse.RequestMessage.Method.Method.ToUpperInvariant()} {httpResponse.RequestMessage.RequestUri}";

            if (!httpResponse.IsSuccessStatusCode)
            {
                ahkResult.AddProblem($"{requestMethodAndUrl} hibas valaszkod {httpResponse.StatusCode}. {requestMethodAndUrl} yields invalid response {httpResponse.StatusCode}.");
                return(TryResult <TResult> .Failed());
            }

            try
            {
                var value = await httpResponse.Content.ReadAsAsync <TResult>();

                if (value == null)
                {
                    ahkResult.AddProblem($"{requestMethodAndUrl} valasz tartalma hibas. {requestMethodAndUrl} yields invalid content.");
                    return(TryResult <TResult> .Failed());
                }

                return(TryResult <TResult> .Ok(value));
            }
            catch (Exception ex)
            {
                ahkResult.AddProblem(ex, $"{requestMethodAndUrl} valasz tartalma hibas. {requestMethodAndUrl} yields invalid content.");
                return(TryResult <TResult> .Failed());
            }
        }