How to automatically run tests when there's any change in my project (Django)?

后端 未结 14 1904
有刺的猬
有刺的猬 2020-12-23 19:45

At the moment I am running python manage.py test every once in a while after I make significant changes in my django project. Is it possible to run those tests

14条回答
  •  死守一世寂寞
    2020-12-23 20:20

    I wrote a Gulp task to automatically run ./manage.py test whenever any specified Python files are changed or removed. You'll need Node for this.

    First, install Gulp:

    yarn add -D gulp@next
    

    Then use the following gulpfile.js and make any necessary adjustments:

    const { exec } = require('child_process');
    const gulp = require('gulp');
    
    const runDjangoTests = (done) => {
      const task = exec('./manage.py test --keepdb', {
        shell: '/bin/bash', // Accept SIGTERM signal. Doesn't work with /bin/sh
      });
    
      task.stdout.pipe(process.stdout);
      task.stderr.pipe(process.stderr);
    
      task.on('exit', () => {
        done();
      });
    
      return task;
    };
    
    gulp.task('test', runDjangoTests);
    
    gulp.task('watch', (done) => {
      let activeTask;
      const watcher = gulp.watch('**/*.py', {
        // Ignore whatever directories you need to
        ignored: ['.venv/*', 'node_modules'],
      });
    
      const runTask = (message) => {
        if (activeTask) {
          activeTask.kill();
          console.log('\n');
        }
    
        console.log(message);
        activeTask = runDjangoTests(done);
      };
    
      watcher.on('change', (path) => {
        runTask(`File ${path} was changed. Running tests:`);
      });
    
      watcher.on('unlink', (path) => {
        runTask(`File ${path} was removed. Running tests:`);
      });
    });
    

    Then simply run node node_modules/gulp/bin/gulp.js watch to run the task :)

提交回复
热议问题