Skip to content

Instantly share code, notes, and snippets.

@hughdbrown
Created June 20, 2019 17:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hughdbrown/ffc507825618fee3528c5206a8927274 to your computer and use it in GitHub Desktop.
Save hughdbrown/ffc507825618fee3528c5206a8927274 to your computer and use it in GitHub Desktop.
Script to resolve where a pytest fixture lives. I wish I were joking.
#!/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