Commits

George Ribeiro committed 504a461

infraestrutura de testes unitarios pronta.

  • Participants
  • Parent commits edef30c

Comments (0)

Files changed (15)

File db/__init__.py

-from sqlalchemy import create_engine
+from sqlalchemy import create_engine as sqlalchemy_create_engine
 from sqlalchemy.orm import sessionmaker
-
+from sqlalchemy.orm import mapper, clear_mappers
 from mapping import metadata
 
-engine = create_engine('postgresql+psycopg2://postgres:root@localhost:5432/tutorial', echo=True)
+def create_engine(uri):
+    return sqlalchemy_create_engine(uri)
 
-Session = sessionmaker()
-
-def map_entities():
-    from sqlalchemy.orm import mapper
+def mapper_all():
+    clear_mappers()
     from entities import Funcionario, Usuario
     from mapping import funcionarios_table, usuarios_table
     mapper(Funcionario, funcionarios_table)
     mapper(Usuario, usuarios_table)
+
+def create_all(engine):
+    metadata.create_all(engine)
+
+def create_session(engine):
+    Session = sessionmaker(bind=engine)
+    return Session()
     
-def DBSession():
-    map_entities()
-    Session.configure(bind=engine)
-    return Session()

File db/entities.py

     def __init__(self, name):
         self.name = name
         
-    def repr(self):
+    def __repr__(self):
         return "<Funcionario: %d>" % self.id
         
 class Usuario(object):
         self.senha = senha
         self.email = email
         
-    def repr(self):
+    def __repr__(self):
         return "<Usuario: %d>" % self.id

File db/mapping.py

     Column('nome', String, unique=True),
     Column('senha', String),
     Column('email', String),
-)
+)

File farmacia/__init__.py

-from flask import Flask
-from views.funcionarios import funcionarios
+from flask import Flask, g, render_template
+from db import create_engine, create_session, mapper_all
 
-SECRET_KEY = 'fe721db6-765b-4af9-90af-c798201618c4'
+configurations = {
+    'development':'farmacia.config.DevelopmentConfig',
+    'test':'farmacia.config.TestConfig',
+}
 
-app = Flask(__name__)
-app.config.from_object(__name__)
-app.register_module(funcionarios)
+def create_app(config):
+    if not config in configurations.keys():
+        raise Exception('Configuration Invalid')
+    
+    app = Flask(__name__)
+    app.config.from_object(configurations[config])
+    
+    from views.funcionarios import funcionarios
+    app.register_module(funcionarios)
+    
+    engine = create_engine(app.config['DATABASE_URI'])
+    mapper_all()
+    
+    @app.errorhandler(404)
+    def page_not_found(error):
+        return render_template('404.html'), 404
 
+    @app.before_request
+    def before_request():
+        g.dbsession = create_session(engine)
+
+    @app.after_request
+    def after_request(response):
+        g.dbsession.close()
+        return response
+    
+    return app

File farmacia/config.py

+import os
+ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
+
+class Config(object):
+    SECRET_KEY = '8e3b62d7-b8a0-43cc-9da1-37a31aef2f06'
+
+class DevelopmentConfig(Config):
+    DATABASE_URI = 'postgresql+psycopg2://postgres:root@localhost:5432/tutorial'
+    
+class TestConfig(Config):
+    DATABASE = os.path.join(ROOT_PATH, 'tutorial_test.db')
+    DATABASE_URI = 'sqlite:///%s' % os.path.join(DATABASE)

File farmacia/templates/404.html

+{% extends "base.html" %}
+
+{% block title %}{{ super() }} | Página não encontrada{% endblock %}
+
+{% block content %}
+  <h3>Página não encontrada. Desculpe.</h3>
+{% endblock %}

File farmacia/templates/base.html

+<!doctype html>
 <html>
   
 <head>

File farmacia/templates/funcionarios/delete.html

 
 {% block content %}
   <h3>Deletar Funcionário</h3>
-  <p>Você deseja realmente deletar o funcionário {{ funcionario.name }}?</p>
+  <p>Você deseja realmente deletar o funcionário "{{ funcionario.name }}"?</p>
   <form action="" method="post" accept-charset="utf-8">
     <p>
       <input type="submit" value="Sim" />

File farmacia/views/funcionarios.py

 from flask import Module, render_template, redirect, url_for, request, \
-    flash
+    flash, abort, g
 
-from db import DBSession
+from db import create_session, create_engine
 from db.repositories import Repository
 from db.entities import Funcionario
 
 funcionarios = Module(__name__, url_prefix='/')
 
-dbsession = DBSession()
-
 @funcionarios.route('')
 def index():
-    repository = Repository(dbsession)
+    repository = Repository(g.dbsession)
     object_list = repository.query(Funcionario).order_by(Funcionario.id).all()
     return render_template('funcionarios/index.html', funcionarios=object_list)
 
             erros.append('Campo nome eh obrigatorio.')
             return render_template('funcionarios/new.html', erros=erros)
         f = Funcionario(request.form['name'])
-        repository = Repository(dbsession)
+        repository = Repository(g.dbsession)
         repository.save(f)
         flash('Registro salvo com sucesso.')
         return redirect(url_for('index'))
     
 @funcionarios.route('edit/<int:funcionario_id>', methods=['GET', 'POST'])
 def edit(funcionario_id):
-    repository = Repository(dbsession)
+    repository = Repository(g.dbsession)
     funcionario = repository.get_by_id(Funcionario, funcionario_id)
+    if funcionario is None:
+        abort(404)
     if request.method == 'POST':
         funcionario.name = request.form['name']
         repository.save(funcionario)
     
 @funcionarios.route('delete/<int:funcionario_id>', methods=['GET', 'POST'])
 def delete(funcionario_id):
-    repository = Repository(dbsession)
+    repository = Repository(g.dbsession)
     funcionario = repository.get_by_id(Funcionario, funcionario_id)
+    if funcionario is None:
+        abort(404)
     if request.method == 'POST':
         repository.delete(funcionario)
         flash('Registro Excluido com sucesso.')
 #!/usr/bin/env python
 
-from farmacia import app
-app.run(debug=True)
+from farmacia import create_app
+create_app('development').run(debug=True)

File test/functional/views/__init__.py

Empty file added.

File test/functional/views/funcionarios.py

+# encoding: utf8 
+
+from test.helper import TestHelper
+
+class TestViewFuncionario(TestHelper):
+    
+    def test_entro_na_pagina_incial_e_vejo_o_titulo_farmacia(self):
+        app = self.get_app()
+        resp = app.get('/')
+        self.assertEquals(resp.status_code, 200)
+        self.assertTrue('Farmácia' in resp.data)
+    
+    def test_tento_editar_funcionario_que_nao_existe_e_vou_para_pagina_404(self):
+        app = self.get_app()
+        dbsession = self.get_session()
+        # iniciar banco com dados
+        from db.entities import Funcionario
+        from db.repositories import Repository
+        rep = Repository(dbsession)
+        rep.save(Funcionario('1'))
+        
+        resp = app.get('/edit/1')
+        self.assertEquals(resp.status_code, 200)
+        resp = app.get('/edit/2')
+        self.assertEquals(resp.status_code, 404)
+        
+    def test_eh_independente_do_anterior(self):
+        session = self.get_session()
+        from db.repositories import Repository
+        from db.entities import Funcionario
+        rep = Repository(session)
+        self.assertEquals(rep.query(Funcionario).count(), 0)

File test/helper.py

 import unittest
 
 class TestHelper(unittest.TestCase):
+    def tearDown(self):
+        import os
+        from farmacia import config
+        databasename = config.TestConfig().DATABASE
+        os.remove(databasename)
+        
     def get_session(self):
-        from sqlalchemy import create_engine
-        from sqlalchemy.orm import clear_mappers
-        engine = create_engine('sqlite:///:memory:')
-        from db import Session, map_entities, metadata
-        metadata.create_all(engine)
-        Session.configure(bind=engine)
-        clear_mappers()
-        map_entities()
-        return Session()
+        from db import create_session, create_all, create_engine, mapper_all
+        from farmacia.config import TestConfig
+        database_uri = TestConfig().DATABASE_URI
+        engine = create_engine(database_uri)
+        create_all(engine)
+        mapper_all()
+        return create_session(engine)
+        
+    def get_app(self):
+        from farmacia import create_app, config
+        from db import create_all, create_engine
+        database_uri = config.TestConfig().DATABASE_URI
+        engine = create_engine(database_uri)
+        create_all(engine)
+        return create_app('test').test_client()

File test/unit/test_usuario.py

-import unittest
-from test.helper import TestHelper
-
-class TestUsuario(TestHelper):
-    
-    def test_posso_criar_e_recuperar_um_usuario(self):
-        session = self.get_session()
-        from db.entities import Usuario
-        from db.repositories import RepositoryUsuario
-        usuario = Usuario('george', '1234', 'george.rib@gmail.com')
-        rep = RepositoryUsuario(session)
-        rep.save(usuario)
-        self.assertEquals(usuario.id, 1)
-        self.assertNotEquals(usuario.senha, '1234')
-        usuario_recuperado = rep.get_by_id(usuario.id)
-        self.assertEquals(usuario_recuperado, usuario)
-        import hashlib
-        senha_criptografada = hashlib.new('sha1', '1234').hexdigest()
-        self.assertEquals(usuario_recuperado.senha, senha_criptografada)
-        
-    def test_posso_deletar_um_usuario(self):
-        session = self.get_session()
-        from db.entities import Usuario
-        from db.repositories import RepositoryUsuario
-        rep = RepositoryUsuario(session)
-        for i in xrange(5):
-            usuario = Usuario(str(i), str(i), str(i))
-            rep.save(usuario)
-        usuario = rep.get_by_id(3)
-        rep.delete(usuario)
-        self.assertEquals(rep.query().count(), 4)
-        self.assertEquals(rep.get_by_id(3), None)
-        
-    def _salvar_usuarios(self):
-        session = self.get_session()
-        from db.entities import Usuario
-        from db.repositories import RepositoryUsuario
-        rep = RepositoryUsuario(session)
-        usuario1 = Usuario("george", "4321", "george.rib@gmail.com")
-        rep.save(usuario1)
-        usuario2 = Usuario("george", "1234", "george-ribeiro@hotmail.com")
-        rep.save(usuario2)
-        
-    def test_nao_posso_salvar_usuarios_com_mesmo_nome(self):
-        from sqlalchemy.exc import IntegrityError
-        self.assertRaises(IntegrityError, self._salvar_usuarios,)
-        

File test/unit/usuario.py

+from test.helper import TestHelper
+
+class TestUsuario(TestHelper):
+    
+    def test_posso_criar_e_recuperar_um_usuario(self):
+        session = self.get_session()
+        from db.entities import Usuario
+        from db.repositories import RepositoryUsuario
+        usuario = Usuario('george', '1234', 'george.rib@gmail.com')
+        rep = RepositoryUsuario(session)
+        rep.save(usuario)
+        self.assertEquals(usuario.id, 1)
+        self.assertNotEquals(usuario.senha, '1234')
+        usuario_recuperado = rep.get_by_id(usuario.id)
+        self.assertEquals(usuario_recuperado, usuario)
+        import hashlib
+        senha_criptografada = hashlib.new('sha1', '1234').hexdigest()
+        self.assertEquals(usuario_recuperado.senha, senha_criptografada)
+        
+    def test_posso_deletar_um_usuario(self):
+        session = self.get_session()
+        from db.entities import Usuario
+        from db.repositories import RepositoryUsuario
+        rep = RepositoryUsuario(session)
+        for i in xrange(5):
+            usuario = Usuario(str(i), str(i), str(i))
+            rep.save(usuario)
+        usuario = rep.get_by_id(3)
+        rep.delete(usuario)
+        self.assertEquals(rep.query().count(), 4)
+        self.assertEquals(rep.get_by_id(3), None)
+        
+    def _salvar_usuarios(self):
+        session = self.get_session()
+        from db.entities import Usuario
+        from db.repositories import RepositoryUsuario
+        rep = RepositoryUsuario(session)
+        usuario1 = Usuario("george", "4321", "george.rib@gmail.com")
+        rep.save(usuario1)
+        usuario2 = Usuario("george", "1234", "george-ribeiro@hotmail.com")
+        rep.save(usuario2)
+        
+    def test_nao_posso_salvar_usuarios_com_mesmo_nome(self):
+        from sqlalchemy.exc import IntegrityError
+        self.assertRaises(IntegrityError, self._salvar_usuarios,)
+