Commit 04d079fcff9e3a86845af2b5ba4526bdfef5c834
1 parent
2d647a18
tests: Add helper for looping over samples
Showing
1 changed file
with
24 additions
and
1 deletions
tests/test_utils/testdata_reader.py
| @@ -7,7 +7,7 @@ using them. | @@ -7,7 +7,7 @@ using them. | ||
| 7 | """ | 7 | """ |
| 8 | 8 | ||
| 9 | import os, sys, zipfile | 9 | import os, sys, zipfile |
| 10 | -from os.path import dirname, abspath, normpath, join | 10 | +from os.path import dirname, abspath, normpath, relpath, join, basename |
| 11 | from . import DATA_BASE_DIR | 11 | from . import DATA_BASE_DIR |
| 12 | 12 | ||
| 13 | # Passwort used to encrypt problematic test samples inside a zip container | 13 | # Passwort used to encrypt problematic test samples inside a zip container |
| @@ -59,3 +59,26 @@ def read_encrypted(relative_path, filename=None): | @@ -59,3 +59,26 @@ def read_encrypted(relative_path, filename=None): | ||
| 59 | def get_path_from_root(relative_path): | 59 | def get_path_from_root(relative_path): |
| 60 | """Convert path relative to test data base dir to an absolute path.""" | 60 | """Convert path relative to test data base dir to an absolute path.""" |
| 61 | return join(DATA_BASE_DIR, relative_path) | 61 | return join(DATA_BASE_DIR, relative_path) |
| 62 | + | ||
| 63 | + | ||
| 64 | +def loop_over_files(subdir=''): | ||
| 65 | + """ | ||
| 66 | + Find all files, decrypting problematic files on the fly. | ||
| 67 | + | ||
| 68 | + Does a `os.walk` through all test data or the given subdir and yields a | ||
| 69 | + 2-tuple for each sample: the path to the file relative to `DATA_BASE_DIR` | ||
| 70 | + and the contents of the file, with the file being unzipped first if it ends | ||
| 71 | + with .zip. | ||
| 72 | + | ||
| 73 | + :arg str subdir: Optional subdir of test data dir that caller is interested | ||
| 74 | + in | ||
| 75 | + """ | ||
| 76 | + # create temp dir to extract files into | ||
| 77 | + | ||
| 78 | + for base_dir, _, files in os.walk(join(DATA_BASE_DIR, subdir)): | ||
| 79 | + for filename in files: | ||
| 80 | + relative_path = relpath(join(base_dir, filename), DATA_BASE_DIR) | ||
| 81 | + if filename.endswith('.zip'): | ||
| 82 | + yield relative_path, read_encrypted(relative_path) | ||
| 83 | + else: | ||
| 84 | + yield relative_path, read(relative_path) |