Created
August 29, 2016 15:40
-
-
Save Swind/cebeba7e32e2f27686ffcae63157dd07 to your computer and use it in GitHub Desktop.
pytest utils
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import inspect | |
import os | |
# http://stackoverflow.com/questions/3589311/get-defining-class-of-unbound-method-object-in-python-3/25959545#25959545 | |
def get_class_that_defined_method(meth): | |
if inspect.ismethod(meth): | |
for cls in inspect.getmro(meth.__self__.__class__): | |
if cls.__dict__.get(meth.__name__) is meth: | |
return cls | |
meth = meth.__func__ # fallback to __qualname__ parsing | |
if inspect.isfunction(meth): | |
cls = getattr(inspect.getmodule(meth), | |
meth.__qualname__.split('.<locals>', 1)[0].rsplit('.', 1)[0]) | |
if isinstance(cls, type): | |
return cls | |
return None # not required since None would have been implicitly returned anyway | |
def convert_to_pytest_str(item): | |
file_path = inspect.getfile(item) | |
if inspect.isfunction(item): | |
parent = get_class_that_defined_method(item) | |
return "{file_path}::{class_name}::{function_name}".format( | |
file_path=file_path, | |
class_name=parent.__name__, | |
function_name=item.__name__) | |
elif inspect.isclass(item): | |
return "{file_path}::{class_name}".format( | |
file_path=file_path, | |
class_name=item.__name__) | |
elif inspect.ismodule(item): | |
if os.path.basename(file_path) == "__init__.py": | |
return os.path.dirname(file_path) | |
else: | |
return file_path | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment