File: test_http.py

package info (click to toggle)
django-htmx 1.23.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 816 kB
  • sloc: javascript: 3,395; python: 956; makefile: 27; sh: 19
file content (290 lines) | stat: -rw-r--r-- 8,393 bytes parent folder | download
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
from __future__ import annotations

import json
from uuid import UUID

import pytest
from django.core.serializers.json import DjangoJSONEncoder
from django.http import HttpResponse, StreamingHttpResponse
from django.test import SimpleTestCase

from django_htmx.http import (
    HttpResponseClientRedirect,
    HttpResponseClientRefresh,
    HttpResponseLocation,
    HttpResponseStopPolling,
    push_url,
    replace_url,
    reswap,
    retarget,
    trigger_client_event,
)


class HttpResponseStopPollingTests(SimpleTestCase):
    def test_success(self):
        response = HttpResponseStopPolling()

        assert response.status_code == 286
        assert response.reason_phrase == "Stop Polling"


class HttpResponseClientRedirectTests(SimpleTestCase):
    def test_success(self):
        response = HttpResponseClientRedirect("https://example.com")

        assert response.status_code == 200
        assert response["HX-Redirect"] == "https://example.com"
        assert "Location" not in response

    def test_repr(self):
        response = HttpResponseClientRedirect("https://example.com")

        assert repr(response) == (
            '<HttpResponseClientRedirect status_code=200, "text/html; '
            + 'charset=utf-8", url="https://example.com">'
        )


class HttpResponseLocationTests(SimpleTestCase):
    def test_success(self):
        response = HttpResponseLocation("/home/")

        assert response.status_code == 200
        assert "Location" not in response
        spec = json.loads(response["HX-Location"])
        assert spec == {"path": "/home/"}

    def test_success_complete(self):
        response = HttpResponseLocation(
            "/home/",
            source="#button",
            event="doubleclick",
            target="#main",
            swap="innerHTML",
            select="#content",
            headers={"year": "2022"},
            values={"banner": "true"},
        )

        assert response.status_code == 200
        assert "Location" not in response
        spec = json.loads(response["HX-Location"])
        assert spec == {
            "path": "/home/",
            "source": "#button",
            "event": "doubleclick",
            "target": "#main",
            "swap": "innerHTML",
            "select": "#content",
            "headers": {"year": "2022"},
            "values": {"banner": "true"},
        }


class HttpResponseClientRefreshTests(SimpleTestCase):
    def test_success(self):
        response = HttpResponseClientRefresh()

        assert response.status_code == 200
        assert response["Content-Type"] == "text/html; charset=utf-8"
        assert response["HX-Refresh"] == "true"


class PushUrlTests(SimpleTestCase):
    def test_success(self):
        response = HttpResponse()

        response2 = push_url(response, "/index.html")

        assert response2 is response
        assert response["HX-Push-Url"] == "/index.html"

    def test_success_false(self):
        response = HttpResponse()

        response2 = push_url(response, False)

        assert response2 is response
        assert response["HX-Push-Url"] == "false"


class ReplaceUrlTests(SimpleTestCase):
    def test_success(self):
        response = HttpResponse()

        response2 = replace_url(response, "/index.html")

        assert response2 is response
        assert response["HX-Replace-Url"] == "/index.html"

    def test_success_false(self):
        response = HttpResponse()

        response2 = replace_url(response, False)

        assert response2 is response
        assert response["HX-Replace-Url"] == "false"


class ReswapTests(SimpleTestCase):
    def test_success(self):
        response = HttpResponse()

        response2 = reswap(response, "outerHTML")

        assert response2 is response
        assert response["HX-Reswap"] == "outerHTML"


class RetargetTests(SimpleTestCase):
    def test_success(self):
        response = HttpResponse()

        response2 = retarget(response, "#heading")

        assert response2 is response
        assert response["HX-Retarget"] == "#heading"


class TriggerClientEventTests(SimpleTestCase):
    def test_fail_bad_after_value(self):
        response = HttpResponse()

        with pytest.raises(ValueError) as exinfo:
            trigger_client_event(
                response,
                "custom-event",
                {},
                after="bad-value",  # type: ignore [arg-type]
            )

        assert exinfo.value.args == (
            "Value for 'after' must be one of: 'receive', 'settle', or 'swap'.",
        )

    def test_fail_header_there_not_json(self):
        response = HttpResponse()
        response["HX-Trigger"] = "broken{"

        with pytest.raises(ValueError) as exinfo:
            trigger_client_event(response, "custom-event", {})

        assert exinfo.value.args == ("'HX-Trigger' value should be valid JSON.",)

    def test_success(self):
        response = HttpResponse()

        result = trigger_client_event(
            response, "showConfetti", {"colours": ["purple", "red"]}
        )

        assert result is response
        assert (
            response["HX-Trigger"] == '{"showConfetti": {"colours": ["purple", "red"]}}'
        )

    def test_success_no_params(self):
        response = HttpResponse()

        result = trigger_client_event(response, "showConfetti")

        assert result is response
        assert response["HX-Trigger"] == '{"showConfetti": {}}'

    def test_success_streaming(self):
        response = StreamingHttpResponse(iter((b"hello",)))

        result = trigger_client_event(
            response, "showConfetti", {"colours": ["purple", "red"]}
        )

        assert result is response
        assert (
            response["HX-Trigger"] == '{"showConfetti": {"colours": ["purple", "red"]}}'
        )

    def test_success_multiple_events(self):
        response = HttpResponse()

        result1 = trigger_client_event(
            response, "showConfetti", {"colours": ["purple"]}
        )
        result2 = trigger_client_event(response, "showMessage", {"value": "Well done!"})

        assert result1 is response
        assert result2 is response
        assert response["HX-Trigger"] == (
            '{"showConfetti": {"colours": ["purple"]},'
            + ' "showMessage": {"value": "Well done!"}}'
        )

    def test_success_override(self):
        response = HttpResponse()

        trigger_client_event(response, "showMessage", {"value": "That was okay."})
        trigger_client_event(response, "showMessage", {"value": "Well done!"})

        assert response["HX-Trigger"] == '{"showMessage": {"value": "Well done!"}}'

    def test_success_after_settle(self):
        response = HttpResponse()

        trigger_client_event(
            response, "showMessage", {"value": "Great!"}, after="settle"
        )

        assert (
            response["HX-Trigger-After-Settle"]
            == '{"showMessage": {"value": "Great!"}}'
        )

    def test_success_after_swap(self):
        response = HttpResponse()

        trigger_client_event(response, "showMessage", {"value": "Great!"}, after="swap")

        assert (
            response["HX-Trigger-After-Swap"] == '{"showMessage": {"value": "Great!"}}'
        )

    def test_django_json_encoder(self):
        response = HttpResponse()
        uuid_value = UUID("{12345678-1234-5678-1234-567812345678}")

        trigger_client_event(response, "showMessage", {"uuid": uuid_value})

        assert (
            response["HX-Trigger"]
            == '{"showMessage": {"uuid": "12345678-1234-5678-1234-567812345678"}}'
        )

    def test_custom_json_encoder(self):
        class Bean:
            pass

        class BeanEncoder(DjangoJSONEncoder):
            def default(self, o):
                if isinstance(o, Bean):
                    return "bean"

                return super().default(o)

        response = HttpResponse()

        trigger_client_event(
            response,
            "showMessage",
            {
                "a": UUID("{12345678-1234-5678-1234-567812345678}"),
                "b": Bean(),
            },
            encoder=BeanEncoder,
        )

        assert response["HX-Trigger"] == (
            '{"showMessage": {'
            + '"a": "12345678-1234-5678-1234-567812345678",'
            + ' "b": "bean"'
            + "}}"
        )