dsa-ou / algoesup

Algorithmic essays support: examples, templates, guides, library
https://dsa-ou.github.io/algoesup/
BSD 3-Clause "New" or "Revised" License
2 stars 0 forks source link

Testing Methods: self is counted as argument, but user does not supply it in test table #49

Open densnow opened 2 days ago

densnow commented 2 days ago

This issue relates to testing methods that return some object and do not have any side effects (i.e modifying the state of the object) e.g.

sms10000 = SMS('10000words.txt')
test(sms10000.completions, words_tests_10000)

test() gets the number of arguments that the function being tested expects by accessing function.__code__.co_argcount and compares this number with the number of arguments given in the test table. However, for methods, the first argument (the instance of the class, conventionally named self) is not supplied by the user, yet is still used and counted by co_argcount. Therefore, when testing a method with a table that has the correct number of arguments, test() will raise an error, since the arg count will always be one greater than number of args supplied by the user.

Suggested fix:

import inspect

...

expects = function.__code__.co_argcount
if inspect.ismethod(function):
    expects -= 1

...

inspect is part of the standard library so doesn't introduce any dependencies. But some other options could be to write our own is_method() function, or use a parameter with a default value and have user decide if method is being passed.

mwermelinger commented 1 day ago

Thanks for spotting this! Using inspect is fine. Could you please create the branch, apply the fix, test also with normal functions and do a PR? Thanks!