Skip to content

Instantly share code, notes, and snippets.

@harmo
Last active May 26, 2017 09:35
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 harmo/c664957efd9a31acebf623ad727b5e40 to your computer and use it in GitHub Desktop.
Save harmo/c664957efd9a31acebf623ad727b5e40 to your computer and use it in GitHub Desktop.
import subprocess
import time
import os
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class WatchMeDo(FileSystemEventHandler):
"""
Launch pytest command, based on current updated file.
This script assume that a directory 'tests' exists,
on root at the module directory.
Also, tests files must have the same name and directories as
tested files.
"""
def process(self, event):
if not event.is_directory:
if '.py' in event._src_path:
try:
real_path = self.get_real_path(event._src_path)
except Exception as e:
print(e)
return
subprocess.run(['pytest', real_path])
def on_modified(self, event):
self.process(event)
def on_created(self, event):
self.process(event)
def get_real_path(self, src_path):
real_path = os.path.realpath(src_path)
base_file = os.path.basename(real_path)
if not base_file.startswith('test_'):
path = os.path.abspath(os.path.dirname(src_path))
dirs = path.strip(os.environ.get('PROJECT_PATH')).split('/')
root = dirs.pop(0)
new_path = os.path.join(
root, 'tests', '/'.join(dirs), 'test_%s' % base_file
)
new_path = os.path.join(path, 'test_%s' % base_file)
if os.path.isfile(new_path):
return new_path
else:
raise FileNotFoundError('File not found %s' % new_path)
return real_path
if __name__ == "__main__":
event_handler = WatchMeDo()
observer = Observer()
observer.schedule(event_handler, path='.', recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment