[PYTHON] Run unit tests the moment you save the file

Overview

Until now, when coding with vim, the same operation was done by repeating "** write code, → execute unit test **", but the unit test is executed the moment the file is saved. I made it possible.

Save it if you display it in another pane such as another tmux as shown in the screenshot above. You can see the execution result of the unit test at the moment.

Source code

Gist

qiita.rb


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import datetime
import time
import os
from stat import *
import commands
import fnmatch
 
 
def watch(dir, command, extension):
    timestamp = time.mktime(datetime.datetime.now().utctimetuple())
    while True:
 
        for root, dirnames, filenames in os.walk(dir):
            for filename in fnmatch.filter(filenames, '*' + extension):
                file = os.path.join(root, filename)
                file_timestamp = os.stat(file)[ST_MTIME]
                if timestamp < file_timestamp:
                    timestamp = file_timestamp
                    print "Executing..."
                    print(commands.getoutput(command))
                    break
        #100ms wait
        time.sleep(0.1)
 
def help():
    print(u'The first argument is the directory to be monitored.')
    print(u'The second argument is the command to be executed when there is a change in the monitored file.')
    print(u'The third argument is the extension')
    print(u'Example: % dirwatch . \'phpunit\' \'php\'')
    print(u'In the example, hello is displayed when there is a change in the file in the current directory.')
 
if __name__ == '__main__':
    #Display help when there are not enough arguments.
    if 4 > len(sys.argv):
        help()
    else:
        watch(sys.argv[1], sys.argv[2], sys.argv[3])

Example of installation

% wget https://gist.github.com/matsubo/4992894/raw/36c0c4a08953effabfa2731ccd5186f2d6c92347/dirwatch.py
% chmod 755 dirwatch.py

argument

% ./dirwatch.py [File monitoring destination directory] [Command to execute when the file is changed] [File extension to be monitored]

Execution example

% ./dirwatch.py /path/to/sourcecode/ phpunit php
% ./dirwatch.py /path/to/sourcecode/ "phpunit Tests/UserRegistrationTest.php" php

As shown below, the unit test is executed the moment the file is saved. It is very good to develop with test first, divide the window with screen or tmux and always display it. phpunitの例

Recommended Posts

Run unit tests the moment you save the file
Can you delete the file?
Save the binary file in Python
Run tests automatically when saving file
Get the path to the systemd unit file
Until you install Caffe and run the sample
Until you run the changefinder sample in python
Save the object to a file with pickle
[Python] You can save an object to a file by using the pickle module.
Selectively run tests
Python unit tests
Until you install Gauge and run the official sample