Posts de March, 2013

[Igor Sobreira] Trying to write clean code is making me stupid

Tuesday, March 26th, 2013

[Igor Sobreira] Testing infinite loops

Sunday, March 17th, 2013

Yesterday I was working on a script that should run forever, or at least until the user stops it. The library behind it was already tested except for this little function:

def collect(directory):
    sequential = Sequential(directory)
    live = Live(directory)

    while 1:
        live.process()
        sequential.process()

this is the entry point of my library. I have an executable that just parses a directory name from command line and call this function. It’s purpose it to collect all files from a directory, filter based on some rules, and publish the file names in a queue which will be consumed by another script. It runs forever because newly created files are detected and collected too.

Anyway, what it does doesn’t really matter, the problem is: how to test this function since it’s supposed to run forever?

I don’t mind to have just unit tests for this function because I already have more integration-like tests for the classes it uses. The first solution I thought was something like this:

def collect(directory):
    sequential = Sequential(directory)
    live = Live(directory)

    while should_continue():  # new function to mock on tests: UGLY!
        live.process()
        sequential.process()

def should_continue():
    return True

this way I could mock should_continue() in my test and make it return False to abort the loop when I want. That works but it’s ugly! I don’t like to add dependency injections only for tests.

I asked on #python on irc and marienz gave a neat idea: raise an exception.
I could mock live.process() and sequential.process() and raise an exception, this way I know they were called as I expected and also it will also abort the loop!

import pytest
import mock

# this is the library under test
import collectors

# replace original classed with mock objects
@mock.patch('collectors.Sequential')
@mock.patch('collectors.Live')
def test_collect_should_loop_forever_processing_both_collectors(
        collectors_Live, collectors_Sequential):

    # build mock instances. process() method will raise error
    # when called for the 2nd time. The code for `ErrorAfter`
    # is bellow
    seq = mock.Mock(['process'])
    seq.process.side_effect = ErrorAfter(2)
    live = mock.Mock(['process'])
    live.process.side_effect = ErrorAfter(2)

    # ensure mocked classes builds my mocked instances
    collectors_Sequential.return_value = seq
    collectors_Live.return_value = live

    # `ErrorAfter` will raise `CallableExhausted`
    with pytest.raises(CallableExhausted):
        collectors.collect('/tmp/files')

    # make sure our classed are instantiated with directory
    collectors_Sequential.assert_called_once_with('/tmp/files')
    collectors_Live.assert_called_once_with('/tmp/files')

This test uses py.test and mock. I hope the comments explains enough. The idea is simple: make process() raise an Exception to abort the loop.
The ErrorAfter class is a small helper, it builds a callable object that will raise a specific exception after n calls. I created a custom exception here to make sure my test fails if any other exception is raised. See the code bellow.

class ErrorAfter(object):
    '''
    Callable that will raise `CallableExhausted`
    exception after `limit` calls

    '''
    def __init__(self, limit):
        self.limit = limit
        self.calls = 0

    def __call__(self):
        self.calls += 1
        if self.calls > self.limit:
            raise CallableExhausted

class CallableExhausted(Exception):
    pass

Conclusion

Try to avoid as much as possible to create dependency injections specifically for your tests. In dynamic languages like Python it’s very easy to replace a specific component with a mock object without adding extra complexity to your code just to allow unit testing.

This was the first time I had to test a infinite loop, it’s possible and easy!

[Davidson Fellipe] Opinion about frameworks for front end development

Sunday, March 17th, 2013

Originally published in edition No. 5, iMasters Magazine, Year 2, on March 2013.

In this fifth edition’s iMasters Magazine, magazine’s major brazilian portal about web development, I wrote an opinion about Frameworks for Front-end Development.

” It’s a fact that has emerged some interesting about frameworks for front end development, and also, comes the growth of frontend community involvement with the open source world, bringing an ecosystem much more collaborative. These Frameworks end up creating or helping to set standardizations code, with a good documentation centralized, and often, supporting web standards and good accessibility, but the developers must be think about impacts that he will bring the performance, learning curve for team and maintenance cost among the options market can highlight: Twitter Bootstrap, Skeleton, ZURB Foundation.”

To read this complete article, visit the magazine (free online version): http://issuu.com/imasters

[Rafael Biriba] Globo.com abre novas vagas de estágio para agosto de 2013

Wednesday, March 13th, 2013

http://www.globo.com/estag

Estão abertas mais uma vez as inscrições para estagiar na Globo.com.

Para se candidatar o periodo de formatura exigido é: agosto/2014 a agosto/2015

Não perca essa oportunidade de participar no desenvolvimento de um dos maiores portais da internet Brasileira… As inscrições podem ser feitas pelo site http://www.globo.com/estag

Etapas do processo seletivo: ( 2013 )
- Inscrições:  ainda não informado
- Prova On-line: ainda não informado
- Entrevista Coletiva: ainda não informado
Painel: ainda não informado
- Entrevista com o Gestor: ainda não informado
- Início do Estágio: Agosto de 2013

Fique atento ao seu email, pois as convocações iniciais deverão ser feitas por meio dele
Visite também o site para mais detalhes: http://www.globo.com/estag

Informações adicionais:
Quem pode participar?
Estudantes matriculados em cursos de nível superior, com previsão de formatura para agosto de 2014 ou  agosto de 2015, compatíveis com as áreas/vagas existentes, disponíveis para a cidade do Rio de Janeiro

Existem vagas para que áreas?
Vagas em diversas áreas para estudantes dos mais variados cursos: Administração, Psicologia, Comunicação Social, Comunicação Visual, Design, Desenho Industrial, Estatística, Engenharia de Produção, Cursos das áreas de Tecnologia (Ciência da Computação, Engenharia da Computação, Análise de Sistemas) entre outros

Aproveite e dê uma olhada no restante do blog. Dicas importantes podem ser obtidas nos comentários dos outros posts antigos sobre os processos seletivos, principalmente nos posts de processos seletivos antigos, pois muitas duvidas foram respondida pelos comentários… Fique atento para não haver repetição de dúvidas…

ATENÇÃO para esta dica adicional =) Se a sua previão de formatura não estiver entre a solicitada (ago/14 a ago/15), inscreva-se mesmo assim. Quem sabe você não consegue entrar… ;)

Como sempre estou a disposição para responder qualquer pergunta (Dado que eu fui um estagiário e também um efetivado na Globo.com)

Dependendo da pergunta/dúvida, posso pedir para que alguém do RH da Globo.com para responder ;)

531745_437006493041878_8651260_n

 

Boa sorte a todos !

TwitterFacebookShare