Browse Source

Desacopla testes do crud e faz passar testes básicos

Remove dependência da app comissoes, cria novos stubs e
settings separado. Faz passar os testes básicos.
pull/216/head
Marcio Mazza 9 years ago
committed by Eduardo Edson Batista Cordeiro Alves
parent
commit
3837380520
  1. 23
      crud_tests/models.py
  2. 39
      crud_tests/settings.py
  3. 201
      crud_tests/test_flux.py
  4. 23
      crud_tests/urls.py
  5. 12
      crud_tests/views.py

23
crud_tests/models.py

@ -0,0 +1,23 @@
from django.db import models
class Continent(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class Country(models.Model):
name = models.CharField(max_length=50)
continent = models.ForeignKey(Continent)
is_cold = models.BooleanField(choices=[(True, 'Yes'), (False, 'No')])
population = models.PositiveIntegerField(blank=True, null=True)
description = models.TextField(blank=True)
class Meta:
verbose_name = 'Country'
verbose_name_plural = 'Countries'
def __str__(self):
return self.name

39
crud_tests/settings.py

@ -0,0 +1,39 @@
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
},
}
INSTALLED_APPS = (
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.messages',
'crud_tests',
'crispy_forms',
)
ROOT_URLCONF = 'crud_tests.urls'
USE_TZ = True
SECRET_KEY = 'zzz...'
TEMPLATES = [{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
}]
SILENCED_SYSTEM_CHECKS = [
'1_7.W001', # Unset MIDDLEWARE_CLASSES warning
]
TIME_ZONE = 'America/Sao_Paulo'
USE_I18N = True
USE_L10N = False
USE_TZ = True
# DATE_FORMAT = 'N j, Y'
DATE_FORMAT = 'd/m/Y'
SHORT_DATE_FORMAT = 'd/m/Y'
DATE_INPUT_FORMATS = ('%d/%m/%Y', '%m-%d-%Y', '%Y-%m-%d')

201
crud_tests/test_flux.py

@ -2,29 +2,25 @@ import pytest
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
from model_mommy import mommy from model_mommy import mommy
from comissoes.models import Comissao, TipoComissao from crud import (NO_ENTRIES_MSG, build_crud, from_to, get_field_display,
from .crud import (NO_ENTRIES_MSG, build_crud, from_to, get_field_display,
make_pagination) make_pagination)
pytestmark = pytest.mark.django_db from .models import Continent, Country
from .views import country_crud
# XXX These tests are based on comissoes app pytestmark = pytest.mark.django_db
# but could be done with a stub one
@pytest.mark.parametrize("layout, result", [ @pytest.mark.parametrize("layout, result", [
([['Dados Complementares']], []), # missing rows definition ([['Dados Complementares']], []), # missing rows definition
([
['Dados Básicos', ([['Basic', [('name', 9), ('population', 3)]],
[('nome', 9), ('sigla', 3)], ['More Details', [('description', 12)]],
[('tipo', 3), ('data_criacao', 3), ('unidade_deliberativa', 3), ]
], ],
['Dados Complementares', [('finalidade', 12)]], ], ['name', 'population']),
['nome', 'sigla', 'tipo', 'data_criacao', 'unidade_deliberativa']),
]) ])
def test_listview_get_fieldnames(layout, result): def test_listview_get_fieldnames(layout, result):
crud = build_crud(Comissao, 'stub_help_path', layout) crud = build_crud(Country, 'stub_help_path', layout)
view = crud.CrudListView() view = crud.CrudListView()
assert view.field_names == result assert view.field_names == result
@ -74,84 +70,66 @@ def test_make_pagination(index, num_pages, result):
def test_get_field_display(): def test_get_field_display():
stub = mommy.prepare(Comissao, unidade_deliberativa=True) stub = mommy.prepare(Country, is_cold=True)
assert get_field_display(stub, 'nome')[1] == stub.nome assert get_field_display(stub, 'name')[1] == stub.name
assert get_field_display(stub, 'tipo')[1] == str(stub.tipo) assert get_field_display(stub, 'continent')[1] == str(stub.continent)
# must return choice display, not the value # must return choice display, not the value
assert stub.unidade_deliberativa is True assert stub.is_cold is True
assert get_field_display(stub, 'unidade_deliberativa')[1] == 'Sim' assert get_field_display(stub, 'is_cold')[1] == 'Yes'
# None is displayed as empty string # None is displayed as an empty string
assert stub.finalidade is None assert stub.population is None
assert get_field_display(stub, 'finalidade')[1] == '' assert get_field_display(stub, 'population')[1] == ''
def test_crud_detail_view_fieldsets(monkeypatch): def test_crud_detail_view_fieldsets(monkeypatch):
crud = build_crud( view = country_crud.CrudDetailView()
Comissao, 'stub_help_path', [ stub = mommy.make(Country,
name='Brazil',
['Dados Básicos', continent__name='South America',
[('nome', 9), ('sigla', 3)], is_cold=False)
[('tipo', 3), ('data_criacao', 3), ('unidade_deliberativa', 3), ]
],
['Dados Complementares',
[('finalidade', 12)]
],
])
view = crud.CrudDetailView()
stub = mommy.make(Comissao,
nome='nome!!!',
tipo__nome='tipo!!!',
sigla='sigla!!!',
data_criacao='2011-01-01',
unidade_deliberativa=True)
# to test None displayed as empty string # to test None displayed as empty string
assert stub.finalidade is None assert stub.population is None
def get_object(): def get_object():
return stub return stub
monkeypatch.setattr(view, 'get_object', get_object) monkeypatch.setattr(view, 'get_object', get_object)
assert view.fieldsets == [ assert view.fieldsets == [
{'legend': 'Dados Básicos', {'legend': 'Basic Data',
'rows': [[{'id': 'nome', 'rows': [[{'id': 'name',
'span': 9, 'span': 9,
'text': 'nome!!!', 'text': stub.name,
'verbose_name': 'Nome'}, 'verbose_name': 'name'},
{'id': 'sigla', {'id': 'continent',
'span': 3, 'span': 3,
'text': 'sigla!!!', 'text': stub.continent.name,
'verbose_name': 'Sigla'}], 'verbose_name': 'continent'}
],
[{'id': 'tipo', [{'id': 'population',
'span': 3, 'span': 6,
'text': 'tipo!!!', 'text': '',
'verbose_name': 'Tipo'}, 'verbose_name': 'population'},
{'id': 'data_criacao', {'id': 'is_cold',
'span': 3, 'span': 6,
'text': '2011-01-01', 'text': 'No',
'verbose_name': 'Data de Criação'}, 'verbose_name': 'is cold'}]]},
{'id': 'unidade_deliberativa', {'legend': 'More Details',
'span': 3, 'rows': [[{'id': 'description',
'text': 'Sim',
'verbose_name': 'Unidade Deliberativa'}]]},
{'legend': 'Dados Complementares',
'rows': [[{'id': 'finalidade',
'span': 12, 'span': 12,
'text': '', 'text': '',
'verbose_name': 'Finalidade'}]]}] 'verbose_name': 'description'}]]}]
def test_reverse(): def test_reverse():
assert '/comissoes/' == reverse('comissao:list') assert '/countries/' == reverse('country:list')
assert '/comissoes/create' == reverse('comissao:create') assert '/countries/create' == reverse('country:create')
assert '/comissoes/2' == reverse('comissao:detail', args=(2,)) assert '/countries/2' == reverse('country:detail', args=(2,))
assert '/comissoes/2/edit' == reverse('comissao:update', args=(2,)) assert '/countries/2/edit' == reverse('country:update', args=(2,))
assert '/comissoes/2/delete' == reverse('comissao:delete', args=(2,)) assert '/countries/2/delete' == reverse('country:delete', args=(2,))
def assert_h1(res, title): def assert_h1(res, title):
@ -162,14 +140,14 @@ NO_ENTRIES_MSG = str(NO_ENTRIES_MSG) # "unlazy"
def assert_on_list_page(res): def assert_on_list_page(res):
assert_h1(res, 'Comissões') assert_h1(res, 'Countries')
assert 'Adicionar Comissão' in res assert 'Adicionar Country' in res
assert res.html.find('table') or NO_ENTRIES_MSG in res assert res.html.find('table') or NO_ENTRIES_MSG in res
# XXX ... characterize better # XXX ... characterize better
def assert_on_create_page(res): def assert_on_create_page(res):
assert_h1(res, 'Adicionar Comissão') assert_h1(res, 'Adicionar Country')
form = res.form form = res.form
assert not any( assert not any(
form[k].value for k in form.fields if k != 'csrfmiddlewaretoken') form[k].value for k in form.fields if k != 'csrfmiddlewaretoken')
@ -195,14 +173,14 @@ def test_flux_list_paginate_detail(
entries_labels = [] entries_labels = []
for i in range(num_entries): for i in range(num_entries):
# letter = next(letters) # letter = next(letters)
nome, sigla, tipo = 'nome %s' % i, 'sigla %s' % i, 'tipo %s' % i name, continent = 'name %s' % i, 'continent %s' % i
entries_labels.append([nome, sigla, tipo]) entries_labels.append([name, continent])
mommy.make(Comissao, nome=nome, sigla=sigla, tipo__nome=tipo) mommy.make(Country, name=name, continent__name=continent)
from .teststubs.urls_for_list_test import crud from .teststubs.urls_for_list_test import crud
crud.CrudListView.paginate_by = page_size crud.CrudListView.paginate_by = page_size
res = app.get('/comissoes/') res = app.get('/countries/')
if num_entries == 0: if num_entries == 0:
assert_on_list_page(res) assert_on_list_page(res)
@ -217,7 +195,8 @@ def test_flux_list_paginate_detail(
table = res.html.find('table') table = res.html.find('table')
assert table assert table
header, *trs = table.findAll('tr') header, *trs = table.findAll('tr')
assert header.text.strip().split() == ['Nome', 'Sigla', 'Tipo'] assert header.text.strip().split() == [
'name', 'Sigla', 'continent']
rows = [[td.text.strip() for td in tr.findAll('td')] rows = [[td.text.strip() for td in tr.findAll('td')]
for tr in trs] for tr in trs]
@ -230,38 +209,38 @@ def test_flux_list_paginate_detail(
assert paginator.text.strip().split() == page_list assert paginator.text.strip().split() == page_list
assert_at_page(res, 1) assert_at_page(res, 1)
res_detail = res.click('nome 1') res_detail = res.click('name 1')
assert_on_detail_page(res_detail, 'nome 1') assert_on_detail_page(res_detail, 'name 1')
if len(ranges) > 1: if len(ranges) > 1:
res = res.click('2', href='page=2') res = res.click('2', href='page=2')
assert_at_page(res, 2) assert_at_page(res, 2)
fist_entry_on_2nd_page = 'nome %s' % page_size fist_entry_on_2nd_page = 'name %s' % page_size
res_detail = res.click(fist_entry_on_2nd_page) res_detail = res.click(fist_entry_on_2nd_page)
assert_on_detail_page(res_detail, fist_entry_on_2nd_page) assert_on_detail_page(res_detail, fist_entry_on_2nd_page)
res = res.click('1', href='page=1') res = res.click('1', href='page=1')
assert_at_page(res, 1) assert_at_page(res, 1)
res_detail = res.click('nome 1') res_detail = res.click('name 1')
assert_on_detail_page(res_detail, 'nome 1') assert_on_detail_page(res_detail, 'name 1')
@pytest.mark.parametrize("cancel, make_invalid_submit", [ @pytest.mark.parametrize("cancel, make_invalid_submit", [
(a, b) for a in (True, False) for b in (True, False)]) (a, b) for a in (True, False) for b in (True, False)])
def test_flux_list_create_detail(app, cancel, make_invalid_submit): def test_flux_list_create_detail(app, cancel, make_invalid_submit):
# to have a couple an option for tipo field # to have a couple an option for continent field
stub_tipo = mommy.make(TipoComissao) stub_continent = mommy.make(Continent)
res = app.get('/comissoes/') res = app.get('/countries/')
# on list page # on list page
assert_on_list_page(res) assert_on_list_page(res)
res = res.click('Adicionar Comissão') res = res.click('Adicionar Country')
previous_objects = set(Comissao.objects.all()) previous_objects = set(Country.objects.all())
# on create page # on create page
assert_on_create_page(res) assert_on_create_page(res)
@ -272,7 +251,7 @@ def test_flux_list_create_detail(app, cancel, make_invalid_submit):
# back to list page # back to list page
assert_on_list_page(res) assert_on_list_page(res)
# db has not changed # db has not changed
assert previous_objects == set(Comissao.objects.all()) assert previous_objects == set(Country.objects.all())
else: else:
# and a test detour ! # and a test detour !
if make_invalid_submit: if make_invalid_submit:
@ -281,34 +260,34 @@ def test_flux_list_create_detail(app, cancel, make_invalid_submit):
'Formulário inválido. O registro não foi criado.' in res 'Formulário inválido. O registro não foi criado.' in res
assert_on_create_page(res) assert_on_create_page(res)
# db has not changed # db has not changed
assert previous_objects == set(Comissao.objects.all()) assert previous_objects == set(Country.objects.all())
# now fill out some fields # now fill out some fields
form = res.form form = res.form
stub_name = '### Nome Especial ###' stub_name = '### name Especial ###'
form['nome'] = stub_name form['name'] = stub_name
form['sigla'] = 'SIGLA' form['sigla'] = 'SIGLA'
form['tipo'] = stub_tipo.id form['continent'] = stub_continent.id
form['data_criacao'] = '1/1/2001' form['data_criacao'] = '1/1/2001'
res = form.submit() res = form.submit()
# on redirect to detail page # on redirect to detail page
created = Comissao.objects.get(nome=stub_name) created = Country.objects.get(name=stub_name)
assert res.url.endswith('/comissoes/%s' % created.id) assert res.url.endswith('/countries/%s' % created.id)
res = res.follow() res = res.follow()
# on detail page # on detail page
assert_on_detail_page(res, stub_name) assert_on_detail_page(res, stub_name)
assert 'Registro criado com sucesso!' in res assert 'Registro criado com sucesso!' in res
[new_obj] = list(set(Comissao.objects.all()) - previous_objects) [new_obj] = list(set(Country.objects.all()) - previous_objects)
assert new_obj.nome == stub_name assert new_obj.name == stub_name
def get_detail_page(app): def get_detail_page(app):
stub = mommy.make(Comissao, nome='Comissão Stub') stub = mommy.make(Country, name='Country Stub')
res = app.get('/comissoes/%s' % stub.id) res = app.get('/countries/%s' % stub.id)
# on detail page # on detail page
assert_on_detail_page(res, stub.nome) assert_on_detail_page(res, stub.name)
return stub, res return stub, res
@ -318,29 +297,29 @@ def test_flux_detail_update_detail(app, cancel):
res = res.click('Editar') res = res.click('Editar')
# on update page # on update page
assert_h1(res, stub.nome) assert_h1(res, stub.name)
# test bifurcation ! # test bifurcation !
if cancel: if cancel:
res = res.click('Cancelar') res = res.click('Cancelar')
# back to detail page # back to detail page
assert_on_detail_page(res, stub.nome) assert_on_detail_page(res, stub.name)
assert Comissao.objects.get(pk=stub.pk).nome == stub.nome assert Country.objects.get(pk=stub.pk).name == stub.name
else: else:
form = res.form form = res.form
new_name = '### New Name ###' new_name = '### New Name ###'
form['nome'] = new_name form['name'] = new_name
res = form.submit() res = form.submit()
# on redirect to detail page # on redirect to detail page
assert res.url.endswith('/comissoes/%s' % stub.id) assert res.url.endswith('/countries/%s' % stub.id)
res = res.follow() res = res.follow()
# back to detail page # back to detail page
assert_on_detail_page(res, new_name) assert_on_detail_page(res, new_name)
assert 'Registro alterado com sucesso!' in res assert 'Registro alterado com sucesso!' in res
assert Comissao.objects.get(pk=stub.pk).nome == new_name assert Country.objects.get(pk=stub.pk).name == new_name
@pytest.mark.parametrize("cancel", [True, False]) @pytest.mark.parametrize("cancel", [True, False])
@ -350,23 +329,23 @@ def test_flux_detail_delete_list(app, cancel):
# on delete page # on delete page
assert 'Tem certeza que deseja apagar' in res assert 'Tem certeza que deseja apagar' in res
assert stub.nome in res assert stub.name in res
# test bifurcation ! # test bifurcation !
if cancel: if cancel:
res = res.click('Cancelar') res = res.click('Cancelar')
# back to detail page # back to detail page
assert_on_detail_page(res, stub.nome) assert_on_detail_page(res, stub.name)
assert Comissao.objects.filter(pk=stub.pk) assert Country.objects.filter(pk=stub.pk)
else: else:
res = res.form.submit() res = res.form.submit()
# on redirect to list page # on redirect to list page
assert res.url.endswith('/comissoes/') assert res.url.endswith('/countries/')
res = res.follow() res = res.follow()
# on list page # on list page
assert 'Registro excluído com sucesso!' in res assert 'Registro excluído com sucesso!' in res
assert_h1(res, 'Comissões') assert_h1(res, 'Countries')
assert not Comissao.objects.filter(pk=stub.pk) assert not Country.objects.filter(pk=stub.pk)

23
crud_tests/urls.py

@ -1,24 +1,9 @@
from django.conf.urls import include, url from django.conf.urls import include, url
from comissoes.models import Comissao from .views import country_crud
from comissoes.urls import comissao_url_patterns
from crud import build_crud
crud = build_crud(
Comissao, '', [
['Dados Básicos',
[('nome', 9), ('sigla', 3)],
[('tipo', 3)]
],
['Dados Complementares',
[('finalidade', 12)]
],
])
urlpatterns = [ urlpatterns = [
url(r'^comissoes/', include(( url(r'^countries/', include(country_crud.urlpatterns,
crud.urlpatterns + comissao_url_patterns[len(crud.urlpatterns):], country_crud.namespace,
crud.namespace, crud.namespace))), country_crud.namespace)),
] ]

12
crud_tests/views.py

@ -0,0 +1,12 @@
from crud import build_crud
from .models import Country
country_crud = build_crud(
Country, 'help_path', [
['Basic Data',
[('name', 9), ('continent', 3)],
[('population', 6), ('is_cold', 6)]
],
['More Details', [('description', 12)]],
])
Loading…
Cancel
Save