Best practices for scientific coding

Test-driven development (TDD)

https://medium.com/indonesia-sehat-mental/test-driven-development-is-it-really-necessary-5a527874b190

What is a unit test?

def sum(a, b):
  return a + b
def test__sum(a, b):
  assert sum(1, 1) == 2

Source

Test

Test coverage

You should aim for 100% test coverage

Every single function must have a unit test.

How to write testable functions

If you try to test your code now, it's going to be hard

  1. Functions are too long
  2. Result is not testable
def run_simulation():
  data = pd.read_csv("file.csv")
  # do some data manipulation...
  simulator = Simulator()...
  # setup simulator ...
  results = simulator.run()
  # do some plotting ...

Common bad function

How to write testable functions

Each function does one thing only

Preferably no side effects

def does_thing_1():
  pass

def does_thing_2():
  pass

def does_thing_3():
  pass


def do_all_things():
  thing_1 = does_thing_1()
  thing_2 = does_thing_2()
  thing_3 = does_thing_3()
  return ...
def test__does_thing_1():
  pass

def test__does_thing_2():
  pass

def test__does_thing_3():
  pass


def test__do_all_things():
  thing_1 = does_thing_1()
  thing_2 = does_thing_2()
  thing_3 = does_thing_3()
  return ...

Source

Test

How to write testable functions

Very important:

TEST NEEDS TO BE WRITTEN FIRST!

This ensures our function can be tested

+

our code is easier to use by design

Test-driven development

https://medium.com/indonesia-sehat-mental/test-driven-development-is-it-really-necessary-5a527874b190

icemobile.com/test-driven-development

How to run tests?

pytest

Package structure

This should only contain source files.

Not scripts, example runs, data, etc.

This should only contain source files.

Not scripts, example runs, data, etc.

Continuous integration

(or how to add new features to the code)

  1. Make a feature branch in GitHub.
  2. Write tests for new feature.
  3. Run tests and ensure they fail.
  4. Write code to pass the tests.
  5. Make a Pull Request (PR).
  6. Ask someone to review the PR.
  7. Merge to main branch.

GitHub tools

  • Code coverage
  • GitHub actions for automatic testing.

Best practices coding

By arnauqb

Best practices coding

  • 335