Pages

Monday, 25 April 2011

Calling only once setUp in unittest in python

In python unittest the setUp function gets called every time you need to run a single TestCase (no matter if you run it using TestSuite or simply unittest.main()).

So if you have to test something that requires a complex setUp routine (like loading 50000 records from SQL or preparing an orangemochafrappuccino) but that can be reused all along your TestSuite you have the same problem I had.

Now all around the internet there are posts saying "You could do that" or "One way to do that" or "Once I did that like this..." or even worse "The standard way of doing it is...".

But none of these posts really gets to the bottom of it, they all give you a piece of information. I couldn't find one place that told you "copy/paste this code and be happy".

So, after figuring it out, I can now tell you "copy/paste this code and be happy".
import unittest
from my_program import MyClass

class MyClassTest(unittest.TestCase):
    # First define a class variable that determines 
    # if setUp was ever run
    ClassIsSetup = False

    def setUp(self):
        # If it was not setup yet, do it
        if not self.ClassIsSetup:
            print "Initializing testing environment"
            # run the real setup
            self.setupClass()
            # remember that it was setup already
            self.__class__.ClassIsSetup = True
                               
    def setupClass(self):
        # Do the real setup
        unittest.TestCase.setUp(self)
        # you want to have persistent things to test
        self.__class__.myclass = MyClass()
        # (you can call this later with self.myclass)

You can do the same for the unittest.tearDown since it is exactly the same code.

Mocking LDAP calls with minimock in python

When using unittest in python you often need to mock objects and calls to those objects.

You don't need _an_entire_ LDAP server just to test a search nor you need a full blown SMTP server to test a function that accidentally sends a mail (that you don't want to send while testing anyway).

So minimock is one easy way (the easiest I found) to do the job.

What the docs don't really tell you (nor does a google search) is how to return real things when you need to call a method of an object.

Say you have some code like this:
import ldap
class MyClass:
...
    def ldapsearch(self, uid):
        self.conn = ldap.open(self.conf.ldapserver)
        self.conn.bind_s(binddn, bindpw, ldap.AUTH_SIMPLE)
        self.conn.search_s(basedn, ldap.SCOPE_SUBTREE, 'uid=%s' % uid, ['uid'])
        return True

and you want to test this and moreover you want that search to return a given set of data.

from minimock import Mock
import ldap
from my_program import MyClass

class MyClassTest(unittest.TestCase):
...
    def test_ldapsearch(self):
        # create your fake ldap connection
        ldap.open = Mock('ldap.open')
        ldap.open.mock_returns = Mock('ldap_connection')
        # instantiate your class
        myclass = MyClass()
        # now tell to minimock that in case we do a search_s on 
        # a conn method this should be intercepted and mocked
        # returning a testuser1 value the way LDAP would do
        myclass.conn.search_s.mock_returns = [[1,{'uid':['testuser1'], \
                                        'mail':['test.user1@mail.com']}]]
        # This will return testuser1 no matter what
        # and show you on screen the operations performed
        self.assertEqual(myclass.ldapsearch('onetwoonetwo'), True)

This should help you inject whatever values you want there and also clarify a bit how to minimock wants you to think (that is the only way I could make it work).

Tuesday, 8 March 2011

DLink DVG-2001S advanced configuration

A loooong time ago I bought this SIP router, the DLink DVG-2001S. After years of using it and being bothered by the infamous call waiting alert I got fed up and tried to get rid of it.

Obviously no freaking way you can do that through the web interface... luckily that didn't stop me from doing telnet to the device and hacking a bit into it.
telnet < ip_device_of_your_device > 23
sip show
This should show more or less what is your configured line. Usually this will be #1.
Line 1 configuration
  phone_number = xxx
  display_name = xxx
  user_agent_port = 5060
  auth_username = xxx
  auth_password = xxx
  sig_tos = 0
  rtp_tos = 0
  oob_dtmf = 1
  allow_callwaiting = 1
  ec = 1
  vad = 0
  display_cid[0]=1
Now that allow_callwaiting = 1 is the problem.
sip set 1 allow_callwaiting 0
Will fix the thing. If you really want to be sure you can also do
sip set cw_at 0
 (This *should* disable the alert tone)

Wednesday, 9 February 2011

Downgrade from squeeze to lenny..

If you were distracted in the last 3 days and forgot that Debian 'stable' became 'squeeze' last Sunday, or just inadvertently issude 'apt-get upgrade' on your lenny machine, wondering why you had more than 200 packages to update, but still pressing Yes Yes Yes... well you have done the thing I did at least  on one of my servers...

But no problem, downgrading is easy in apt.

Just put:

Package: *
Pin: release a=oldstable
Pin-Priority: 1001
in /etc/apt/preferences and do again
apt-get update && apt-get upgrade
I was so lucky to have to force jsut one package
dpkg -i --force-overwrite /var/cache/apt/archives/sysvinit_2.86.ds1-61_i386.deb
 And reinstall one of them because apticron was failing the downgrade

apt-get install mktemp --reinstall && apt-get install apticron
Cheers

Tuesday, 25 January 2011

TomTom Go 750 and adding a simple microSD to it

So I was all happy about my new TomTom that I decided to upgrade the maps to the latest version (for free since it was the first time).

That turned out in an unbelievably long and painful operation.

First attempt. Connect the device to the computer and just push the upgrade button.

"You don't have enough space on the device. Choose what area you want to upgrade"

No, thanks I want the whole Europe Maps.

Go to the shop. Buy a 4G microSD.

Second attempt. Insert the microSD into the device. Connect the device, select the microSD "as the device" and push the upgrade button.

"You don't have enough space on the device. Choose what area you want to upgrade"

For God sake I have 4G free... couldn't you just select that automagically? No, uh?

Ok... let me see how those maps are stored there... ah just a simple directory...

Third attempt.

  • Take out the microSD and use the card reader to connect it to the computer
  • Connect the device.
  • Take a backup of the device.
  • Open the file browser.
  • Move the 'Europe_2G' maps to the microSD
  • Slap the microSD into the navigator
  • Turn on the device
  • Select Europe maps
  • Reconnect the device to the computer
  • Push the button 'upgrade'

HOORAY! The downloads start... 28 minutes...

"ERROR! You don't have enough space on your computer for temporary files"

WHAT!? I had 2.3G free... Ok let me remove something. Now with 7G free I can go.

  • Push the upgrade button again.

"ERROR! Map decoding error... blablabla"

Jesus!

Find the downloaded maps. Remove them.

  • Push the upgrade button again.

And finally after another 45 minutes... I had the maps upgraded.

So if you plan to do the same make sure you have at least 5G free because it looks like TomTom takes a backup before doing the upgrade...

Painful though I would work on improving this... Attila... Michal... you listening? ;)

Tuesday, 6 April 2010

Pasta alla bolognese (finnish recipe a la Stezz)

[This post is sponsored by Misha]

This is the way it's called all over the world even though we call it in Italy "Pasta al ragù" (the ragù is "alla bolognese").

It's mainly made of tomato and minced meat BUT not only of that (and this is basically the difference between the one you find in "JukkaPekka's restaurant" and a proper italian one).

INGREDIENTS for 4 persons
  • 1/2 onion
  • 1 carrot
  • a bit of persil
  • 1 glass of red wine
  • salt
  • extravirgin olive oil
  • 1.6Kg of sleeved tomatoes
  • 0.4 Kg of minced meat (naudanjauheliha)


PREPARATION
Slice carrot, onion and celery in thin slices. Put 1 dl of oil into a casserole just to cover the bottom and put the carrot onion persil and celery in. Start frying at low temperature until the onion gets yellowish.

Then throw the minced meat in and cook until it gets brown. At that point put the red wine and let evaporate.

Now it's time to raise the temperature and to put the tomatoes that you previously slightly pressed.

Add 1-2 dl more of oil if needed and cook for 30/40 minutes (this would pretty much depend on the temperature you are cooking at) stirring regularly. You will understand that it's done when the sauce reduced its quantity to half of the original one. At that point the meat will be 50% of the tomatoes (you started at 25%).

Add salt as you like.

Cook the pasta now and take it out one minute before you usually would and finish cooking it in the sauce.

Add parmigiano in big quantity.

Enjoy.

Spaghetti Bolognese - Michaelangelo, Aspendale...Image by avlxyz via Flickr

To give you an idea this is the desired result. You can see how all the pasta is red and cooked together with the sauce.








Spaghetti Bolognese with Ground BuffaloImage by 1JLS via Flickr

This is how it shouldn't look like, you can see the sauce on top of the pasta (and probably the pasta is like glue now...)









Reblog this post [with Zemanta]

Saturday, 30 January 2010

Italy vs. Finland (a statistical approach)

I've come across an economic measure called Gini index, the index is commonly used as a measure of inequality of income or wealth. A low Gini coefficient indicates a more equal distribution, with 0 corresponding to complete equality, while higher Gini coefficients indicate more unequal distribution, with 1 corresponding to complete inequality.

So I got interested in what the Gini coefficient might be in Finland and, as expected, it's not that high. But the most interesting thing is when it is compared to the italian one and its evolution during last years (unfortunately data is there until 2005 only).

It's incredible to see that after the introduction of the Euro in Italy the inequality has increased of 4 percent points while in Finland only of 2 points (with an absolute difference of 7%).

This basically means that after 2001 the rich are richer and the poor are poorer (and this is not big news). But more in Italy than in Finland.

Another quite interesting figure is the one that photographs the gross domestic product (GDP) per capita in purchasing power. GDP is a measure for the economic activity. It is defined as the value of all goods and services produced less the value of any goods or services used in their creation. The volume index of GDP per capita in Purchasing Power Standards (PPS) is expressed in relation to the European Union (EU-27) average set to equal 100. If the index of a country is higher than 100, this country's level of GDP per head is higher than the EU average and vice versa. Basic figures are expressed in PPS, i.e. a common currency that eliminates the differences in price levels between countries allowing meaningful volume comparisons of GDP between countries.

If we check this graph it's pretty evident (and also stunning) how after the introduction of the common european currency the average 'money to spend' of italians has been dropping like hell while in Finland remained mostly unchanged. With an end result of 15% difference between the two countries.

The whole post was an attempt to proof (mostly to myself) my personal perception that while in Italy people have less money to spend and there are still a lot of people that go around in a Ferrari, in Finland, while there are obviously poor and rich, the average guy can still live decently and the distance between poor and rich is not as unfair as in Italy.

(*) Data source:
Gini index
GDP per capita in PPS


Reblog this post [with Zemanta]