commit 48fcbc69e4ed13a44ff160ba35997a46487f997f
Author: Megan <mchang01(a)wesleyan.edu>
Date: Tue Jun 26 17:05:35 2012 -0400
First code review changes.
---
test/unit/util/proc.py | 86 +++++++++++++++++++++++++----------------------
1 files changed, 46 insertions(+), 40 deletions(-)
diff --git a/test/unit/util/proc.py b/test/unit/util/proc.py
index 2e3dd67..7ea119b 100644
--- a/test/unit/util/proc.py
+++ b/test/unit/util/proc.py
@@ -7,6 +7,7 @@ import time
import unittest
import operator
import functools
+import itertools
import cStringIO
import test.mocking as mocking
@@ -24,25 +25,34 @@ class TargetError(Exception):
def __str__(self):
return repr(self.value)
-def mock_fn(exp_args, return_vals, target=None):
+def mock_fn(arguments_returns, target=None):
"""
Provides a lambda function that may be used to mock another function.
- :param list of tuples exp_args: expected input value(s) to be used for comparison
- :param list return_vals: value(s) to be returned if expected input matches given input
+ :param dict args_rets: expected input value(s) as tuples are the key and return values are the values of the dictionary.
:param function target: target function to be called if mocking doesn't cover this input
:precondition: len(exp_args) = len(return_vals)
- return_vals[i] a=exp_args[i]
- :returns: function _mocker such that: f(*a) = target(*a) a != exp_args[i] and target != None
- raise TargetError a != exp_args[i] and target = None
+ :returns: function _mocker such that...
+ *return_vals[i] a = exp_args[i]
+ *target(*a) a != exp_args[i] and target != None
+ *raise TargetError a != exp_args[i] and target = None
"""
- def _mocked(tgt, exp_args, return_vals, *arg):
+ def _mocked(args_rets, tgt, *arg):
try:
- #
- i = operator.indexOf(exp_args, arg)
+ # First check if given input matches one of the inputs to be mocked.
+ return args_rets[arg]
+ except KeyError:
+ if tgt:
+ return tgt(*arg)
+ else:
+ raise TargetError("A relevant function could not be applied")
+ '''
+ try:
+ # First check if given input matches one of the inputs to be mocked.
+ i = operator.indexOf(args_rets, arg)
except ValueError:
i = -1
if i == -1:
@@ -52,17 +62,19 @@ def mock_fn(exp_args, return_vals, target=None):
raise TargetError("A relevant function could not be applied")
else:
return return_vals[i]
-
- return functools.partial(_mocked, target, exp_args, return_vals)
+ '''
+ return functools.partial(_mocked, arguments_returns, target)
def find_subsets(xs):
"""
Used with the builtin zip function to create all possible combinations
- of two lists. Called in test_get_stats().
+ of the elements of two lists.
+
+ Called in test_get_stats().
:param xs: list of tuples given by calling zip on two lists
- :returns: a list of lists of tuples
+ :returns: a list of lists of tuples containing all possible combinations of arguments. Will be of the form [[(arg1, resp1),(arg2, resp2),...], [(arg1, resp1),(arg3, resp3),...],...]
"""
# Base case is the empty list.
@@ -88,8 +100,7 @@ class TestProc(unittest.TestCase):
Tests the get_system_start_time function.
"""
- mocking.mock(proc._get_line, mock_fn([("/proc/stat", "btime", 'system start time')],
- ["btime 1001001"]))
+ mocking.mock(proc._get_line, mock_fn({('/proc/stat', 'btime', 'system start time'):'btime 1001001'}))
# Single test as get_system_start_time takes no arguments
self.assertEquals(1001001, proc.get_system_start_time())
@@ -99,8 +110,7 @@ class TestProc(unittest.TestCase):
Tests the get_physical_memory function.
"""
- mocking.mock(proc._get_line, mock_fn([("/proc/meminfo",
- "MemTotal:", 'system physical memory')], ["MemTotal: 12345 kB"]))
+ mocking.mock(proc._get_line, mock_fn({('/proc/meminfo', 'MemTotal:', 'system physical memory'):'MemTotal: 12345 kB'}))
self.assertEquals((12345*1024), proc.get_physical_memory())
@@ -109,8 +119,7 @@ class TestProc(unittest.TestCase):
Tests the get_cwd function with a given pid.
"""
- mocking.mock(os.readlink, mock_fn([('/proc/24019/cwd',)],
- ['/home/directory/TEST'], os.listdir), os)
+ mocking.mock(os.readlink, mock_fn({('/proc/24019/cwd',):'/home/directory/TEST'}, os.listdir), os)
# Test edge case of pid = 0 and a standard pid.
self.assertEquals('', proc.get_cwd(0))
@@ -127,8 +136,8 @@ class TestProc(unittest.TestCase):
for pid in pid_list:
pid_id, user_id = pid
status_path = "/proc/%s/status" % pid_id
- mocking.mock(proc._get_line, mock_fn([(status_path, "Uid:", "uid")],
- ["Uid: %s" % user_id]))
+ mocking.mock(proc._get_line, mock_fn({(status_path, 'Uid:', 'uid'):'Uid: %s' % user_id}))
+
self.assertEquals(user_id, proc.get_uid(pid_id))
def test_get_memory_usage(self):
@@ -138,9 +147,7 @@ class TestProc(unittest.TestCase):
This is the only function in proc.py that calls _get_lines explicitly.
"""
- mocking.mock(proc._get_lines, mock_fn([("/proc/1111/status",
- ("VmRSS:", "VmSize:"), 'memory usage')], [{"VmRSS:": "VmRSS: 100 kB",
- "VmSize:":"VmSize: 1800 kB"}]))
+ mocking.mock(proc._get_lines, mock_fn({('/proc/1111/status', ('VmRSS:', 'VmSize:'), 'memory usage'):{'VmRSS:':'VmRSS: 100 kB', 'VmSize:':'VmSize: 1800 kB'}}))
# Test edge case of pid = 0 and a standard pid
self.assertEqual((0,0), proc.get_memory_usage(0))
@@ -165,8 +172,7 @@ class TestProc(unittest.TestCase):
# Tests the case where no stat_types are specified.
- mocking.mock(proc._get_line, mock_fn(
- [(stat_path, str(24062), 'process ')], [stat]))
+ mocking.mock(proc._get_line, mock_fn({(stat_path, str(24062), 'process '):stat}))
self.assertEquals((), proc.get_stats(24062))
# Don't handle empty set of commands here. (just did above)
@@ -177,8 +183,8 @@ class TestProc(unittest.TestCase):
# and (resp1,resp2,...).
arg, response = zip(*sub)
- mocking.mock(proc._get_line, mock_fn(
- [(stat_path, str(24062), 'process %s' % ", ".join(arg))], [stat]))
+ mocking.mock(proc._get_line, mock_fn({(stat_path, str(24062), 'process %s' % ', '.join(arg)):stat}))
+
# Iterates through each combination of commands.
self.assertEquals(response, proc.get_stats(24062, *arg))
@@ -197,9 +203,7 @@ class TestProc(unittest.TestCase):
elif a == 'stime':
response += ('0',)
- mocking.mock(proc._get_line, mock_fn(
- [('/proc/0/stat', str(0), 'process %s' % ", ".join(arg))], [stat]))
-
+ mocking.mock(proc._get_line, mock_fn({('/proc/0/stat', str(0), 'process %s' % ', '.join(arg)):stat}))
self.assertEquals(response, proc.get_stats(0, *arg))
def test_get_connections(self):
@@ -209,23 +213,25 @@ class TestProc(unittest.TestCase):
pid = 1111
fd_list = ['1', '2', '3', '4']
- fd_paths = []
+ '''
for fd in fd_list:
fd_paths.append(('/proc/%s/fd/%s' % (str(pid), fd),))
+ '''
readlink_results = ['socket:[99999999]', 'socket:[IIIIIIII]', 'pipe:[30303]', 'pipe:[40404]']
+ input_vals = {}
+ for i in range(len(fd_list)):
+ input_vals[('/proc/%s/fd/%s' % (str(pid), fd_list[i]),)] = readlink_results[i]
# Will be put in cStringIO wrappers and treated as files.
tcp = '\n 0: 11111111:1111 22222222:2222 01 44444444:44444444 55:55555555 66666666 1111 8 99999999'
udp = '\n A: BBBBBBBB:BBBB CCCCCCCC:CCCC DD EEEEEEEE:EEEEEEEE FF:FFFFFFFF GGGGGGGG 1111 H IIIIIIII'
- file_list = [cStringIO.StringIO(tcp), cStringIO.StringIO(udp)]
- contents_list = [tcp, udp]
-
- # Mock os.listdir, os.readlink, and open.
- mocking.mock(os.listdir, mock_fn([('/proc/%s/fd' % str(pid),)], [fd_list], os.listdir), os)
- mocking.mock(os.readlink, mock_fn(fd_paths, readlink_results, os.readlink), os)
+ file_vals = {('/proc/net/tcp',):cStringIO.StringIO(tcp), ('/proc/net/udp',):cStringIO.StringIO(udp)}
- mocking.mock(open, mock_fn([('/proc/net/tcp',), ('/proc/net/udp',)], file_list, open))
+ # Mock os.listdir, os.readlink, and open with mock_fn.
+ mocking.mock(os.listdir, mock_fn({('/proc/%s/fd' % str(pid),):fd_list}, os.listdir), os)
+ mocking.mock(os.readlink, mock_fn(input_vals, os.readlink), os)
+ mocking.mock(open, mock_fn(file_vals, open))
# Tests the edge case of pid = 0.
self.assertEquals([], proc.get_connections(0))
@@ -240,5 +246,5 @@ class TestProc(unittest.TestCase):
local_ip, local_port = proc._decode_proc_address_encoding(l_addr)
foreign_ip, foreign_port = proc._decode_proc_address_encoding(f_addr)
results.append((local_ip, local_port, foreign_ip, foreign_port))
-
+ print "results: %s" % results
self.assertEquals(results, proc.get_connections(1111))