Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/dask/utils_test.py: 29%

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

104 statements  

1from __future__ import annotations 

2 

3import contextlib 

4import importlib 

5import os 

6import time 

7from typing import TYPE_CHECKING 

8 

9if TYPE_CHECKING: 

10 from dask.highlevelgraph import HighLevelGraph, Layer 

11 

12 

13def inc(x): 

14 return x + 1 

15 

16 

17def dec(x): 

18 return x - 1 

19 

20 

21def add(x, y): 

22 return x + y 

23 

24 

25def slowadd(a, b, delay=0.1): 

26 time.sleep(delay) 

27 return a + b 

28 

29 

30def xdist_worker_port(base_port: int) -> int: 

31 """Pick a TCP port that does not clash with the other pytest-xdist workers. 

32 

33 Test modules that bind a fixed port, e.g. to talk to a local server, cannot run in 

34 parallel unless every worker uses a port of its own. 

35 

36 Outside of pytest-xdist, or when the worker id does not end with a number, 

37 ``base_port`` is returned unchanged. 

38 """ 

39 worker = os.environ.get("PYTEST_XDIST_WORKER", "") 

40 index = worker.removeprefix("gw") 

41 return base_port + int(index) if index.isdigit() else base_port 

42 

43 

44class GetFunctionTestMixin: 

45 """ 

46 The GetFunctionTestCase class can be imported and used to test foreign 

47 implementations of the `get` function specification. It aims to enforce all 

48 known expectations of `get` functions. 

49 

50 To use the class, inherit from it and override the `get` function. For 

51 example: 

52 

53 > from dask.utils_test import GetFunctionTestMixin 

54 > class TestCustomGet(GetFunctionTestMixin): 

55 get = staticmethod(myget) 

56 

57 Note that the foreign `myget` function has to be explicitly decorated as a 

58 staticmethod. 

59 """ 

60 

61 def test_get(self): 

62 d = {":x": 1, ":y": (inc, ":x"), ":z": (add, ":x", ":y")} 

63 

64 assert self.get(d, ":x") == 1 

65 assert self.get(d, ":y") == 2 

66 assert self.get(d, ":z") == 3 

67 

68 def test_badkey(self): 

69 d = {":x": 1, ":y": (inc, ":x"), ":z": (add, ":x", ":y")} 

70 try: 

71 result = self.get(d, "badkey") 

72 except KeyError: 

73 pass 

74 else: 

75 msg = "Expected `{}` with badkey to raise KeyError.\n" 

76 msg += f"Obtained '{result}' instead." 

77 assert False, msg.format(self.get.__name__) 

78 

79 def test_nested_badkey(self): 

80 d = {"x": 1, "y": 2, "z": (sum, ["x", "y"])} 

81 

82 try: 

83 result = self.get(d, [["badkey"], "y"]) 

84 except KeyError: 

85 pass 

86 else: 

87 msg = "Expected `{}` with badkey to raise KeyError.\n" 

88 msg += f"Obtained '{result}' instead." 

89 assert False, msg.format(self.get.__name__) 

90 

91 def test_data_not_in_dict_is_ok(self): 

92 d = {"x": 1, "y": (add, "x", 10)} 

93 assert self.get(d, "y") == 11 

94 

95 def test_get_with_list(self): 

96 d = {"x": 1, "y": 2, "z": (sum, ["x", "y"])} 

97 

98 assert self.get(d, ["x", "y"]) == (1, 2) 

99 assert self.get(d, "z") == 3 

100 

101 def test_get_with_list_top_level(self): 

102 d = { 

103 "a": [1, 2, 3], 

104 "b": "a", 

105 "c": [1, (inc, 1)], 

106 "d": [(sum, "a")], 

107 "e": ["a", "b"], 

108 "f": [[[(sum, "a"), "c"], (sum, "b")], 2], 

109 } 

110 assert self.get(d, "a") == [1, 2, 3] 

111 assert self.get(d, "b") == [1, 2, 3] 

112 assert self.get(d, "c") == [1, 2] 

113 assert self.get(d, "d") == [6] 

114 assert self.get(d, "e") == [[1, 2, 3], [1, 2, 3]] 

115 assert self.get(d, "f") == [[[6, [1, 2]], 6], 2] 

116 

117 def test_get_with_nested_list(self): 

118 d = {"x": 1, "y": 2, "z": (sum, ["x", "y"])} 

119 

120 assert self.get(d, [["x"], "y"]) == ((1,), 2) 

121 assert self.get(d, "z") == 3 

122 

123 def test_get_works_with_unhashables_in_values(self): 

124 f = lambda x, y: x + len(y) 

125 d = {"x": 1, "y": (f, "x", {1})} 

126 

127 assert self.get(d, "y") == 2 

128 

129 def test_nested_tasks(self): 

130 d = {"x": 1, "y": (inc, "x"), "z": (add, (inc, "x"), "y")} 

131 

132 assert self.get(d, "z") == 4 

133 

134 def test_get_stack_limit(self): 

135 d = {f"x{i + 1}": (inc, f"x{i}") for i in range(10000)} 

136 d["x0"] = 0 

137 assert self.get(d, "x10000") == 10000 

138 

139 def test_with_HighLevelGraph(self): 

140 from dask.highlevelgraph import HighLevelGraph 

141 

142 layers = {"a": {"x": 1, "y": (inc, "x")}, "b": {"z": (add, (inc, "x"), "y")}} 

143 dependencies = {"a": (), "b": {"a"}} 

144 graph = HighLevelGraph(layers, dependencies) 

145 assert self.get(graph, "z") == 4 

146 

147 

148def import_or_none(name): 

149 """Import a module and return it; in case of failure; return None""" 

150 try: 

151 return importlib.import_module(name) 

152 except (ImportError, AttributeError): 

153 return None 

154 

155 

156def hlg_layer(hlg: HighLevelGraph, prefix: str) -> Layer: 

157 "Get the first layer from a HighLevelGraph whose name starts with a prefix" 

158 for key, lyr in hlg.layers.items(): 

159 if key.startswith(prefix): 

160 return lyr 

161 raise KeyError(f"No layer starts with {prefix!r}: {list(hlg.layers)}") 

162 

163 

164def hlg_layer_topological(hlg: HighLevelGraph, i: int) -> Layer: 

165 "Get the layer from a HighLevelGraph at position ``i``, topologically" 

166 return hlg.layers[hlg._toposort_layers()[i]] 

167 

168 

169@contextlib.contextmanager 

170def _check_warning(condition: bool, category: type[Warning], message: str): 

171 """Conditionally check if a warning is raised""" 

172 if condition: 

173 import pytest 

174 

175 with pytest.warns(category, match=message) as ctx: 

176 yield ctx 

177 else: 

178 with contextlib.nullcontext() as ctx: 

179 yield ctx 

180 

181 

182def assert_scipy_sparse_matrix_deprecated(extra_condition: bool = True): 

183 """Context manager that conditionally checks for the SciPy sparse matrix deprecation 

184 warning. 

185 """ 

186 from dask.array.scipy_compat import SCIPY_GE_200 

187 

188 return _check_warning( 

189 extra_condition and SCIPY_GE_200, 

190 DeprecationWarning, 

191 "is being replaced by", 

192 )