|
38 | 38 | # SOFTWARE.
|
39 | 39 | import datetime
|
40 | 40 |
|
41 |
| -from . import CPyExtType, CPyExtTestCase, CPyExtFunction, unhandled_error_compare |
| 41 | +from . import CPyExtType, CPyExtTestCase, CPyExtFunction, unhandled_error_compare, is_native_object |
42 | 42 |
|
43 | 43 | __dir__ = __file__.rpartition("/")[0]
|
44 | 44 |
|
45 | 45 |
|
| 46 | +def create_datetime_subclass(typename): |
| 47 | + return CPyExtType( |
| 48 | + f"Native{typename}Subclass", |
| 49 | + struct_base=f'PyDateTime_{typename} base;', |
| 50 | + tp_new='0', |
| 51 | + tp_alloc='0', |
| 52 | + tp_free='0', |
| 53 | + includes='#include "datetime.h"', |
| 54 | + ready_code=f''' |
| 55 | + PyDateTime_IMPORT; |
| 56 | + PyTypeObject* t = PyDateTimeAPI->{typename}Type; |
| 57 | + Py_XINCREF(t); |
| 58 | + Native{typename}SubclassType.tp_base = t; |
| 59 | + ''', |
| 60 | + ) |
| 61 | + |
| 62 | + |
| 63 | +NativeDateSubclass = create_datetime_subclass("Date") |
| 64 | +NativeTimeSubclass = create_datetime_subclass("Time") |
| 65 | +NativeDateTimeSubclass = create_datetime_subclass("DateTime") |
| 66 | +NativeDeltaSubclass = create_datetime_subclass("Delta") |
| 67 | + |
| 68 | + |
| 69 | +class ManagedNativeDateSubclass(NativeDateSubclass): |
| 70 | + pass |
| 71 | + |
| 72 | + |
| 73 | +class ManagedNativeTimeSubclass(NativeTimeSubclass): |
| 74 | + pass |
| 75 | + |
| 76 | + |
| 77 | +class ManagedNativeDateTimeSubclass(NativeDateTimeSubclass): |
| 78 | + pass |
| 79 | + |
| 80 | + |
| 81 | +class ManagedNativeDeltaSubclass(NativeDeltaSubclass): |
| 82 | + pass |
| 83 | + |
| 84 | + |
46 | 85 | class TestPyDateTime(CPyExtTestCase):
|
47 | 86 |
|
48 | 87 | def compile_module(self, name):
|
@@ -577,3 +616,30 @@ def test_write_and_invoke_member(self):
|
577 | 616 | )
|
578 | 617 | tester = TestWriteAndInvokeMemeber()
|
579 | 618 | assert tester.getDate() == "foo"
|
| 619 | + |
| 620 | + |
| 621 | +class TestNativeSubclasses: |
| 622 | + def test_time(self): |
| 623 | + for t in (NativeTimeSubclass, ManagedNativeTimeSubclass): |
| 624 | + x = t(hour=6) |
| 625 | + assert is_native_object(x) |
| 626 | + assert x.hour == 6 |
| 627 | + |
| 628 | + def test_date(self): |
| 629 | + for t in (NativeDateSubclass, ManagedNativeDateSubclass): |
| 630 | + x = t(1992, 4, 11) |
| 631 | + assert is_native_object(x) |
| 632 | + assert x.day == 11 |
| 633 | + |
| 634 | + def test_datetime(self): |
| 635 | + for t in (NativeDateTimeSubclass, ManagedNativeDateTimeSubclass): |
| 636 | + x = t(1992, 4, 11, hour=13) |
| 637 | + assert is_native_object(x) |
| 638 | + assert x.day == 11 |
| 639 | + assert x.hour == 13 |
| 640 | + |
| 641 | + def test_timedelta(self): |
| 642 | + for t in (NativeDeltaSubclass, ManagedNativeDeltaSubclass): |
| 643 | + x = t(hours=6) |
| 644 | + assert is_native_object(x) |
| 645 | + assert x.seconds == 21600 |
0 commit comments