learning-it by example

#171 AI coding and productivity 6.4 min

TDD With an AI Assistant: Red, Green, Refactor (unittest)

A first draft passed all five tests and still charged minus two pounds.

1. What three steps of test-driven development does the video describe?
2. A first-draft discount function passed all 5 spec tests. What did one extra test, a 300 pence item with the FIVEOFF code, show?
3. Does a green run, where every test passes, show that the code is right?
4. How does the video's one-line fix stop the price going below zero?
5. Why does the video say the expected value in a test should come from the rule, not from the code?

Practice only: nothing is saved and no score counts towards anything. Each answer comes with the reason.

  1. Walk through red, green, refactor

    Copy the code folder first. Run these in order: python check.py stub, python check.py draft1, python check.py draft1 --edge, python check.py draft2 --edge, python check.py final --edge. Write down the line that says how many tests passed each time, and say what each stage tells you. They should match 0 of 5, 5 of 5, 5 of 6, 6 of 6 and 6 of 6.

    A hint

    The --edge flag adds the test the first spec forgot.

  2. Test the exact boundary

    Add this test to the EdgeSpec class in spec.py: price 500 with FIVEOFF should be 0. Predict whether draft1 passes it, then run python check.py draft1 --edge. On my machine only the below-zero test failed, so that run said 6 of 7 passed.

    A hint

    Work out 500 minus 500 by hand.

  3. Add a SAVE20 code

    Remove the test you added in the last exercise first. Add a test to EdgeSpec: price 2000 with SAVE20 should be 1600. Run python check.py final --edge and read the error. Then add "SAVE20": 20 to the PERCENT_OFF table in final.py and run again. On my machine the first run showed ValueError: unknown code: SAVE20 and the second said 7 of 7 passed.

    A hint

    The refactor turned the codes into data, so a new code is one line in a table.

  4. Decide a rounding rule

    The video says no test fixes how ten percent of an odd price is rounded. Add a test for 25 pence with SAVE10, with the price you think is right as the expected value, and run python check.py final --edge. On my machine the code gives 23, so a test expecting 22 failed with AssertionError: 23 != 22. Decide whether 23 is what you want, and if not, say which rule you would pick.

    A hint

    In final.py the percentage is taken with // 100, which rounds down.

These tasks are for you to try on your own machine. Nothing is checked or saved.

What this does not show

No AI was run in this video: the first draft is hand-written to look like a typical assistant draft.

Up next in AI coding and productivity

More in AI coding and productivity

All AI coding and productivity videos

Related videos