Elentok's Blog

About me

Mercurial: Automatically run unittests before commit

To force Mercurial to run your unit tests before each commit and not to allow committing unless the unit tests pass you can use the "precommit" hook.

In the repository root, edit the ".hg\hgrc" file and add the following lines:

precommit = path-to-tests-script
            (e.g. "qtodotxt\test\runtests.py")

It is very important that if the unit tests fail the script will return an non-zero exit code, in the QTodoTxt test-runner script (you can the source here I do the following:

  • Initialize an "exit_code" variable to 0
  • I run the standard python unittests:

    tests = unittest.defaultTestLoader.discover('.',
    result = unittest.TextTestRunner(verbosity=2).run(tests)
    if not result.wasSuccessful():
      exit_code = 1
  • Then I run the doctests:
    for doctest_file in os.listdir(testsdir):
      if doctest_file.endswith('.doctest'):
        result = doctest.testfile(
            os.path.join(testsdir, doctest_file))
        if result.failed > 0:
          exit_code = 2
  • And at the end I use the sys.exit method to return the correct exit code:
Next:Restart the Windows File Sharing Service to fix weird problems