Created
June 20, 2019 17:04
-
-
Save hughdbrown/af4c973bb276fd5d5211de1183c59f85 to your computer and use it in GitHub Desktop.
Script to resolve where a pytest fixture lives. I wish I were joking.
This file contains hidden or 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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
"""Resolve where some test fixture lives | |
Provides CLI: | |
* start -- location in tree of directories to start | |
* resolve -- resource to resolve | |
""" | |
from glob import glob | |
import os | |
import os.path | |
import re | |
import sys | |
import click | |
start_option = click.option( | |
'--start', | |
type=str, | |
help='directory to start search in', | |
) | |
resolve_option = click.option( | |
'--resolve', | |
type=str, | |
help='Name of resource to resolve', | |
) | |
def parent(path): | |
i = path.rindex('/') | |
return path[:i] | |
def resolver2(path, resolve, pwd, import_flag=True): | |
if not os.path.exists(path): | |
print("*** No {}".format(path)) | |
return False | |
# print("Trying {}".format(path)) | |
with open(path) as handle: | |
data = [line.rstrip() for line in handle] | |
regex = re.compile(r"""^\s*def {}\(""".format(resolve)) | |
for i, line in enumerate(data, start=1): | |
m = regex.match(line) | |
if m: | |
j = len(pwd) | |
print("# {} matched in {} at line {}".format(resolve, path, i)) | |
if import_flag: | |
print("from {} import {}".format( | |
path[j + 1:].replace('.py', '').replace('/', '.'), | |
resolve | |
)) | |
return True | |
return False | |
def resolver(path, resolve, pwd): | |
conftest = "conftest.py" | |
local_conf = os.path.join(path, conftest) | |
if resolver2(local_conf, resolve, pwd, import_flag=False): | |
return True | |
else: | |
for filename in glob(os.path.join(path, "*.py")): | |
if not filename.endswith(conftest): | |
if resolver2(filename, resolve, pwd): | |
return True | |
return False | |
@click.command() | |
@start_option | |
@resolve_option | |
def main(start, resolve): | |
pwd = os.path.realpath(os.path.expanduser(os.curdir)) | |
resolve_path = os.path.realpath(os.path.expanduser(start)) | |
if pwd in resolve_path: | |
path = resolve_path | |
while path != pwd: | |
if resolver(path, resolve, pwd): | |
break | |
path = parent(path) | |
else: | |
print(pwd) | |
print(resolve_path) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment