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
|
# SPDX-FileCopyrightText: 2026 Dennis Fink <me+coding@dennisfink.me>
#
# SPDX-License-Identifier: BSD-3-Clause
import re
from collections.abc import Callable
from typing import Any
import huey as huey_package
import pytest
from flask import Flask, current_app, has_app_context
from huey import crontab
from webmentions_ssg.tasks.extension import FlaskHuey
def test_init_without_app() -> None:
huey = FlaskHuey()
assert huey.app is None
with pytest.raises(RuntimeError, match="Huey has not been initialized"):
_ = huey.huey
def test_init_with_app(app: Flask) -> None:
huey = FlaskHuey(app)
assert huey.app is app
assert huey.huey.name == app.import_name
assert huey.huey.results is True
assert huey.huey.store_none is False
assert huey.huey.utc is True
assert huey.huey.immediate is True
assert app.extensions["huey"] is huey
def test_init_app_uses_huey_configuration(app: Flask) -> None:
app.config["HUEY"] = {
"url": "memory://",
"name": "custom-name",
"results": False,
"store_none": True,
"utc": False,
"immediate": False,
}
huey = FlaskHuey()
huey.init_app(app)
assert huey.huey.name == "custom-name"
assert huey.huey.results is False
assert huey.huey.store_none is True
assert huey.huey.utc is False
assert huey.huey.immediate is False
def test_huey_url_takes_precedence_over_huey_configuration(app: Flask) -> None:
app.config["HUEY"] = {"url": "blackhole://"}
app.config["HUEY_URL"] = "memory://"
huey = FlaskHuey(app)
assert type(huey.huey).__name__ == "MemoryHuey"
def task_decorator(
huey: FlaskHuey, periodic: bool
) -> Callable[[Callable[..., Any]], Any]:
if periodic:
return huey.periodic_task(crontab(minute="*"))
return huey.task()
@pytest.mark.parametrize("periodic", [False, True], ids=["task", "periodic-task"])
def test_task_runs_in_app_context(app: Flask, periodic: bool) -> None:
huey = FlaskHuey(app)
@task_decorator(huey, periodic)
def add(a: int, b: int) -> int:
assert has_app_context()
return a + b
assert add.call_local(2, 3) == 5
@pytest.mark.parametrize("periodic", [False, True], ids=["task", "periodic-task"])
def test_task_raises_without_app(app: Flask, periodic: bool) -> None:
huey = FlaskHuey(app)
@task_decorator(huey, periodic)
def task() -> None:
pass
huey.app = None
with pytest.raises(RuntimeError, match="Flask app is not available"):
task.call_local()
@pytest.mark.parametrize("periodic", [False, True], ids=["task", "periodic-task"])
def test_task_declaration_before_init_and_rebind_after_init(periodic: bool) -> None:
"""Verify that imported tasks switch to the latest application backend.
:param periodic: Pytest fixture providing the periodic-task test function.
"""
queue = FlaskHuey()
observed_apps: list[str] = []
@task_decorator(queue, periodic)
def identify_app() -> str:
name = current_app.import_name
observed_apps.append(name)
return name
assert identify_app.__name__ == "identify_app"
with pytest.raises(RuntimeError, match="Huey has not been initialized"):
identify_app.call_local()
first = Flask("first")
first.config["TESTING"] = True
queue.init_app(first)
assert identify_app.call_local() == "first"
# Huey discards periodic-task results, even in immediate mode. Verify
# execution through a side effect as well as the returned result.
assert identify_app().get() == (None if periodic else "first")
assert observed_apps == ["first", "first"]
previous_backend = queue.huey
second = Flask("second")
second.config["TESTING"] = True
queue.init_app(second)
assert queue.huey is not previous_backend
assert identify_app.call_local() == "second"
assert identify_app().get() == (None if periodic else "second")
assert observed_apps == ["first", "first", "second", "second"]
# The new broker must recognize the registered task when deserializing work.
queued = identify_app.s()
restored = queue.huey.deserialize_task(queue.huey.serialize_task(queued))
assert type(restored) is type(queued)
def test_multiple_deferred_tasks_registered_on_initialization() -> None:
queue = FlaskHuey()
@queue.task(retries=2, retry_delay=50)
def first(value: int) -> int:
return value + 1
@queue.task()
def second(value: int) -> int:
return first.call_local(value) + 1
app = Flask("tasks")
app.config["TESTING"] = True
queue.init_app(app)
assert second(2).get() == 4
assert first.call_local(2) == 3
def test_getattr_delegates_to_huey(app: Flask) -> None:
huey = FlaskHuey(app)
assert huey.immediate is True
@pytest.mark.parametrize(
("url", "backend_name", "storage_kwargs"),
[
("redis://localhost:6379/0", "RedisHuey", {"url": "redis://localhost:6379/0"}),
(
"rediss://localhost:6379/0",
"RedisHuey",
{"url": "rediss://localhost:6379/0"},
),
(
"redis+priority://localhost:6379/0",
"PriorityRedisHuey",
{"url": "redis://localhost:6379/0"},
),
(
"redis+expire://localhost:6379/0",
"RedisExpireHuey",
{"url": "redis://localhost:6379/0"},
),
(
"redis+priority+expire://localhost:6379/0",
"PriorityRedisExpireHuey",
{"url": "redis://localhost:6379/0"},
),
(
"rediss+priority+expire://localhost:6379/0",
"PriorityRedisExpireHuey",
{"url": "rediss://localhost:6379/0"},
),
("sqlite:///huey.db", "SqliteHuey", {"filename": "huey.db"}),
("sqlite:///var/huey.db", "SqliteHuey", {"filename": "var/huey.db"}),
("sqlite:////var/huey.db", "SqliteHuey", {"filename": "/var/huey.db"}),
("file:///huey-queue", "FileHuey", {"path": "huey-queue"}),
# Three slashes are relative here, despite RFC 8089 file-URI semantics.
("file:///var/huey-queue", "FileHuey", {"path": "var/huey-queue"}),
("file:////var/huey-queue", "FileHuey", {"path": "/var/huey-queue"}),
(
"postgres://user:password@localhost/database",
"PostgresHuey",
{"dsn": "postgres://user:password@localhost/database"},
),
(
"postgresql://user:password@localhost/database",
"PostgresHuey",
{"dsn": "postgresql://user:password@localhost/database"},
),
("memory://", "MemoryHuey", {}),
("blackhole://", "BlackHoleHuey", {}),
],
)
def test_backend_from_url(
monkeypatch: pytest.MonkeyPatch,
url: str,
backend_name: str,
storage_kwargs: dict[str, str],
) -> None:
backend_class = type(f"Test{backend_name}", (), {})
monkeypatch.setattr(huey_package, backend_name, backend_class)
actual_class, actual_storage_kwargs = FlaskHuey.backend_from_url(url)
assert actual_class is backend_class
assert actual_storage_kwargs == storage_kwargs
@pytest.mark.parametrize(
("url", "message"),
[
(
"sqlite://var/huey.db",
"SQLite Huey URLs must look like sqlite:///huey.db (relative) "
"or sqlite:////var/huey.db (absolute)",
),
("sqlite:///", "SQLite Huey URL must include a database path"),
(
"file://var/huey-queue",
"File Huey URLs must look like file:///huey-queue (relative) "
"or file:////var/huey-queue (absolute)",
),
("file:///", "File Huey URL must include a directory path"),
("amqp://localhost", "Unsupported HUEY_URL scheme: 'amqp'"),
("redis+typo://localhost", "Unsupported HUEY_URL scheme: 'redis+typo'"),
(
"rediss+priority+typo://localhost",
"Unsupported HUEY_URL scheme: 'rediss+priority+typo'",
),
("redis+://localhost", "Unsupported HUEY_URL scheme: 'redis+'"),
("redisish://localhost", "Unsupported HUEY_URL scheme: 'redisish'"),
],
)
def test_backend_from_url_rejects_invalid_url(url: str, message: str) -> None:
with pytest.raises(RuntimeError, match=re.escape(message)):
FlaskHuey.backend_from_url(url)
|