Coverage for /pythoncovmergedfiles/medio/medio/src/airflow/tests/hooks/test_subprocess.py: 0%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1#
2# Licensed to the Apache Software Foundation (ASF) under one
3# or more contributor license agreements. See the NOTICE file
4# distributed with this work for additional information
5# regarding copyright ownership. The ASF licenses this file
6# to you under the Apache License, Version 2.0 (the
7# "License"); you may not use this file except in compliance
8# with the License. You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing,
13# software distributed under the License is distributed on an
14# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15# KIND, either express or implied. See the License for the
16# specific language governing permissions and limitations
17# under the License.
18from __future__ import annotations
20import signal
21from pathlib import Path
22from subprocess import PIPE, STDOUT
23from tempfile import TemporaryDirectory
24from unittest import mock
25from unittest.mock import MagicMock
27import pytest
29from airflow.hooks.subprocess import SubprocessHook
31OS_ENV_KEY = "SUBPROCESS_ENV_TEST"
32OS_ENV_VAL = "this-is-from-os-environ"
35class TestSubprocessHook:
36 @pytest.mark.parametrize(
37 "env,expected",
38 [
39 ({"ABC": "123", "AAA": "456"}, {"ABC": "123", "AAA": "456", OS_ENV_KEY: ""}),
40 ({}, {OS_ENV_KEY: ""}),
41 (None, {OS_ENV_KEY: OS_ENV_VAL}),
42 ],
43 ids=["with env", "empty env", "no env"],
44 )
45 def test_env(self, env, expected):
46 """
47 Test that env variables are exported correctly to the command environment.
48 When ``env`` is ``None``, ``os.environ`` should be passed to ``Popen``.
49 Otherwise, the variables in ``env`` should be available, and ``os.environ`` should not.
50 """
51 hook = SubprocessHook()
53 def build_cmd(keys, filename):
54 """
55 Produce bash command to echo env vars into filename.
56 Will always echo the special test var named ``OS_ENV_KEY`` into the file to test whether
57 ``os.environ`` is passed or not.
58 """
59 return "\n".join(f"echo {k}=${k}>> {filename}" for k in [*keys, OS_ENV_KEY])
61 with TemporaryDirectory() as tmp_dir, mock.patch.dict("os.environ", {OS_ENV_KEY: OS_ENV_VAL}):
62 tmp_file = Path(tmp_dir, "test.txt")
63 command = build_cmd(env and env.keys() or [], tmp_file.as_posix())
64 hook.run_command(command=["bash", "-c", command], env=env)
65 actual = dict([x.split("=") for x in tmp_file.read_text().splitlines()])
66 assert actual == expected
68 @pytest.mark.parametrize(
69 "val,expected",
70 [
71 ("test-val", "test-val"),
72 ("test-val\ntest-val\n", ""),
73 ("test-val\ntest-val", "test-val"),
74 ("", ""),
75 ],
76 )
77 def test_return_value(self, val, expected):
78 hook = SubprocessHook()
79 result = hook.run_command(command=["bash", "-c", f'echo "{val}"'])
80 assert result.output == expected
82 @mock.patch.dict("os.environ", clear=True)
83 @mock.patch(
84 "airflow.hooks.subprocess.TemporaryDirectory",
85 return_value=MagicMock(__enter__=MagicMock(return_value="/tmp/airflowtmpcatcat")),
86 )
87 @mock.patch(
88 "airflow.hooks.subprocess.Popen",
89 return_value=MagicMock(stdout=MagicMock(readline=MagicMock(side_effect=StopIteration), returncode=0)),
90 )
91 def test_should_exec_subprocess(self, mock_popen, mock_temporary_directory):
92 hook = SubprocessHook()
93 hook.run_command(command=["bash", "-c", 'echo "stdout"'])
95 mock_popen.assert_called_once_with(
96 ["bash", "-c", 'echo "stdout"'],
97 cwd="/tmp/airflowtmpcatcat",
98 env={},
99 preexec_fn=mock.ANY,
100 stderr=STDOUT,
101 stdout=PIPE,
102 )
104 def test_task_decode(self):
105 hook = SubprocessHook()
106 command = ["bash", "-c", 'printf "This will cause a coding error \\xb1\\xa6\\x01\n"']
107 result = hook.run_command(command=command)
108 assert result.exit_code == 0
110 @mock.patch("os.getpgid", return_value=123)
111 @mock.patch("os.killpg")
112 def test_send_sigterm(self, mock_killpg, mock_getpgid):
113 hook = SubprocessHook()
114 hook.sub_process = MagicMock()
115 hook.send_sigterm()
116 mock_killpg.assert_called_with(123, signal.SIGTERM)