1# Copyright 2021 The gRPC Authors
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14"""
15Houses py_grpc_gevent_test.
16"""
17
18load("@grpc_python_dependencies//:requirements.bzl", "requirement")
19
20_GRPC_LIB = "//src/python/grpcio/grpc:grpcio"
21
22_COPIED_MAIN_SUFFIX = ".gevent.main"
23
24def py_grpc_gevent_test(
25        name,
26        srcs,
27        main = None,
28        deps = None,
29        data = None,
30        **kwargs):
31    """Runs a Python test with gevent monkeypatched in.
32
33    Args:
34      name: The name of the test.
35      srcs: The source files.
36      main: The main file of the test.
37      deps: The dependencies of the test.
38      data: The data dependencies of the test.
39      **kwargs: Any other test arguments.
40    """
41    if main == None:
42        if len(srcs) != 1:
43            fail("When main is not provided, srcs must be of size 1.")
44        main = srcs[0]
45    deps = [] if deps == None else deps
46    data = [] if data == None else data
47    lib_name = name + ".gevent.lib"
48    supplied_python_version = kwargs.pop("python_version", "")
49    if supplied_python_version and supplied_python_version != "PY3":
50        fail("py_grpc_gevent_test only supports python_version=PY3")
51    native.py_library(
52        name = lib_name,
53        srcs = srcs,
54    )
55    augmented_deps = deps + [
56        ":{}".format(lib_name),
57        requirement("gevent"),
58    ]
59    if _GRPC_LIB not in augmented_deps:
60        augmented_deps.append(_GRPC_LIB)
61
62    # The main file needs to be in the same package as the test file.
63    copied_main_name = name + _COPIED_MAIN_SUFFIX
64    copied_main_filename = copied_main_name + ".py"
65    native.genrule(
66        name = copied_main_name,
67        srcs = ["//bazel:_gevent_test_main.py"],
68        outs = [copied_main_filename],
69        cmd = "cp $< $@",
70    )
71
72    # TODO(https://github.com/grpc/grpc/issues/27542): Remove once gevent is deemed non-flaky.
73    if "flaky" in kwargs:
74        kwargs.pop("flaky")
75
76    native.py_test(
77        name = name + ".gevent",
78        args = [name],
79        data = data,
80        deps = augmented_deps,
81        srcs = [copied_main_filename],
82        main = copied_main_filename,
83        python_version = "PY3",
84        flaky = False,
85        **kwargs
86    )
87