Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A Python function "what" after Ruby gem "what_methods". "what" function checks all the method of an object and returns the method names which match the expected result. Ruby gem what_methods is here: https://github.com/BMorearty/what_methods
# coding: utf-8
"""
A Python function "what" after Ruby gem "what_methods".
"what" function checks all the method of an object
and returns the method names which match the expected result.
Last updated: 2013/12/23
"""
from copy import copy
import unittest
def what(obj, expected, *args):
"""returns method names which match the expected result.
@param obj An object you want to check the methods of.
@param result The expected result of the method execution.
@param args Parameters to pass to the methods.
@return A list of method names whose returned value matches the expectation.
"""
# Get all the callable attributes.
# [(name, body), ...]
methods = [x for x in dir(obj) \
if callable(getattr(obj, x))]
# Get the attributes whose returned value matches the expected one.
methods_matched = []
for method in methods:
obj_copied = copy(obj)
try:
actual = getattr(obj_copied, method)(*args)
if actual == expected:
methods_matched.append(method)
except (AttributeError, LookupError, TypeError, ValueError) as e:
pass
return methods_matched
class TestWhat(unittest.TestCase):
"""TestCases for what function
"""
def test_int(self):
self.assertIn("__add__", what(3, 5, 2))
self.assertIn("__sub__", what(3, 2, 1))
def test_float(self):
self.assertIn("__int__", what(3.14, 3))
def test_string(self):
s1 = "abc"
self.assertIn("__len__", what(s1, 3))
self.assertIn("__getitem__", what(s1, "c", -1))
self.assertIn("__add__", what(s1, "abcd", "d"))
def test_list(self):
self.assertIn("__getitem__", what(["cat", "dog", "elephant"], "elephant", -1))
self.assertIn("pop", what(["cat", "dog"], "dog"))
def test_dict(self):
self.assertIn("__len__", what({"ab": 3, "bb": 5}, 2))
self.assertIn("__getitem__", what({"ab": 3, "bb": 5}, 3, "ab"))
if __name__ == "__main__":
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment