Posts de October, 2016

[Igor Sobreira] Generating test functions dynamically in Python

Friday, October 21st, 2016

Some tests I write get tedious and repetitive, even with custom asserts to make it easier. For instance, take this test from a Django project I’m working on:

import myapp.views

def test_my_view_requires_login():

I have a @login_required decorator and a function assert_login_required that checks if a view has been decorated with it. I know the test is quite small but I decided to do some metaprogramming and simplify it even further:

import myapp.views


Here is the code for ensure_login_required:

import sys

def ensure_login_required(view):
    Generate a test function checking that 'view' is using @login_required
    def test_func():

    # get global namespace from where this function is being called, if I use
    # globals() here I'll actually get the global namespace of this module
    namespace = sys._getframe(1).f_globals
    namespace['test_%s_requires_login' % view.__name__] = test_func

[Igor Sobreira] Posting strings using HTTPie

Wednesday, October 19th, 2016

Some time ago I came across this great command line tool to make http requests: HTTPie. Simple and intuitive API:

http PUT X-API-Token:123 name=Igor

this sends that PUT as JSON. To submit as form (application/x-www-form-urlencoded; charset=utf-8), just set the -f flag.

Now it took me some time to figure out how to send a raw string as body. It turns out you can just write to it’s stdin:

echo '{"name":"Igor"}' | http PUT

Nice API.