File: test_list_object.py

package info (click to toggle)
python-stripe 12.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 12,864 kB
  • sloc: python: 157,573; makefile: 13; sh: 9
file content (568 lines) | stat: -rw-r--r-- 18,697 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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
import json

import pytest

import stripe


class TestListObject(object):
    @pytest.fixture
    def list_object(self):
        return stripe.ListObject.construct_from(
            {"object": "list", "url": "/my/path", "data": ["foo"]}, "mykey"
        )

    def test_list(self, http_client_mock, list_object):
        http_client_mock.stub_request(
            "get",
            path="/my/path",
            query_string="myparam=you",
            rbody='{"object": "list", "data": [{"object": "charge", "foo": "bar"}]}',
        )

        res = list_object.list(myparam="you", stripe_account="acct_123")

        http_client_mock.assert_requested(
            "get",
            path="/my/path",
            query_string="myparam=you",
            stripe_account="acct_123",
        )
        assert isinstance(res, stripe.ListObject)
        assert res.stripe_account == "acct_123"
        assert isinstance(res.data, list)
        assert isinstance(res.data[0], stripe.Charge)
        assert res.data[0].foo == "bar"

    def test_create(self, http_client_mock, list_object):
        http_client_mock.stub_request(
            "post", path="/my/path", rbody='{"object": "charge", "foo": "bar"}'
        )

        res = list_object.create(myparam="eter", stripe_account="acct_123")

        http_client_mock.assert_requested(
            "post",
            path="/my/path",
            post_data="myparam=eter",
            stripe_account="acct_123",
        )
        assert isinstance(res, stripe.Charge)
        assert res.foo == "bar"
        assert res.stripe_account == "acct_123"

    def test_create_maintains_list_properties(
        self, http_client_mock, list_object
    ):
        # Testing with real requests because our mock makes it impossible to
        # test otherwise
        charge = stripe.Charge.retrieve("ch_123", api_key="sk_test_custom")
        res = charge.refunds.create(amount=123)
        http_client_mock.assert_requested(
            "post", path="/v1/charges/ch_123/refunds", post_data="amount=123"
        )
        assert res.api_key == "sk_test_custom"

    def test_retrieve(self, http_client_mock, list_object):
        http_client_mock.stub_request(
            "get",
            path="/my/path/myid",
            query_string="myparam=cow",
            rbody='{"object": "charge", "foo": "bar"}',
        )

        res = list_object.retrieve(
            "myid", myparam="cow", stripe_account="acct_123"
        )

        http_client_mock.assert_requested(
            "get",
            path="/my/path/myid",
            query_string="myparam=cow",
            stripe_account="acct_123",
        )
        assert isinstance(res, stripe.Charge)
        assert res.foo == "bar"
        assert res.stripe_account == "acct_123"

    def test_is_empty(self):
        lo = stripe.ListObject.construct_from({"data": []}, None)
        assert lo.is_empty is True

    def test_empty_list(self):
        lo = stripe.ListObject._empty_list()
        assert lo.is_empty

    def test_iter(self):
        arr = [{"id": 1}, {"id": 2}, {"id": 3}]
        expected = stripe.util.convert_to_stripe_object(arr, api_mode="V1")
        lo = stripe.ListObject.construct_from({"data": arr}, None)
        assert list(lo) == expected

    def test_iter_reversed(self):
        arr = [{"id": 1}, {"id": 2}, {"id": 3}]
        expected = stripe.util.convert_to_stripe_object(
            list(reversed(arr)), api_mode="V1"
        )
        lo = stripe.ListObject.construct_from({"data": arr}, None)
        assert list(reversed(lo)) == expected

    def test_len(self, list_object):
        assert len(list_object) == 1

    def test_bool(self, list_object):
        assert list_object

        empty = stripe.ListObject.construct_from(
            {"object": "list", "url": "/my/path", "data": []}, "mykey"
        )
        assert bool(empty) is False

    def test_next_page(self, http_client_mock):
        lo = stripe.ListObject.construct_from(
            {
                "object": "list",
                "data": [{"id": 1}],
                "has_more": True,
                "url": "/things",
            },
            None,
        )

        http_client_mock.stub_request(
            "get",
            path="/things",
            query_string="starting_after=1",
            rbody='{"object": "list", "data": [{"id": 2}], "has_more": false, "url": "/things"}',
        )

        next_lo = lo.next_page()
        assert not next_lo.is_empty
        assert next_lo.data[0].id == 2

    def test_next_page_with_filters(self, http_client_mock):
        lo = stripe.ListObject.construct_from(
            {
                "object": "list",
                "data": [{"id": 1}],
                "has_more": True,
                "url": "/things",
            },
            None,
        )
        lo._retrieve_params = {"expand": ["data.source"], "limit": 3}

        http_client_mock.stub_request(
            "get",
            path="/things",
            query_string="expand[0]=data.source&limit=3&starting_after=1",
            rbody='{"object": "list", "data": [{"id": 2}], "has_more": false, "url": "/things"}',
        )

        next_lo = lo.next_page()
        assert next_lo._retrieve_params == {
            "expand": ["data.source"],
            "limit": 3,
            "starting_after": 1,
        }

    def test_next_page_empty_list(self):
        lo = stripe.ListObject.construct_from(
            {
                "object": "list",
                "data": [{"id": 1}],
                "has_more": False,
                "url": "/things",
            },
            None,
        )

        next_lo = lo.next_page()
        assert next_lo == stripe.ListObject._empty_list()

    def test_prev_page(self, http_client_mock):
        lo = stripe.ListObject.construct_from(
            {
                "object": "list",
                "data": [{"id": 2}],
                "has_more": True,
                "url": "/things",
            },
            None,
        )

        http_client_mock.stub_request(
            "get",
            path="/things",
            query_string="ending_before=2",
            rbody='{"object": "list", "data": [{"id": 1}], "has_more": false, "url": "/things"}',
        )

        previous_lo = lo.previous_page()
        assert not previous_lo.is_empty
        assert previous_lo.data[0].id == 1

    def test_prev_page_with_filters(self, http_client_mock):
        lo = stripe.ListObject.construct_from(
            {
                "object": "list",
                "data": [{"id": 2}],
                "has_more": True,
                "url": "/things",
            },
            None,
        )
        lo._retrieve_params = {"expand": ["data.source"], "limit": 3}

        http_client_mock.stub_request(
            "get",
            path="/things",
            query_string="ending_before=2&expand[0]=data.source&limit=3",
            rbody='{"object": "list", "data": [{"id": 1}], "has_more": false, "url": "/things"}',
        )

        previous_lo = lo.previous_page()
        assert previous_lo._retrieve_params == {
            "expand": ["data.source"],
            "limit": 3,
            "ending_before": 2,
        }

    def test_serialize_empty_list(self):
        empty = stripe.ListObject.construct_from(
            {"object": "list", "data": []}, "mykey"
        )
        serialized = str(empty)
        deserialized = stripe.ListObject.construct_from(
            json.loads(serialized), "mykey"
        )
        assert deserialized == empty

    def test_serialize_nested_empty_list(self):
        empty = stripe.ListObject.construct_from(
            {"object": "list", "data": []}, "mykey"
        )
        obj = stripe.stripe_object.StripeObject.construct_from(
            {"nested": empty}, "mykey"
        )
        serialized = str(obj)
        deserialized = stripe.stripe_object.StripeObject.construct_from(
            json.loads(serialized), "mykey"
        )
        assert deserialized.nested == empty


class TestAutoPaging:
    @staticmethod
    def pageable_model_response(ids, has_more):
        return {
            "object": "list",
            "url": "/v1/pageablemodels",
            "data": [{"id": id, "object": "pageablemodel"} for id in ids],
            "has_more": has_more,
        }

    def test_iter_one_page(self, http_client_mock):
        lo = stripe.ListObject.construct_from(
            self.pageable_model_response(["pm_123", "pm_124"], False), "mykey"
        )

        http_client_mock.assert_no_request()

        seen = [item["id"] for item in lo.auto_paging_iter()]

        assert seen == ["pm_123", "pm_124"]

    def test_iter_two_pages(self, http_client_mock):
        lo = stripe.ListObject.construct_from(
            self.pageable_model_response(["pm_123", "pm_124"], True), "mykey"
        )
        lo._retrieve_params = {"foo": "bar"}

        http_client_mock.stub_request(
            "get",
            path="/v1/pageablemodels",
            query_string="starting_after=pm_124&foo=bar",
            rbody=json.dumps(
                self.pageable_model_response(["pm_125", "pm_126"], False)
            ),
        )

        seen = [item["id"] for item in lo.auto_paging_iter()]

        http_client_mock.assert_requested(
            "get",
            path="/v1/pageablemodels",
            query_string="starting_after=pm_124&foo=bar",
        )

        assert seen == ["pm_123", "pm_124", "pm_125", "pm_126"]

    def test_iter_reverse(self, http_client_mock):
        lo = stripe.ListObject.construct_from(
            self.pageable_model_response(["pm_125", "pm_126"], True), "mykey"
        )
        lo._retrieve_params = {"foo": "bar", "ending_before": "pm_127"}

        http_client_mock.stub_request(
            "get",
            path="/v1/pageablemodels",
            query_string="ending_before=pm_125&foo=bar",
            rbody=json.dumps(
                self.pageable_model_response(["pm_123", "pm_124"], False)
            ),
        )

        seen = [item["id"] for item in lo.auto_paging_iter()]

        http_client_mock.assert_requested(
            "get",
            path="/v1/pageablemodels",
            query_string="ending_before=pm_125&foo=bar",
        )

        assert seen == ["pm_126", "pm_125", "pm_124", "pm_123"]

    def test_class_method_two_pages(self, http_client_mock):
        http_client_mock.stub_request(
            "get",
            path="/v1/charges",
            query_string="limit=25&foo=bar",
            rbody='{"object": "list", "data": [{"id": "ch_001"}], "url": "/v1/charges", "has_more": false}',
        )

        seen = [
            item["id"]
            for item in stripe.Charge.auto_paging_iter(limit=25, foo="bar")
        ]

        http_client_mock.assert_requested(
            "get", path="/v1/charges", query_string="limit=25&foo=bar"
        )
        assert seen == ["ch_001"]

    def test_iter_forwards_api_key_resource(self, http_client_mock):
        http_client_mock.stub_request(
            "get",
            path="/v1/charges",
            rbody='{"object": "list", "data": [{"id": "ch_001"}], "url": "/v1/charges", "has_more": true}',
        )

        http_client_mock.stub_request(
            "get",
            path="/v1/charges",
            query_string="starting_after=ch_001",
            rbody='{"object": "list", "data": [{"id": "ch_002"}], "url": "/v1/charges", "has_more": false}',
        )

        lo = stripe.Charge.list(api_key="sk_test_iter_forwards_options")

        assert lo.api_key == "sk_test_iter_forwards_options"

        seen = [item["id"] for item in lo.auto_paging_iter()]

        http_client_mock.assert_requested(
            "get", path="/v1/charges", api_key="sk_test_iter_forwards_options"
        )

        http_client_mock.assert_requested(
            "get",
            path="/v1/charges",
            query_string="starting_after=ch_001",
            api_key="sk_test_iter_forwards_options",
        )
        assert seen == ["ch_001", "ch_002"]

    def test_iter_forwards_api_key_client(self, http_client_mock):
        client = stripe.StripeClient(
            http_client=http_client_mock.get_mock_http_client(),
            api_key="sk_test_xyz",
        )

        http_client_mock.stub_request(
            "get",
            path="/v1/charges",
            rbody='{"object": "list", "data": [{"id": "x"}], "url": "/v1/charges", "has_more": true}',
        )

        http_client_mock.stub_request(
            "get",
            path="/v1/charges",
            query_string="starting_after=x",
            rbody='{"object": "list", "data": [{"id": "y"}, {"id": "z"}], "url": "/v1/charges", "has_more": false}',
        )

        lo = client.charges.list(
            options={"api_key": "sk_test_iter_forwards_options"}
        )

        seen = [item["id"] for item in lo.auto_paging_iter()]

        assert seen == ["x", "y", "z"]
        http_client_mock.assert_requested(
            "get",
            path="/v1/charges",
            api_key="sk_test_iter_forwards_options",
        )
        http_client_mock.assert_requested(
            "get",
            path="/v1/charges",
            query_string="starting_after=x",
            api_key="sk_test_iter_forwards_options",
        )

    def test_forwards_api_key_to_nested_resources(self, http_client_mock):
        http_client_mock.stub_request(
            "get",
            path="/v1/products",
            rbody='{"object": "list", "data": [{"id": "prod_001", "object": "product"}], "url": "/v1/products", "has_more": true}',
        )

        lo = stripe.Product.list(api_key="sk_test_iter_forwards_options")
        assert lo.api_key == "sk_test_iter_forwards_options"

        http_client_mock.assert_requested(
            "get", path="/v1/products", api_key="sk_test_iter_forwards_options"
        )

        http_client_mock.stub_request(
            "delete",
            path="/v1/products/prod_001",
        )

        lo.data[0].delete()

        http_client_mock.assert_requested(
            "delete",
            path="/v1/products/prod_001",
            api_key="sk_test_iter_forwards_options",
        )
        assert lo.data[0].api_key == "sk_test_iter_forwards_options"

    # TODO(xavdid): re-add test with a new endpoint
    # def test_iter_with_params(self, http_client_mock: HTTPClientMock):
    #     http_client_mock.stub_request(
    #         "get",
    #         path="/v1/invoices/upcoming/lines",
    #         query_string="customer=cus_123&expand[0]=data.price&limit=1",
    #         rbody=json.dumps(
    #             {
    #                 "object": "list",
    #                 "data": [
    #                     {
    #                         "id": "prod_001",
    #                         "object": "product",
    #                         "price": {"object": "price", "id": "price_123"},
    #                     }
    #                 ],
    #                 "url": "/v1/invoices/upcoming/lines?customer=cus_123&expand%5B%5D=data.price",
    #                 "has_more": True,
    #             }
    #         ),
    #     )
    #     # second page
    #     http_client_mock.stub_request(
    #         "get",
    #         path="/v1/invoices/upcoming/lines",
    #         query_string="customer=cus_123&expand[0]=data.price&limit=1&starting_after=prod_001",
    #         rbody=json.dumps(
    #             {
    #                 "object": "list",
    #                 "data": [
    #                     {
    #                         "id": "prod_002",
    #                         "object": "product",
    #                         "price": {"object": "price", "id": "price_123"},
    #                     }
    #                 ],
    #                 "url": "/v1/invoices/upcoming/lines?customer=cus_123&expand%5B%5D=data.price",
    #                 "has_more": False,
    #             }
    #         ),
    #     )

    #     lo = stripe.Invoice.upcoming_lines(
    #         api_key="sk_test_invoice_lines",
    #         customer="cus_123",
    #         expand=["data.price"],
    #         limit=1,
    #     )

    #     seen = [item["id"] for item in lo.auto_paging_iter()]

    #     assert seen == ["prod_001", "prod_002"]


class TestAutoPagingAsync:
    @staticmethod
    def pageable_model_response(ids, has_more):
        return {
            "object": "list",
            "url": "/v1/pageablemodels",
            "data": [{"id": id, "object": "pageablemodel"} for id in ids],
            "has_more": has_more,
        }

    @pytest.mark.anyio
    async def test_iter_one_page(self, http_client_mock):
        lo = stripe.ListObject.construct_from(
            self.pageable_model_response(["pm_123", "pm_124"], False), "mykey"
        )

        http_client_mock.assert_no_request()

        seen = [item["id"] async for item in lo.auto_paging_iter()]

        assert seen == ["pm_123", "pm_124"]

    @pytest.mark.anyio
    async def test_iter_two_pages(self, http_client_mock):
        lo = stripe.ListObject.construct_from(
            self.pageable_model_response(["pm_123", "pm_124"], True), "mykey"
        )
        lo._retrieve_params = {"foo": "bar"}

        http_client_mock.stub_request(
            "get",
            path="/v1/pageablemodels",
            query_string="starting_after=pm_124&foo=bar",
            rbody=json.dumps(
                self.pageable_model_response(["pm_125", "pm_126"], False)
            ),
        )

        seen = [item["id"] async for item in lo.auto_paging_iter()]

        http_client_mock.assert_requested(
            "get",
            path="/v1/pageablemodels",
            query_string="starting_after=pm_124&foo=bar",
        )

        assert seen == ["pm_123", "pm_124", "pm_125", "pm_126"]

    @pytest.mark.anyio
    async def test_iter_reverse(self, http_client_mock):
        lo = stripe.ListObject.construct_from(
            self.pageable_model_response(["pm_125", "pm_126"], True), "mykey"
        )
        lo._retrieve_params = {"foo": "bar", "ending_before": "pm_127"}

        http_client_mock.stub_request(
            "get",
            path="/v1/pageablemodels",
            query_string="ending_before=pm_125&foo=bar",
            rbody=json.dumps(
                self.pageable_model_response(["pm_123", "pm_124"], False)
            ),
        )

        seen = [item["id"] async for item in lo.auto_paging_iter()]

        http_client_mock.assert_requested(
            "get",
            path="/v1/pageablemodels",
            query_string="ending_before=pm_125&foo=bar",
        )

        assert seen == ["pm_126", "pm_125", "pm_124", "pm_123"]