File size: 58,418 Bytes
1856027 | 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 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 | # Copyright 2015 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import base64
import datetime
import decimal
import json
import os
import warnings
import pytest
import packaging
import unittest
from unittest import mock
import google.api_core
@pytest.mark.skipif(
packaging.version.parse(getattr(google.api_core, "__version__", "0.0.0"))
< packaging.version.Version("2.15.0"),
reason="universe_domain not supported with google-api-core < 2.15.0",
)
class Test_get_client_universe(unittest.TestCase):
def test_with_none(self):
from google.cloud.bigquery._helpers import _get_client_universe
self.assertEqual("googleapis.com", _get_client_universe(None))
def test_with_dict(self):
from google.cloud.bigquery._helpers import _get_client_universe
options = {"universe_domain": "foo.com"}
self.assertEqual("foo.com", _get_client_universe(options))
def test_with_dict_empty(self):
from google.cloud.bigquery._helpers import _get_client_universe
options = {"universe_domain": ""}
self.assertEqual("googleapis.com", _get_client_universe(options))
def test_with_client_options(self):
from google.cloud.bigquery._helpers import _get_client_universe
from google.api_core import client_options
options = client_options.from_dict({"universe_domain": "foo.com"})
self.assertEqual("foo.com", _get_client_universe(options))
@mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"})
def test_with_environ(self):
from google.cloud.bigquery._helpers import _get_client_universe
self.assertEqual("foo.com", _get_client_universe(None))
@mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"})
def test_with_environ_and_dict(self):
from google.cloud.bigquery._helpers import _get_client_universe
options = ({"credentials_file": "file.json"},)
self.assertEqual("foo.com", _get_client_universe(options))
@mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"})
def test_with_environ_and_empty_options(self):
from google.cloud.bigquery._helpers import _get_client_universe
from google.api_core import client_options
options = client_options.from_dict({})
self.assertEqual("foo.com", _get_client_universe(options))
@mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": ""})
def test_with_environ_empty(self):
from google.cloud.bigquery._helpers import _get_client_universe
self.assertEqual("googleapis.com", _get_client_universe(None))
class Test_validate_universe(unittest.TestCase):
def test_with_none(self):
from google.cloud.bigquery._helpers import _validate_universe
# should not raise
_validate_universe("googleapis.com", None)
def test_with_no_universe_creds(self):
from google.cloud.bigquery._helpers import _validate_universe
from .helpers import make_creds
creds = make_creds(None)
# should not raise
_validate_universe("googleapis.com", creds)
def test_with_matched_universe_creds(self):
from google.cloud.bigquery._helpers import _validate_universe
from .helpers import make_creds
creds = make_creds("googleapis.com")
# should not raise
_validate_universe("googleapis.com", creds)
def test_with_mismatched_universe_creds(self):
from google.cloud.bigquery._helpers import _validate_universe
from .helpers import make_creds
creds = make_creds("foo.com")
with self.assertRaises(ValueError):
_validate_universe("googleapis.com", creds)
class Test_not_null(unittest.TestCase):
def _call_fut(self, value, field):
from google.cloud.bigquery._helpers import _not_null
return _not_null(value, field)
def test_w_none_nullable(self):
self.assertFalse(self._call_fut(None, _Field("NULLABLE")))
def test_w_none_required(self):
self.assertTrue(self._call_fut(None, _Field("REQUIRED")))
def test_w_value(self):
self.assertTrue(self._call_fut(object(), object()))
class Test_int_from_json(unittest.TestCase):
def _call_fut(self, value, field):
from google.cloud.bigquery._helpers import _int_from_json
return _int_from_json(value, field)
def test_w_none_nullable(self):
self.assertIsNone(self._call_fut(None, _Field("NULLABLE")))
def test_w_none_required(self):
with self.assertRaises(TypeError):
self._call_fut(None, _Field("REQUIRED"))
def test_w_string_value(self):
coerced = self._call_fut("42", object())
self.assertEqual(coerced, 42)
def test_w_float_value(self):
coerced = self._call_fut(42, object())
self.assertEqual(coerced, 42)
class Test_json_from_json(unittest.TestCase):
def _call_fut(self, value, field):
from google.cloud.bigquery._helpers import _json_from_json
return _json_from_json(value, field)
def test_w_none_nullable(self):
self.assertIsNone(self._call_fut(None, _Field("NULLABLE")))
def test_w_none_required(self):
with self.assertRaises(TypeError):
self._call_fut(None, _Field("REQUIRED"))
def test_w_json_field(self):
data_field = _Field("REQUIRED", "data", "JSON")
value = json.dumps(
{"v": {"key": "value"}},
)
expected_output = {"v": {"key": "value"}}
coerced_output = self._call_fut(value, data_field)
self.assertEqual(coerced_output, expected_output)
def test_w_string_value(self):
coerced = self._call_fut('"foo"', object())
self.assertEqual(coerced, "foo")
class Test_float_from_json(unittest.TestCase):
def _call_fut(self, value, field):
from google.cloud.bigquery._helpers import _float_from_json
return _float_from_json(value, field)
def test_w_none_nullable(self):
self.assertIsNone(self._call_fut(None, _Field("NULLABLE")))
def test_w_none_required(self):
with self.assertRaises(TypeError):
self._call_fut(None, _Field("REQUIRED"))
def test_w_string_value(self):
coerced = self._call_fut("3.1415", object())
self.assertEqual(coerced, 3.1415)
def test_w_float_value(self):
coerced = self._call_fut(3.1415, object())
self.assertEqual(coerced, 3.1415)
class Test_decimal_from_json(unittest.TestCase):
def _call_fut(self, value, field):
from google.cloud.bigquery._helpers import _decimal_from_json
return _decimal_from_json(value, field)
def test_w_none_nullable(self):
self.assertIsNone(self._call_fut(None, _Field("NULLABLE")))
def test_w_none_required(self):
with self.assertRaises(TypeError):
self._call_fut(None, _Field("REQUIRED"))
def test_w_string_value(self):
coerced = self._call_fut("3.1415", object())
self.assertEqual(coerced, decimal.Decimal("3.1415"))
def test_w_float_value(self):
coerced = self._call_fut(3.1415, object())
# There is no exact float representation of 3.1415.
self.assertEqual(coerced, decimal.Decimal(3.1415))
class Test_bool_from_json(unittest.TestCase):
def _call_fut(self, value, field):
from google.cloud.bigquery._helpers import _bool_from_json
return _bool_from_json(value, field)
def test_w_none_nullable(self):
self.assertIsNone(self._call_fut(None, _Field("NULLABLE")))
def test_w_none_required(self):
with self.assertRaises(AttributeError):
self._call_fut(None, _Field("REQUIRED"))
def test_w_value_t(self):
coerced = self._call_fut("T", object())
self.assertTrue(coerced)
def test_w_value_true(self):
coerced = self._call_fut("True", object())
self.assertTrue(coerced)
def test_w_value_1(self):
coerced = self._call_fut("1", object())
self.assertTrue(coerced)
def test_w_value_other(self):
coerced = self._call_fut("f", object())
self.assertFalse(coerced)
class Test_string_from_json(unittest.TestCase):
def _call_fut(self, value, field):
from google.cloud.bigquery._helpers import _string_from_json
return _string_from_json(value, field)
def test_w_none_nullable(self):
self.assertIsNone(self._call_fut(None, _Field("NULLABLE")))
def test_w_none_required(self):
self.assertIsNone(self._call_fut(None, _Field("REQUIRED")))
def test_w_string_value(self):
coerced = self._call_fut("Wonderful!", object())
self.assertEqual(coerced, "Wonderful!")
class Test_bytes_from_json(unittest.TestCase):
def _call_fut(self, value, field):
from google.cloud.bigquery._helpers import _bytes_from_json
return _bytes_from_json(value, field)
def test_w_none_nullable(self):
self.assertIsNone(self._call_fut(None, _Field("NULLABLE")))
def test_w_none_required(self):
with self.assertRaises(TypeError):
self._call_fut(None, _Field("REQUIRED"))
def test_w_base64_encoded_bytes(self):
expected = b"Wonderful!"
encoded = base64.standard_b64encode(expected)
coerced = self._call_fut(encoded, object())
self.assertEqual(coerced, expected)
def test_w_base64_encoded_text(self):
expected = b"Wonderful!"
encoded = base64.standard_b64encode(expected).decode("ascii")
coerced = self._call_fut(encoded, object())
self.assertEqual(coerced, expected)
class Test_timestamp_from_json(unittest.TestCase):
def _call_fut(self, value, field):
from google.cloud.bigquery._helpers import _timestamp_from_json
return _timestamp_from_json(value, field)
def test_w_none_nullable(self):
self.assertIsNone(self._call_fut(None, _Field("NULLABLE")))
def test_w_none_required(self):
with self.assertRaises(TypeError):
self._call_fut(None, _Field("REQUIRED"))
def test_w_string_int_value(self):
from google.cloud._helpers import _EPOCH
coerced = self._call_fut("1234567", object())
self.assertEqual(
coerced, _EPOCH + datetime.timedelta(seconds=1, microseconds=234567)
)
def test_w_int_value(self):
from google.cloud._helpers import _EPOCH
coerced = self._call_fut(1234567, object())
self.assertEqual(
coerced, _EPOCH + datetime.timedelta(seconds=1, microseconds=234567)
)
class Test_timestamp_query_param_from_json(unittest.TestCase):
def _call_fut(self, value, field):
from google.cloud.bigquery import _helpers
return _helpers._timestamp_query_param_from_json(value, field)
def test_w_none_nullable(self):
self.assertIsNone(self._call_fut(None, _Field("NULLABLE")))
def test_w_timestamp_valid(self):
from google.cloud._helpers import UTC
samples = [
(
"2016-12-20 15:58:27.339328+00:00",
datetime.datetime(2016, 12, 20, 15, 58, 27, 339328, tzinfo=UTC),
),
(
"2016-12-20 15:58:27+00:00",
datetime.datetime(2016, 12, 20, 15, 58, 27, tzinfo=UTC),
),
(
"2016-12-20T15:58:27.339328+00:00",
datetime.datetime(2016, 12, 20, 15, 58, 27, 339328, tzinfo=UTC),
),
(
"2016-12-20T15:58:27+00:00",
datetime.datetime(2016, 12, 20, 15, 58, 27, tzinfo=UTC),
),
(
"2016-12-20 15:58:27.339328Z",
datetime.datetime(2016, 12, 20, 15, 58, 27, 339328, tzinfo=UTC),
),
(
"2016-12-20 15:58:27Z",
datetime.datetime(2016, 12, 20, 15, 58, 27, tzinfo=UTC),
),
(
"2016-12-20T15:58:27.339328Z",
datetime.datetime(2016, 12, 20, 15, 58, 27, 339328, tzinfo=UTC),
),
(
"2016-12-20T15:58:27Z",
datetime.datetime(2016, 12, 20, 15, 58, 27, tzinfo=UTC),
),
]
for timestamp_str, expected_result in samples:
self.assertEqual(
self._call_fut(timestamp_str, _Field("NULLABLE")), expected_result
)
def test_w_timestamp_invalid(self):
with self.assertRaises(ValueError):
self._call_fut("definitely-not-a-timestamp", _Field("NULLABLE"))
class Test_datetime_from_json(unittest.TestCase):
def _call_fut(self, value, field):
from google.cloud.bigquery._helpers import _datetime_from_json
return _datetime_from_json(value, field)
def test_w_none_nullable(self):
self.assertIsNone(self._call_fut(None, _Field("NULLABLE")))
def test_w_none_required(self):
with self.assertRaises(TypeError):
self._call_fut(None, _Field("REQUIRED"))
def test_w_string_value(self):
coerced = self._call_fut("2016-12-02T18:51:33", object())
self.assertEqual(coerced, datetime.datetime(2016, 12, 2, 18, 51, 33))
def test_w_microseconds(self):
coerced = self._call_fut("2015-05-22T10:11:12.987654", object())
self.assertEqual(coerced, datetime.datetime(2015, 5, 22, 10, 11, 12, 987654))
class Test_date_from_json(unittest.TestCase):
def _call_fut(self, value, field):
from google.cloud.bigquery._helpers import _date_from_json
return _date_from_json(value, field)
def test_w_none_nullable(self):
self.assertIsNone(self._call_fut(None, _Field("NULLABLE")))
def test_w_none_required(self):
with self.assertRaises(TypeError):
self._call_fut(None, _Field("REQUIRED"))
def test_w_string_value(self):
coerced = self._call_fut("1987-09-22", object())
self.assertEqual(coerced, datetime.date(1987, 9, 22))
class Test_time_from_json(unittest.TestCase):
def _call_fut(self, value, field):
from google.cloud.bigquery._helpers import _time_from_json
return _time_from_json(value, field)
def test_w_none_nullable(self):
self.assertIsNone(self._call_fut(None, _Field("NULLABLE")))
def test_w_none_required(self):
with self.assertRaises(TypeError):
self._call_fut(None, _Field("REQUIRED"))
def test_w_string_value(self):
coerced = self._call_fut("12:12:27", object())
self.assertEqual(coerced, datetime.time(12, 12, 27))
def test_w_subsecond_string_value(self):
coerced = self._call_fut("12:12:27.123456", object())
self.assertEqual(coerced, datetime.time(12, 12, 27, 123456))
def test_w_bogus_string_value(self):
with self.assertRaises(ValueError):
self._call_fut("12:12:27.123", object())
class Test_range_from_json(unittest.TestCase):
def _call_fut(self, value, field):
from google.cloud.bigquery._helpers import _range_from_json
return _range_from_json(value, field)
def test_w_none_nullable(self):
self.assertIsNone(self._call_fut(None, _Field("NULLABLE")))
def test_w_none_required(self):
with self.assertRaises(TypeError):
self._call_fut(None, _Field("REQUIRED"))
def test_w_wrong_format(self):
range_field = _Field(
"NULLABLE",
field_type="RANGE",
range_element_type=_Field("NULLABLE", element_type="DATE"),
)
with self.assertRaises(ValueError):
self._call_fut("[2009-06-172019-06-17)", range_field)
def test_w_wrong_element_type(self):
range_field = _Field(
"NULLABLE",
field_type="RANGE",
range_element_type=_Field("NULLABLE", element_type="TIME"),
)
with self.assertRaises(ValueError):
self._call_fut("[15:31:38, 15:50:38)", range_field)
def test_w_unbounded_value(self):
range_field = _Field(
"NULLABLE",
field_type="RANGE",
range_element_type=_Field("NULLABLE", element_type="DATE"),
)
coerced = self._call_fut("[UNBOUNDED, 2019-06-17)", range_field)
self.assertEqual(
coerced,
{"start": None, "end": datetime.date(2019, 6, 17)},
)
def test_w_date_value(self):
range_field = _Field(
"NULLABLE",
field_type="RANGE",
range_element_type=_Field("NULLABLE", element_type="DATE"),
)
coerced = self._call_fut("[2009-06-17, 2019-06-17)", range_field)
self.assertEqual(
coerced,
{
"start": datetime.date(2009, 6, 17),
"end": datetime.date(2019, 6, 17),
},
)
def test_w_datetime_value(self):
range_field = _Field(
"NULLABLE",
field_type="RANGE",
range_element_type=_Field("NULLABLE", element_type="DATETIME"),
)
coerced = self._call_fut(
"[2009-06-17T13:45:30, 2019-06-17T13:45:30)", range_field
)
self.assertEqual(
coerced,
{
"start": datetime.datetime(2009, 6, 17, 13, 45, 30),
"end": datetime.datetime(2019, 6, 17, 13, 45, 30),
},
)
def test_w_timestamp_value(self):
from google.cloud._helpers import _EPOCH
range_field = _Field(
"NULLABLE",
field_type="RANGE",
range_element_type=_Field("NULLABLE", element_type="TIMESTAMP"),
)
coerced = self._call_fut("[1234567, 1234789)", range_field)
self.assertEqual(
coerced,
{
"start": _EPOCH + datetime.timedelta(seconds=1, microseconds=234567),
"end": _EPOCH + datetime.timedelta(seconds=1, microseconds=234789),
},
)
class Test_record_from_json(unittest.TestCase):
def _call_fut(self, value, field):
from google.cloud.bigquery._helpers import _record_from_json
return _record_from_json(value, field)
def test_w_none_nullable(self):
self.assertIsNone(self._call_fut(None, _Field("NULLABLE")))
def test_w_none_required(self):
with self.assertRaises(TypeError):
self._call_fut(None, _Field("REQUIRED"))
def test_w_nullable_subfield_none(self):
subfield = _Field("NULLABLE", "age", "INTEGER")
field = _Field("REQUIRED", fields=[subfield])
value = {"f": [{"v": None}]}
coerced = self._call_fut(value, field)
self.assertEqual(coerced, {"age": None})
def test_w_scalar_subfield(self):
subfield = _Field("REQUIRED", "age", "INTEGER")
field = _Field("REQUIRED", fields=[subfield])
value = {"f": [{"v": 42}]}
coerced = self._call_fut(value, field)
self.assertEqual(coerced, {"age": 42})
def test_w_scalar_subfield_geography(self):
subfield = _Field("REQUIRED", "geo", "GEOGRAPHY")
field = _Field("REQUIRED", fields=[subfield])
value = {"f": [{"v": "POINT(1, 2)"}]}
coerced = self._call_fut(value, field)
self.assertEqual(coerced, {"geo": "POINT(1, 2)"})
def test_w_repeated_subfield(self):
subfield = _Field("REPEATED", "color", "STRING")
field = _Field("REQUIRED", fields=[subfield])
value = {"f": [{"v": [{"v": "red"}, {"v": "yellow"}, {"v": "blue"}]}]}
coerced = self._call_fut(value, field)
self.assertEqual(coerced, {"color": ["red", "yellow", "blue"]})
def test_w_record_subfield(self):
full_name = _Field("REQUIRED", "full_name", "STRING")
area_code = _Field("REQUIRED", "area_code", "STRING")
local_number = _Field("REQUIRED", "local_number", "STRING")
rank = _Field("REQUIRED", "rank", "INTEGER")
phone = _Field(
"NULLABLE", "phone", "RECORD", fields=[area_code, local_number, rank]
)
person = _Field("REQUIRED", "person", "RECORD", fields=[full_name, phone])
value = {
"f": [
{"v": "Phred Phlyntstone"},
{"v": {"f": [{"v": "800"}, {"v": "555-1212"}, {"v": 1}]}},
]
}
expected = {
"full_name": "Phred Phlyntstone",
"phone": {"area_code": "800", "local_number": "555-1212", "rank": 1},
}
coerced = self._call_fut(value, person)
self.assertEqual(coerced, expected)
class Test_field_to_index_mapping(unittest.TestCase):
def _call_fut(self, schema):
from google.cloud.bigquery._helpers import _field_to_index_mapping
return _field_to_index_mapping(schema)
def test_w_empty_schema(self):
self.assertEqual(self._call_fut([]), {})
def test_w_non_empty_schema(self):
schema = [
_Field("REPEATED", "first", "INTEGER"),
_Field("REQUIRED", "second", "INTEGER"),
_Field("REPEATED", "third", "INTEGER"),
]
self.assertEqual(self._call_fut(schema), {"first": 0, "second": 1, "third": 2})
class Test_row_tuple_from_json(unittest.TestCase):
def _call_fut(self, row, schema):
from google.cloud.bigquery._helpers import _row_tuple_from_json
with _field_isinstance_patcher():
return _row_tuple_from_json(row, schema)
def test_w_single_scalar_column(self):
# SELECT 1 AS col
col = _Field("REQUIRED", "col", "INTEGER")
row = {"f": [{"v": "1"}]}
self.assertEqual(self._call_fut(row, schema=[col]), (1,))
def test_w_unknown_type(self):
# SELECT 1 AS col
col = _Field("REQUIRED", "col", "UNKNOWN")
row = {"f": [{"v": "1"}]}
with warnings.catch_warnings(record=True) as warned:
self.assertEqual(self._call_fut(row, schema=[col]), ("1",))
self.assertEqual(len(warned), 1)
warning = warned[0]
self.assertTrue("UNKNOWN" in str(warning))
self.assertTrue("col" in str(warning))
def test_w_single_scalar_geography_column(self):
# SELECT 1 AS col
col = _Field("REQUIRED", "geo", "GEOGRAPHY")
row = {"f": [{"v": "POINT(1, 2)"}]}
self.assertEqual(self._call_fut(row, schema=[col]), ("POINT(1, 2)",))
def test_w_single_struct_column(self):
# SELECT (1, 2) AS col
sub_1 = _Field("REQUIRED", "sub_1", "INTEGER")
sub_2 = _Field("REQUIRED", "sub_2", "INTEGER")
col = _Field("REQUIRED", "col", "RECORD", fields=[sub_1, sub_2])
row = {"f": [{"v": {"f": [{"v": "1"}, {"v": "2"}]}}]}
self.assertEqual(self._call_fut(row, schema=[col]), ({"sub_1": 1, "sub_2": 2},))
def test_w_single_array_column(self):
# SELECT [1, 2, 3] as col
col = _Field("REPEATED", "col", "INTEGER")
row = {"f": [{"v": [{"v": "1"}, {"v": "2"}, {"v": "3"}]}]}
self.assertEqual(self._call_fut(row, schema=[col]), ([1, 2, 3],))
def test_w_unknown_type_repeated(self):
# SELECT 1 AS col
col = _Field("REPEATED", "col", "UNKNOWN")
row = {"f": [{"v": [{"v": "1"}, {"v": "2"}, {"v": "3"}]}]}
with warnings.catch_warnings(record=True) as warned:
self.assertEqual(self._call_fut(row, schema=[col]), (["1", "2", "3"],))
self.assertEqual(len(warned), 1)
warning = warned[0]
self.assertTrue("UNKNOWN" in str(warning))
self.assertTrue("col" in str(warning))
def test_w_struct_w_nested_array_column(self):
# SELECT ([1, 2], 3, [4, 5]) as col
first = _Field("REPEATED", "first", "INTEGER")
second = _Field("REQUIRED", "second", "INTEGER")
third = _Field("REPEATED", "third", "INTEGER")
col = _Field("REQUIRED", "col", "RECORD", fields=[first, second, third])
row = {
"f": [
{
"v": {
"f": [
{"v": [{"v": "1"}, {"v": "2"}]},
{"v": "3"},
{"v": [{"v": "4"}, {"v": "5"}]},
]
}
}
]
}
self.assertEqual(
self._call_fut(row, schema=[col]),
({"first": [1, 2], "second": 3, "third": [4, 5]},),
)
def test_w_unknown_type_subfield(self):
# SELECT [(1, 2, 3), (4, 5, 6)] as col
first = _Field("REPEATED", "first", "UNKNOWN1")
second = _Field("REQUIRED", "second", "UNKNOWN2")
third = _Field("REPEATED", "third", "INTEGER")
col = _Field("REQUIRED", "col", "RECORD", fields=[first, second, third])
row = {
"f": [
{
"v": {
"f": [
{"v": [{"v": "1"}, {"v": "2"}]},
{"v": "3"},
{"v": [{"v": "4"}, {"v": "5"}]},
]
}
}
]
}
with warnings.catch_warnings(record=True) as warned:
self.assertEqual(
self._call_fut(row, schema=[col]),
({"first": ["1", "2"], "second": "3", "third": [4, 5]},),
)
self.assertEqual(len(warned), 2) # 1 warning per unknown field.
warned = [str(warning) for warning in warned]
self.assertTrue(
any(["first" in warning and "UNKNOWN1" in warning for warning in warned])
)
self.assertTrue(
any(["second" in warning and "UNKNOWN2" in warning for warning in warned])
)
def test_w_array_of_struct(self):
# SELECT [(1, 2, 3), (4, 5, 6)] as col
first = _Field("REQUIRED", "first", "INTEGER")
second = _Field("REQUIRED", "second", "INTEGER")
third = _Field("REQUIRED", "third", "INTEGER")
col = _Field("REPEATED", "col", "RECORD", fields=[first, second, third])
row = {
"f": [
{
"v": [
{"v": {"f": [{"v": "1"}, {"v": "2"}, {"v": "3"}]}},
{"v": {"f": [{"v": "4"}, {"v": "5"}, {"v": "6"}]}},
]
}
]
}
self.assertEqual(
self._call_fut(row, schema=[col]),
(
[
{"first": 1, "second": 2, "third": 3},
{"first": 4, "second": 5, "third": 6},
],
),
)
def test_w_array_of_struct_w_array(self):
# SELECT [([1, 2, 3], 4), ([5, 6], 7)]
first = _Field("REPEATED", "first", "INTEGER")
second = _Field("REQUIRED", "second", "INTEGER")
col = _Field("REPEATED", "col", "RECORD", fields=[first, second])
row = {
"f": [
{
"v": [
{
"v": {
"f": [
{"v": [{"v": "1"}, {"v": "2"}, {"v": "3"}]},
{"v": "4"},
]
}
},
{"v": {"f": [{"v": [{"v": "5"}, {"v": "6"}]}, {"v": "7"}]}},
]
}
]
}
self.assertEqual(
self._call_fut(row, schema=[col]),
([{"first": [1, 2, 3], "second": 4}, {"first": [5, 6], "second": 7}],),
)
class Test_rows_from_json(unittest.TestCase):
def _call_fut(self, rows, schema):
from google.cloud.bigquery._helpers import _rows_from_json
with _field_isinstance_patcher():
return _rows_from_json(rows, schema)
def test_w_record_subfield(self):
from google.cloud.bigquery.table import Row
full_name = _Field("REQUIRED", "full_name", "STRING")
area_code = _Field("REQUIRED", "area_code", "STRING")
local_number = _Field("REQUIRED", "local_number", "STRING")
rank = _Field("REQUIRED", "rank", "INTEGER")
phone = _Field(
"NULLABLE", "phone", "RECORD", fields=[area_code, local_number, rank]
)
color = _Field("REPEATED", "color", "STRING")
schema = [full_name, phone, color]
rows = [
{
"f": [
{"v": "Phred Phlyntstone"},
{"v": {"f": [{"v": "800"}, {"v": "555-1212"}, {"v": 1}]}},
{"v": [{"v": "orange"}, {"v": "black"}]},
]
},
{
"f": [
{"v": "Bharney Rhubble"},
{"v": {"f": [{"v": "877"}, {"v": "768-5309"}, {"v": 2}]}},
{"v": [{"v": "brown"}]},
]
},
{"f": [{"v": "Wylma Phlyntstone"}, {"v": None}, {"v": []}]},
]
phred_phone = {"area_code": "800", "local_number": "555-1212", "rank": 1}
bharney_phone = {"area_code": "877", "local_number": "768-5309", "rank": 2}
f2i = {"full_name": 0, "phone": 1, "color": 2}
expected = [
Row(("Phred Phlyntstone", phred_phone, ["orange", "black"]), f2i),
Row(("Bharney Rhubble", bharney_phone, ["brown"]), f2i),
Row(("Wylma Phlyntstone", None, []), f2i),
]
coerced = self._call_fut(rows, schema)
self.assertEqual(coerced, expected)
def test_w_int64_float64_bool(self):
from google.cloud.bigquery.table import Row
# "Standard" SQL dialect uses 'INT64', 'FLOAT64', 'BOOL'.
candidate = _Field("REQUIRED", "candidate", "STRING")
votes = _Field("REQUIRED", "votes", "INT64")
percentage = _Field("REQUIRED", "percentage", "FLOAT64")
incumbent = _Field("REQUIRED", "incumbent", "BOOL")
schema = [candidate, votes, percentage, incumbent]
rows = [
{"f": [{"v": "Phred Phlyntstone"}, {"v": 8}, {"v": 0.25}, {"v": "true"}]},
{"f": [{"v": "Bharney Rhubble"}, {"v": 4}, {"v": 0.125}, {"v": "false"}]},
{
"f": [
{"v": "Wylma Phlyntstone"},
{"v": 20},
{"v": 0.625},
{"v": "false"},
]
},
]
f2i = {"candidate": 0, "votes": 1, "percentage": 2, "incumbent": 3}
expected = [
Row(("Phred Phlyntstone", 8, 0.25, True), f2i),
Row(("Bharney Rhubble", 4, 0.125, False), f2i),
Row(("Wylma Phlyntstone", 20, 0.625, False), f2i),
]
coerced = self._call_fut(rows, schema)
self.assertEqual(coerced, expected)
class Test_int_to_json(unittest.TestCase):
def _call_fut(self, value):
from google.cloud.bigquery._helpers import _int_to_json
return _int_to_json(value)
def test_w_int(self):
self.assertEqual(self._call_fut(123), "123")
def test_w_string(self):
self.assertEqual(self._call_fut("123"), "123")
class Test_float_to_json(unittest.TestCase):
def _call_fut(self, value):
from google.cloud.bigquery._helpers import _float_to_json
return _float_to_json(value)
def test_w_none(self):
self.assertEqual(self._call_fut(None), None)
def test_w_non_numeric(self):
with self.assertRaises(TypeError):
self._call_fut(object())
def test_w_integer(self):
result = self._call_fut(123)
self.assertIsInstance(result, float)
self.assertEqual(result, 123.0)
def test_w_float(self):
self.assertEqual(self._call_fut(1.23), 1.23)
def test_w_float_as_string(self):
self.assertEqual(self._call_fut("1.23"), 1.23)
def test_w_nan(self):
result = self._call_fut(float("nan"))
self.assertEqual(result.lower(), "nan")
def test_w_nan_as_string(self):
result = self._call_fut("NaN")
self.assertEqual(result.lower(), "nan")
def test_w_infinity(self):
result = self._call_fut(float("inf"))
self.assertEqual(result.lower(), "inf")
def test_w_infinity_as_string(self):
result = self._call_fut("inf")
self.assertEqual(result.lower(), "inf")
def test_w_negative_infinity(self):
result = self._call_fut(float("-inf"))
self.assertEqual(result.lower(), "-inf")
def test_w_negative_infinity_as_string(self):
result = self._call_fut("-inf")
self.assertEqual(result.lower(), "-inf")
class Test_decimal_to_json(unittest.TestCase):
def _call_fut(self, value):
from google.cloud.bigquery._helpers import _decimal_to_json
return _decimal_to_json(value)
def test_w_float(self):
self.assertEqual(self._call_fut(1.23), 1.23)
def test_w_string(self):
self.assertEqual(self._call_fut("1.23"), "1.23")
def test_w_decimal(self):
self.assertEqual(self._call_fut(decimal.Decimal("1.23")), "1.23")
class Test_bool_to_json(unittest.TestCase):
def _call_fut(self, value):
from google.cloud.bigquery._helpers import _bool_to_json
return _bool_to_json(value)
def test_w_true(self):
self.assertEqual(self._call_fut(True), "true")
def test_w_false(self):
self.assertEqual(self._call_fut(False), "false")
def test_w_string(self):
self.assertEqual(self._call_fut("false"), "false")
class Test_bytes_to_json(unittest.TestCase):
def _call_fut(self, value):
from google.cloud.bigquery._helpers import _bytes_to_json
return _bytes_to_json(value)
def test_w_non_bytes(self):
non_bytes = object()
self.assertIs(self._call_fut(non_bytes), non_bytes)
def test_w_bytes(self):
source = b"source"
expected = "c291cmNl"
converted = self._call_fut(source)
self.assertEqual(converted, expected)
class Test_timestamp_to_json_parameter(unittest.TestCase):
def _call_fut(self, value):
from google.cloud.bigquery._helpers import _timestamp_to_json_parameter
return _timestamp_to_json_parameter(value)
def test_w_float(self):
self.assertEqual(self._call_fut(1.234567), 1.234567)
def test_w_string(self):
ZULU = "2016-12-20 15:58:27.339328+00:00"
self.assertEqual(self._call_fut(ZULU), ZULU)
def test_w_datetime_wo_zone(self):
ZULU = "2016-12-20 15:58:27.339328+00:00"
when = datetime.datetime(2016, 12, 20, 15, 58, 27, 339328)
self.assertEqual(self._call_fut(when), ZULU)
def test_w_datetime_w_non_utc_zone(self):
class _Zone(datetime.tzinfo):
def utcoffset(self, _):
return datetime.timedelta(minutes=-240)
ZULU = "2016-12-20 19:58:27.339328+00:00"
when = datetime.datetime(2016, 12, 20, 15, 58, 27, 339328, tzinfo=_Zone())
self.assertEqual(self._call_fut(when), ZULU)
def test_w_datetime_w_utc_zone(self):
from google.cloud._helpers import UTC
ZULU = "2016-12-20 15:58:27.339328+00:00"
when = datetime.datetime(2016, 12, 20, 15, 58, 27, 339328, tzinfo=UTC)
self.assertEqual(self._call_fut(when), ZULU)
class Test_timestamp_to_json_row(unittest.TestCase):
def _call_fut(self, value):
from google.cloud.bigquery._helpers import _timestamp_to_json_row
return _timestamp_to_json_row(value)
def test_w_float(self):
self.assertEqual(self._call_fut(1.234567), 1.234567)
def test_w_string(self):
ZULU = "2016-12-20 15:58:27.339328+00:00"
self.assertEqual(self._call_fut(ZULU), ZULU)
def test_w_datetime_no_zone(self):
when = datetime.datetime(2016, 12, 20, 15, 58, 27, 339328)
self.assertEqual(self._call_fut(when), "2016-12-20T15:58:27.339328Z")
def test_w_datetime_w_utc_zone(self):
from google.cloud._helpers import UTC
when = datetime.datetime(2020, 11, 17, 1, 6, 52, 353795, tzinfo=UTC)
self.assertEqual(self._call_fut(when), "2020-11-17T01:06:52.353795Z")
def test_w_datetime_w_non_utc_zone(self):
class EstZone(datetime.tzinfo):
def utcoffset(self, _):
return datetime.timedelta(minutes=-300)
when = datetime.datetime(2020, 11, 17, 1, 6, 52, 353795, tzinfo=EstZone())
self.assertEqual(self._call_fut(when), "2020-11-17T06:06:52.353795Z")
class Test_datetime_to_json(unittest.TestCase):
def _call_fut(self, value):
from google.cloud.bigquery._helpers import _datetime_to_json
return _datetime_to_json(value)
def test_w_string(self):
RFC3339 = "2016-12-03T14:14:51Z"
self.assertEqual(self._call_fut(RFC3339), RFC3339)
def test_w_datetime(self):
from google.cloud._helpers import UTC
when = datetime.datetime(2016, 12, 3, 14, 11, 27, 123456, tzinfo=UTC)
self.assertEqual(self._call_fut(when), "2016-12-03T14:11:27.123456")
def test_w_datetime_w_non_utc_zone(self):
class EstZone(datetime.tzinfo):
def utcoffset(self, _):
return datetime.timedelta(minutes=-300)
when = datetime.datetime(2016, 12, 3, 14, 11, 27, 123456, tzinfo=EstZone())
self.assertEqual(self._call_fut(when), "2016-12-03T19:11:27.123456")
class Test_date_to_json(unittest.TestCase):
def _call_fut(self, value):
from google.cloud.bigquery._helpers import _date_to_json
return _date_to_json(value)
def test_w_string(self):
RFC3339 = "2016-12-03"
self.assertEqual(self._call_fut(RFC3339), RFC3339)
def test_w_datetime(self):
when = datetime.date(2016, 12, 3)
self.assertEqual(self._call_fut(when), "2016-12-03")
class Test_time_to_json(unittest.TestCase):
def _call_fut(self, value):
from google.cloud.bigquery._helpers import _time_to_json
return _time_to_json(value)
def test_w_string(self):
RFC3339 = "12:13:41"
self.assertEqual(self._call_fut(RFC3339), RFC3339)
def test_w_datetime(self):
when = datetime.time(12, 13, 41)
self.assertEqual(self._call_fut(when), "12:13:41")
def _make_field(
field_type,
mode="NULLABLE",
name="testing",
fields=(),
range_element_type=None,
):
from google.cloud.bigquery.schema import SchemaField
return SchemaField(
name=name,
field_type=field_type,
mode=mode,
fields=fields,
range_element_type=range_element_type,
)
class Test_scalar_field_to_json(unittest.TestCase):
def _call_fut(self, field, value):
from google.cloud.bigquery._helpers import _scalar_field_to_json
return _scalar_field_to_json(field, value)
def test_w_unknown_field_type(self):
field = _make_field("UNKNOWN")
original = object()
with warnings.catch_warnings(record=True) as warned:
converted = self._call_fut(field, original)
self.assertIs(converted, original)
self.assertEqual(len(warned), 1)
warning = warned[0]
self.assertTrue("UNKNOWN" in str(warning))
def test_w_known_field_type(self):
field = _make_field("INT64")
original = 42
converted = self._call_fut(field, original)
self.assertEqual(converted, str(original))
def test_w_scalar_none(self):
import google.cloud.bigquery._helpers as module_under_test
scalar_types = module_under_test._SCALAR_VALUE_TO_JSON_ROW.keys()
for type_ in scalar_types:
field = _make_field(type_)
original = None
converted = self._call_fut(field, original)
self.assertIsNone(converted, msg=f"{type_} did not return None")
class Test_single_field_to_json(unittest.TestCase):
def _call_fut(self, field, value):
from google.cloud.bigquery._helpers import _single_field_to_json
return _single_field_to_json(field, value)
def test_w_none(self):
field = _make_field("INT64")
original = None
converted = self._call_fut(field, original)
self.assertIsNone(converted)
def test_w_record(self):
subfields = [
_make_field("INT64", name="one"),
_make_field("STRING", name="two"),
]
field = _make_field("RECORD", fields=subfields)
original = {"one": 42, "two": "two"}
converted = self._call_fut(field, original)
self.assertEqual(converted, {"one": "42", "two": "two"})
def test_w_scalar(self):
field = _make_field("INT64")
original = 42
converted = self._call_fut(field, original)
self.assertEqual(converted, str(original))
def test_w_scalar_ignores_mode(self):
field = _make_field("STRING", mode="REPEATED")
original = "hello world"
converted = self._call_fut(field, original)
self.assertEqual(converted, original)
def test_w_scalar_json(self):
field = _make_field("JSON")
original = {"alpha": "abc", "num": [1, 2, 3]}
converted = self._call_fut(field, original)
self.assertEqual(converted, json.dumps(original))
class Test_repeated_field_to_json(unittest.TestCase):
def _call_fut(self, field, value):
from google.cloud.bigquery._helpers import _repeated_field_to_json
return _repeated_field_to_json(field, value)
def test_w_empty(self):
field = _make_field("INT64", mode="REPEATED")
original = []
converted = self._call_fut(field, original)
self.assertEqual(converted, original)
self.assertEqual(field.mode, "REPEATED")
def test_w_non_empty(self):
field = _make_field("INT64", mode="REPEATED")
original = [42]
converted = self._call_fut(field, original)
self.assertEqual(converted, [str(value) for value in original])
self.assertEqual(field.mode, "REPEATED")
class Test_record_field_to_json(unittest.TestCase):
def _call_fut(self, field, value):
from google.cloud.bigquery._helpers import _record_field_to_json
return _record_field_to_json(field, value)
def test_w_empty(self):
fields = []
original = []
converted = self._call_fut(fields, original)
self.assertEqual(converted, {})
def test_w_non_empty_list(self):
fields = [
_make_field("INT64", name="one", mode="NULLABLE"),
_make_field("STRING", name="two", mode="NULLABLE"),
]
original = [42, "two"]
converted = self._call_fut(fields, original)
self.assertEqual(converted, {"one": "42", "two": "two"})
def test_w_list_missing_fields(self):
fields = [
_make_field("INT64", name="one", mode="NULLABLE"),
_make_field("STRING", name="two", mode="NULLABLE"),
]
original = [42]
with self.assertRaisesRegex(ValueError, r".*not match schema length.*"):
self._call_fut(fields, original)
def test_w_list_too_many_fields(self):
fields = [
_make_field("INT64", name="one", mode="NULLABLE"),
_make_field("STRING", name="two", mode="NULLABLE"),
]
original = [42, "two", "three"]
with self.assertRaisesRegex(ValueError, r".*not match schema length.*"):
self._call_fut(fields, original)
def test_w_non_empty_dict(self):
fields = [
_make_field("INT64", name="one", mode="NULLABLE"),
_make_field("STRING", name="two", mode="NULLABLE"),
]
original = {"one": 42, "two": "two"}
converted = self._call_fut(fields, original)
self.assertEqual(converted, {"one": "42", "two": "two"})
def test_w_some_missing_nullables(self):
fields = [
_make_field("INT64", name="one", mode="NULLABLE"),
_make_field("STRING", name="two", mode="NULLABLE"),
]
original = {"one": 42}
converted = self._call_fut(fields, original)
# missing fields should not be converted to an explicit None
self.assertEqual(converted, {"one": "42"})
def test_w_all_missing_nullables(self):
fields = [
_make_field("INT64", name="one", mode="NULLABLE"),
_make_field("STRING", name="two", mode="NULLABLE"),
]
original = {}
converted = self._call_fut(fields, original)
# we should get an empty dict, not None
self.assertEqual(converted, {})
def test_w_explicit_none_value(self):
fields = [
_make_field("INT64", name="one", mode="NULLABLE"),
_make_field("STRING", name="two", mode="NULLABLE"),
_make_field("BOOL", name="three", mode="REPEATED"),
]
original = {"three": None, "one": 42, "two": None}
converted = self._call_fut(fields, original)
# None values should be dropped regardless of the field type
self.assertEqual(converted, {"one": "42"})
def test_w_dict_unknown_fields(self):
fields = [
_make_field("INT64", name="one", mode="NULLABLE"),
_make_field("STRING", name="two", mode="NULLABLE"),
]
original = {
"whoami": datetime.date(2020, 7, 20),
"one": 111,
"two": "222",
"void": None,
}
converted = self._call_fut(fields, original)
# Unknown fields should be included (if not None), but converted as strings.
self.assertEqual(
converted,
{"whoami": "2020-07-20", "one": "111", "two": "222"},
)
class Test_range_field_to_json(unittest.TestCase):
def _call_fut(self, field, value):
from google.cloud.bigquery._helpers import _range_field_to_json
return _range_field_to_json(field, value)
def test_w_date(self):
field = _make_field("RANGE", range_element_type="DATE")
start = datetime.date(2016, 12, 3)
original = {"start": start}
converted = self._call_fut(field.range_element_type, original)
expected = {"start": "2016-12-03", "end": None}
self.assertEqual(converted, expected)
def test_w_date_string(self):
field = _make_field("RANGE", range_element_type="DATE")
original = {"start": "2016-12-03"}
converted = self._call_fut(field.range_element_type, original)
expected = {"start": "2016-12-03", "end": None}
self.assertEqual(converted, expected)
def test_w_datetime(self):
field = _make_field("RANGE", range_element_type="DATETIME")
start = datetime.datetime(2016, 12, 3, 14, 11, 27, 123456)
original = {"start": start}
converted = self._call_fut(field.range_element_type, original)
expected = {"start": "2016-12-03T14:11:27.123456", "end": None}
self.assertEqual(converted, expected)
def test_w_datetime_string(self):
field = _make_field("RANGE", range_element_type="DATETIME")
original = {"start": "2016-12-03T14:11:27.123456"}
converted = self._call_fut(field.range_element_type, original)
expected = {"start": "2016-12-03T14:11:27.123456", "end": None}
self.assertEqual(converted, expected)
def test_w_timestamp(self):
from google.cloud._helpers import UTC
field = _make_field("RANGE", range_element_type="TIMESTAMP")
start = datetime.datetime(2016, 12, 3, 14, 11, 27, 123456, tzinfo=UTC)
original = {"start": start}
converted = self._call_fut(field.range_element_type, original)
expected = {"start": "2016-12-03T14:11:27.123456Z", "end": None}
self.assertEqual(converted, expected)
def test_w_timestamp_string(self):
field = _make_field("RANGE", range_element_type="TIMESTAMP")
original = {"start": "2016-12-03T14:11:27.123456Z"}
converted = self._call_fut(field.range_element_type, original)
expected = {"start": "2016-12-03T14:11:27.123456Z", "end": None}
self.assertEqual(converted, expected)
def test_w_timestamp_float(self):
field = _make_field("RANGE", range_element_type="TIMESTAMP")
original = {"start": 12.34567}
converted = self._call_fut(field.range_element_type, original)
expected = {"start": 12.34567, "end": None}
self.assertEqual(converted, expected)
def test_w_string_literal(self):
field = _make_field("RANGE", range_element_type="DATE")
original = "[2016-12-03, UNBOUNDED)"
converted = self._call_fut(field.range_element_type, original)
expected = {"start": "2016-12-03", "end": None}
self.assertEqual(converted, expected)
def test_w_unsupported_range_element_type(self):
field = _make_field("RANGE", range_element_type="TIME")
with self.assertRaises(ValueError):
self._call_fut(
field.range_element_type,
{"start": datetime.time(12, 13, 41)},
)
def test_w_no_range_element_type(self):
field = _make_field("RANGE")
with self.assertRaises(ValueError):
self._call_fut(field.range_element_type, "2016-12-03")
def test_w_incorrect_literal_format(self):
field = _make_field("RANGE", range_element_type="DATE")
original = "[2016-12-03, UNBOUNDED]"
with self.assertRaises(ValueError):
self._call_fut(field.range_element_type, original)
def test_w_unsupported_representation(self):
field = _make_field("RANGE", range_element_type="DATE")
with self.assertRaises(ValueError):
self._call_fut(field.range_element_type, object())
class Test_field_to_json(unittest.TestCase):
def _call_fut(self, field, value):
from google.cloud.bigquery._helpers import _field_to_json
return _field_to_json(field, value)
def test_w_none(self):
field = _make_field("INT64")
original = None
converted = self._call_fut(field, original)
self.assertIsNone(converted)
def test_w_repeated(self):
field = _make_field("INT64", mode="REPEATED")
original = [42, 17]
converted = self._call_fut(field, original)
self.assertEqual(converted, [str(value) for value in original])
def test_w_record(self):
subfields = [
_make_field("INT64", name="one"),
_make_field("STRING", name="two"),
]
field = _make_field("RECORD", fields=subfields)
original = {"one": 42, "two": "two"}
converted = self._call_fut(field, original)
self.assertEqual(converted, {"one": "42", "two": "two"})
def test_w_scalar(self):
field = _make_field("INT64")
original = 42
converted = self._call_fut(field, original)
self.assertEqual(converted, str(original))
def test_w_range(self):
field = _make_field("RANGE", range_element_type="DATE")
original = {"start": "2016-12-03", "end": "2024-12-03"}
converted = self._call_fut(field, original)
self.assertEqual(converted, original)
class Test_snake_to_camel_case(unittest.TestCase):
def _call_fut(self, value):
from google.cloud.bigquery._helpers import _snake_to_camel_case
return _snake_to_camel_case(value)
def test_w_snake_case_string(self):
self.assertEqual(self._call_fut("friendly_name"), "friendlyName")
def test_w_camel_case_string(self):
self.assertEqual(self._call_fut("friendlyName"), "friendlyName")
class Test__get_sub_prop(unittest.TestCase):
def _call_fut(self, container, keys, **kw):
from google.cloud.bigquery._helpers import _get_sub_prop
return _get_sub_prop(container, keys, **kw)
def test_w_empty_container_default_default(self):
self.assertIsNone(self._call_fut({}, ["key1"]))
def test_w_missing_key_explicit_default(self):
self.assertEqual(self._call_fut({"key2": 2}, ["key1"], default=1), 1)
def test_w_matching_single_key_in_sequence(self):
self.assertEqual(self._call_fut({"key1": 1}, ["key1"]), 1)
def test_w_matching_single_string_key(self):
data = {"k": {"e": {"y": "foo"}}, "key": "bar"}
self.assertEqual(self._call_fut(data, "key"), "bar")
def test_w_matching_first_key_missing_second_key(self):
self.assertIsNone(self._call_fut({"key1": {"key3": 3}}, ["key1", "key2"]))
def test_w_matching_first_key_matching_second_key(self):
self.assertEqual(self._call_fut({"key1": {"key2": 2}}, ["key1", "key2"]), 2)
class Test__set_sub_prop(unittest.TestCase):
def _call_fut(self, container, keys, value):
from google.cloud.bigquery._helpers import _set_sub_prop
return _set_sub_prop(container, keys, value)
def test_w_empty_container_single_key_in_sequence(self):
container = {}
self._call_fut(container, ["key1"], "value")
self.assertEqual(container, {"key1": "value"})
def test_w_empty_container_single_string_key(self):
container = {}
self._call_fut(container, "key", "value")
self.assertEqual(container, {"key": "value"})
def test_w_empty_container_nested_keys(self):
container = {}
self._call_fut(container, ["key1", "key2", "key3"], "value")
self.assertEqual(container, {"key1": {"key2": {"key3": "value"}}})
def test_w_existing_value(self):
container = {"key1": "before"}
self._call_fut(container, ["key1"], "after")
self.assertEqual(container, {"key1": "after"})
def test_w_nested_keys_existing_value(self):
container = {"key1": {"key2": {"key3": "before"}}}
self._call_fut(container, ["key1", "key2", "key3"], "after")
self.assertEqual(container, {"key1": {"key2": {"key3": "after"}}})
class Test__del_sub_prop(unittest.TestCase):
def _call_fut(self, container, keys):
from google.cloud.bigquery._helpers import _del_sub_prop
return _del_sub_prop(container, keys)
def test_w_single_key(self):
container = {"key1": "value"}
self._call_fut(container, ["key1"])
self.assertEqual(container, {})
def test_w_empty_container_nested_keys(self):
container = {}
self._call_fut(container, ["key1", "key2", "key3"])
self.assertEqual(container, {"key1": {"key2": {}}})
def test_w_existing_value_nested_keys(self):
container = {"key1": {"key2": {"key3": "value"}}}
self._call_fut(container, ["key1", "key2", "key3"])
self.assertEqual(container, {"key1": {"key2": {}}})
class Test__int_or_none(unittest.TestCase):
def _call_fut(self, value):
from google.cloud.bigquery._helpers import _int_or_none
return _int_or_none(value)
def test_w_num_string(self):
self.assertEqual(self._call_fut("123"), 123)
def test_w_none(self):
self.assertIsNone(self._call_fut(None))
def test_w_int(self):
self.assertEqual(self._call_fut(123), 123)
def test_w_non_num_string(self):
with self.assertRaises(ValueError):
self._call_fut("ham")
class Test__str_or_none(unittest.TestCase):
def _call_fut(self, value):
from google.cloud.bigquery._helpers import _str_or_none
return _str_or_none(value)
def test_w_int(self):
self.assertEqual(self._call_fut(123), "123")
def test_w_none(self):
self.assertIsNone(self._call_fut(None))
def test_w_str(self):
self.assertEqual(self._call_fut("ham"), "ham")
class _Field(object):
def __init__(
self,
mode,
name="unknown",
field_type="UNKNOWN",
fields=(),
range_element_type=None,
element_type=None,
):
self.mode = mode
self.name = name
self.field_type = field_type
self.fields = fields
self.range_element_type = range_element_type
self.element_type = element_type
def _field_isinstance_patcher():
"""A patcher thank makes _Field instances seem like SchemaField instances."""
from google.cloud.bigquery.schema import SchemaField
def fake_isinstance(instance, target_class):
if instance.__class__.__name__ != "_Field":
return isinstance(instance, target_class) # pragma: NO COVER
# pretend that _Field() instances are actually instances of SchemaField
return target_class is SchemaField or (
isinstance(target_class, tuple) and SchemaField in target_class
)
patcher = mock.patch(
"google.cloud.bigquery.schema.isinstance", side_effect=fake_isinstance
)
return patcher
def test_decimal_as_float_api_repr():
"""Make sure decimals get converted to float."""
import google.cloud.bigquery.query
from decimal import Decimal
param = google.cloud.bigquery.query.ScalarQueryParameter(
"x", "FLOAT64", Decimal(42)
)
assert param.to_api_repr() == {
"parameterType": {"type": "FLOAT64"},
"parameterValue": {"value": 42.0},
"name": "x",
}
class Test__get_bigquery_host(unittest.TestCase):
@staticmethod
def _call_fut():
from google.cloud.bigquery._helpers import _get_bigquery_host
return _get_bigquery_host()
def test_wo_env_var(self):
from google.cloud.bigquery._helpers import _DEFAULT_HOST
with mock.patch("os.environ", {}):
host = self._call_fut()
self.assertEqual(host, _DEFAULT_HOST)
def test_w_env_var(self):
from google.cloud.bigquery._helpers import BIGQUERY_EMULATOR_HOST
HOST = "https://api.example.com"
with mock.patch("os.environ", {BIGQUERY_EMULATOR_HOST: HOST}):
host = self._call_fut()
self.assertEqual(host, HOST)
|