A property, not an example
Why it matters An example checks one input you thought of. A property checks a rule that must hold for every input, so you can throw thousands of inputs at it, including the awkward ones you never thought of.
An export tool writes records as CSV lines. join(fields) turns a list of strings into one line; split(line) turns it back. A field that contains a comma, a double quote or a newline is wrapped in double quotes, and any double quote inside it is written twice:
join(["Leeds", "Smith, Ann", 'say "hi"'])
# -> 'Leeds,"Smith, Ann","say ""hi"""'Property: a statement true of every valid input. Common shapes: round trip (decode(encode(x)) == x), ordering (the output of a sort is in order and holds the same items), invariant (a balance never goes negative), agreement (a fast version gives the same answer as a slow, obvious one).
A round trip is the property that fits a codec. Generate random lists of fields from a small, nasty alphabet (letters, spaces, commas, quotes, newlines, empty strings) and check that splitting the joined line gives back the same list. Use random.Random(seed) so a failure repeats.
A property can also miss things. A version that quotes every field still round-trips perfectly. Only a check on the line it writes would catch that.
Write my_test(csv). It receives an object with csv.join(fields) and csv.split(line); raise if they break any rule, return quietly if they are correct. The rules: fields are strings (a list always has at least one field, and fields may be empty or hold spaces); split(join(fields)) == fields for every list; a field containing a comma, a double quote or a newline is wrapped in double quotes with inner quotes doubled; any other field is written exactly as it is. Pass bar: pass the correct version and catch at least 5 of the 6 broken versions.
Spotted a problem in this lesson? Report it · Ask about this lesson
This exercise opens soon
Finish the lesson before it and this one unlocks. The whole course is free, no account needed, and you can read this lesson right now.
This browser is blocking cookies for learn.floati.life, so lessons you finished here cannot open in order. Allow cookies for this site and reload.