| 1 | from hypothesis import given, strategies as st |
| 2 | |
| 3 | from io import BytesIO, TextIOWrapper |
| 4 | import os |
| 5 | |
| 6 | def translate_newlines(text): |
| 7 | text = text.replace('\r\n', '\n') |
| 8 | text = text.replace('\r', '\n') |
| 9 | return text.replace('\n', os.linesep) |
| 10 | |
| 11 | @st.composite |
| 12 | def st_readline_universal( |
| 13 | draw, st_nlines=st.integers(min_value=0, max_value=10)): |
| 14 | n_lines = draw(st_nlines) |
| 15 | lines = draw(st.lists( |
| 16 | st.text(st.characters(blacklist_characters='\r\n')), |
| 17 | min_size=n_lines, max_size=n_lines)) |
| 18 | limits = [] |
| 19 | for line in lines: |
| 20 | limit = draw(st.integers(min_value=0, max_value=len(line) + 5)) |
| 21 | limits.append(limit) |
| 22 | limits.append(-1) |
| 23 | endings = draw(st.lists( |
| 24 | st.sampled_from(['\n', '\r', '\r\n']), |
| 25 | min_size=n_lines, max_size=n_lines)) |
| 26 | return ( |
| 27 | ''.join(line + ending for line, ending in zip(lines, endings)), |
| 28 | limits) |
| 29 | |
| 30 | @given(data=st_readline_universal(), |
| 31 | mode=st.sampled_from(['\r', '\n', '\r\n', '', None])) |
| 32 | def test_readline(data, mode): |
| 33 | txt, limits = data |
| 34 | textio = TextIOWrapper( |
| 35 | BytesIO(txt.encode('utf-8', 'surrogatepass')), |
| 36 | encoding='utf-8', errors='surrogatepass', newline=mode) |
| 37 | lines = [] |
| 38 | for limit in limits: |
| 39 | line = textio.readline(limit) |
| 40 | if limit >= 0: |
| 41 | assert len(line) <= limit |
| 42 | if line: |
| 43 | lines.append(line) |
| 44 | elif limit: |
| 45 | break |
| 46 | if mode is None: |
| 47 | txt = translate_newlines(txt) |
| 48 | assert txt.startswith(u''.join(lines)) |