-
Notifications
You must be signed in to change notification settings - Fork 42
/
noxfile.py
982 lines (856 loc) · 31 KB
/
noxfile.py
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
# -*- coding: utf-8 -*-
#
# Copyright 2018 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
#
# https://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.
from __future__ import absolute_import
import argparse
import multiprocessing
import os
import pathlib
import re
import shutil
import time
from typing import Dict, List
import warnings
import nox
import nox.sessions
BLACK_VERSION = "black==22.3.0"
ISORT_VERSION = "isort==5.12.0"
# pytest-retry is not yet compatible with pytest 8.x.
# https://github.com/str0zzapreti/pytest-retry/issues/32
PYTEST_VERSION = "pytest<8.0.0dev"
SPHINX_VERSION = "sphinx==4.5.0"
LINT_PATHS = [
"docs",
"bigframes",
"tests",
"third_party",
"noxfile.py",
"setup.py",
]
DEFAULT_PYTHON_VERSION = "3.10"
UNIT_TEST_PYTHON_VERSIONS = ["3.9", "3.10", "3.11", "3.12"]
UNIT_TEST_STANDARD_DEPENDENCIES = [
"mock",
"asyncmock",
"freezegun",
PYTEST_VERSION,
"pytest-cov",
"pytest-asyncio",
"pytest-mock",
]
UNIT_TEST_EXTERNAL_DEPENDENCIES: List[str] = []
UNIT_TEST_LOCAL_DEPENDENCIES: List[str] = []
UNIT_TEST_DEPENDENCIES: List[str] = []
UNIT_TEST_EXTRAS: List[str] = []
UNIT_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {"3.12": ["polars"]}
# There are 4 different ibis-framework 9.x versions we want to test against.
# 3.10 is needed for Windows tests.
SYSTEM_TEST_PYTHON_VERSIONS = ["3.9", "3.10", "3.11", "3.12"]
SYSTEM_TEST_STANDARD_DEPENDENCIES = [
"jinja2",
"mock",
"openpyxl",
PYTEST_VERSION,
"pytest-cov",
"pytest-retry",
"pytest-timeout",
"pytest-xdist",
"google-cloud-testutils",
"tabulate",
"xarray",
]
SYSTEM_TEST_EXTERNAL_DEPENDENCIES = [
"google-cloud-bigquery",
]
SYSTEM_TEST_LOCAL_DEPENDENCIES: List[str] = []
SYSTEM_TEST_DEPENDENCIES: List[str] = []
SYSTEM_TEST_EXTRAS: List[str] = ["tests"]
SYSTEM_TEST_EXTRAS_BY_PYTHON: Dict[str, List[str]] = {}
LOGGING_NAME_ENV_VAR = "BIGFRAMES_PERFORMANCE_LOG_NAME"
CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute()
# Sessions are executed in the order so putting the smaller sessions
# ahead to fail fast at presubmit running.
# 'docfx' is excluded since it only needs to run in 'docs-presubmit'
nox.options.sessions = [
"lint",
"lint_setup_py",
"mypy",
"format",
"docs",
"docfx",
"unit",
"unit_noextras",
"system-3.9",
"system-3.12",
"cover",
"cleanup",
]
# Error if a python version is missing
nox.options.error_on_missing_interpreters = True
@nox.session(python=DEFAULT_PYTHON_VERSION)
def lint(session):
"""Run linters.
Returns a failure if the linters find linting errors or sufficiently
serious code quality issues.
"""
session.install("flake8", BLACK_VERSION)
session.run(
"black",
"--check",
*LINT_PATHS,
)
session.run("flake8", *LINT_PATHS)
@nox.session(python=DEFAULT_PYTHON_VERSION)
def blacken(session):
"""Run black. Format code to uniform standard."""
session.install(BLACK_VERSION)
session.run(
"black",
*LINT_PATHS,
)
@nox.session(python=DEFAULT_PYTHON_VERSION)
def format(session):
"""
Run isort to sort imports. Then run black
to format code to uniform standard.
"""
session.install(BLACK_VERSION, ISORT_VERSION)
# Use the --fss option to sort imports using strict alphabetical order.
# See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections
session.run(
"isort",
*LINT_PATHS,
)
session.run(
"black",
*LINT_PATHS,
)
@nox.session(python=DEFAULT_PYTHON_VERSION)
def lint_setup_py(session):
"""Verify that setup.py is valid (including RST check)."""
session.install("docutils", "pygments")
session.run("python", "setup.py", "check", "--restructuredtext", "--strict")
def install_unittest_dependencies(session, install_test_extra, *constraints):
standard_deps = UNIT_TEST_STANDARD_DEPENDENCIES + UNIT_TEST_DEPENDENCIES
session.install(*standard_deps, *constraints)
if UNIT_TEST_EXTERNAL_DEPENDENCIES:
warnings.warn(
"'unit_test_external_dependencies' is deprecated. Instead, please "
"use 'unit_test_dependencies' or 'unit_test_local_dependencies'.",
DeprecationWarning,
)
session.install(*UNIT_TEST_EXTERNAL_DEPENDENCIES, *constraints)
if UNIT_TEST_LOCAL_DEPENDENCIES:
session.install(*UNIT_TEST_LOCAL_DEPENDENCIES, *constraints)
if install_test_extra and UNIT_TEST_EXTRAS_BY_PYTHON:
extras = UNIT_TEST_EXTRAS_BY_PYTHON.get(session.python, [])
elif install_test_extra and UNIT_TEST_EXTRAS:
extras = UNIT_TEST_EXTRAS
else:
extras = []
if extras:
session.install("-e", f".[{','.join(extras)}]", *constraints)
else:
session.install("-e", ".", *constraints)
def run_unit(session, install_test_extra):
"""Run the unit test suite."""
constraints_path = str(
CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt"
)
install_unittest_dependencies(session, install_test_extra, "-c", constraints_path)
# Run py.test against the unit tests.
scripts_path = "scripts"
tests_path = os.path.join("tests", "unit")
third_party_tests_path = os.path.join("third_party", "bigframes_vendored")
session.run(
"py.test",
"--quiet",
f"--junitxml=unit_{session.python}_sponge_log.xml",
"--cov=bigframes",
f"--cov={tests_path}",
"--cov-append",
"--cov-config=.coveragerc",
"--cov-report=term-missing",
"--cov-fail-under=0",
tests_path,
third_party_tests_path,
scripts_path,
*session.posargs,
)
@nox.session(python=UNIT_TEST_PYTHON_VERSIONS)
def unit(session):
run_unit(session, install_test_extra=True)
@nox.session(python=UNIT_TEST_PYTHON_VERSIONS[-1])
def unit_noextras(session):
run_unit(session, install_test_extra=False)
@nox.session(python=DEFAULT_PYTHON_VERSION)
def mypy(session):
"""Run type checks with mypy."""
# Editable mode is not compatible with mypy when there are multiple
# package directories. See:
# https://github.com/python/mypy/issues/10564#issuecomment-851687749
session.install(".")
# Just install the dependencies' type info directly, since "mypy --install-types"
# might require an additional pass.
deps = (
set(
[
"mypy",
"pandas-stubs",
"types-protobuf",
"types-python-dateutil",
"types-requests",
"types-setuptools",
"types-tabulate",
"polars",
]
)
| set(SYSTEM_TEST_STANDARD_DEPENDENCIES)
| set(UNIT_TEST_STANDARD_DEPENDENCIES)
)
session.install(*deps)
shutil.rmtree(".mypy_cache", ignore_errors=True)
session.run(
"mypy",
"bigframes",
os.path.join("tests", "system"),
os.path.join("tests", "unit"),
"--check-untyped-defs",
"--explicit-package-bases",
'--exclude="^third_party"',
)
def install_systemtest_dependencies(session, install_test_extra, *constraints):
# Use pre-release gRPC for system tests.
# Exclude version 1.49.0rc1 which has a known issue.
# See https://github.com/grpc/grpc/pull/30642
session.install("--pre", "grpcio!=1.49.0rc1")
session.install(*SYSTEM_TEST_STANDARD_DEPENDENCIES, *constraints)
if SYSTEM_TEST_EXTERNAL_DEPENDENCIES:
session.install(*SYSTEM_TEST_EXTERNAL_DEPENDENCIES, *constraints)
if SYSTEM_TEST_LOCAL_DEPENDENCIES:
session.install("-e", *SYSTEM_TEST_LOCAL_DEPENDENCIES, *constraints)
if SYSTEM_TEST_DEPENDENCIES:
session.install("-e", *SYSTEM_TEST_DEPENDENCIES, *constraints)
if install_test_extra and SYSTEM_TEST_EXTRAS_BY_PYTHON:
extras = SYSTEM_TEST_EXTRAS_BY_PYTHON.get(session.python, [])
elif install_test_extra and SYSTEM_TEST_EXTRAS:
extras = SYSTEM_TEST_EXTRAS
else:
extras = []
if extras:
session.install("-e", f".[{','.join(extras)}]", *constraints)
else:
session.install("-e", ".", *constraints)
def run_system(
session: nox.sessions.Session,
prefix_name,
test_folder,
*,
check_cov=False,
install_test_extra=True,
print_duration=False,
extra_pytest_options=(),
timeout_seconds=900,
num_workers=20,
):
"""Run the system test suite."""
constraints_path = str(
CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt"
)
# Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true.
if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false":
session.skip("RUN_SYSTEM_TESTS is set to false, skipping")
# Install pyopenssl for mTLS testing.
if os.environ.get("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") == "true":
session.install("pyopenssl")
install_systemtest_dependencies(session, install_test_extra, "-c", constraints_path)
# Run py.test against the system tests.
pytest_cmd = [
"py.test",
"--quiet",
f"-n={num_workers}",
# Any individual test taking longer than 15 mins will be terminated.
f"--timeout={timeout_seconds}",
# Log 20 slowest tests
"--durations=20",
f"--junitxml={prefix_name}_{session.python}_sponge_log.xml",
]
if print_duration:
pytest_cmd.extend(
[
"--durations=0",
]
)
if check_cov:
pytest_cmd.extend(
[
"--cov=bigframes",
f"--cov={test_folder}",
"--cov-append",
"--cov-config=.coveragerc",
"--cov-report=term-missing",
"--cov-fail-under=0",
]
)
pytest_cmd.extend(extra_pytest_options)
session.run(
*pytest_cmd,
*session.posargs,
test_folder,
)
@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS)
def system(session: nox.sessions.Session):
"""Run the system test suite."""
run_system(
session=session,
prefix_name="system",
test_folder=os.path.join("tests", "system", "small"),
check_cov=True,
)
@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS[-1])
def system_noextras(session: nox.sessions.Session):
"""Run the system test suite."""
run_system(
session=session,
prefix_name="system_noextras",
test_folder=os.path.join("tests", "system", "small"),
install_test_extra=False,
)
@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS[-1])
def doctest(session: nox.sessions.Session):
"""Run the system test suite."""
run_system(
session=session,
prefix_name="doctest",
extra_pytest_options=(
"--doctest-modules",
"third_party",
"--ignore",
"third_party/bigframes_vendored/ibis",
"--ignore",
"bigframes/core/compile/polars",
),
test_folder="bigframes",
check_cov=True,
num_workers=5,
)
@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS[-1])
def e2e(session: nox.sessions.Session):
"""Run the large tests in system test suite."""
run_system(
session=session,
prefix_name="e2e",
test_folder=os.path.join("tests", "system", "large"),
print_duration=True,
)
@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS[-1])
def load(session: nox.sessions.Session):
"""Run the very large tests in system test suite."""
run_system(
session=session,
prefix_name="load",
test_folder=os.path.join("tests", "system", "load"),
print_duration=True,
timeout_seconds=60 * 60 * 12,
)
@nox.session(python=DEFAULT_PYTHON_VERSION)
def cover(session):
"""Run the final coverage report.
This outputs the coverage report aggregating coverage from the test runs
(including system test runs), and then erases coverage data.
"""
session.install("coverage", "pytest-cov")
# Create a coverage report that includes only the product code.
session.run(
"coverage",
"report",
"--include=bigframes/*",
"--show-missing",
"--fail-under=86",
)
# Make sure there is no dead code in our test directories.
session.run(
"coverage",
"report",
"--show-missing",
"--include=tests/unit/*",
"--include=tests/system/small/*",
# TODO(b/353775058) resume coverage to 100 when the issue is fixed.
"--fail-under=99",
)
session.run("coverage", "erase")
@nox.session(python=DEFAULT_PYTHON_VERSION)
def docs(session):
"""Build the docs for this library."""
session.install("-e", ".")
session.install(
# We need to pin to specific versions of the `sphinxcontrib-*` packages
# which still support sphinx 4.x.
# See https://github.com/googleapis/sphinx-docfx-yaml/issues/344
# and https://github.com/googleapis/sphinx-docfx-yaml/issues/345.
"sphinxcontrib-applehelp==1.0.4",
"sphinxcontrib-devhelp==1.0.2",
"sphinxcontrib-htmlhelp==2.0.1",
"sphinxcontrib-qthelp==1.0.3",
"sphinxcontrib-serializinghtml==1.1.5",
SPHINX_VERSION,
"alabaster",
"recommonmark",
)
shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True)
session.run(
"python",
"scripts/publish_api_coverage.py",
"docs",
)
session.run(
"sphinx-build",
"-W", # warnings as errors
"-T", # show full traceback on exception
"-N", # no colors
"-b",
"html",
"-d",
os.path.join("docs", "_build", "doctrees", ""),
os.path.join("docs", ""),
os.path.join("docs", "_build", "html", ""),
)
@nox.session(python=DEFAULT_PYTHON_VERSION)
def docfx(session):
"""Build the docfx yaml files for this library."""
session.install("-e", ".")
session.install(
# We need to pin to specific versions of the `sphinxcontrib-*` packages
# which still support sphinx 4.x.
# See https://github.com/googleapis/sphinx-docfx-yaml/issues/344
# and https://github.com/googleapis/sphinx-docfx-yaml/issues/345.
"sphinxcontrib-applehelp==1.0.4",
"sphinxcontrib-devhelp==1.0.2",
"sphinxcontrib-htmlhelp==2.0.1",
"sphinxcontrib-qthelp==1.0.3",
"sphinxcontrib-serializinghtml==1.1.5",
SPHINX_VERSION,
"alabaster",
"recommonmark",
"gcp-sphinx-docfx-yaml==3.0.1",
)
shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True)
session.run(
"python",
"scripts/publish_api_coverage.py",
"docs",
)
session.run(
"sphinx-build",
"-T", # show full traceback on exception
"-N", # no colors
"-D",
(
"extensions=sphinx.ext.autodoc,"
"sphinx.ext.autosummary,"
"docfx_yaml.extension,"
"sphinx.ext.intersphinx,"
"sphinx.ext.coverage,"
"sphinx.ext.napoleon,"
"sphinx.ext.todo,"
"sphinx.ext.viewcode,"
"recommonmark"
),
"-b",
"html",
"-d",
os.path.join("docs", "_build", "doctrees", ""),
os.path.join("docs", ""),
os.path.join("docs", "_build", "html", ""),
)
def prerelease(session: nox.sessions.Session, tests_path, extra_pytest_options=()):
constraints_path = str(
CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt"
)
# Ignore officially released versions of certain packages specified in
# testing/constraints-*.txt and install a more recent, pre-release versions
# directly
already_installed = set()
# PyArrow prerelease packages are published to an alternative PyPI host.
# https://arrow.apache.org/docs/python/install.html#installing-nightly-packages
session.install(
"--extra-index-url",
"https://pypi.fury.io/arrow-nightlies/",
"--prefer-binary",
"--pre",
"--upgrade",
"pyarrow",
)
already_installed.add("pyarrow")
session.install(
"--prefer-binary",
"--pre",
"--upgrade",
# We exclude each version individually so that we can continue to test
# some prerelease packages. See:
# https://github.com/googleapis/python-bigquery-dataframes/pull/268#discussion_r1423205172
# "pandas!=2.1.4, !=2.2.0rc0, !=2.2.0, !=2.2.1",
"pandas",
)
already_installed.add("pandas")
# Ibis has introduced breaking changes. Let's exclude ibis head
# from prerelease install list for now. We should enable the head back
# once bigframes supports the version at HEAD.
# session.install(
# "--upgrade",
# "-e", # Use -e so that py.typed file is included.
# "git+https://github.com/ibis-project/ibis.git#egg=ibis-framework",
# )
session.install(
"--upgrade",
"--pre",
"ibis-framework>=9.0.0,<=9.2.0",
)
already_installed.add("ibis-framework")
# Workaround https://github.com/googleapis/python-db-dtypes-pandas/issues/178
session.install("--no-deps", "db-dtypes")
already_installed.add("db-dtypes")
# Ensure we catch breaking changes in the client libraries early.
session.install(
"--upgrade",
"git+https://github.com/googleapis/python-bigquery.git#egg=google-cloud-bigquery",
)
already_installed.add("google-cloud-bigquery")
session.install(
"--upgrade",
"-e",
"git+https://github.com/googleapis/python-bigquery-storage.git#egg=google-cloud-bigquery-storage",
)
already_installed.add("google-cloud-bigquery-storage")
session.install(
"--upgrade",
"git+https://github.com/googleapis/python-bigquery-pandas.git#egg=pandas-gbq",
)
already_installed.add("pandas-gbq")
session.install(
*set(UNIT_TEST_STANDARD_DEPENDENCIES + SYSTEM_TEST_STANDARD_DEPENDENCIES),
"-c",
constraints_path,
)
# Because we test minimum dependency versions on the minimum Python
# version, the first version we test with in the unit tests sessions has a
# constraints file containing all dependencies and extras.
with open(
CURRENT_DIRECTORY
/ "testing"
/ f"constraints-{UNIT_TEST_PYTHON_VERSIONS[0]}.txt",
encoding="utf-8",
) as constraints_file:
constraints_text = constraints_file.read()
# Ignore leading whitespace and comment lines.
deps = [
match.group(1)
for match in re.finditer(
r"^\s*(\S+)(?===\S+)", constraints_text, flags=re.MULTILINE
)
if match.group(1) not in already_installed
]
# We use --no-deps to ensure that pre-release versions aren't overwritten
# by the version ranges in setup.py.
session.install(*deps)
session.install("--no-deps", "-e", ".")
# Print out prerelease package versions.
session.run("python", "-m", "pip", "freeze")
# Run py.test against the tests.
session.run(
"py.test",
"--quiet",
"-n=20",
# Any individual test taking longer than 10 mins will be terminated.
"--timeout=600",
f"--junitxml={os.path.split(tests_path)[-1]}_prerelease_{session.python}_sponge_log.xml",
"--cov=bigframes",
f"--cov={tests_path}",
"--cov-append",
"--cov-config=.coveragerc",
"--cov-report=term-missing",
"--cov-fail-under=0",
tests_path,
*extra_pytest_options,
*session.posargs,
)
@nox.session(python=UNIT_TEST_PYTHON_VERSIONS[-1])
def unit_prerelease(session: nox.sessions.Session):
"""Run the unit test suite with prerelease dependencies."""
prerelease(session, os.path.join("tests", "unit"))
@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS[-1])
def system_prerelease(session: nox.sessions.Session):
"""Run the system test suite with prerelease dependencies."""
small_tests_dir = os.path.join("tests", "system", "small")
# Let's exclude remote function tests from the prerelease tests, since the
# some of the package dependencies propagate to the cloud run functions'
# requirements.txt, and the prerelease package versions may not be available
# in the standard pip install.
# This would mean that we will only rely on the standard remote function
# tests.
small_remote_function_tests = os.path.join(
small_tests_dir, "test_remote_function.py"
)
assert os.path.exists(small_remote_function_tests)
prerelease(
session,
os.path.join("tests", "system", "small"),
(f"--ignore={small_remote_function_tests}",),
)
@nox.session(python=SYSTEM_TEST_PYTHON_VERSIONS)
def notebook(session: nox.Session):
google_cloud_project = os.getenv("GOOGLE_CLOUD_PROJECT")
if not google_cloud_project:
session.error(
"Set GOOGLE_CLOUD_PROJECT environment variable to run notebook session."
)
session.install("-e", ".[all]")
session.install(
"pytest",
"pytest-xdist",
"pytest-retry",
"nbmake",
"google-cloud-aiplatform",
"matplotlib",
"seaborn",
)
notebooks_list = list(pathlib.Path("notebooks/").glob("*/*.ipynb"))
denylist = [
# Regionalized testing is manually added later.
"notebooks/location/regionalized.ipynb",
# These notebooks contain special colab `param {type:"string"}`
# comments, which make it easy for customers to fill in their
# own information.
#
# With the notebooks_fill_params.py script, we are able to find and
# replace the PROJECT_ID parameter, but not the others.
#
# TODO(b/357904266): Test these notebooks by replacing parameters with
# appropriate values and omitting cleanup logic that may break
# our test infrastructure.
"notebooks/getting_started/ml_fundamentals_bq_dataframes.ipynb", # Needs DATASET.
"notebooks/ml/bq_dataframes_ml_linear_regression.ipynb", # Needs DATASET_ID.
"notebooks/generative_ai/bq_dataframes_ml_drug_name_generation.ipynb", # Needs CONNECTION.
# TODO(b/332737009): investigate why we get 404 errors, even though
# bq_dataframes_llm_code_generation creates a bucket in the sample.
"notebooks/generative_ai/bq_dataframes_llm_code_generation.ipynb", # Needs BUCKET_URI.
"notebooks/generative_ai/sentiment_analysis.ipynb", # Too slow
"notebooks/generative_ai/bq_dataframes_llm_gemini_2.ipynb", # Gemini 2.0 backend hasn't ready in prod.
# TODO(b/366290533): to protect BQML quota
"notebooks/generative_ai/bq_dataframes_llm_claude3_museum_art.ipynb",
"notebooks/vertex_sdk/sdk2_bigframes_pytorch.ipynb", # Needs BUCKET_URI.
"notebooks/vertex_sdk/sdk2_bigframes_sklearn.ipynb", # Needs BUCKET_URI.
"notebooks/vertex_sdk/sdk2_bigframes_tensorflow.ipynb", # Needs BUCKET_URI.
# The experimental notebooks imagine features that don't yet
# exist or only exist as temporary prototypes.
"notebooks/experimental/longer_ml_demo.ipynb",
"notebooks/experimental/semantic_operators.ipynb",
# The notebooks that are added for more use cases, such as backing a
# blog post, which may take longer to execute and need not be
# continuously tested.
"notebooks/apps/synthetic_data_generation.ipynb",
]
# Convert each Path notebook object to a string using a list comprehension.
notebooks = [str(nb) for nb in notebooks_list]
# Remove tests that we choose not to test.
notebooks = list(filter(lambda nb: nb not in denylist, notebooks))
# Regionalized notebooks
notebooks_reg = {
"regionalized.ipynb": [
"asia-southeast1",
"eu",
"europe-west4",
"southamerica-west1",
"us",
"us-central1",
]
}
notebooks_reg = {
os.path.join("notebooks/location", nb): regions
for nb, regions in notebooks_reg.items()
}
# The pytest --nbmake exits silently with "no tests ran" message if
# one of the notebook paths supplied does not exist. Let's make sure that
# each path exists.
for nb in notebooks + list(notebooks_reg):
assert os.path.exists(nb), nb
# Determine whether to enable multi-process mode based on the environment
# variable. If BENCHMARK_AND_PUBLISH is "true", it indicates we're running
# a benchmark, so we disable multi-process mode. If BENCHMARK_AND_PUBLISH
# is "false", we enable multi-process mode for faster execution.
multi_process_mode = os.getenv("BENCHMARK_AND_PUBLISH", "false") == "false"
try:
# Populate notebook parameters and make a backup so that the notebooks
# are runnable.
session.run(
"python",
CURRENT_DIRECTORY / "scripts" / "notebooks_fill_params.py",
*notebooks,
)
processes = []
for notebook in notebooks:
args = (
"python",
"scripts/run_and_publish_benchmark.py",
"--notebook",
f"--benchmark-path={notebook}",
)
if multi_process_mode:
process = multiprocessing.Process(
target=session.run,
args=args,
)
process.start()
processes.append(process)
# Adding a small delay between starting each
# process to avoid potential race conditions。
time.sleep(1)
else:
session.run(*args)
for notebook, regions in notebooks_reg.items():
for region in regions:
region_args = (
"python",
"scripts/run_and_publish_benchmark.py",
"--notebook",
f"--benchmark-path={notebook}",
f"--region={region}",
)
if multi_process_mode:
process = multiprocessing.Process(
target=session.run,
args=region_args,
)
process.start()
processes.append(process)
# Adding a small delay between starting each
# process to avoid potential race conditions。
time.sleep(1)
else:
session.run(*region_args)
for process in processes:
process.join()
finally:
# Prevent our notebook changes from getting checked in to git
# accidentally.
session.run(
"python",
CURRENT_DIRECTORY / "scripts" / "notebooks_restore_from_backup.py",
*notebooks,
)
session.run(
"python",
"scripts/run_and_publish_benchmark.py",
"--notebook",
"--publish-benchmarks=notebooks/",
)
@nox.session(python=DEFAULT_PYTHON_VERSION)
def benchmark(session: nox.Session):
session.install("-e", ".[all]")
base_path = os.path.join("tests", "benchmark")
parser = argparse.ArgumentParser()
parser.add_argument(
"-i",
"--iterations",
type=int,
default=1,
help="Number of iterations to run each benchmark.",
)
parser.add_argument(
"-o",
"--output-csv",
nargs="?",
const=True,
default=False,
help=(
"Determines whether to output results to a CSV file. If no location is provided, "
"a temporary location is automatically generated."
),
)
parser.add_argument(
"-b",
"--benchmark-filter",
nargs="+",
help=(
"List of file or directory names to include in the benchmarks. If not provided, "
"all benchmarks are run."
),
)
args = parser.parse_args(session.posargs)
benchmark_script_list: List[pathlib.Path] = []
if args.benchmark_filter:
for filter_item in args.benchmark_filter:
full_path = os.path.join(base_path, filter_item)
if os.path.isdir(full_path):
benchmark_script_list.extend(pathlib.Path(full_path).rglob("*.py"))
elif os.path.isfile(full_path) and full_path.endswith(".py"):
benchmark_script_list.append(pathlib.Path(full_path))
else:
raise ValueError(
f"Item {filter_item} does not match any valid file or directory"
)
else:
benchmark_script_list = list(pathlib.Path(base_path).rglob("*.py"))
try:
for benchmark in benchmark_script_list:
if benchmark.name in ("__init__.py", "utils.py"):
continue
session.run(
"python",
"scripts/run_and_publish_benchmark.py",
f"--benchmark-path={benchmark}",
f"--iterations={args.iterations}",
)
finally:
session.run(
"python",
"scripts/run_and_publish_benchmark.py",
f"--publish-benchmarks={base_path}",
f"--iterations={args.iterations}",
f"--output-csv={args.output_csv}",
)
@nox.session(python="3.10")
def release_dry_run(session):
env = {}
# If the project root is not set, then take current directory as the project
# root. See the release script for how the project root is set/used. This is
# specially useful when the developer runs the nox session on local machine.
if not os.environ.get("PROJECT_ROOT") and not os.environ.get(
"KOKORO_ARTIFACTS_DIR"
):
env["PROJECT_ROOT"] = "."
session.run(".kokoro/release-nightly.sh", "--dry-run", env=env)
@nox.session(python=DEFAULT_PYTHON_VERSION)
def cleanup(session):
"""Clean up stale and/or temporary resources in the test project."""
google_cloud_project = os.getenv("GOOGLE_CLOUD_PROJECT")
cleanup_options = []
if google_cloud_project:
cleanup_options.append(f"--project-id={google_cloud_project}")
# Cleanup a few stale (more than 12 hours old) temporary cloud run
# functions created by bigframems. This will help keeping the test GCP
# project within the "Number of functions" quota
# https://cloud.google.com/functions/quotas#resource_limits
recency_cutoff_hours = 12
cleanup_count_per_location = 20
cleanup_options.extend(
[
f"--recency-cutoff={recency_cutoff_hours}",
"cleanup",
f"--number={cleanup_count_per_location}",
]
)
session.install("-e", ".")
session.run("python", "scripts/manage_cloud_functions.py", *cleanup_options)