Best practices for scientific coding
Test-driven development (TDD)
![](https://s3.amazonaws.com/media-p.slid.es/uploads/900381/images/10004375/pasted-from-clipboard.png)
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
- Functions are too long
- 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
![](https://s3.amazonaws.com/media-p.slid.es/uploads/900381/images/10004375/pasted-from-clipboard.png)
Test-driven development
https://medium.com/indonesia-sehat-mental/test-driven-development-is-it-really-necessary-5a527874b190
![](https://s3.amazonaws.com/media-p.slid.es/uploads/900381/images/10004385/pasted-from-clipboard.png)
icemobile.com/test-driven-development
How to run tests?
pytest
![](https://s3.amazonaws.com/media-p.slid.es/uploads/900381/images/10004449/pasted-from-clipboard.png)
Package structure
![](https://s3.amazonaws.com/media-p.slid.es/uploads/900381/images/10001275/pasted-from-clipboard.png)
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)
- Make a feature branch in GitHub.
- Write tests for new feature.
- Run tests and ensure they fail.
- Write code to pass the tests.
- Make a Pull Request (PR).
- Ask someone to review the PR.
- Merge to main branch.
GitHub tools
- Code coverage
- GitHub actions for automatic testing.
![](https://s3.amazonaws.com/media-p.slid.es/uploads/900381/images/10005042/pasted-from-clipboard.png)
![](https://s3.amazonaws.com/media-p.slid.es/uploads/900381/images/10005044/pasted-from-clipboard.png)
![](https://s3.amazonaws.com/media-p.slid.es/uploads/900381/images/10005046/pasted-from-clipboard.png)
Best practices coding
By arnauqb
Best practices coding
- 335