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 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
|
"""Unit tests for utility functions and classes.
"""
from copy import copy, deepcopy
from os import remove, rmdir
from unittest import TestCase
import pytest
from numpy import array
from numpy.testing import assert_allclose
from cogent3.util.misc import (
ClassChecker,
ConstrainedContainer,
ConstrainedDict,
ConstrainedList,
ConstraintError,
Delegator,
DistanceFromMatrix,
FunctionWrapper,
MappedDict,
MappedList,
NestedSplitter,
add_lowercase,
adjusted_gt_minprob,
adjusted_within_bounds,
curry,
docstring_to_summary_rest,
extend_docstring_from,
get_independent_coords,
get_merged_by_value_coords,
get_merged_overlapping_coords,
get_object_provenance,
get_run_start_indices,
get_setting_from_environ,
get_true_spans,
identity,
is_char,
is_char_or_noniterable,
is_iterable,
iterable,
list_flatten,
not_list_tuple,
recursive_flatten,
)
class UtilsTests(TestCase):
"""Tests of individual functions in utils"""
def setUp(self):
""" """
self.files_to_remove = []
self.dirs_to_remove = []
def tearDown(self):
""" """
list(map(remove, self.files_to_remove))
list(map(rmdir, self.dirs_to_remove))
def test_adjusted_gt_minprob(self):
"""correctly adjust a prob vector so all values > minval"""
vector = [0.8, 0.2, 0.0, 0.0]
minprob = 1e-3
got = adjusted_gt_minprob(vector, minprob=minprob)
self.assertTrue(got.min() > minprob)
minprob = 1e-6
got = adjusted_gt_minprob(vector, minprob=minprob)
self.assertTrue(got.min() > minprob)
minprob = 0
got = adjusted_gt_minprob(vector, minprob=minprob)
self.assertTrue(got.min() > minprob)
def test_adjusted_probs_2D(self):
"""correctly adjust a 2D array"""
data = [
[1.0000, 0.0000, 0.0000, 0.0000],
[0.0000, 1.0000, 0.0000, 0.0000],
[0.1250, 0.1250, 0.6250, 0.1250],
[0.1250, 0.1250, 0.1250, 0.6250],
]
got = adjusted_gt_minprob(data)
assert_allclose(got, data, atol=1e-5)
def test_adjusted_within_bounds(self):
"""values correctly adjusted within specified bounds"""
l, u = 1e-5, 2
eps = 1e-6
got = adjusted_within_bounds(l - eps, l, u, eps=eps)
assert_allclose(got, l)
got = adjusted_within_bounds(u + eps, l, u, eps=eps)
assert_allclose(got, u)
with self.assertRaises(ValueError):
got = adjusted_within_bounds(u + 4, l, u, eps=eps, action="raise")
with self.assertRaises(ValueError):
got = adjusted_within_bounds(u - 4, l, u, eps=eps, action="raise")
def test_identity(self):
"""should return same object"""
foo = [1, "a", lambda x: x]
exp = id(foo)
self.assertEqual(id(identity(foo)), exp)
def test_iterable(self):
"""iterable(x) should return x or [x], always an iterable result"""
self.assertEqual(iterable("x"), "x")
self.assertEqual(iterable(""), "")
self.assertEqual(iterable(3), [3])
self.assertEqual(iterable(None), [None])
self.assertEqual(iterable({"a": 1}), {"a": 1})
self.assertEqual(iterable(["a", "b", "c"]), ["a", "b", "c"])
def test_is_iterable(self):
"""is_iterable should return True for iterables"""
# test str
self.assertEqual(is_iterable("aa"), True)
# test list
self.assertEqual(is_iterable([3, "aa"]), True)
# test Number, expect False
self.assertEqual(is_iterable(3), False)
def test_is_char(self):
"""is_char(obj) should return True when obj is a char"""
self.assertEqual(is_char("a"), True)
self.assertEqual(is_char("ab"), False)
self.assertEqual(is_char(""), True)
self.assertEqual(is_char([3]), False)
self.assertEqual(is_char(3), False)
def test_is_char_or_noniterable(self):
"""is_char_or_noniterable should return True or False"""
self.assertEqual(is_char_or_noniterable("a"), True)
self.assertEqual(is_char_or_noniterable("ab"), False)
self.assertEqual(is_char_or_noniterable(3), True)
self.assertEqual(is_char_or_noniterable([3]), False)
def test_recursive_flatten(self):
"""recursive_flatten should remove all nesting from nested sequences"""
self.assertEqual(recursive_flatten([1, [2, 3], [[4, [5]]]]), [1, 2, 3, 4, 5])
# test default behavior on str unpacking
self.assertEqual(
recursive_flatten(["aa", [8, "cc", "dd"], ["ee", ["ff", "gg"]]]),
["a", "a", 8, "c", "c", "d", "d", "e", "e", "f", "f", "g", "g"],
)
def test_not_list_tuple(self):
"""not_list_tuple(obj) should return False when obj is list or tuple"""
self.assertEqual(not_list_tuple([8, 3]), False)
self.assertEqual(not_list_tuple((8, 3)), False)
self.assertEqual(not_list_tuple("34"), True)
def test_list_flatten(self):
"""list_flatten should remove all nesting, str is untouched"""
self.assertEqual(
list_flatten(["aa", [8, "cc", "dd"], ["ee", ["ff", "gg"]]]),
["aa", 8, "cc", "dd", "ee", "ff", "gg"],
)
def test_recursive_flatten_max_depth(self):
"""recursive_flatten should not remover more than max_depth levels"""
self.assertEqual(recursive_flatten([1, [2, 3], [[4, [5]]]]), [1, 2, 3, 4, 5])
self.assertEqual(
recursive_flatten([1, [2, 3], [[4, [5]]]], 0), [1, [2, 3], [[4, [5]]]]
)
self.assertEqual(
recursive_flatten([1, [2, 3], [[4, [5]]]], 1), [1, 2, 3, [4, [5]]]
)
self.assertEqual(
recursive_flatten([1, [2, 3], [[4, [5]]]], 2), [1, 2, 3, 4, [5]]
)
self.assertEqual(recursive_flatten([1, [2, 3], [[4, [5]]]], 3), [1, 2, 3, 4, 5])
self.assertEqual(
recursive_flatten([1, [2, 3], [[4, [5]]]], 5000), [1, 2, 3, 4, 5]
)
def test_add_lowercase(self):
"""add_lowercase should add lowercase version of each key w/ same val"""
d = {
"a": 1,
"b": "test",
"A": 5,
"C": 123,
"D": [],
"AbC": "XyZ",
None: "3",
"$": "abc",
145: "5",
}
add_lowercase(d)
assert d["d"] is d["D"]
d["D"].append(3)
self.assertEqual(d["D"], [3])
self.assertEqual(d["d"], [3])
self.assertNotEqual(d["a"], d["A"])
self.assertEqual(
d,
{
"a": 1,
"b": "test",
"A": 5,
"C": 123,
"c": 123,
"D": [3],
"d": [3],
"AbC": "XyZ",
"abc": "xyz",
None: "3",
"$": "abc",
145: "5",
},
)
# should work with strings
d = "ABC"
self.assertEqual(add_lowercase(d), "ABCabc")
# should work with tuples
d = tuple("ABC")
self.assertEqual(add_lowercase(d), tuple("ABCabc"))
# should work with lists
d = list("ABC")
self.assertEqual(add_lowercase(d), list("ABCabc"))
# should work with sets
d = set("ABC")
self.assertEqual(add_lowercase(d), set("ABCabc"))
# ...even frozensets
d = frozenset("ABC")
self.assertEqual(add_lowercase(d), frozenset("ABCabc"))
def test_add_lowercase_tuple(self):
"""add_lowercase should deal with tuples correctly"""
d = {("A", "B"): "C", ("D", "e"): "F", ("b", "c"): "H"}
add_lowercase(d)
self.assertEqual(
d,
{
("A", "B"): "C",
("a", "b"): "c",
("D", "e"): "F",
("d", "e"): "f",
("b", "c"): "H",
},
)
def test_DistanceFromMatrix(self):
"""DistanceFromMatrix should return correct elements"""
m = {"a": {"3": 4, 6: 1}, "b": {"3": 5, "6": 2}}
d = DistanceFromMatrix(m)
self.assertEqual(d("a", "3"), 4)
self.assertEqual(d("a", 6), 1)
self.assertEqual(d("b", "3"), 5)
self.assertEqual(d("b", "6"), 2)
self.assertRaises(KeyError, d, "c", 1)
self.assertRaises(KeyError, d, "b", 3)
def test_independent_spans(self):
"""get_independent_coords returns truly non-overlapping (decorated) spans"""
# single span is returned
data = [(0, 20, "a")]
got = get_independent_coords(data)
self.assertEqual(got, data)
# multiple non-overlapping
data = [(20, 30, "a"), (35, 40, "b"), (65, 75, "c")]
got = get_independent_coords(data)
self.assertEqual(got, data)
# over-lapping first/second returns first occurrence by default
data = [(20, 30, "a"), (25, 40, "b"), (65, 75, "c")]
got = get_independent_coords(data)
self.assertEqual(got, [(20, 30, "a"), (65, 75, "c")])
# but randomly the first or second if random_tie_breaker is chosen
got = get_independent_coords(data, random_tie_breaker=True)
self.assertTrue(
got in ([(20, 30, "a"), (65, 75, "c")], [(25, 40, "b"), (65, 75, "c")])
)
# over-lapping second/last returns first occurrence by default
data = [(20, 30, "a"), (30, 60, "b"), (50, 75, "c")]
got = get_independent_coords(data)
self.assertEqual(got, [(20, 30, "a"), (30, 60, "b")])
# but randomly the first or second if random_tie_breaker is chosen
got = get_independent_coords(data, random_tie_breaker=True)
self.assertTrue(
got in ([(20, 30, "a"), (50, 75, "c")], [(20, 30, "a"), (30, 60, "b")])
)
# over-lapping middle returns first occurrence by default
data = [(20, 24, "a"), (25, 40, "b"), (30, 35, "c"), (65, 75, "d")]
got = get_independent_coords(data)
self.assertEqual(got, [(20, 24, "a"), (25, 40, "b"), (65, 75, "d")])
# but randomly the first or second if random_tie_breaker is chosen
got = get_independent_coords(data, random_tie_breaker=True)
self.assertTrue(
got
in (
[(20, 24, "a"), (25, 40, "b"), (65, 75, "d")],
[(20, 24, "a"), (30, 35, "c"), (65, 75, "d")],
)
)
def test_get_merged_spans(self):
"""tests merger of overlapping spans"""
sample = [[0, 10], [12, 15], [13, 16], [18, 25], [19, 20]]
result = get_merged_overlapping_coords(sample)
expect = [[0, 10], [12, 16], [18, 25]]
self.assertEqual(result, expect)
sample = [[0, 10], [5, 9], [12, 16], [18, 20], [19, 25]]
result = get_merged_overlapping_coords(sample)
expect = [[0, 10], [12, 16], [18, 25]]
self.assertEqual(result, expect)
# test with tuples
sample = tuple(map(tuple, sample))
result = get_merged_overlapping_coords(sample)
expect = [[0, 10], [12, 16], [18, 25]]
self.assertEqual(result, expect)
def test_get_run_start_indices(self):
"""return indices corresponding to start of a run of identical values"""
# 0 1 2 3 4 5 6 7
data = [1, 2, 3, 3, 3, 4, 4, 5]
expect = [[0, 1], [1, 2], [2, 3], [5, 4], [7, 5]]
got = get_run_start_indices(data)
self.assertEqual(list(got), expect)
# raise an exception if try and provide a converter and num digits
def wrap_gen(): # need to wrap generator so we can actually test this
gen = get_run_start_indices(data, digits=1, converter_func=lambda x: x)
def call():
for v in gen:
pass
return call
self.assertRaises(AssertionError, wrap_gen())
def test_merged_by_value_spans(self):
"""correctly merge adjacent spans with the same value"""
# initial values same
data = [[20, 21, 0], [21, 22, 0], [22, 23, 1], [23, 24, 0]]
self.assertEqual(
get_merged_by_value_coords(data), [[20, 22, 0], [22, 23, 1], [23, 24, 0]]
)
# middle values same
data = [[20, 21, 0], [21, 22, 1], [22, 23, 1], [23, 24, 0]]
self.assertEqual(
get_merged_by_value_coords(data), [[20, 21, 0], [21, 23, 1], [23, 24, 0]]
)
# last values same
data = [[20, 21, 0], [21, 22, 1], [22, 23, 0], [23, 24, 0]]
self.assertEqual(
get_merged_by_value_coords(data), [[20, 21, 0], [21, 22, 1], [22, 24, 0]]
)
# all unique values
data = [[20, 21, 0], [21, 22, 1], [22, 23, 2], [23, 24, 0]]
self.assertEqual(
get_merged_by_value_coords(data),
[[20, 21, 0], [21, 22, 1], [22, 23, 2], [23, 24, 0]],
)
# all values same
data = [[20, 21, 0], [21, 22, 0], [22, 23, 0], [23, 24, 0]]
self.assertEqual(get_merged_by_value_coords(data), [[20, 24, 0]])
# all unique values to 2nd decimal
data = [[20, 21, 0.11], [21, 22, 0.12], [22, 23, 0.13], [23, 24, 0.14]]
self.assertEqual(
get_merged_by_value_coords(data),
[[20, 21, 0.11], [21, 22, 0.12], [22, 23, 0.13], [23, 24, 0.14]],
)
# all values same at 1st decimal
data = [[20, 21, 0.11], [21, 22, 0.12], [22, 23, 0.13], [23, 24, 0.14]]
self.assertEqual(get_merged_by_value_coords(data, digits=1), [[20, 24, 0.1]])
def test_get_object_provenance(self):
"""correctly deduce object provenance"""
from cogent3 import DNA, SequenceCollection, get_model
result = get_object_provenance("abncd")
self.assertEqual(result, "str")
got = get_object_provenance(DNA)
self.assertEqual(got, "cogent3.core.moltype.MolType")
sm = get_model("HKY85")
got = get_object_provenance(sm)
self.assertEqual(
got, "cogent3.evolve.substitution_model.TimeReversibleNucleotide"
)
# handle a type
instance = SequenceCollection(dict(a="ACG", b="GGG"))
instance_prov = get_object_provenance(instance)
self.assertEqual(instance_prov, "cogent3.core.alignment.SequenceCollection")
type_prov = get_object_provenance(SequenceCollection)
self.assertEqual(instance_prov, type_prov)
def test_get_object_provenance_builtins(self):
"""allow identifying builtins too"""
from gzip import GzipFile, compress
obj_prov = get_object_provenance(compress)
self.assertEqual(obj_prov, "gzip.compress")
obj_prov = get_object_provenance(GzipFile)
self.assertEqual(obj_prov, "gzip.GzipFile")
d = dict(a=23, b=1)
obj_prov = get_object_provenance(d)
self.assertEqual(obj_prov, "dict")
obj_prov = get_object_provenance(dict)
self.assertEqual(obj_prov, "dict")
def test_NestedSplitter(self):
"""NestedSplitter should make a function which return expected list"""
# test delimiters, constructor, filter_
line = "ii=0; oo= 9, 6 5; ; xx= 8; "
cmds = [
"NestedSplitter(';=,')(line)",
"NestedSplitter([';', '=', ','])(line)",
"NestedSplitter([(';'), '=', ','], constructor=None)(line)",
"NestedSplitter([(';'), '=', ','], filter_=None)(line)",
"NestedSplitter([(';',1), '=', ','])(line)",
"NestedSplitter([(';',-1), '=', ','])(line)",
]
results = [
[["ii", "0"], ["oo", ["9", "6 5"]], "", ["xx", "8"], ""],
[["ii", "0"], ["oo", ["9", "6 5"]], "", ["xx", "8"], ""],
[["ii", "0"], [" oo", [" 9", " 6 5"]], " ", [" xx", " 8"], " "],
[["ii", "0"], ["oo", ["9", "6 5"]], ["xx", "8"]],
[["ii", "0"], ["oo", ["9", "6 5; ; xx"], "8;"]],
[["ii", "0; oo", ["9", "6 5; ; xx"], "8"], ""],
]
for cmd, result in zip(cmds, results):
self.assertEqual(eval(cmd), result)
# test uncontinous level of delimiters
test = "a; b,c; d,e:f; g:h;" # g:h should get [[g,h]] instead of [g,h]
self.assertEqual(
NestedSplitter(";,:")(test),
["a", ["b", "c"], ["d", ["e", "f"]], [["g", "h"]], ""],
)
# test empty
self.assertEqual(NestedSplitter(";,:")(""), [""])
self.assertEqual(NestedSplitter(";,:")(" "), [""])
self.assertEqual(NestedSplitter(";,:", filter_=None)(" ;, :"), [[[]]])
def test_curry(self):
"""curry should generate the function with parameters setted"""
curry_test = curry(lambda x, y: x == y, 5)
knowns = ((3, False), (9, False), (5, True))
for arg2, result in knowns:
self.assertEqual(curry_test(arg2), result)
@pytest.mark.filterwarnings("ignore::UserWarning")
def test_get_setting_from_environ(self):
"""correctly recovers environment variables"""
import os
def make_env_setting(d):
return ",".join([f"{k}={v}" for k, v in d.items()])
env_name = "DUMMY_SETTING"
os.environ.pop(env_name, None)
setting = dict(num_pos=2, num_seq=4, name="blah")
single_setting = dict(num_pos=2)
correct_names_types = dict(num_pos=int, num_seq=int, name=str)
incorrect_names_types = dict(num_pos=int, num_seq=int, name=float)
for stng in (setting, single_setting):
os.environ[env_name] = make_env_setting(stng)
got = get_setting_from_environ(env_name, correct_names_types)
for key in got:
self.assertEqual(got[key], setting[key])
os.environ[env_name] = make_env_setting(setting)
got = get_setting_from_environ(env_name, incorrect_names_types)
assert "name" not in got
for key in got:
self.assertEqual(got[key], setting[key])
# malformed env setting
os.environ[env_name] = make_env_setting(setting).replace("=", "")
got = get_setting_from_environ(env_name, correct_names_types)
self.assertEqual(got, {})
os.environ.pop(env_name, None)
class _my_dict(dict):
"""Used for testing subclass behavior of ClassChecker"""
pass
class ClassCheckerTests(TestCase):
"""Unit tests for the ClassChecker class."""
def setUp(self):
"""define a few standard checkers"""
self.strcheck = ClassChecker(str)
self.intcheck = ClassChecker(int, int)
self.numcheck = ClassChecker(float, int, int)
self.emptycheck = ClassChecker()
self.dictcheck = ClassChecker(dict)
self.mydictcheck = ClassChecker(_my_dict)
def test_init_good(self):
"""ClassChecker should init OK when initialized with classes"""
self.assertEqual(self.strcheck.Classes, [str])
self.assertEqual(self.numcheck.Classes, [float, int, int])
self.assertEqual(self.emptycheck.Classes, [])
def test_init_bad(self):
"""ClassChecker should raise TypeError if initialized with non-class"""
self.assertRaises(TypeError, ClassChecker, "x")
self.assertRaises(TypeError, ClassChecker, str, None)
def test_contains(self):
"""ClassChecker should return True only if given instance of class"""
self.assertEqual(self.strcheck.__contains__("3"), True)
self.assertEqual(self.strcheck.__contains__("ahsdahisad"), True)
self.assertEqual(self.strcheck.__contains__(3), False)
self.assertEqual(self.strcheck.__contains__({3: "c"}), False)
self.assertEqual(self.intcheck.__contains__("ahsdahisad"), False)
self.assertEqual(self.intcheck.__contains__("3"), False)
self.assertEqual(self.intcheck.__contains__(3.0), False)
self.assertEqual(self.intcheck.__contains__(3), True)
self.assertEqual(self.intcheck.__contains__(4**60), True)
self.assertEqual(self.intcheck.__contains__(4**60 * -1), True)
d = _my_dict()
self.assertEqual(self.dictcheck.__contains__(d), True)
self.assertEqual(self.dictcheck.__contains__({"d": 1}), True)
self.assertEqual(self.mydictcheck.__contains__(d), True)
self.assertEqual(self.mydictcheck.__contains__({"d": 1}), False)
self.assertEqual(self.emptycheck.__contains__("d"), False)
self.assertEqual(self.numcheck.__contains__(3), True)
self.assertEqual(self.numcheck.__contains__(3.0), True)
self.assertEqual(self.numcheck.__contains__(-3), True)
self.assertEqual(self.numcheck.__contains__(-3.0), True)
self.assertEqual(self.numcheck.__contains__(3e-300), True)
self.assertEqual(self.numcheck.__contains__(0), True)
self.assertEqual(self.numcheck.__contains__(4**1000), True)
self.assertEqual(self.numcheck.__contains__("4**1000"), False)
def test_str(self):
"""ClassChecker str should be the same as str(self.Classes)"""
for c in [
self.strcheck,
self.intcheck,
self.numcheck,
self.emptycheck,
self.dictcheck,
self.mydictcheck,
]:
self.assertEqual(str(c), str(c.Classes))
def test_copy(self):
"""copy.copy should work correctly on ClassChecker"""
c = copy(self.strcheck)
assert c is not self.strcheck
assert "3" in c
assert 3 not in c
assert c.Classes is self.strcheck.Classes
def test_deepcopy(self):
"""copy.deepcopy should work correctly on ClassChecker"""
c = deepcopy(self.strcheck)
assert c is not self.strcheck
assert "3" in c
assert 3 not in c
assert c.Classes is not self.strcheck.Classes
class modifiable_string(str):
"""Mutable class to allow arbitrary attributes to be set"""
pass
class _list_and_string(list, Delegator):
"""Trivial class to demonstrate Delegator."""
def __init__(self, items, string):
Delegator.__init__(self, string)
self.NormalAttribute = "default"
self._x = None
self._constant = "c"
for i in items:
self.append(i)
def _get_rand_property(self):
return self._x
def _set_rand_property(self, value):
self._x = value
prop = property(_get_rand_property, _set_rand_property)
def _get_constant_property(self):
return self._constant
constant = property(_get_constant_property)
class DelegatorTests(TestCase):
"""Verify that Delegator works with attributes and properties."""
def test_init(self):
"""Delegator should init OK when data supplied"""
_list_and_string([1, 2, 3], "abc")
self.assertRaises(TypeError, _list_and_string, [123])
def test_getattr(self):
"""Delegator should find attributes in correct places"""
ls = _list_and_string([1, 2, 3], "abcd")
# behavior as list
self.assertEqual(len(ls), 3)
self.assertEqual(ls[0], 1)
ls.reverse()
self.assertEqual(ls, [3, 2, 1])
# behavior as string
self.assertEqual(ls.upper(), "ABCD")
self.assertEqual(len(ls.upper()), 4)
self.assertEqual(ls.replace("a", "x"), "xbcd")
# behavior of normal attributes
self.assertEqual(ls.NormalAttribute, "default")
# behavior of properties
self.assertEqual(ls.prop, None)
self.assertEqual(ls.constant, "c")
# shouldn't be allowed to get unknown properties
self.assertRaises(AttributeError, getattr, ls, "xyz")
# if the unknown property can be set in the forwarder, do it there
flex = modifiable_string("abcd")
ls_flex = _list_and_string([1, 2, 3], flex)
ls_flex.blah = "zxc"
self.assertEqual(ls_flex.blah, "zxc")
self.assertEqual(flex.blah, "zxc")
# should get AttributeError if changing a read-only property
self.assertRaises(AttributeError, setattr, ls, "constant", "xyz")
def test_setattr(self):
"""Delegator should set attributes in correct places"""
ls = _list_and_string([1, 2, 3], "abcd")
# ability to create a new attribute
ls.xyz = 3
self.assertEqual(ls.xyz, 3)
# modify a normal attribute
ls.NormalAttribute = "changed"
self.assertEqual(ls.NormalAttribute, "changed")
# modify a read/write property
ls.prop = "xyz"
self.assertEqual(ls.prop, "xyz")
def test_copy(self):
"""copy.copy should work correctly on Delegator"""
l = ["a"]
d = Delegator(l)
c = copy(d)
assert c is not d
assert c._handler is d._handler
def test_deepcopy(self):
"""copy.deepcopy should work correctly on Delegator"""
l = ["a"]
d = Delegator(l)
c = deepcopy(d)
assert c is not d
assert c._handler is not d._handler
assert c._handler == d._handler
class FunctionWrapperTests(TestCase):
"""Tests of the FunctionWrapper class"""
def test_init(self):
"""FunctionWrapper should initialize with any callable"""
f = FunctionWrapper(str)
g = FunctionWrapper(id)
h = FunctionWrapper(iterable)
x = 3
self.assertEqual(f(x), "3")
self.assertEqual(g(x), id(x))
self.assertEqual(h(x), [3])
def test_copy(self):
"""copy should work for FunctionWrapper objects"""
f = FunctionWrapper(str)
c = copy(f)
assert c is not f
assert c.Function is f.Function
# NOTE: deepcopy does not work for FunctionWrapper objects because you
# can't copy a function.
class _simple_container(object):
"""example of a container to constrain"""
def __init__(self, data):
self._data = list(data)
def __getitem__(self, item):
return self._data.__getitem__(item)
class _constrained_simple_container(_simple_container, ConstrainedContainer):
"""constrained version of _simple_container"""
def __init__(self, data):
_simple_container.__init__(self, data)
ConstrainedContainer.__init__(self, None)
class ConstrainedContainerTests(TestCase):
"""Tests of the generic ConstrainedContainer interface."""
def setUp(self):
"""Make a couple of standard containers"""
self.alphabet = _constrained_simple_container("abc")
self.numbers = _constrained_simple_container([1, 2, 3])
self.alphacontainer = "abcdef"
self.numbercontainer = ClassChecker(int)
def test_matchesConstraint(self):
"""ConstrainedContainer matchesConstraint should return true if items ok"""
self.assertEqual(self.alphabet.matches_constraint(self.alphacontainer), True)
self.assertEqual(self.alphabet.matches_constraint(self.numbercontainer), False)
self.assertEqual(self.numbers.matches_constraint(self.alphacontainer), False)
self.assertEqual(self.numbers.matches_constraint(self.numbercontainer), True)
def test_other_is_valid(self):
"""ConstrainedContainer should use constraint for checking other"""
self.assertEqual(self.alphabet.other_is_valid("12d8jc"), True)
self.alphabet.constraint = self.alphacontainer
self.assertEqual(self.alphabet.other_is_valid("12d8jc"), False)
self.alphabet.constraint = list("abcdefghijkl12345678")
self.assertEqual(self.alphabet.other_is_valid("12d8jc"), True)
self.assertEqual(self.alphabet.other_is_valid("z"), False)
def test_item_is_valid(self):
"""ConstrainedContainer should use constraint for checking item"""
self.assertEqual(self.alphabet.item_is_valid(3), True)
self.alphabet.constraint = self.alphacontainer
self.assertEqual(self.alphabet.item_is_valid(3), False)
self.assertEqual(self.alphabet.item_is_valid("a"), True)
def test_sequence_is_valid(self):
"""ConstrainedContainer should use constraint for checking sequence"""
self.assertEqual(self.alphabet.sequence_is_valid("12d8jc"), True)
self.alphabet.constraint = self.alphacontainer
self.assertEqual(self.alphabet.sequence_is_valid("12d8jc"), False)
self.alphabet.constraint = list("abcdefghijkl12345678")
self.assertEqual(self.alphabet.sequence_is_valid("12d8jc"), True)
self.assertEqual(self.alphabet.sequence_is_valid("z"), False)
def test_Constraint(self):
"""ConstrainedContainer should only allow valid constraints to be set"""
try:
self.alphabet.constraint = self.numbers
except ConstraintError:
pass
else:
raise AssertionError(
"Failed to raise ConstraintError with invalid constraint."
)
self.alphabet.constraint = "abcdefghi"
self.alphabet.constraint = ["a", "b", "c", 1, 2, 3]
self.numbers.constraint = list(range(20))
self.numbers.constraint = range(20)
self.numbers.constraint = [5, 1, 3, 7, 2]
self.numbers.constraint = {1: "a", 2: "b", 3: "c"}
self.assertRaises(ConstraintError, setattr, self.numbers, "constraint", "1")
class ConstrainedListTests(TestCase):
"""Tests that bad data can't sneak into ConstrainedLists."""
def test_init_good_data(self):
"""ConstrainedList should init OK if list matches constraint"""
self.assertEqual(ConstrainedList("abc", "abcd"), list("abc"))
self.assertEqual(ConstrainedList("", "abcd"), list(""))
items = [1, 2, 3.2234, (["a"], ["b"]), list("xyz")]
# should accept anything str() does if no constraint is passed
self.assertEqual(ConstrainedList(items), items)
self.assertEqual(ConstrainedList(items, None), items)
self.assertEqual(ConstrainedList("12345"), list("12345"))
# check that list is formatted correctly and chars are all there
test_list = list("12345")
self.assertEqual(ConstrainedList(test_list, "12345"), test_list)
def test_init_bad_data(self):
"""ConstrainedList should fail init with items not in constraint"""
self.assertRaises(ConstraintError, ConstrainedList, "1234", "123")
self.assertRaises(ConstraintError, ConstrainedList, [1, 2, 3], ["1", "2", "3"])
def test_add_prevents_bad_data(self):
"""ConstrainedList should allow addition only of compliant data"""
a = ConstrainedList("123", "12345")
b = ConstrainedList("444", "4")
c = ConstrainedList("45", "12345")
d = ConstrainedList("x")
self.assertEqual(a + b, list("123444"))
self.assertEqual(a + c, list("12345"))
self.assertRaises(ConstraintError, b.__add__, c)
self.assertRaises(ConstraintError, c.__add__, d)
# should be OK if constraint removed
b.constraint = None
self.assertEqual(b + c, list("44445"))
self.assertEqual(b + d, list("444x"))
# should fail if we add the constraint back
b.constraint = {"4": 1, 5: 2}
self.assertRaises(ConstraintError, b.__add__, c)
def test_iadd_prevents_bad_data(self):
"""ConstrainedList should allow in-place addition only of compliant data"""
a = ConstrainedList("12", "123")
a += "2"
self.assertEqual(a, list("122"))
self.assertEqual(a.constraint, "123")
self.assertRaises(ConstraintError, a.__iadd__, "4")
def test_imul(self):
"""ConstrainedList imul should preserve constraint"""
a = ConstrainedList("12", "123")
a *= 3
self.assertEqual(a, list("121212"))
self.assertEqual(a.constraint, "123")
def test_mul(self):
"""ConstrainedList mul should preserve constraint"""
a = ConstrainedList("12", "123")
b = a * 3
self.assertEqual(b, list("121212"))
self.assertEqual(b.constraint, "123")
def test_rmul(self):
"""ConstrainedList rmul should preserve constraint"""
a = ConstrainedList("12", "123")
b = 3 * a
self.assertEqual(b, list("121212"))
self.assertEqual(b.constraint, "123")
def test_setitem(self):
"""ConstrainedList setitem should work only if item in constraint"""
a = ConstrainedList("12", "123")
a[0] = "3"
self.assertEqual(a, list("32"))
self.assertRaises(ConstraintError, a.__setitem__, 0, 3)
a = ConstrainedList("1" * 20, "123")
self.assertRaises(ConstraintError, a.__setitem__, slice(0, 1, 1), [3])
self.assertRaises(ConstraintError, a.__setitem__, slice(0, 1, 1), ["111"])
a[2:9:2] = "3333"
self.assertEqual(a, list("11313131311111111111"))
def test_append(self):
"""ConstrainedList append should work only if item in constraint"""
a = ConstrainedList("12", "123")
a.append("3")
self.assertEqual(a, list("123"))
self.assertRaises(ConstraintError, a.append, 3)
def test_extend(self):
"""ConstrainedList extend should work only if all items in constraint"""
a = ConstrainedList("12", "123")
a.extend("321")
self.assertEqual(a, list("12321"))
self.assertRaises(ConstraintError, a.extend, ["1", "2", 3])
def test_insert(self):
"""ConstrainedList insert should work only if item in constraint"""
a = ConstrainedList("12", "123")
a.insert(0, "2")
self.assertEqual(a, list("212"))
self.assertRaises(ConstraintError, a.insert, 0, [2])
def test_getslice(self):
"""ConstrainedList getslice should remember constraint"""
a = ConstrainedList("123333", "12345")
b = a[2:4]
self.assertEqual(b, list("33"))
self.assertEqual(b.constraint, "12345")
def test_setslice(self):
"""ConstrainedList setslice should fail if slice has invalid chars"""
a = ConstrainedList("123333", "12345")
a[2:4] = ["2", "2"]
self.assertEqual(a, list("122233"))
self.assertRaises(ConstraintError, a.__setslice__, 2, 4, [2, 2])
a[:] = []
self.assertEqual(a, [])
self.assertEqual(a.constraint, "12345")
def test_setitem_masks(self):
"""ConstrainedList setitem with masks should transform input"""
a = ConstrainedList("12333", list(range(5)), lambda x: int(x) + 1)
self.assertEqual(a, [2, 3, 4, 4, 4])
self.assertRaises(ConstraintError, a.append, 4)
b = a[1:3]
assert b.mask is a.mask
assert "1" not in a
assert "2" not in a
assert 2 in a
assert "x" not in a
class MappedListTests(TestCase):
"""MappedList should behave like ConstrainedList, but map items."""
def test_setitem_masks(self):
"""MappedList setitem with masks should transform input"""
a = MappedList("12333", list(range(5)), lambda x: int(x) + 1)
self.assertEqual(a, [2, 3, 4, 4, 4])
self.assertRaises(ConstraintError, a.append, 4)
b = a[1:3]
assert b.mask is a.mask
assert "1" in a
assert "x" not in a
class ConstrainedDictTests(TestCase):
"""Tests that bad data can't sneak into ConstrainedDicts."""
def test_init_good_data(self):
"""ConstrainedDict should init OK if list matches constraint"""
self.assertEqual(
ConstrainedDict(dict.fromkeys("abc"), "abcd"), dict.fromkeys("abc")
)
self.assertEqual(ConstrainedDict("", "abcd"), dict(""))
items = [1, 2, 3.2234, tuple("xyz")]
# should accept anything dict() does if no constraint is passed
self.assertEqual(ConstrainedDict(dict.fromkeys(items)), dict.fromkeys(items))
self.assertEqual(
ConstrainedDict(dict.fromkeys(items), None), dict.fromkeys(items)
)
self.assertEqual(
ConstrainedDict([(x, 1) for x in "12345"]), dict.fromkeys("12345", 1)
)
# check that list is formatted correctly and chars are all there
test_dict = dict.fromkeys("12345")
self.assertEqual(ConstrainedDict(test_dict, "12345"), test_dict)
def test_init_sequence(self):
"""ConstrainedDict should init from sequence, unlike normal dict"""
self.assertEqual(ConstrainedDict("abcda"), {"a": 2, "b": 1, "c": 1, "d": 1})
def test_init_bad_data(self):
"""ConstrainedDict should fail init with items not in constraint"""
self.assertRaises(
ConstraintError, ConstrainedDict, dict.fromkeys("1234"), "123"
)
self.assertRaises(
ConstraintError, ConstrainedDict, dict.fromkeys([1, 2, 3]), ["1", "2", "3"]
)
def test_setitem(self):
"""ConstrainedDict setitem should work only if key in constraint"""
a = ConstrainedDict(dict.fromkeys("12"), "123")
a["1"] = "3"
self.assertEqual(a, {"1": "3", "2": None})
self.assertRaises(ConstraintError, a.__setitem__, 1, "3")
def test_copy(self):
"""ConstrainedDict copy should retain constraint"""
a = ConstrainedDict(dict.fromkeys("12"), "123")
b = a.copy()
self.assertEqual(a.constraint, b.constraint)
self.assertRaises(ConstraintError, a.__setitem__, 1, "3")
self.assertRaises(ConstraintError, b.__setitem__, 1, "3")
def test_fromkeys(self):
"""ConstrainedDict instance fromkeys should retain constraint"""
a = ConstrainedDict(dict.fromkeys("12"), "123")
b = a.fromkeys("23")
self.assertEqual(a.constraint, b.constraint)
self.assertRaises(ConstraintError, a.__setitem__, 1, "3")
self.assertRaises(ConstraintError, b.__setitem__, 1, "3")
b["2"] = 5
self.assertEqual(b, {"2": 5, "3": None})
def test_setdefault(self):
"""ConstrainedDict setdefault shouldn't allow bad keys"""
a = ConstrainedDict({"1": None, "2": "xyz"}, "123")
self.assertEqual(a.setdefault("2", None), "xyz")
self.assertEqual(a.setdefault("1", None), None)
self.assertRaises(ConstraintError, a.setdefault, "x", 3)
a.setdefault("3", 12345)
self.assertEqual(a, {"1": None, "2": "xyz", "3": 12345})
def test_update(self):
"""ConstrainedDict should allow update only of compliant data"""
a = ConstrainedDict(dict.fromkeys("123"), "12345")
b = ConstrainedDict(dict.fromkeys("444"), "4")
c = ConstrainedDict(dict.fromkeys("45"), "12345")
d = ConstrainedDict([["x", "y"]])
a.update(b)
self.assertEqual(a, dict.fromkeys("1234"))
a.update(c)
self.assertEqual(a, dict.fromkeys("12345"))
self.assertRaises(ConstraintError, b.update, c)
self.assertRaises(ConstraintError, c.update, d)
# should be OK if constraint removed
b.constraint = None
b.update(c)
self.assertEqual(b, dict.fromkeys("45"))
b.update(d)
self.assertEqual(b, {"4": None, "5": None, "x": "y"})
# should fail if we add the constraint back
b.constraint = {"4": 1, 5: 2, "5": 1, "x": 1}
self.assertRaises(ConstraintError, b.update, {4: 1})
b.update({5: 1})
self.assertEqual(b, {"4": None, "5": None, "x": "y", 5: 1})
def test_setitem_masks(self):
"""ConstrainedDict setitem should work only if key in constraint"""
key_mask = str
def val_mask(x):
return int(x) + 3
d = ConstrainedDict({1: 4, 2: 6}, "123", key_mask, val_mask)
d[1] = "456"
self.assertEqual(d, {"1": 459, "2": 9})
d["1"] = 234
self.assertEqual(d, {"1": 237, "2": 9})
self.assertRaises(ConstraintError, d.__setitem__, 4, "3")
e = d.copy()
assert e.mask is d.mask
assert "1" in d
assert not 1 in d
class MappedDictTests(TestCase):
"""MappedDict should work like ConstrainedDict, but map keys."""
def test_setitem_masks(self):
"""MappedDict setitem should work only if key in constraint"""
key_mask = str
def val_mask(x):
return int(x) + 3
d = MappedDict({1: 4, 2: 6}, "123", key_mask, val_mask)
d[1] = "456"
self.assertEqual(d, {"1": 459, "2": 9})
d["1"] = 234
self.assertEqual(d, {"1": 237, "2": 9})
self.assertRaises(ConstraintError, d.__setitem__, 4, "3")
e = d.copy()
assert e.mask is d.mask
assert "1" in d
assert 1 in d
assert 1 not in list(d.keys())
assert "x" not in list(d.keys())
def test_getitem(self):
"""MappedDict getitem should automatically map key."""
key_mask = str
d = MappedDict({}, "123", key_mask)
self.assertEqual(d, {})
d["1"] = 5
self.assertEqual(d, {"1": 5})
self.assertEqual(d[1], 5)
def test_get(self):
"""MappedDict get should automatically map key."""
key_mask = str
d = MappedDict({}, "123", key_mask)
self.assertEqual(d, {})
d["1"] = 5
self.assertEqual(d, {"1": 5})
self.assertEqual(d.get(1, "x"), 5)
self.assertEqual(d.get(5, "x"), "x")
def test_has_key(self):
"""MappedDict has_key should automatically map key."""
key_mask = str
d = MappedDict({}, "123", key_mask)
self.assertEqual(d, {})
d["1"] = 5
assert "1" in d
assert 1 in d
assert "5" not in d
def f():
"""This is a function docstring."""
pass
@extend_docstring_from(f)
def foo_append():
"""I am foo."""
pass
@extend_docstring_from(f)
def foo_mirror():
pass
@extend_docstring_from(f, pre=True)
def foo_prepend():
"""I am foo."""
pass
class ExtendDocstringTests(TestCase):
@extend_docstring_from(f)
def foo_append(self):
"""I am foo."""
pass
@extend_docstring_from(f)
def foo_mirror(self):
pass
@extend_docstring_from(f, pre=True)
def foo_prepend(self):
"""I am foo."""
pass
class TemplateClass:
"""This is a class docstring."""
pass
@extend_docstring_from(TemplateClass)
class FooAppend:
"""I am foo."""
pass
@extend_docstring_from(TemplateClass)
class FooMirror:
pass
@extend_docstring_from(TemplateClass, pre=True)
class FooPrepend:
"""I am foo."""
pass
def test_function_append(self):
self.assertEqual(foo_append.__doc__, "This is a function docstring.\nI am foo.")
def test_function_mirror(self):
self.assertEqual(foo_mirror.__doc__, "This is a function docstring.\n")
def test_function_prepend(self):
self.assertEqual(
foo_prepend.__doc__, "I am foo.\nThis is a function docstring."
)
def test_method_append(self):
self.assertEqual(
self.foo_append.__doc__, "This is a function docstring.\nI am foo."
)
def test_method_mirror(self):
self.assertEqual(self.foo_mirror.__doc__, "This is a function docstring.\n")
def test_method_prepend(self):
self.assertEqual(
self.foo_prepend.__doc__, "I am foo.\nThis is a function docstring."
)
def test_class_append(self):
self.assertEqual(
self.FooAppend.__doc__, "This is a class docstring.\nI am foo."
)
def test_class_mirror(self):
self.assertEqual(self.FooMirror.__doc__, "This is a class docstring.\n")
def test_class_prepend(self):
self.assertEqual(
self.FooPrepend.__doc__, "I am foo.\nThis is a class docstring."
)
def test_not_in_jupyter():
from cogent3.util.misc import in_jupyter
assert not in_jupyter()
def test_is_in_jupyter():
# an ugly hack, the in_jupyter function relies entirely on whether a
# get_ipython variable exists in the name space
import cogent3.util.misc as module
from cogent3.util.misc import in_jupyter
module.get_ipython = lambda x: x
assert in_jupyter()
del module.get_ipython
def foo1():
"""some text"""
def foo2():
"""some text
Notes
-----
body
"""
def foo3():
"""
Notes
-----
body
"""
def foo4(): ...
_sum_expect = "some text"
_body_expect = ["Notes", "-----", "body"]
@pytest.mark.parametrize(
"foo,sum_exp,body_exp",
(
(foo1, _sum_expect, []),
(foo2, _sum_expect, _body_expect),
(foo3, "", _body_expect),
(foo4, "", []),
),
)
def test_docstring_to_summary_rest(foo, sum_exp, body_exp):
summary, body = docstring_to_summary_rest(foo.__doc__)
assert summary == sum_exp and body.split() == body_exp
def test_get_true_spans_absolute():
got = get_true_spans(array([0, 1, 1, 0, 1]))
assert_allclose(got, array([[1, 2], [4, 1]]))
got = get_true_spans(array([0, 0]))
assert not len(got)
got = get_true_spans(array([0, 0, 1, 1]))
assert_allclose(got, array([[2, 2]]))
got = get_true_spans(array([1, 0, 0, 1, 1]))
assert_allclose(got, array([[0, 1], [3, 2]]))
got = get_true_spans(array([1, 0, 0, 1, 1, 1, 1, 0, 1, 1]))
assert_allclose(got, array([[0, 1], [3, 4], [8, 2]]))
got = get_true_spans(
# abs 0 1 2 3 4 5 6 7 8 9
array([1, 0, 0, 1, 1, 1, 1, 0, 1, 1]),
absolute_pos=False,
# u 0 1 2
)
assert_allclose(got, array([[0, 1], [2, 4], [3, 2]]))
got = get_true_spans(array([0, 0, 0, 1, 1, 1, 0, 0]))
assert_allclose(got, array([(3, 3)]))
def test_get_true_spans_not_absolute():
got = get_true_spans(array([0, 1, 1, 0, 1]), absolute_pos=False)
assert_allclose(got, array([[1, 2], [2, 1]]))
got = get_true_spans(array([1, 0, 0, 1, 1, 1, 1, 0, 1, 1]), absolute_pos=False)
assert_allclose(got, array([[0, 1], [2, 4], [3, 2]]))
|