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. 203
      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')

203
crud_tests/test_flux.py

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