diff --git a/_sources/lectures/TWP45/TWP45_3.rst b/_sources/lectures/TWP45/TWP45_3.rst index 24660a01d6..24ac28d3b1 100644 --- a/_sources/lectures/TWP45/TWP45_3.rst +++ b/_sources/lectures/TWP45/TWP45_3.rst @@ -1,140 +1,127 @@ -Probando la API de TasteDive -============================ +Probando la API de TVMaze +========================= -TasteDive es una herramienta que: +TVMaze es una herramienta que: - le ayuda a descubrir nueva música, películas, programas de televisión, libros, autores, juegos, - podcasts y personas con intereses compartidos. - -- TasteDive + Te permite buscar programas de televisión y obtener información sobre ellos. + Proporciona una API RESTful para acceder a los datos. -En el siguiente ejercicio usaremos la API de TasteDive para buscar obras o artistas similares a otra de nuestra -elección. -La documentación de la API de `TasteDive `_. +En el siguiente ejemplo, utilizaremos la API de TVMaze para buscar programas de televisión. La URL base es API de `TVMaze `_. -.. activecode:: ac_l45_3a +.. activecode:: ac_l45_3a_es :nocodelens: :language: python - En este caso, utilizaremos la librería ``requests`` para hacer la solicitud a la API. La url base - es ``"https://tastedive.com/api/similar"``. A esta url se le va a pasar un parámetro ``q`` con el - valor de la artista Ariana Grande. Al final la url se va a ver de la siguiente forma: ``"https://tastedive.com/api/similar?q=ariana+grande"``. - Note que después de la url base se escribe un ``?`` para indicar que siguen los parámetros. + En este caso, utilizaremos la biblioteca ``requests`` para hacer la solicitud a la API. La URL base + es ``"https://api.tvmaze.com/search/shows"``. A esta URL se le pasará un parámetro ``q`` con el + valor del programa "big bang theory". Finalmente, la URL se verá así: ``"https://api.tvmaze.com/search/shows?q=big+bang+theory"``. + Ten en cuenta que después de la URL base, se escribe un ``?`` para indicar que siguen los parámetros. ~~~~ import requests import json - api_url = "https://tastedive.com/api/similar" - proxy = "https://cors.bridged.cc/" + api_url = "http://api.tvmaze.com/search/shows" - # Los parámetros que se le pasaran a la url los escribimos dentro de un diccionario - parametros = {"q": "ariana grande"} + # Los parámetros que se pasarán a la URL se escriben dentro de un diccionario + # no necesitamos agregar espacios en los parámetros, porque la biblioteca requests lo hará por nosotros + parameters = {"q": "big bang theory"} - # Solicitamos a la api los datos - respuesta = requests.get(proxy + api_url, params=parametros) - # Ahora imprimimos la url - print(respuesta.url) + # Solicitamos los datos de la API + response = requests.get(api_url, params=parameters) + + # Ahora imprimimos la URL + print(response.url) print() - # Transformamos los datos de formato json a Python - datos = json.loads(respuesta.text) + # Transformamos los datos en formato JSON a datos de Python + data = json.loads(response.text) + + print(data) - print(datos) -En el ejemplo anterior pudo apreciar que la API regresa un texto, que si lo pasamos por ``json.loads`` -se transforma a un diccionario de Python. Sin embargo, no es del todo legible. Esto se puede solucionar con +En el ejemplo anterior, pudiste ver que la API devuelve texto, que si se pasa a través de ``json.loads``, +se transforma en un diccionario de Python. Sin embargo, no es completamente legible. Esto se puede solucionar con ``json.dumps``. -.. activecode:: ac_l45_3b +.. activecode:: ac_l45_3b_es :language: python3 :python3_interpreter: brython - Ahora vamos a solicitar información de la banda Coldplay. Esta vez vamos a imprimir los datos de forma - que sean legibles. Esto lo hacemos con el argumento ``indent`` de la función ``dumps`` de ``json``. - Vamos a usar ``urllib`` para hacer la solicitud. + Ahora, solicitaremos información sobre el programa "golden girls". Esta vez imprimiremos los datos en un + formato legible para el usuario. Utilizaremos ``urllib`` para hacer la solicitud. ~~~~ import urllib.request import urllib.parse import json - api_url = "https://tastedive.com/api/similar?" - proxy = "https://cors.bridged.cc/" - # La siguiente línea es para los parámetros de la url. - parametros = urllib.parse.urlencode({"q": "coldplay"}) + api_url = "http://api.tvmaze.com/search/shows?" + # La siguiente línea es para los parámetros de la URL + # no necesitamos agregar espacios en los parámetros, porque la biblioteca requests lo hará por nosotros + parameters = urllib.parse.urlencode({"q": "golden girls"}) - solicitud = urllib.request.urlopen(proxy + api_url + parametros) - datos = json.loads(solicitud.read()) + request = urllib.request.urlopen(api_url + parameters) + data = json.loads(request.read()) - # Imprimimos los datos de forma legible para un usuario - print(json.dumps(datos, indent=4)) + # Imprimimos los datos en un formato legible para el usuario + print(json.dumps(data, indent=4)) + print("La consulta devolvió " + str(len(data)) + " resultados") - # Podemos ver que la api arrojó 20 resultados relacionados con - # la solicitud - print(len(datos["Similar"]["Results"])) | El siguiente ejercicio viene con calificación automática. -.. activecode:: ac_l45_3c +.. activecode:: ac_l45_3c_es :nocodelens: :language: python - Ahora va a preguntar a TasteDive por la película Coco. Entonces el diccionario ``parametros`` debe tener el - valor ``"Coco"`` asignado a la llave ``"q"``. Además, esta vez solo queremos 5 resultados en vez de 20. Para - esto existe un parámetro llamado ``"limit"``, que puede ser asignado al número de resultados que se necesiten. - Otro parámetro que le pasará a la url será ``"info"`` y tendrá el valor de 1. Lo que hará esto es que los - resultados vendrán con un texto extra con información sobre la película. + Ahora pediremos a TVMaze el programa "suits". Luego, al diccionario ``parameters`` se le deberá asignar el valor + ``"suits"`` a la clave ``"q"``. + + Primero, solicitarás desde la API lo que se describió anteriormente, y guardarás esto en la variable ``request``. + En otra variable, ``request_url``, guarda la URL de la solicitud. Luego, asigna los datos a la variable ``data``. + A continuación, asignarás a la variable ``results`` el número de resultados que devolvió la solicitud + (como se hizo en el ejemplo anterior). - Primero, va a solicitar a la API lo descrito anteriormente, y guardará esto en la variable ``solicitud``. En - otra variable, ``solicitud_url``, guarde la url de la solicitud. Después asignará los datos a la variable ``datos``. - Después va asignar a la variable ``resultados`` el número de resultados que arrojó la solicitud - (como se hizo en el ejemplo anterior). Como pusimos un límite, este número debe coincidir con el límite. + Ahora, calcularás el promedio de clasificación de todos los programas que se devolvieron. + Guardarás esto en la variable ``average_rating``. **Sugerencia**: las clasificaciones se encuentran dentro de + ``data["show"]["rating"]["average"]``. Necesitarás usar un bucle for para calcular el promedio. - Ahora va a crear la lista ``peliculas_similares``. Dentro de ``datos`` usted tiene un diccionario de diccionarios - y listas. Lo que hará será buscar los conjuntos dentro de los cuales se encuentren los nombres de las películas - similares a Coco, y va a agregar a ``peliculas_similares`` el nombre de esas películas. En total deben ser 5. - **Pista**: los datos de las películas se encuentran dentro de ``datos["Similar"]["Results"]``, y la llave para - acceder a ellas es ``"Name"``. + Por último, buscarás el número de veces que aparece la palabra ``"Drama"`` en los géneros relacionados con suits. + Guarda ese número en la variable ``drama_count``. **Sugerencia**: los géneros se encuentran dentro de + ``data["show"]["genres"]``. Necesitarás usar un bucle for para calcular el número de dramas. - Por último, va a buscar el número de veces que aparece la palabra ``"Pixar"`` en los textos de información de las - películas relacionadas a Coco. Ese número lo va a guardar en la variable ``pixar``. **Pista**: ``"wTeaser"`` es la - llave que guarda el texto. Esta llave se encuentra en el mismo diccionario que el nombre de las películas. ~~~~ import requests import json - api_url = "https://tastedive.com/api/similar" - proxy = "https://cors.bridged.cc/" - - # Agregue los parámetros - parametros = {} - - # Complete el código - solicitud = - solicitud_url = - datos = - - # Asigne la variable resultados - - # print(f"resultados: {resultados}") - - # Cree peliculas_similares - # Utilice un ciclo for para encontrar las peliculas similares y agregarlas - # a la variable correspondiente + api_url = "http://api.tvmaze.com/search/shows" + parameters = {} + request = + request_url = + data = + results = - # print(f"Pelis: {peliculas_similares} len: {len(peliculas_similares)}") + total_rating = 0 + rated_shows = 0 + for show in data: + # completar el bucle - pixar = 0 - # Busque el número de ocurrencias de "Pixar" dentro de los datos + drama_count = 0 + for show in data: + # completar el bucle - # print(f"Pixar: {pixar}") + print("URL de la solicitud:", request_url) + print("Resultados:", results) + print("Clasificación promedio:", average_rating) + print("Número de dramas:", drama_count) ==== from unittest.gui import TestCaseGui @@ -143,18 +130,13 @@ El siguiente ejercicio viene con calificación automática. class myTests(TestCaseGui): def testOne(self): self.assertEqual( - solicitud_url, - "https://cors.bridged.cc/https://tastedive.com/api/similar?q=Coco&limit=5&info=1", - "Probando que la url sea: https://cors.bridged.cc/https://tastedive.com/api/similar?q=Coco&limit=5&info=1", - ) - self.assertEqual(resultados, 5, "Probando que resultados esté asignado correctamente.") - self.assertEqual(len(peliculas_similares), 5, "Probando que peliculas_similares sean: 5") - self.assertEqual( - peliculas_similares, - ["Toy Story 3", "Finding Nemo", "Inside Out", "Spirited Away", "Monsters, Inc."], - "Esperado: ['Toy Story 3', 'Finding Nemo', 'Inside Out', 'Spirited Away', 'Monsters, Inc.']", + request_url, + "http://api.tvmaze.com/search/shows?q=suits", + "Probando que la URL sea: http://api.tvmaze.com/search/shows?q=suits", ) - self.assertEqual(pixar, 5, "Probando que pixar esté asignado correctamente.") + self.assertEqual(results, 10, "Probando que los resultados se asignen correctamente.") + self.assertEqual(average_rating, 7.8, "Probando que la clasificación promedio sea: 7.8") + self.assertEqual(drama_count, 6, "Probando que drama_count se asigne correctamente.") myTests().main() diff --git a/_sources/lectures/TWP45/TWP45_3_en.rst b/_sources/lectures/TWP45/TWP45_3_en.rst index 6b0fdded10..117ee9e836 100644 --- a/_sources/lectures/TWP45/TWP45_3_en.rst +++ b/_sources/lectures/TWP45/TWP45_3_en.rst @@ -1,36 +1,36 @@ -Testing the TasteDive API -============================ +Testing the TVMaze API +====================== -TasteDive is a tool that: +TVMaze is a tool that: - helps you discover new music, movies, TV shows, books, authors, games, - podcasts, and people with shared interests. - -- TasteDive + Allows you to search for TV shows and get information about them. + Provides a RESTful API to access the data. -In the following exercise, we will use the TasteDive API to search for works or artists similar to another of our choice. -The documentation for the `TasteDive API `_. -.. activecode:: ac_l45_3a_en +In the following example, we will use the TVMaze API to search for TV shows. The base url is `TVMaze API `_. + +.. activecode:: ac_l45_3a_en_ :nocodelens: :language: python In this case, we will use the ``requests`` library to make the API request. The base url - is ``"https://tastedive.com/api/similar"``. To this url, a parameter ``q`` with the - value of the artist Ariana Grande will be passed. Finally, the url will look like this: ``"https://tastedive.com/api/similar?q=ariana+grande"``. + is ``"https://api.tvmaze.com/search/shows"``. To this url, a parameter ``q`` with the + value of the show big bang theory will be passed. Finally, the url will look like this: ``"https://api.tvmaze.com/search/shows?q=big+bang+theory"``. Note that after the base url, a ``?`` is written to indicate that the parameters follow. ~~~~ import requests import json - api_url = "https://tastedive.com/api/similar" - proxy = "https://cors.bridged.cc/" + api_url = "http://api.tvmaze.com/search/shows" # The parameters that will be passed to the url are written inside a dictionary - parameters = {"q": "ariana grande"} + # we don't need to add spaces in parameters, because the requests library will do it for us + parameters = {"q": "big bang theory"} + # We request the data from the api - response = requests.get(proxy + api_url, params=parameters) + response = requests.get(api_url, params=parameters) # Now we print the url print(response.url) @@ -46,12 +46,12 @@ In the previous example, you could see that the API returns text, which if passe transforms into a Python dictionary. However, it is not entirely readable. This can be solved with ``json.dumps``. -.. activecode:: ac_l45_3b_en +.. activecode:: ac_l4fds5_3b_en_ :language: python3 :python3_interpreter: brython - Now, we will request information about the band Coldplay. This time we will print the data in a + Now, we will request information about the show golden girls. This time we will print the data in a readable format. We will use ``urllib`` to make the request. ~~~~ @@ -59,78 +59,68 @@ transforms into a Python dictionary. However, it is not entirely readable. This import urllib.parse import json - api_url = "https://tastedive.com/api/similar?" - proxy = "https://cors.bridged.cc/" + api_url = "http://api.tvmaze.com/search/shows?" # The following line is for the url parameters - parameters = urllib.parse.urlencode({"q": "coldplay"}) + # we don't need to add spaces in parameters, because the requests library will do it for us + parameters = urllib.parse.urlencode({"q": "golden girls"}) - request = urllib.request.urlopen(proxy + api_url + parameters) + request = urllib.request.urlopen(api_url + parameters) data = json.loads(request.read()) # We print the data in a user-readable format print(json.dumps(data, indent=4)) - - # We can see that the api returned 20 results related to the request - print(len(data["Similar"]["Results"])) + print("The query returned " + str(len(data)) + " results") | The following exercise comes with automatic grading. -.. activecode:: ac_l45_3c_en +.. activecode:: ac_l45_3c_en_ :nocodelens: :language: python - Now we will ask TasteDive for the movie Coco. Then the dictionary ``parameters`` should have the - value ``"Coco"`` assigned to the key ``"q"``. Additionally, this time we only want 5 results instead of 20. - For this, there is a parameter called ``"limit"``, which can be assigned to the number of results needed. - Another parameter that will be passed to the url will be ``"info"`` and its value will be 1. This will make - the results come with extra text with information about the movie. + Now we will ask TVMaze for the show suits. Then the dictionary ``parameters`` should have the value + ``"suits"`` assigned to the key ``"q"``. - First, you will request from the API what was described above, and save this in the variable ``request``. - In another variable, ``request_url``, save the url of the request. Then, assign the data to the variable ``data``. + First, you will request from the API what was described above, and save this in the variable ``request``. + In another variable, ``request_url``, save the url of the request. Then, assign the data to the variable ``data``. Next, assign the variable ``results`` the number of results that the request returned - (as was done in the previous example). Because we set a limit, this number should match the limit. + (as was done in the previous example). - Now, you will create the list ``similar_movies``. Inside ``data`` you have a dictionary of dictionaries - and lists. What you will do is to search through the sets within which are the names of the movies - similar to Coco, and you will add the names of those movies to ``similar_movies``. There should be 5 in total. - **Hint**: the movie data is located within ``data["Similar"]["Results"]``, and the key to access it is ``"Name"``. + Now, you will calculate the average rating of all the shows that were returned. + You will save this in the variable ``average_rating``. **Hint**: the ratings are located within + ``data["show"]["rating"]["average"]``. You will need to use a for loop to calculate the average. + + Lastly you will search for the number of times the word ``"Drama"`` appears in the genres related to suits. + You will save that number in the variable ``drama_count``. **Hint**: the genres are located within + ``data["show"]["genres"]``. You will need to use a for loop to calculate the number of dramas. - Lastly, you will search for the number of times the word ``"Pixar"`` appears in the information texts of the - movies related to Coco. You will save that number in the variable ``pixar``. **Hint**: ``"wTeaser"`` is the - key that stores the text. This key is located in the same dictionary as the movie names. ~~~~ import requests import json - api_url = "https://tastedive.com/api/similar" - proxy = "https://cors.bridged.cc/" - - # Add the parameters + api_url = "http://api.tvmaze.com/search/shows" parameters = {} - - # Complete the code request = request_url = data = + results = - # Assign the variable results - - # print(f"results: {results}") - - # Create similar_movies - # Use a for loop to find the similar movies and add them - # to the corresponding variable - - # print(f"Movies: {similar_movies} len: {len(similar_movies)}") + total_rating = 0 + rated_shows = 0 + for show in data: + # complete the loop - pixar = 0 - # Find the number of occurrences of "Pixar" within the data + drama_count = 0 + for show in data: + # complete the loop - # print(f"Pixar: {pixar}") + print("Request url:", request_url) + print("Results:", results) + print("Average rating:", average_rating) + print("Number of dramas:", drama_count) ==== from unittest.gui import TestCaseGui @@ -140,17 +130,12 @@ The following exercise comes with automatic grading. def testOne(self): self.assertEqual( request_url, - "https://cors.bridged.cc/https://tastedive.com/api/similar?q=Coco&limit=5&info=1", - "Testing that the url is: https://cors.bridged.cc/https://tastedive.com/api/similar?q=Coco&limit=5&info=1", - ) - self.assertEqual(results, 5, "Testing that results is assigned correctly.") - self.assertEqual(len(similar_movies), 5, "Testing that similar_movies are: 5") - self.assertEqual( - similar_movies, - ["Toy Story 3", "Finding Nemo", "Inside Out", "Spirited Away", "Monsters, Inc."], - "Expected: ['Toy Story 3', 'Finding Nemo', 'Inside Out', 'Spirited Away', 'Monsters, Inc.']", + "http://api.tvmaze.com/search/shows?q=suits", + "Testing that the url is: http://api.tvmaze.com/search/shows?q=suits", ) - self.assertEqual(pixar, 5, "Testing that pixar is assigned correctly.") + self.assertEqual(results, 10, "Testing that results is assigned correctly.") + self.assertEqual(average_rating, 7.8, "Testing that similar_movies are: 7.8") + self.assertEqual(drama_count, 6, "Testing that drama_count is assigned correctly.") - myTests().main() \ No newline at end of file + myTests().main() diff --git a/tests/cassettes/test_l45_3[chromium].yaml b/tests/cassettes/test_l45_3[chromium].yaml deleted file mode 100644 index ed65de801e..0000000000 --- a/tests/cassettes/test_l45_3[chromium].yaml +++ /dev/null @@ -1,108 +0,0 @@ -interactions: -- request: - body: null - headers: - Accept: - - '*/*' - Accept-Encoding: - - gzip, deflate - Connection: - - keep-alive - User-Agent: - - python-requests/2.25.1 - method: GET - uri: https://tastedive.com/api/similar?q=Coco&limit=5&info=1 - response: - body: - string: !!binary | - H4sIAAAAAAAAA7xZbW8bua7+K0RwD9oCEzdpNu2m95OTtEnTpO3G2e1Z3BwU9IieYa0RvZIm7mTR - /35AacaZdLvb08XB/RI4sl4o8eHDh/TvWzNu2KLfeg6/b71yC9l6Dv/3+9YbbGjrOWwdSSlbBWxd - dav0fyM3TDqwviIM5Ic5wAEQnuzsPoNpQ55LdFBKs2oj+W103GAkAwt0EUMHC7YNrLyYtiQD8w7e - 8Sf0ME3zWBzMYmtYAqAz4MnqUWnee7QRjjk40jVlbD2FCRymr8UBOhDPFTu0wIZQl5wTwc9u6bms - C+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dvNJKYHqSWo4PAzJoMSDGxjManbagRK7tOLp0QSmKYbv - hb2WWK13SX5EgRVXYUjJa45lDb+2c5wjPOwf9VGxuZtqLwXfR5mnFpxazq5fkLqdsa6l1VJSKz9n - ACE9l8BCZU6tDdK+kL1nU5Ltqd/a93brtsFeM/znMmDw0Ychwr+TUA67f7bLg59++2k57pONR+8R - yoW4oN4p4JUrJ99ilPuzR0H8/6cH7gRAlq1DF/cuo6buw4mIadDlRNnBke+0l1bALNINwWEbSmq4 - 6Hv8R6LklsKwgxOez0Nf8TrHC/JwxUmdxnHH2vyJ/Oi7GUNjShWhoXnbF9H0ico2lSLjp/hW12vE - JGUfTCrt1wJN7xDIKbS/z7sJXG/NWmupu94C/cA3mClUbRNH29SRUehG1584V4m+8EyJw5YE7/FW - 1mHJees9oGZlRVdtdHdsLXrQMq3qtvN9UpbFMvHJPbAkqihrqHQ6RgqwknVugYUSkxdzuJQ1W+PJ - TeBU1vprRH73/qI9gczJMt1ozVT31gzLMjXIJy77IqAm/fGCIDjCZch0kRyZrSwgv1PP3UvKXbfh - hxPlHSX/vq3DcUhoUQQsRvrPA3t4jn88OfrwypV/I7SPTuYVngquXl6MQns8+vlfnz//GwAA//8D - AKm19kZ5HAAA - headers: - CF-Cache-Status: - - DYNAMIC - CF-RAY: - - 67723118df2c0c23-DFW - Connection: - - keep-alive - Content-Encoding: - - gzip - Content-Type: - - application/json - Date: - - Fri, 30 Jul 2021 22:58:27 GMT - Expect-CT: - - max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" - NEL: - - '{"report_to":"cf-nel","max_age":604800}' - Report-To: - - '{"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=DOg4nNAu%2Fiu%2Ban7bDEVbWUtAaWoNIx47k2M6X4SOkhH8Kcvi7%2BZ%2FN%2Bv5Fno6pViNfu7hwVS%2FOkpAi%2BOLEdGBmz7LqljkT%2F2azOkMAxcsgAkzFw7h%2Bvyl8HRWl83A002B"}],"group":"cf-nel","max_age":604800}' - Server: - - cloudflare - Set-Cookie: - - tk_s=.eJyrVsrJT04syczPU7KqVkrOLKmMz0vMTVWyUopKLMgvSMxT0lFKzi_NKymqjE_OTwFJ-EYgiUEV-6ZWZCbnA8WLS5NSMssyi4EGxhvCZL0SczKLgdK1tQCMBicW.E-YVkw.zBr5-FLnnrHSV3b0oZK7V256L0c; - Domain=.tastedive.com; HttpOnly; Path=/ - Transfer-Encoding: - - chunked - Vary: - - Cookie - alt-svc: - - h3-27=":443"; ma=86400, h3-28=":443"; ma=86400, h3-29=":443"; ma=86400, h3=":443"; - ma=86400 - status: - code: 200 - message: OK -version: 1 diff --git a/tests/cassettes/test_l45_3_en[chromium].yaml b/tests/cassettes/test_l45_3_en[chromium].yaml deleted file mode 100644 index ed65de801e..0000000000 --- a/tests/cassettes/test_l45_3_en[chromium].yaml +++ /dev/null @@ -1,108 +0,0 @@ -interactions: -- request: - body: null - headers: - Accept: - - '*/*' - Accept-Encoding: - - gzip, deflate - Connection: - - keep-alive - User-Agent: - - python-requests/2.25.1 - method: GET - uri: https://tastedive.com/api/similar?q=Coco&limit=5&info=1 - response: - body: - string: !!binary | - H4sIAAAAAAAAA7xZbW8bua7+K0RwD9oCEzdpNu2m95OTtEnTpO3G2e1Z3BwU9IieYa0RvZIm7mTR - /35AacaZdLvb08XB/RI4sl4o8eHDh/TvWzNu2KLfeg6/b71yC9l6Dv/3+9YbbGjrOWwdSSlbBWxd - dav0fyM3TDqwviIM5Ic5wAEQnuzsPoNpQ55LdFBKs2oj+W103GAkAwt0EUMHC7YNrLyYtiQD8w7e - 8Sf0ME3zWBzMYmtYAqAz4MnqUWnee7QRjjk40jVlbD2FCRymr8UBOhDPFTu0wIZQl5wTwc9u6bms - C+Cohhr2VMa8Y81NOqWU7fHw1HhGBxdi2eEErmpKRj8IcCNcEpQYIoSIPsDUxVpcByfibtHSbQEn - SBZO0JfX7c4OGYRD8g5tAYfkPmLDDg49xljA1KJzCD/PU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- ACE9l8BCZU6tDdK+kL1nU5Ltqd/a93brtsFeM/znMmDw0Ychwr+TUA67f7bLg59++2k57pONR+8R - yoW4oN4p4JUrJ99ilPuzR0H8/6cH7gRAlq1DF/cuo6buw4mIadDlRNnBke+0l1bALNINwWEbSmq4 - 6Hv8R6LklsKwgxOez0Nf8TrHC/JwxUmdxnHH2vyJ/Oi7GUNjShWhoXnbF9H0ico2lSLjp/hW12vE - JGUfTCrt1wJN7xDIKbS/z7sJXG/NWmupu94C/cA3mClUbRNH29SRUehG1584V4m+8EyJw5YE7/FW - 1mHJees9oGZlRVdtdHdsLXrQMq3qtvN9UpbFMvHJPbAkqihrqHQ6RgqwknVugYUSkxdzuJQ1W+PJ - TeBU1vprRH73/qI9gczJMt1ozVT31gzLMjXIJy77IqAm/fGCIDjCZch0kRyZrSwgv1PP3UvKXbfh - hxPlHSX/vq3DcUhoUQQsRvrPA3t4jn88OfrwypV/I7SPTuYVngquXl6MQns8+vlfnz//GwAA//8D - AKm19kZ5HAAA - headers: - CF-Cache-Status: - - DYNAMIC - CF-RAY: - - 67723118df2c0c23-DFW - Connection: - - keep-alive - Content-Encoding: - - gzip - Content-Type: - - application/json - Date: - - Fri, 30 Jul 2021 22:58:27 GMT - Expect-CT: - - max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" - NEL: - - '{"report_to":"cf-nel","max_age":604800}' - Report-To: - - '{"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=DOg4nNAu%2Fiu%2Ban7bDEVbWUtAaWoNIx47k2M6X4SOkhH8Kcvi7%2BZ%2FN%2Bv5Fno6pViNfu7hwVS%2FOkpAi%2BOLEdGBmz7LqljkT%2F2azOkMAxcsgAkzFw7h%2Bvyl8HRWl83A002B"}],"group":"cf-nel","max_age":604800}' - Server: - - cloudflare - Set-Cookie: - - tk_s=.eJyrVsrJT04syczPU7KqVkrOLKmMz0vMTVWyUopKLMgvSMxT0lFKzi_NKymqjE_OTwFJ-EYgiUEV-6ZWZCbnA8WLS5NSMssyi4EGxhvCZL0SczKLgdK1tQCMBicW.E-YVkw.zBr5-FLnnrHSV3b0oZK7V256L0c; - Domain=.tastedive.com; HttpOnly; Path=/ - Transfer-Encoding: - - chunked - Vary: - - Cookie - alt-svc: - - h3-27=":443"; ma=86400, h3-28=":443"; ma=86400, h3-29=":443"; ma=86400, h3=":443"; - ma=86400 - status: - code: 200 - message: OK -version: 1 diff --git a/tests/test_TWP45.py b/tests/test_TWP45.py index 2f0a8ed1f0..674690a2eb 100644 --- a/tests/test_TWP45.py +++ b/tests/test_TWP45.py @@ -18,49 +18,6 @@ def test_l45_1(page): # Test the src attribute from image matches the Facebook URL assert img_src == "https://graph.facebook.com/ACDC/picture?type=large" - -@pytest.mark.vcr() -def test_l45_3(page): - # Go to TWP45 page - page.goto("lectures/TWP45/TWP45_3.html") - - # request data for the exercise to the .yaml file - res = requests.get( - "https://tastedive.com/api/similar?q=Coco&limit=5&info=1") - data = json.loads(res.text) - movies = [] - pixar = 0 - for mov in data["Similar"]["Results"]: - movies.append(mov["Name"]) - for mov in data["Similar"]["Results"]: - for wrd in mov["wTeaser"].split(): - if wrd == "Pixar": - pixar += 1 - - # Do the exercise - page.click("#ac_l45_3c >> text=parametros = {}") - # Clear all code - page.keyboard.press("Control+A") - page.keyboard.press("Backspace") - - instructions1 = [ - f"solicitud_url = 'https://cors.bridged.cc/{res.url}'", - f'resultados = {len(data["Similar"]["Results"])}', - f"peliculas_similares = {movies}", - ] - - for i in instructions1: - page.keyboard.type(i, delay=0) - page.keyboard.press("Enter") - - page.keyboard.type(f"pixar = {pixar}") - - # Run and check it passed all tests - page.click("#ac_l45_3c >> *css=button >> text=Run") - page.hover("#ac_l45_3c >> text=You passed:") - assert page.inner_text( - "#ac_l45_3c >> text=You passed:") == "You passed: 100.0% of the tests" - def test_l45_1_en(page): page.goto("lectures/TWP45/TWP45_1_en.html") @@ -78,44 +35,13 @@ def test_l45_1_en(page): assert img_src == "https://graph.facebook.com/ACDC/picture?type=large" -@pytest.mark.vcr() -def test_l45_3_en(page): - # Go to TWP45 page - page.goto("lectures/TWP45/TWP45_3_en.html") - - # request data for the exercise to the .yaml file - res = requests.get( - "https://tastedive.com/api/similar?q=Coco&limit=5&info=1") - data = json.loads(res.text) - movies = [] - pixar = 0 - for mov in data["Similar"]["Results"]: - movies.append(mov["Name"]) - for mov in data["Similar"]["Results"]: - for wrd in mov["wTeaser"].split(): - if wrd == "Pixar": - pixar += 1 - - # Do the exercise - page.click("#ac_l45_3c_en >> text=parameters = {}") - # Clear all code - page.keyboard.press("Control+A") - page.keyboard.press("Backspace") - - instructions1 = [ - f"request_url = 'https://cors.bridged.cc/{res.url}'", - f'results = {len(data["Similar"]["Results"])}', - f"similar_movies = {movies}", - ] - - for i in instructions1: - page.keyboard.type(i, delay=0) - page.keyboard.press("Enter") +def test_l45_3_api(): + """Tests fetching data from the provided URL""" + # Send a GET request to the URL for a sample user + url = "http://api.tvmaze.com/search/shows?q=suits" - page.keyboard.type(f"pixar = {pixar}") + # Send a GET request to the URL + response = requests.get(url) - # Run and check it passed all tests - page.click("#ac_l45_3c_en >> *css=button >> text=Run") - page.hover("#ac_l45_3c_en >> text=You passed:") - assert page.inner_text( - "#ac_l45_3c_en >> text=You passed:") == "You passed: 100.0% of the tests" + # Check for successful response (status code 200) + assert response.status_code == 200, f"Expected status code 200, but got {response.status_code}, Data can not be fetched from the provided URL"