Raúl Villares
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Nameday === ###### tags: `pycones` ## Leyenda :rotating_light: Test en rojo :white_check_mark: Test en verde :construction_worker: Refactorización --- ## Nameday retriever - Diseñar antes de empezar (TDD != no pensar) - ¿Qué queremos hacer? Llamar a una api externa. - Esto es caro. Necesitamos doblar la llamada. - Además del diseña, puede ser interesante hacer un spike para ver qué librerías vamos a necesitar, cómo leemos la respuesta del api,... Así tendremos todo esto claro a la hora de montar los tests y será más fluido. ![](https://i.imgur.com/CSJlBSE.png) ### 1A :rotating_light: El servicio tiene que llamar al cliente http (test de colaboración) - Empezar por la aserción - ¿Qué tipo de doble necesitamos? Spy. - Empezar con *have_been_called* (general) y luego pasarlo a *have_been_called_with* (concreto) ```python= from mamba import description, context, it from expects import expect from doublex import Spy from doublex_expects import have_been_called_with import nameday with description('nameday retriever specs'): with context('getting today\'s namedays for an specific country'): with it('calls http client with proper url'): A_COUNTRY = 'country' TODAY_COUNTRY_NAMEDAYS_URL = 'https://api.abalin.net/get/today?country={}'.format(A_COUNTRY) http_client = Spy() nameday_retriever = nameday.NamedayRetriever(http_client) nameday_retriever.today(country=A_COUNTRY) expect(http_client.get).to(have_been_called_with(TODAY_COUNTRY_NAMEDAYS_URL)) ``` - Vamos construyendo el código de producción según nos lo pide el test: - Crear la clase HttpClient **no es necesario en este paso iteración** - Crear clase NamedayRetriever - Que recibe una instancia del cliente http (doble) como colaborador - Con el método today ```python= class NamedayRetriever(object): def __init__(self, http_client): self._client = http_client def today(self, country): pass ``` ### 1B :white_check_mark: El servicio tiene que llamar al cliente http (test de colaboración) ```python= class NamedayRetriever(object): def __init__(self, http_client): self._client = http_client def today(self, country): self._client.get('https://api.abalin.net/get/today?country={}'.format(country)) ``` ### 1C :construction_worker: El servicio tiene que llamar al cliente http (test de colaboración) - Podemos refactorizar y crear una constante con un buen nombre para la url ```python= # -*- coding: utf-8 -*- class HttpClient(object): def get(self, url): pass class NamedayRetriever(object): TODAY_BASE_URL = 'https://api.abalin.net/get/today?country={}' def __init__(self, http_client): self._client = http_client def today(self, country): self._client.get(self.TODAY_BASE_URL.format(country)) ``` --- ### 2A :rotating_light: El servicio devuelve la lista de nombres del santoral de hoy para el país indicado - Vamos a necesitar la preparación del anterior test (nota mental: refactorizar luego) - También es muy interesante empezar por la aserción, nos va diciendo que vamos a ir necesitando - ¿Qué doble ahora? Stub - Nos vamos a la web para ver que retorna la llamada real - Aprovechar para enseñar las funciones focus y skip de mamba (el primer test se rompe hasta que refactoricemos los tests y pongamos un before.each) ```python= from mamba import description, context, it from expects import expect, equal from doublex import Spy, Stub, when from doublex_expects import have_been_called_with import nameday with description('nameday retriever specs'): with context('getting today\'s namedays for a specific country'): with it('calls http client with proper url'): A_COUNTRY = 'country' TODAY_COUNTRY_NAMEDAYS_URL = 'https://api.abalin.net/get/today?country={}'.format(A_COUNTRY) http_client = Spy() nameday_retriever = nameday.NamedayRetriever(http_client) nameday_retriever.today(country=A_COUNTRY) expect(http_client.get).to(have_been_called_with(TODAY_COUNTRY_NAMEDAYS_URL)) with it('returns the list of today\'s namedays for the country'): A_COUNTRY = 'country' TODAY_COUNTRY_NAMEDAYS_URL = 'https://api.abalin.net/get/today?country={}'.format(A_COUNTRY) http_client = Stub() TODAY_COUNTRY_RESPONSE = '{"data":{"name_country":"Guido, Ciriaco, Paula","day":8,"month":9}}' when(http_client).get(TODAY_COUNTRY_NAMEDAYS_URL).returns(TODAY_COUNTRY_RESPONSE) nameday_retriever = nameday.NamedayRetriever(http_client) namedays = nameday_retriever.today(country=A_COUNTRY) expect(namedays).to(equal('Guido, Ciriaco, Paula')) ``` ### 2B :white_check_mark: El servicio devuelve la lista de nombres del santoral de hoy para el país indicado ```python= from json import loads as load_json class NamedayRetriever(object): TODAY_BASE_URL = 'https://api.abalin.net/get/today?country={}' def __init__(self, http_client): self._client = http_client def today(self, country): response = self._client.get(self.TODAY_BASE_URL.format(country)) return load_json(response)['data']['name_{}'.format(country)] ``` ### 2C :construction_worker: El servicio devuelve la lista de nombres del santoral de hoy para el país indicado - Los tests están necesitan una limpieza (el código de test es tan importante como el de producción, también le aplica la refactorización) - El contexto before.each de mamba permite ejecutar código antes de cada uno de los tests ```python= from mamba import description, context, it from expects import expect, equal from doublex import Spy, Stub, when from doublex_expects import have_been_called_with import nameday A_COUNTRY = 'country' TODAY_COUNTRY_NAMEDAYS_URL = 'https://api.abalin.net/get/today?country={}'.format(A_COUNTRY) TODAY_COUNTRY_RESPONSE = '{"data":{"name_country":"Adela, Meritxell, Nuria","day":8,"month":9}}' with description('nameday retriever specs'): with context('getting today\'s namedays for a specific country'): with before.each as self: self.http_client = Spy() when(self.http_client).get(TODAY_COUNTRY_NAMEDAYS_URL).returns(TODAY_COUNTRY_RESPONSE) self.nameday_retriever = nameday.NamedayRetriever(self.http_client) with it('calls http client with proper url'): _ = self.nameday_retriever.today(country=A_COUNTRY) expect(self.http_client.get).to(have_been_called_with(TODAY_COUNTRY_NAMEDAYS_URL)) with it('returns the list of today\'s namedays for the country'): namedays = self.nameday_retriever.today(country=A_COUNTRY) expect(namedays).to(equal('Adela, Meritxell, Nuria')) ``` - El código de producción también se puede refactorizar. Aquí una propuesta: ```python= from json import loads as load_json class NamedayRetriever(object): TODAY_BASE_URL = 'https://api.abalin.net/get/today?country={}' DATA_KEY = 'data' def __init__(self, http_client): self._client = http_client def today(self, country): response = self._client.get(self.TODAY_BASE_URL.format(country)) return self._extract_names(response, country) def _extract_names(self, response, country): names_key = 'name_{}'.format(country) data = load_json(response)[self.DATA_KEY] return data[names_key] ``` --- ## HttpClient - La idea es hacer una llamada real a la api y comprobar que lo que nos responde es lo esperado (test de contrato? integración estrecho?) - Para ellos nos fijamos de nuevo en lo que retorna la API, y así sabremos qué queremos comprobar - Comenzamos con el test más simple que se nos ocurre ### 1A :rotating_light: El API devuelve respuesta OK (happy path) ```python from mamba import description, context, it from expects import expect, be_true import nameday with context('http client specs'): with context('getting today\'s namedays for Spain'): with it('returns a valid response'): http_client = nameday.HttpClient() response = http_client.get('https://api.abalin.net/get/today?country=es') expect(response.ok).to(be_true) ``` ### 1B :white_check_mark: El API devuelve respuesta OK (happy path) ```python= # -*- coding: utf-8 -*- from json import loads as load_json import requests class HttpClient(object): def get(self, url): return requests.get(url) ``` - Especial atención el tiempo de ejecución del test en la salida de consola (de nuevo, estos tests son caros... No queremos lanzarlos cada vez que hagamos un pequeño cambio en el código). ```bash= http client specs getting today's namedays for Spain ✓ it returns a valid response (0.8095 seconds) 1 examples ran in 0.8920 seconds ``` ### 1C :construction_worker: El API devuelve respuesta OK (happy path) - Refactorizamos el test: extraemos la cadena hardcodeada a una constante ```python= TODAY_SPAIN_NAMEDAYS_URL = 'https://api.abalin.net/get/today?country=es' with context('http client specs'): with context('getting today\'s namedays for Spain'): with it('returns a valid response'): http_client = nameday.HttpClient() response = http_client.get(TODAY_SPAIN_NAMEDAYS_URL) expect(response.ok).to(be_true) ``` --- ### 2A :white_check_mark: El API devuelve el santoral del país solicitado - El test está directamente en verde porque el código del cliente http ya está acabado. - Con estos tests extra somos más específicos con el contrato - Podemos verlo fallar (bastante recomendable) cambiando el expect (utilizando una key de otro país). Así nos aseguramos que no estamos dando falsos verdes. ```python= with context('http client specs'): with context('getting today\'s namedays for Spain'): with it('returns a valid response'): http_client = nameday.HttpClient() response = http_client.get(TODAY_SPAIN_NAMEDAYS_URL) expect(response.ok).to(be_true) with it('returns namedays for Spain'): http_client = nameday.HttpClient() response = http_client.get(TODAY_SPAIN_NAMEDAYS_URL) expect(response.json().get('data')).to(have_key('name_es')) ``` ### 2B :construction_worker: El API devuelve el santoral del país solicitado ```python= TODAY_SPAIN_NAMEDAYS_URL = 'https://api.abalin.net/get/today?country=es' SPAIN_NAMES_KEY = 'name_es' with context('http client specs'): with before.each: self.http_client = nameday.HttpClient() with context('getting today\'s namedays for Spain'): with it('returns a valid response'): response = self.http_client.get(TODAY_SPAIN_NAMEDAYS_URL) expect(response.ok).to(be_true) with it('returns namedays for Spain'): response = self.http_client.get(TODAY_SPAIN_NAMEDAYS_URL) expect(response.json().get('data')).to(have_key(SPAIN_NAMES_KEY)) ``` --- ### 3A :white_check_mark: El API devuelve el día y mes actual ```python= with context('http client specs'): with before.each: self.http_client = nameday.HttpClient() with context('getting today\'s namedays for Spain'): with it('returns a valid response'): response = self.http_client.get(TODAY_SPAIN_NAMEDAYS_URL) expect(response.ok).to(be_true) with it('returns namedays for Spain'): response = self.http_client.get(TODAY_SPAIN_NAMEDAYS_URL) expect(response.json().get('data')).to(have_key(SPAIN_NAMES_KEY)) with it('returns current day and month'): response = self.http_client.get(TODAY_SPAIN_NAMEDAYS_URL) now = datetime.now() expect(response.json().get('data').get('day')).to(equal(now.day)) expect(response.json().get('data').get('month')).to(equal(now.month)) ``` ### 3B :construction_worker: El API devuelve el día y mes actual - A destacar que tenemos dos aserciones en un mismo test. Podemos dejarlo así (las reglas están para romperlas si tiene sentido hacerlo) o hacer dos tests: uno para el día y otro para el mes ```python= with context('http client specs'): with before.each: self.http_client = nameday.HttpClient() with context('getting today\'s namedays for Spain'): with it('returns a valid response'): response = self.http_client.get(TODAY_SPAIN_NAMEDAYS_URL) expect(response.ok).to(be_true) with it('returns namedays for Spain'): response = self.http_client.get(TODAY_SPAIN_NAMEDAYS_URL) expect(response.json().get('data')).to(have_key(SPAIN_NAMES_KEY)) with it('returns current day'): response = self.http_client.get(TODAY_SPAIN_NAMEDAYS_URL) now = datetime.now() expect(response.json().get('data').get('day')).to(equal(now.day)) with it('returns current month'): response = self.http_client.get(TODAY_SPAIN_NAMEDAYS_URL) now = datetime.now() expect(response.json().get('data').get('month')).to(equal(now.month)) ``` - Otra opción es hacer un matcher personalizado (si creemos que nos aporta algo) ```python= # -*- coding: utf-8 -*- from datetime import datetime from mamba import description, context, it from expects import expect, be_true, have_key, equal from expects.matchers import Matcher import nameday TODAY_SPAIN_NAMEDAYS_URL = 'https://api.abalin.net/get/today?country=es' SPAIN_NAMES_KEY = 'name_es' class contain_current_day_and_month(Matcher): def __init__(self): self._now = datetime.now() def _match(self, response): response_day = response.json().get('data').get('day') response_month = response.json().get('data').get('month') if response_day != self._now.day: return False, ['wrong day'] if response_month != self._now.month: return False, ['wrong month'] return True, ['current day and month found'] with context('http client specs'): with before.each: self.http_client = nameday.HttpClient() with context('getting today\'s namedays for Spain'): with it('returns a valid response'): response = self.http_client.get(TODAY_SPAIN_NAMEDAYS_URL) expect(response.ok).to(be_true) with it('returns namedays for Spain'): response = self.http_client.get(TODAY_SPAIN_NAMEDAYS_URL) expect(response.json().get('data')).to(have_key(SPAIN_NAMES_KEY)) with it('returns current day and month'): response = self.http_client.get(TODAY_SPAIN_NAMEDAYS_URL) expect(response).to(contain_current_day_and_month()) ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully