Day 2: Testing and code quality#

Note

Do not use AI tools to complete the exercises. The goal is to learn how to write code yourself, not to rely on AI tools.

Learning Goals#

  1. Git: Review code from day 1.

  2. Git: Pull latest changes from the main branch.

  3. Understand the concept of unit testing and write a unit test.

  4. Understand the concept of test-driven development (TDD) and apply TDD to extend a class with new functionality.

  5. Use precommit hooks to maintain code style.

  6. Debug your code using a debugger in the IDE

  7. Refactor your code using the IDE.

Preparation#

  1. Create a new branch of the Gitlab repository with your name.

Coding Goals#

We will extend the line class from day 1 to support 3D coordinates and multiple points. We will also implement a method to calculate the slope of the line in a test-driven way. Finally, we will adapt the existing methods to work with the new functionality.

Test-driven development#

In this exercise, we will build on the solution of the exercise from day 1.

  1. Read through this tutorial on test-driven development: Tutorial

  2. Extend the line class, so that the points used to generate the line also have a z coordinate for the elevation.

  3. Change the line class, so that it does not only use two points as start and end point. Instead, it should get a list of more than two coordinates as input, so that we can define more complex lines.

  4. Implement a method called get_slope that calculates the slope of the line in a test-driven way. Start by writing a test in test_main.py. In the test, you should first define your coordinate inputs for the different line segments. Then, you define the slope of the line that you expect given the input coordinates. Next, you should create your line object. Finally, you should assert that the slope returned by the get_slope method is equal to your expected slope. Execute the tests with the command python -m pytest. The test should fail. Now, implement the method to make the test succeed.

Hint: You might want to write multiple tests for different scenarios. Think of different things that could happen with the slope, e.g.

  • What if there is a vertical jump between two points?

  • What if the slope is zero between two points?

  • What if the slope is negative between two points?

  1. You probably already noticed: Now that we implemented a z coordinate and multi-point lines, our methods to return the length and the coordinates of the line, as well as the method to move the line do not work correctly anymore. Adapt these methods in a test-driven way. Write a test for each method and fix the methods until your tests succeed and you are certain that the methods are working correctly again.

Push your changes#

  1. Push your changes to Gitlab and create a merge request.