1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
|
import pytest
import shutil
import sys
from io import StringIO
from augur.errors import AugurError
from augur.io.metadata import InvalidDelimiter, read_table_to_dict, read_metadata_with_sequences, write_records_to_tsv, Metadata
from augur.types import DataErrorMethod
@pytest.fixture
def expected_record():
return {
'strain': 'SEQ_A',
'date': '2020-10-03',
'country': 'USA'
}
@pytest.fixture
def metadata_with_duplicate(tmpdir):
path = str(tmpdir / 'metadata.tsv')
with open(path, 'w') as fh:
fh.write('strain\tdate\tcountry\n')
fh.write('SEQ_A\t2020-10-03\tUSA\n')
fh.write('SEQ_A\t2020-10-03\tUSA\n')
fh.write('SEQ_B\t2020-10-03\tUSA\n')
fh.write('SEQ_B\t2020-10-03\tUSA\n')
return path
@pytest.fixture
def mp_context(monkeypatch):
with monkeypatch.context() as mp:
yield mp
class TestReadMetadataToDict:
def test_read_table_to_dict_with_csv(self, tmpdir, expected_record):
path = str(tmpdir / 'metadata.csv')
with open(path, 'w') as fh:
fh.write('strain,date,country\n')
fh.write('SEQ_A,2020-10-03,USA\n')
record = next(read_table_to_dict(path, (',')))
assert record == expected_record
def test_read_table_to_dict_with_csv_from_stdin(self, mp_context, expected_record):
stdin = StringIO('strain,date,country\nSEQ_A,2020-10-03,USA\n')
mp_context.setattr('sys.stdin', stdin)
record = next(read_table_to_dict(sys.stdin, (',')))
assert record == expected_record
def test_read_table_to_dict_with_tsv(self, tmpdir, expected_record):
path = str(tmpdir / 'metadata.tsv')
with open(path, 'w') as fh:
fh.write('strain\tdate\tcountry\n')
fh.write('SEQ_A\t2020-10-03\tUSA\n')
record = next(read_table_to_dict(path, ('\t')))
assert record == expected_record
def test_read_table_to_dict_with_tsv_from_stdin(self, mp_context, expected_record):
stdin = StringIO('strain\tdate\tcountry\nSEQ_A\t2020-10-03\tUSA\n')
mp_context.setattr('sys.stdin', stdin)
record = next(read_table_to_dict(sys.stdin, ('\t')))
assert record == expected_record
def test_read_table_to_dict_with_bad_delimiter(self, tmpdir):
path = str(tmpdir / 'metadata.txt')
with open(path, 'w') as fh:
fh.write('strain date country\n')
fh.write('SEQ_A 2020-10-03 USA\n')
with pytest.raises(InvalidDelimiter):
next(read_table_to_dict(path, (',', '\t')))
@pytest.mark.parametrize('id_column', ['strain', None])
def test_read_table_to_dict_with_duplicates(self, metadata_with_duplicate, id_column):
with pytest.raises(AugurError) as e_info:
list(read_table_to_dict(metadata_with_duplicate, ('\t'), id_column=id_column))
assert str(e_info.value) == f"Encountered record with duplicate id 'SEQ_A' in {metadata_with_duplicate!r}"
@pytest.mark.parametrize('id_column', ['strain', None])
def test_read_table_to_dict_with_duplicates_error_all(self, metadata_with_duplicate, id_column):
with pytest.raises(AugurError) as e_info:
list(read_table_to_dict(metadata_with_duplicate, ('\t'), DataErrorMethod("error_all"), id_column=id_column))
assert str(e_info.value) == f"The following records are duplicated in {metadata_with_duplicate!r}:\n'SEQ_A'\n'SEQ_B'"
@pytest.mark.parametrize('id_column', ['strain', None])
def test_read_table_to_dict_with_duplicates_warning(self, capsys, metadata_with_duplicate, id_column):
list(read_table_to_dict(metadata_with_duplicate, ('\t'), DataErrorMethod('warn'), id_column=id_column))
captured = capsys.readouterr()
assert captured.err == (
f"WARNING: Encountered record with duplicate id 'SEQ_A' in {metadata_with_duplicate!r}\n"
f"WARNING: Encountered record with duplicate id 'SEQ_B' in {metadata_with_duplicate!r}\n"
f"WARNING: The following records are duplicated in {metadata_with_duplicate!r}:\n'SEQ_A'\n'SEQ_B'\n"
)
def test_read_table_to_dict_with_duplicates_silent(self, capsys, metadata_with_duplicate):
list(read_table_to_dict(metadata_with_duplicate, ('\t'), DataErrorMethod('silent')))
assert "WARNING" not in capsys.readouterr().err
def test_read_table_to_dict_with_duplicate_and_bad_id(self, metadata_with_duplicate):
id_column = "bad_id"
with pytest.raises(AugurError) as e_info:
list(read_table_to_dict(metadata_with_duplicate, ('\t'), id_column=id_column))
assert str(e_info.value) == f"The provided id column {id_column!r} does not exist in {metadata_with_duplicate!r}."
@pytest.fixture
def fasta_file(tmpdir):
path = str(tmpdir / 'sequences.fasta')
with open(path, 'w') as fh:
fh.writelines([
'>SEQ_A\nAAAA\n',
'>SEQ_T\nTTTT\n',
'>SEQ_C\nCCCC\n',
'>SEQ_G\nGGGG\n'
])
return path
@pytest.fixture
def metadata_file(tmpdir):
path = str(tmpdir / 'metadata.tsv')
with open(path, 'w') as fh:
fh.writelines([
'strain\tcountry\tdate\n',
'SEQ_A\tUSA\t2020-10-01\n',
'SEQ_T\tUSA\t2020-10-02\n',
'SEQ_C\tUSA\t2020-10-03\n',
'SEQ_G\tUSA\t2020-10-04\n'
])
return path
def unmatched_sequences():
return [
'>EXTRA_SEQ_A\nAAAAA\n',
'>EXTRA_SEQ_T\nTTTTT\n'
]
def unmatched_metadata():
return [
'EXTRA_METADATA_A\tUSA\t2020-10-01\n',
'EXTRA_METADATA_T\tUSA\t2020-10-02\n',
]
def dup_sequences():
return [
'>SEQ_A\nNNNN\n',
'>SEQ_T\nNNNN\n',
]
def dup_metadata():
return [
'SEQ_C\tUSA\t2020-10-XX\n',
'SEQ_G\tUSA\t2020-10-XX\n',
]
def copy_and_append_to_file(src, dst, appended_content):
shutil.copy(src, dst)
with open(dst, 'a') as fh:
fh.writelines(appended_content)
return dst
@pytest.fixture
def fasta_with_unmatched(tmpdir, fasta_file):
path = str(tmpdir / 'extra-sequences.fasta')
return copy_and_append_to_file(fasta_file, path, unmatched_sequences())
@pytest.fixture
def metadata_with_unmatched(tmpdir, metadata_file):
path = str(tmpdir / 'extra-metadata.tsv')
return copy_and_append_to_file(metadata_file, path, unmatched_metadata())
@pytest.fixture
def fasta_with_dup(tmpdir, fasta_file):
path = str(tmpdir / 'dup-sequences.fasta')
return copy_and_append_to_file(fasta_file, path, dup_sequences())
@pytest.fixture
def metadata_with_dup(tmpdir, metadata_file):
path = str(tmpdir / 'dup-metadata.tsv')
return copy_and_append_to_file(metadata_file, path, dup_metadata())
@pytest.fixture
def fasta_with_unmatched_and_dup(tmpdir, fasta_file):
path = str(tmpdir / 'extra-and-dup-sequences.fasta')
return copy_and_append_to_file(fasta_file, path, unmatched_sequences() + dup_sequences())
@pytest.fixture
def metadata_with_unmatched_and_dup(tmpdir, metadata_file):
path = str(tmpdir / 'extra-and-dup-metadata.tsv')
return copy_and_append_to_file(metadata_file, path, dup_metadata() + unmatched_metadata()) #TODO: CHANGE ORDER HERE
class TestReadMetadataWithSequence:
def test_read_metadata_with_sequence(self, metadata_file, fasta_file):
records = list(read_metadata_with_sequences(metadata_file, ('\t',), fasta_file, 'strain'))
assert len(records) == 4
for record in records:
seq_base = record['strain'].split("_")[-1].upper()
expected_sequence = seq_base * 4
assert record['sequence'] == expected_sequence
def test_read_metadata_with_sequences_with_bad_id(self, metadata_file, fasta_file):
id_field = "bad_id"
with pytest.raises(AugurError) as e_info:
next(read_metadata_with_sequences(metadata_file, ('\t',), fasta_file, id_field))
assert str(e_info.value) == f"The provided sequence id column {id_field!r} does not exist in the metadata."
def test_read_metadata_with_sequences_with_unmatched(self, metadata_with_unmatched, fasta_with_unmatched):
with pytest.raises(AugurError) as e_info:
list(read_metadata_with_sequences(metadata_with_unmatched, ('\t',), fasta_with_unmatched, 'strain'))
assert str(e_info.value) == "Encountered metadata record 'EXTRA_METADATA_A' without a matching sequence."
def test_read_metadata_with_sequences_with_unmatched_error_all(self, metadata_with_unmatched, fasta_with_unmatched):
with pytest.raises(AugurError) as e_info:
list(read_metadata_with_sequences(
metadata_with_unmatched,
('\t',),
fasta_with_unmatched,
'strain',
unmatched_reporting=DataErrorMethod.ERROR_ALL))
assert str(e_info.value) == (
"Encountered the following error(s) when parsing metadata with sequences:\n"
"The output may be incomplete because there were unmatched records.\n"
"The following metadata records did not have a matching sequence:\n"
"'EXTRA_METADATA_A'\n'EXTRA_METADATA_T'\n"
"The following sequence records did not have a matching metadata record:\n"
"'EXTRA_SEQ_A'\n'EXTRA_SEQ_T'"
)
def test_read_metadata_with_sequences_with_unmatched_warning(self, capsys, metadata_with_unmatched, fasta_with_unmatched):
records = list(read_metadata_with_sequences(
metadata_with_unmatched,
('\t',),
fasta_with_unmatched,
'strain',
unmatched_reporting=DataErrorMethod.WARN))
assert len(records) == 4
assert [record['strain'] for record in records] == ['SEQ_A', 'SEQ_T', 'SEQ_C', 'SEQ_G']
captured = capsys.readouterr()
assert captured.err == (
"WARNING: Encountered metadata record 'EXTRA_METADATA_A' without a matching sequence.\n"
"WARNING: Encountered metadata record 'EXTRA_METADATA_T' without a matching sequence.\n"
"WARNING: The output may be incomplete because there were unmatched records.\n"
"The following metadata records did not have a matching sequence:\n"
"'EXTRA_METADATA_A'\n'EXTRA_METADATA_T'\n"
"The following sequence records did not have a matching metadata record:\n"
"'EXTRA_SEQ_A'\n'EXTRA_SEQ_T'\n"
)
def test_read_metadata_with_sequences_with_unmatched_silent(self, capsys, metadata_with_unmatched, fasta_with_unmatched):
records = list(read_metadata_with_sequences(
metadata_with_unmatched,
('\t',),
fasta_with_unmatched,
'strain',
unmatched_reporting=DataErrorMethod.SILENT))
assert len(records) == 4
assert [record['strain'] for record in records] == ['SEQ_A', 'SEQ_T', 'SEQ_C', 'SEQ_G']
assert "WARNING" not in capsys.readouterr().err
def test_read_metadata_with_sequences_with_dup_metadata(self, metadata_with_dup, fasta_file):
with pytest.raises(AugurError) as e_info:
list(read_metadata_with_sequences(metadata_with_dup, ('\t',), fasta_file, 'strain'))
assert str(e_info.value) == "Encountered metadata record with duplicate id 'SEQ_C'."
def test_read_metadata_with_sequences_with_dup_fasta(self, metadata_file, fasta_with_dup):
with pytest.raises(AugurError) as e_info:
list(read_metadata_with_sequences(metadata_file, ('\t',), fasta_with_dup, 'strain'))
assert str(e_info.value) == "Encountered sequence record with duplicate id 'SEQ_A'."
def test_read_metadata_with_sequences_with_dup_both(self, metadata_with_dup, fasta_with_dup):
with pytest.raises(AugurError) as e_info:
list(read_metadata_with_sequences(metadata_with_dup, ('\t',), fasta_with_dup, 'strain'))
# Expected to error on first duplicate sequence since we check sequences first
assert str(e_info.value) == "Encountered sequence record with duplicate id 'SEQ_A'."
def test_read_metadata_with_sequences_with_dup_error_all(self, metadata_with_dup, fasta_with_dup):
with pytest.raises(AugurError) as e_info:
list(read_metadata_with_sequences(
metadata_with_dup,
('\t',),
fasta_with_dup,
'strain',
duplicate_reporting=DataErrorMethod.ERROR_ALL
))
assert str(e_info.value) == (
"Encountered the following error(s) when parsing metadata with sequences:\n"
"The output may not match expectations because there were records with duplicate sequence ids.\n"
f"The following sequence ids were duplicated in {metadata_with_dup!r}:\n"
"'SEQ_C'\n'SEQ_G'\n"
f"The following sequence ids were duplicated in {fasta_with_dup!r}:\n"
"'SEQ_A'\n'SEQ_T'"
)
def test_read_metadata_with_sequences_with_dup_warn(self, capsys, metadata_with_dup, fasta_with_dup):
records = list(read_metadata_with_sequences(
metadata_with_dup,
('\t',),
fasta_with_dup,
'strain',
duplicate_reporting=DataErrorMethod.WARN
))
assert len(records) == 6
assert [record['strain'] for record in records] == ['SEQ_A', 'SEQ_T', 'SEQ_C', 'SEQ_G', 'SEQ_C', 'SEQ_G']
captured = capsys.readouterr()
assert captured.err == (
"WARNING: Encountered sequence record with duplicate id 'SEQ_A'.\n"
"WARNING: Encountered sequence record with duplicate id 'SEQ_T'.\n"
"WARNING: Encountered metadata record with duplicate id 'SEQ_C'.\n"
"WARNING: Encountered metadata record with duplicate id 'SEQ_G'.\n"
"WARNING: The output may not match expectations because there were records with duplicate sequence ids.\n"
f"The following sequence ids were duplicated in {metadata_with_dup!r}:\n"
"'SEQ_C'\n'SEQ_G'\n"
f"The following sequence ids were duplicated in {fasta_with_dup!r}:\n"
"'SEQ_A'\n'SEQ_T'\n"
)
def test_read_metadata_with_sequences_with_dup_silent(self, capsys, metadata_with_dup, fasta_with_dup):
records = list(read_metadata_with_sequences(
metadata_with_dup,
('\t',),
fasta_with_dup,
'strain',
duplicate_reporting=DataErrorMethod.SILENT
))
assert len(records) == 6
assert [record['strain'] for record in records] == ['SEQ_A', 'SEQ_T', 'SEQ_C', 'SEQ_G', 'SEQ_C', 'SEQ_G']
assert "WARNING" not in capsys.readouterr().err
def test_read_metadata_with_sequences_with_extra_and_dup(self, metadata_with_unmatched_and_dup, fasta_with_unmatched_and_dup):
with pytest.raises(AugurError) as e_info:
list(read_metadata_with_sequences(metadata_with_unmatched_and_dup, ('\t',), fasta_with_unmatched_and_dup, 'strain'))
# Expected to error on first duplicate sequence since we check duplicate sequences first
assert str(e_info.value) == "Encountered sequence record with duplicate id 'SEQ_A'."
def test_read_metadata_with_sequences_with_extra_and_dup_error_all(self, metadata_with_unmatched_and_dup, fasta_with_unmatched_and_dup):
with pytest.raises(AugurError) as e_info:
list(read_metadata_with_sequences(
metadata_with_unmatched_and_dup,
('\t',),
fasta_with_unmatched_and_dup,
'strain',
unmatched_reporting=DataErrorMethod.ERROR_ALL,
duplicate_reporting=DataErrorMethod.ERROR_ALL
))
assert str(e_info.value) == (
"Encountered the following error(s) when parsing metadata with sequences:\n"
"The output may not match expectations because there were records with duplicate sequence ids.\n"
f"The following sequence ids were duplicated in {metadata_with_unmatched_and_dup!r}:\n"
"'SEQ_C'\n'SEQ_G'\n"
f"The following sequence ids were duplicated in {fasta_with_unmatched_and_dup!r}:\n"
"'SEQ_A'\n'SEQ_T'\n"
"The output may be incomplete because there were unmatched records.\n"
"The following metadata records did not have a matching sequence:\n"
"'EXTRA_METADATA_A'\n'EXTRA_METADATA_T'\n"
"The following sequence records did not have a matching metadata record:\n"
"'EXTRA_SEQ_A'\n'EXTRA_SEQ_T'"
)
def test_read_metadata_with_sequences_with_extra_and_dup_warn_unmatched(self, capsys, metadata_with_unmatched_and_dup, fasta_with_unmatched_and_dup):
with pytest.raises(AugurError) as e_info:
list(read_metadata_with_sequences(
metadata_with_unmatched_and_dup,
('\t',),
fasta_with_unmatched_and_dup,
'strain',
unmatched_reporting=DataErrorMethod.WARN,
duplicate_reporting=DataErrorMethod.ERROR_ALL
))
# We should see warnings for the unmatched records before the error is raised
captured = capsys.readouterr()
assert captured.err == (
"WARNING: Encountered metadata record 'EXTRA_METADATA_A' without a matching sequence.\n"
"WARNING: Encountered metadata record 'EXTRA_METADATA_T' without a matching sequence.\n"
"WARNING: The output may be incomplete because there were unmatched records.\n"
"The following metadata records did not have a matching sequence:\n"
"'EXTRA_METADATA_A'\n'EXTRA_METADATA_T'\n"
"The following sequence records did not have a matching metadata record:\n"
"'EXTRA_SEQ_A'\n'EXTRA_SEQ_T'\n"
)
assert str(e_info.value) == (
"Encountered the following error(s) when parsing metadata with sequences:\n"
"The output may not match expectations because there were records with duplicate sequence ids.\n"
f"The following sequence ids were duplicated in {metadata_with_unmatched_and_dup!r}:\n"
"'SEQ_C'\n'SEQ_G'\n"
f"The following sequence ids were duplicated in {fasta_with_unmatched_and_dup!r}:\n"
"'SEQ_A'\n'SEQ_T'"
)
def test_read_metadata_with_sequences_with_extra_and_dup_warn_dups(self, capsys, metadata_with_unmatched_and_dup, fasta_with_unmatched_and_dup):
with pytest.raises(AugurError) as e_info:
list(read_metadata_with_sequences(
metadata_with_unmatched_and_dup,
('\t',),
fasta_with_unmatched_and_dup,
'strain',
unmatched_reporting=DataErrorMethod.ERROR_ALL,
duplicate_reporting=DataErrorMethod.WARN
))
# We should see warnings for the unmatched records before the error is raised
captured = capsys.readouterr()
assert captured.err == (
"WARNING: Encountered sequence record with duplicate id 'SEQ_A'.\n"
"WARNING: Encountered sequence record with duplicate id 'SEQ_T'.\n"
"WARNING: Encountered metadata record with duplicate id 'SEQ_C'.\n"
"WARNING: Encountered metadata record with duplicate id 'SEQ_G'.\n"
"WARNING: The output may not match expectations because there were records with duplicate sequence ids.\n"
f"The following sequence ids were duplicated in {metadata_with_unmatched_and_dup!r}:\n"
"'SEQ_C'\n'SEQ_G'\n"
f"The following sequence ids were duplicated in {fasta_with_unmatched_and_dup!r}:\n"
"'SEQ_A'\n'SEQ_T'\n"
)
assert str(e_info.value) == (
"Encountered the following error(s) when parsing metadata with sequences:\n"
"The output may be incomplete because there were unmatched records.\n"
"The following metadata records did not have a matching sequence:\n"
"'EXTRA_METADATA_A'\n'EXTRA_METADATA_T'\n"
"The following sequence records did not have a matching metadata record:\n"
"'EXTRA_SEQ_A'\n'EXTRA_SEQ_T'"
)
def test_read_metadata_with_sequences_with_extra_and_dup_warn_both(self, capsys, metadata_with_unmatched_and_dup, fasta_with_unmatched_and_dup):
records = list(read_metadata_with_sequences(
metadata_with_unmatched_and_dup,
('\t',),
fasta_with_unmatched_and_dup,
'strain',
unmatched_reporting=DataErrorMethod.WARN,
duplicate_reporting=DataErrorMethod.WARN
))
assert len(records) == 6
assert [record['strain'] for record in records] == ['SEQ_A', 'SEQ_T', 'SEQ_C', 'SEQ_G', 'SEQ_C', 'SEQ_G']
captured = capsys.readouterr()
assert captured.err == (
"WARNING: Encountered sequence record with duplicate id 'SEQ_A'.\n"
"WARNING: Encountered sequence record with duplicate id 'SEQ_T'.\n"
"WARNING: Encountered metadata record with duplicate id 'SEQ_C'.\n"
"WARNING: Encountered metadata record with duplicate id 'SEQ_G'.\n"
"WARNING: Encountered metadata record 'EXTRA_METADATA_A' without a matching sequence.\n"
"WARNING: Encountered metadata record 'EXTRA_METADATA_T' without a matching sequence.\n"
"WARNING: The output may not match expectations because there were records with duplicate sequence ids.\n"
f"The following sequence ids were duplicated in {metadata_with_unmatched_and_dup!r}:\n"
"'SEQ_C'\n'SEQ_G'\n"
f"The following sequence ids were duplicated in {fasta_with_unmatched_and_dup!r}:\n"
"'SEQ_A'\n'SEQ_T'\n"
"WARNING: The output may be incomplete because there were unmatched records.\n"
"The following metadata records did not have a matching sequence:\n"
"'EXTRA_METADATA_A'\n'EXTRA_METADATA_T'\n"
"The following sequence records did not have a matching metadata record:\n"
"'EXTRA_SEQ_A'\n'EXTRA_SEQ_T'\n"
)
@pytest.fixture
def output_records():
return iter([
{"strain": "SEQ_A", "country": "USA", "date": "2020-10-01"},
{"strain": "SEQ_T", "country": "USA", "date": "2020-10-02"}
])
@pytest.fixture
def expected_output_tsv():
return (
"strain\tcountry\tdate\n"
"SEQ_A\tUSA\t2020-10-01\n"
"SEQ_T\tUSA\t2020-10-02\n"
)
class TestWriteRecordsToTsv:
def test_write_records_to_tsv(self, tmpdir, output_records, expected_output_tsv):
output_tsv = tmpdir / "output.tsv"
write_records_to_tsv(output_records, output_tsv)
with open(output_tsv, 'r') as output_fh:
assert output_fh.read() == expected_output_tsv
def test_write_records_to_tsv_stdout(self, capsys, output_records, expected_output_tsv):
write_records_to_tsv(output_records, '-')
captured = capsys.readouterr()
assert captured.out == expected_output_tsv
def test_write_records_to_tsv_with_extra_keys(self, capsys):
records_with_extra_keys = iter([
{"key_1": "value_1", "key_2": "value_2"},
{"key_1": "value_1", "key_2": "value_2", "key_3": "value_3"}
])
write_records_to_tsv(records_with_extra_keys, '-')
captured = capsys.readouterr()
assert captured.out == (
"key_1\tkey_2\n"
"value_1\tvalue_2\n"
"value_1\tvalue_2\n"
)
def test_write_records_to_tsv_with_missing_keys(self, capsys):
records_with_missing_keys = iter([
{"key_1": "value_1", "key_2": "value_2"},
{"key_2": "value_2"}
])
write_records_to_tsv(records_with_missing_keys, '-')
captured = capsys.readouterr()
assert captured.out == (
"key_1\tkey_2\n"
"value_1\tvalue_2\n"
"\tvalue_2\n"
)
def test_write_records_to_tsv_with_empty_records(self, tmpdir):
output_file = tmpdir / "output.tsv"
with pytest.raises(AugurError) as e_info:
write_records_to_tsv(iter([]), output_file)
assert str(e_info.value) == f"Unable to write records to {output_file} because provided records were empty."
def write_lines(tmpdir, lines):
path = str(tmpdir / "tmp")
with open(path, 'w') as f:
f.writelines(lines)
return path
class TestMetadataClass:
def test_attributes(self, metadata_file):
"""All attributes are populated."""
m = Metadata(metadata_file, delimiters=[',', '\t'], id_columns=['invalid', 'strain'])
assert m.path == metadata_file
assert m.delimiter == '\t'
assert m.columns == ['strain', 'country', 'date']
assert m.id_column == 'strain'
def test_invalid_delimiter(self, metadata_file):
"""Failure to detect delimiter raises an error."""
with pytest.raises(InvalidDelimiter):
Metadata(metadata_file, delimiters=[':'], id_columns=['strain'])
def test_invalid_id_column(self, metadata_file):
"""Failure to detect an ID column raises an error."""
with pytest.raises(AugurError):
Metadata(metadata_file, delimiters=['\t'], id_columns=['strains'])
def test_rows(self, metadata_file):
"""Check Metadata.rows() output format."""
m = Metadata(metadata_file, delimiters=['\t'], id_columns=['strain'])
assert list(m.rows()) == [
{'country': 'USA', 'date': '2020-10-01', 'strain': 'SEQ_A'},
{'country': 'USA', 'date': '2020-10-02', 'strain': 'SEQ_T'},
{'country': 'USA', 'date': '2020-10-03', 'strain': 'SEQ_C'},
{'country': 'USA', 'date': '2020-10-04', 'strain': 'SEQ_G'},
]
def test_blank_lines(self, tmpdir):
"""Check behavior of lines that are blank and have empty values.
Blank lines are skipped. Lines with delimiters but empty values are still included when reading.
"""
path = write_lines(tmpdir, [
'a,b,c\n',
'1,2,3\n',
'\n',
'3,2,3\n',
',,\n',
'5,2,3\n',
])
m = Metadata(path, delimiters=',', id_columns=['a'])
assert list(m.rows()) == [
{'a': '1', 'b': '2', 'c': '3'},
{'a': '3', 'b': '2', 'c': '3'},
{'a': '' , 'b': '' , 'c': '' },
{'a': '5', 'b': '2', 'c': '3'}
]
def test_rows_strict_extra(self, tmpdir):
"""Test behavior when reading rows with extra entries or delimiters."""
path = write_lines(tmpdir, [
'a,b,c\n',
'1,2,3\n',
'2,2,3,4\n',
'3,2,3,\n',
])
m = Metadata(path, delimiters=',', id_columns=['a'])
with pytest.raises(AugurError):
list(m.rows(strict=True))
assert list(m.rows(strict=False)) == [
{'a': '1', 'b': '2', 'c': '3'},
{'a': '2', 'b': '2', 'c': '3', None: ['4']},
{'a': '3', 'b': '2', 'c': '3', None: ['']},
]
def test_rows_strict_missing(self, tmpdir):
"""Test behavior when reading rows with missing entries or delimiters."""
path = write_lines(tmpdir, [
'a,b,c\n',
'1,2,3\n',
'2,2,\n',
'3,2\n',
])
m = Metadata(path, delimiters=',', id_columns=['a'])
with pytest.raises(AugurError):
list(m.rows(strict=True))
assert list(m.rows(strict=False)) == [
{'a': '1', 'b': '2', 'c': '3'},
{'a': '2', 'b': '2', 'c': ''},
{'a': '3', 'b': '2', 'c': None},
]
|