Commit a1d7a046 authored by Nicolas Wavrant's avatar Nicolas Wavrant

test_free_port: monkey patching an object shouldn't impact other class/test/module/...

parent a2b2ef7e
...@@ -214,5 +214,8 @@ setup(name=name, ...@@ -214,5 +214,8 @@ setup(name=name,
], ],
}, },
test_suite='slapos.test', test_suite='slapos.test',
tests_require=[ 'jsonschema' ], tests_require=[
'jsonschema',
'mock',
],
) )
import socket import socket
import sys
import unittest import unittest
from mock import patch
from slapos.recipe import free_port from slapos.recipe import free_port
class SocketMock(): class SocketMock():
...@@ -14,11 +17,14 @@ class SocketMock(): ...@@ -14,11 +17,14 @@ class SocketMock():
bind = close = nothing_happen bind = close = nothing_happen
import sys def useMock(function):
sys.modules['socket'].socket = SocketMock def withMock(function):
with patch('slapos.recipe.free_port.socket.socket', new=SocketMock):
return function
return withMock
class FreePortTest(unittest.TestCase): class FreePortTest(unittest.TestCase):
def afterSetup(self): def setUp(self):
SocketMock.bind = SocketMock.close = SocketMock.nothing_happen SocketMock.bind = SocketMock.close = SocketMock.nothing_happen
def new_recipe(self, **kw): def new_recipe(self, **kw):
...@@ -48,10 +54,12 @@ class FreePortTest(unittest.TestCase): ...@@ -48,10 +54,12 @@ class FreePortTest(unittest.TestCase):
options.update(kw) options.update(kw)
return free_port.Recipe(buildout=buildout, name='free_port', options=options) return free_port.Recipe(buildout=buildout, name='free_port', options=options)
@useMock
def test_ifNoBusyPortThenMinPortIsAlwaysReturned(self): def test_ifNoBusyPortThenMinPortIsAlwaysReturned(self):
recipe = self.new_recipe(minimum=2000) recipe = self.new_recipe(minimum=2000)
self.assertEqual(recipe.options['port'], '2000') self.assertEqual(recipe.options['port'], '2000')
@useMock
def test_iterateUntilFreePortIsFound(self): def test_iterateUntilFreePortIsFound(self):
def bindFailExceptOnPort2020(socket_instance, binding): def bindFailExceptOnPort2020(socket_instance, binding):
ip, port = binding ip, port = binding
...@@ -61,6 +69,7 @@ class FreePortTest(unittest.TestCase): ...@@ -61,6 +69,7 @@ class FreePortTest(unittest.TestCase):
recipe = self.new_recipe(minimum=2000) recipe = self.new_recipe(minimum=2000)
self.assertEqual(recipe.options['port'], '2020') self.assertEqual(recipe.options['port'], '2020')
@useMock
def test_returnsPort0IfNoPortIsFreeInRange(self): def test_returnsPort0IfNoPortIsFreeInRange(self):
def bindAlwaysFail(socket_instance, binding): def bindAlwaysFail(socket_instance, binding):
raise socket.error() raise socket.error()
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment