Exemple #1
0
        public void GroupByJokeSize_OnlyLongJokeSizes_ReturnsEmptyForOtherSizes()
        {
            // Arrange
            int expected = 0;

            var jokeLong1 = new JokeResponse()
            {
                Joke = "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty"
            };
            var jokeLong2 = new JokeResponse()
            {
                Joke = "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty twenty-one"
            };

            var input = new JokeResponse[]
            {
                jokeLong1,
                jokeLong2
            };

            // Act
            var output            = DadJokeServiceHelpers.GroupByJokeSize(input);
            int actualShortCount  = output.Where(p => p.Key == JokeSize.Short.ToString()).Select(p => p.Value).SingleOrDefault().Count();
            int actualMediumCount = output.Where(p => p.Key == JokeSize.Medium.ToString()).Select(p => p.Value).SingleOrDefault().Count();

            // Assert
            Assert.AreEqual(expected, actualShortCount);
            Assert.AreEqual(expected, actualMediumCount);
        }
 public JokeResult ToJokeResult(JokeResponse jokeResponse)
 {
     return(new JokeResult
     {
         Setup = jokeResponse.Setup,
         Punchline = jokeResponse.Punchline
     });
 }
Exemple #3
0
        //Static method to get the basic URL
        public static JokeResponse GetJokes()
        {
            //Set the url for a basic random search
            string url = "https://icanhazdadjoke.com/";
            //Get the processed joke from the API service
            JokeResponse joke = APIService.Service.GetRandomJoke(url);

            return(joke);
        }
Exemple #4
0
        public JokeResponse GetRandomJoke(string url)
        {
            //Gets response from API
            string responseString = APIConnect(url).Result;
            //Converts Json String to joke response type object
            JokeResponse jokeObject = JsonConvert.DeserializeObject <JokeResponse>(responseString);

            return(jokeObject);
        }
Exemple #5
0
        public void TestMethod1()
        {
            var data = new JokeResponse
            {
                Value = new JokeData()
            };

            data.Value.Should().NotBeNull();
        }
    private JokeResponse[] GetJokeResponses()
    {
        JokeResponse[] responses = new JokeResponse[]
        {
            currentJoke.response1, currentJoke.response2, currentJoke.response3,
        };

        //TODO: Shuffle?
        return(responses);
    }
        public async Task <JokeResponse> AddJokeAsync(JokeResponse newJoke)
        {
            if (newJoke == null)
            {
                throw new ArgumentNullException("There is nothing funny about an empty joke.");
            }

            jokes.Add(newJoke);
            return(newJoke);
        }
Exemple #8
0
        public async Task <IHttpActionResult> PostJokeAsync([FromBody] JokeResponse randomJoke)
        {
            if (randomJoke == null)
            {
                return(BadRequest("No joke to be found."));
            }

            JokeResponse newJoke = await repository.AddJokeAsync(randomJoke);

            return(Ok(newJoke));
        }
Exemple #9
0
        public void GroupByJokeSize_AllJokeSizes_GroupsCorrectly()
        {
            // Arrange
            var jokeShort1 = new JokeResponse()
            {
                Joke = "one two three"
            };
            var jokeShort2 = new JokeResponse()
            {
                Joke = "one two three four five six seven eight nine"
            };
            var jokeMedium1 = new JokeResponse()
            {
                Joke = "one two three four five six seven eight nine ten"
            };
            var jokeMedium2 = new JokeResponse()
            {
                Joke = "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen"
            };
            var jokeLong1 = new JokeResponse()
            {
                Joke = "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty"
            };
            var jokeLong2 = new JokeResponse()
            {
                Joke = "one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty twenty-one"
            };

            var input = new JokeResponse[]
            {
                jokeShort1,
                jokeShort2,
                jokeMedium1,
                jokeMedium2,
                jokeLong1,
                jokeLong2
            };

            // Act
            var output = DadJokeServiceHelpers.GroupByJokeSize(input);

            // Assert
            foreach (var group in output)
            {
                foreach (var joke in group.Value)
                {
                    Assert.AreEqual(group.Key, joke.Size);
                }
            }
        }
        public static async Task SendJoke(CommandContext ctx)
        {
            WebClient webClient = new WebClient();
            string    jokeJson  = webClient.DownloadString("http://api.icndb.com/jokes/random");

            JokeResponse jokeResponse = Newtonsoft.Json.JsonConvert.DeserializeObject <JokeResponse>(jokeJson);

            if (jokeResponse.type == "success")
            {
                await ctx.Channel.SendMessageAsync(jokeResponse.value.joke).ConfigureAwait(false);
            }
            else
            {
                await ctx.Channel.SendMessageAsync($"Yeah... no. {jokeJson}").ConfigureAwait(false);
            }
        }
Exemple #11
0
        static async Task <string> SaveJokeAsync(JokeResponse myJokeResponse)
        {
            // Clear header data, in case any of that happens to exist
            client.DefaultRequestHeaders.Accept.Clear();

            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

            response = await client.PostAsJsonAsync(
                "api/joke", myJokeResponse);

            response.EnsureSuccessStatusCode();

            string jokeToReturn = await response.Content.ReadAsStringAsync();

            return(jokeToReturn);
        }
Exemple #12
0
        public void GroupByJokeSize_EmptyInput_ReturnsEmptyForAllSizes()
        {
            // Arrange
            int expected = 0;

            var input = new JokeResponse[] { };

            // Act
            var output            = DadJokeServiceHelpers.GroupByJokeSize(input);
            int actualShortCount  = output.Where(p => p.Key == JokeSize.Short.ToString()).Select(p => p.Value).SingleOrDefault().Count();
            int actualMediumCount = output.Where(p => p.Key == JokeSize.Medium.ToString()).Select(p => p.Value).SingleOrDefault().Count();
            int actualLongCount   = output.Where(p => p.Key == JokeSize.Long.ToString()).Select(p => p.Value).SingleOrDefault().Count();

            // Assert
            Assert.AreEqual(expected, actualShortCount);
            Assert.AreEqual(expected, actualMediumCount);
            Assert.AreEqual(expected, actualLongCount);
        }
Exemple #13
0
        public static async Task <string> getRandomJoke()
        {
            string ret = "";

            using (HttpClient client = new HttpClient())
            {
                var msg = await client.GetAsync(url);

                if (msg.IsSuccessStatusCode)
                {
                    string response = await msg.Content.ReadAsStringAsync();

                    JokeResponse joke = JsonConvert.DeserializeObject <JokeResponse>(response);
                    if (joke.type.Equals("success"))
                    {
                        ret = joke.value.joke;
                    }
                }
            }

            return(ret);
        }
Exemple #14
0
        public void EmphasizeWithUppercase_MultipleSearchTermOneMatch_EmphasizesMatchingTermOnly()
        {
            // Arrange
            string expected = "this is a DOG joke";

            var inputJokeResponses = new JokeResponse[] {
                new JokeResponse()
                {
                    Joke = "this is a dog joke"
                }
            };

            var inputTermsToEmphasize = new string[] { "cat", "dog" };

            // Act
            string actual = DadJokeServiceHelpers
                            .EmphasizeWithUppercase(inputJokeResponses, inputTermsToEmphasize).
                            Single()
                            .Joke;

            // Assert
            Assert.AreEqual(expected, actual);
        }
Exemple #15
0
        public void EmphasizeWithUppercase_ZeroMatches_DoesNotEmphasize()
        {
            // Arrange
            string expected = "this is a bird joke";

            var inputJokeResponses = new JokeResponse[] {
                new JokeResponse()
                {
                    Joke = "this is a bird joke"
                }
            };

            var inputTermsToEmphasize = new string[] { "cat", "dog" };

            // Act
            string actual = DadJokeServiceHelpers
                            .EmphasizeWithUppercase(inputJokeResponses, inputTermsToEmphasize).
                            Single()
                            .Joke;

            // Assert
            Assert.AreEqual(expected, actual);
        }
Exemple #16
0
            public GetRandomJokeAsyncTests() : base()
            {
                _jokeResponse = new JokeResponse
                {
                    Id        = 1,
                    Type      = "TestType",
                    Setup     = "TestSetup",
                    Punchline = "TestPunchline"
                };

                _mockRestfulClient
                .Setup(x => x.GetAsync <JokeResponse>(It.IsAny <string>()))
                .ReturnsAsync(_jokeResponse);

                _expected = new JokeResult
                {
                    Setup     = "TestSetup",
                    Punchline = "TestPunchline"
                };

                _mockJokeResultMapper
                .Setup(x => x.ToJokeResult(It.IsAny <JokeResponse>()))
                .Returns(_expected);
            }
Exemple #17
0
        public static async Task <IActionResult> GetJoke(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            _httpClient.DefaultRequestHeaders
            .Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var response = await _httpClient.GetAsync("https://icanhazdadjoke.com/");

            var jsonString = await response.Content.ReadAsStringAsync();


            var options = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true,
            };

            JokeResponse jokeResponse = JsonSerializer.Deserialize <JokeResponse>(jsonString, options);

            var translatedJoke = await TranslateToPirate(jokeResponse.Joke);

            if (translatedJoke.translated == "error")
            {
                translatedJoke.translated = jokeResponse.Joke;
            }
            string name = req.Query["name"];


            string responseMessage = string.IsNullOrEmpty(name)
                ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello, {name}. Here is a joke: {translatedJoke.translated}";

            return(new OkObjectResult(responseMessage));
        }
Exemple #18
0
            public void AssertMappings(JokeResponse jokeResponse, JokeResult expected)
            {
                var actual = _objectToTest.ToJokeResult(jokeResponse);

                actual.Should().BeEquivalentTo(expected);
            }
Exemple #19
0
 public void Set(JokeResponse response)
 {
     selectionFrame.SetActive(false);
     text.text     = $"({KeyName}) {response.text}";
     correctAnswer = response.isValid;
 }
Exemple #20
0
        public static void Main(string[] args)
        {
            // The following construct allows the Main method in C# to run asynchronously
            Task.Run(async() =>
            {
                // Start OWIN host for a local web server
                using (WebApp.Start <Startup>(url: baseAddress))
                {
                    // Set the default address of the API
                    client.BaseAddress = new Uri(baseAddress);

                    string randomName         = "";
                    RandomJokeBase randomJoke = null;

                    // Get a random name
                    try
                    {
                        randomName = FetchRandomNameAsync().Result;
                    }
                    catch (HttpResponseException e)
                    {
                        Console.WriteLine("Error retrieving name from external server.");
                    }

                    // default value added since the server is currently generating a 503, unavailable error
                    // (this was only added now, as this endpoint stopped working without any code changes)
                    if (randomName == null || randomName == "")
                    {
                        randomName = "Chuck Norris";
                    }

                    Console.WriteLine("Random name retrieved:");
                    Console.WriteLine(randomName + "\n");

                    // Get a random joke
                    try
                    {
                        randomJoke = FetchRandomJokeAsync("Chuck", "Norris").Result;
                    }
                    catch (HttpResponseException e)
                    {
                        Console.WriteLine("Error retrieving joke from external server. Please try again later");

                        // Close the app immediately, server is unavailable or has unresolved errors
                        Environment.Exit(0);
                    }

                    Console.WriteLine("Random joke retrieved:");
                    Console.WriteLine(randomJoke + "\n");

                    // Retrieve response from the self-hosted API endpoint
                    JokeResponse joke = new JokeResponse {
                        Type = randomJoke.Type, Joke = randomJoke.Value.Joke
                    };
                    string returnedJoke = await SaveJokeAsync(joke);

                    Console.WriteLine(returnedJoke);

                    Console.WriteLine("\nPress any key to exit.");
                    Console.ReadKey();
                }
            }).GetAwaiter().GetResult();
        }