owned this note
owned this note
Published
Linked with GitHub
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())
```