File: test_objmodel.py

package info (click to toggle)
mpi4py 4.0.3-4
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 4,196 kB
  • sloc: python: 32,170; ansic: 13,449; makefile: 602; sh: 314; f90: 178; cpp: 148
file content (363 lines) | stat: -rw-r--r-- 12,680 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
from mpi4py import MPI
import mpiunittest as unittest
import ctypes
import operator
import weakref
import sys
import os


class TestObjModel(unittest.TestCase):

    objects = [
        MPI.Status(),
        MPI.DATATYPE_NULL,
        MPI.REQUEST_NULL,
        MPI.INFO_NULL,
        MPI.ERRHANDLER_NULL,
        MPI.SESSION_NULL,
        MPI.GROUP_NULL,
        MPI.WIN_NULL,
        MPI.OP_NULL,
        MPI.FILE_NULL,
        MPI.MESSAGE_NULL,
        MPI.COMM_NULL,
    ]

    def testEq(self):
        for i, obj1 in enumerate(self.objects):
            objects = self.objects[:]
            obj2 = objects[i]
            self.assertTrue (bool(obj1 == obj2))
            self.assertFalse(bool(obj1 != obj2))
            del objects[i]
            for obj2 in objects:
                self.assertTrue (bool(obj1 != obj2))
                self.assertTrue (bool(obj2 != obj1))
                self.assertFalse(bool(obj1 == obj2))
                self.assertFalse(bool(obj2 == obj1))
            self.assertFalse(bool(None == obj1 ))
            self.assertFalse(bool(obj1 == None ))
            self.assertFalse(bool(obj1 == True ))
            self.assertFalse(bool(obj1 == False))
            self.assertFalse(bool(obj1 == 12345))
            self.assertFalse(bool(obj1 == "abc"))
            self.assertFalse(bool(obj1 == [123]))
            self.assertFalse(bool(obj1 == (1,2)))
            self.assertFalse(bool(obj1 == {0:0}))
            self.assertFalse(bool(obj1 == set()))

    def testNe(self):
        for i, obj1 in enumerate(self.objects):
            objects = self.objects[:]
            obj2 = objects[i]
            self.assertFalse(bool(obj1 != obj2))
            del objects[i]
            for obj2 in objects:
                self.assertTrue(bool(obj1 != obj2))
            self.assertTrue(bool(None != obj1 ))
            self.assertTrue(bool(obj1 != None ))
            self.assertTrue(bool(obj1 != True ))
            self.assertTrue(bool(obj1 != False))
            self.assertTrue(bool(obj1 != 12345))
            self.assertTrue(bool(obj1 != "abc"))
            self.assertTrue(bool(obj1 != [123]))
            self.assertTrue(bool(obj1 != (1,2)))
            self.assertTrue(bool(obj1 != {0:0}))
            self.assertTrue(bool(obj1 != set()))

    def testCmp(self):
        for obj in self.objects:
            for binop in ('lt', 'le', 'gt', 'ge'):
                binop = getattr(operator, binop)
                with self.assertRaises(TypeError):
                    binop(obj, obj)

    def testBool(self):
        for obj in self.objects[1:]:
            self.assertFalse(not not obj)
            self.assertTrue(not obj)
            self.assertFalse(obj)

    def testReduce(self):
        import pickle
        import copy

        def functions(obj):
            for protocol in range(0, pickle.HIGHEST_PROTOCOL + 1):
                yield lambda ob: pickle.loads(pickle.dumps(ob, protocol))
            yield copy.copy
            yield copy.deepcopy

        for obj in self.objects:
            for copier in functions(obj):
                dup = copier(obj)
                self.assertIs(type(dup), type(obj))
                if isinstance(obj, MPI.Status):
                    self.assertIsNot(dup, obj)
                else:
                    self.assertIs(dup, obj)
                cls = type(obj)
                dup = copier(cls(obj))
                self.assertIs(type(dup), cls)
                self.assertIsNot(dup, obj)
                cls = type(f'My{type(obj).__name__}', (type(obj),), {})
                main = __import__('__main__')
                cls.__module__ = main.__name__
                setattr(main, cls.__name__, cls)
                dup = copier(cls(obj))
                delattr(main, cls.__name__)
                self.assertIs(type(dup), cls)
                self.assertIsNot(dup, obj)

    def testHash(self):
        for obj in self.objects:
            ob_hash = lambda: hash(obj)
            self.assertRaises(TypeError, ob_hash)

    def testInit(self):
        for i, obj in enumerate(self.objects):
            klass = type(obj)
            new = klass()
            self.assertEqual(new, obj)
            new = klass(obj)
            self.assertEqual(new, obj)
            objects = self.objects[:]
            del objects[i]
            for other in objects:
                ob_init = lambda: klass(other)
                self.assertRaises(TypeError, ob_init)
            ob_init = lambda: klass(1234)
            self.assertRaises(TypeError, ob_init)
            ob_init = lambda: klass("abc")
            self.assertRaises(TypeError, ob_init)

    def testWeakRef(self):
        for obj in self.objects:
            wr = weakref.ref(obj)
            self.assertIs(wr(), obj)
            self.assertIn(wr, weakref.getweakrefs(obj))
            wr = weakref.proxy(obj)
            self.assertIn(wr, weakref.getweakrefs(obj))

    def testHandle(self):
        objects = self.objects[:]
        objects += [
            MPI.INT,
            MPI.FLOAT,
            MPI.Request(MPI.REQUEST_NULL),
            MPI.Prequest(MPI.REQUEST_NULL),
            MPI.Grequest(MPI.REQUEST_NULL),
            MPI.INFO_ENV,
            MPI.GROUP_EMPTY,
            MPI.ERRORS_RETURN,
            MPI.ERRORS_ABORT,
            MPI.ERRORS_ARE_FATAL,
            MPI.COMM_SELF,
            MPI.COMM_WORLD,
        ]
        for obj in objects:
            if isinstance(obj, MPI.Status):
                continue
            self.assertGreaterEqual(obj.handle, 0)
            newobj = type(obj).fromhandle(obj.handle)
            self.assertEqual(newobj, obj)
            self.assertEqual(type(newobj), type(obj))
            self.assertEqual(newobj.handle, obj.handle)
            with self.assertRaises(AttributeError):
                newobj.handle = None
            with self.assertRaises(AttributeError):
                newobj.handle = obj.handle
            with self.assertRaises(AttributeError):
                del newobj.handle

    def testSafeFreeNull(self):
        objects = self.objects[:]
        for obj in objects:
            if isinstance(obj, MPI.Status):
                continue
            obj.free()
            self.assertFalse(obj)
            obj.free()
            self.assertFalse(obj)

    def testSafeFreeConstant(self):
        objects = [
            MPI.INT,
            MPI.LONG,
            MPI.FLOAT,
            MPI.DOUBLE,
            MPI.INFO_ENV,
            MPI.SUM,
            MPI.PROD,
            MPI.GROUP_EMPTY,
            MPI.ERRORS_ABORT,
            MPI.ERRORS_ARE_FATAL,
            MPI.ERRORS_RETURN,
            MPI.MESSAGE_NO_PROC,
            MPI.COMM_SELF,
            MPI.COMM_WORLD,
        ]
        for obj in filter(None, objects):
            self.assertTrue(obj)
            for _ in range(3):
                obj.free()
                self.assertTrue(obj)
            if not isinstance(obj, MPI.Errhandler):
                clon = type(obj)(obj)
                self.assertTrue(clon)
                for _ in range(3):
                    clon.free()
                    self.assertFalse(clon)
            if hasattr(obj, 'Dup'):
                self.assertTrue(obj)
                dup = obj.Dup()
                self.assertTrue(dup)
                for _ in range(3):
                    dup.free()
                    self.assertFalse(dup)
            self.assertTrue(obj)
            for _ in range(3):
                obj.free()
                self.assertTrue(obj)

    def testSafeFreeCreated(self):
        objects = [
            MPI.COMM_SELF.Isend((None, 0, MPI.BYTE), MPI.PROC_NULL),
            MPI.Op.Create(lambda *_: None),
            MPI.COMM_SELF.Get_group(),
            MPI.COMM_SELF.Get_errhandler(),
        ]
        try:
            objects += [MPI.Info.Create()]
        except (NotImplementedError, MPI.Exception):
            pass
        if os.name == 'posix':
            try:
                objects += [MPI.File.Open(MPI.COMM_SELF, "/dev/null")]
            except NotImplementedError:
                pass
        try:
            objects += [MPI.Win.Create(MPI.BOTTOM)]
        except (NotImplementedError, MPI.Exception):
            pass
        try:
            objects += [MPI.Session.Init()]
        except NotImplementedError:
            pass
        for obj in objects:
            self.assertTrue(obj)
            for _ in range(3):
                obj.free()
                self.assertFalse(obj)

    def testConstants(self):
        import pickle
        names = (
            'BOTTOM',
            'IN_PLACE',
            'BUFFER_AUTOMATIC',
        )
        for name in names:
            constant = getattr(MPI, name)
            self.assertEqual(repr(constant), name)
            self.assertEqual(memoryview(constant).nbytes, 0)
            self.assertEqual(MPI.Get_address(constant), constant)
            if sys.implementation.name != 'pypy':
                self.assertIsNone(memoryview(constant).obj)
            with self.assertRaises(ValueError):
                type(constant)(constant + 1)
            self.assertEqual(repr(constant), name)
            self.assertEqual(constant.__reduce__(), name)
            for protocol in range(pickle.HIGHEST_PROTOCOL):
                value = pickle.loads(pickle.dumps(constant, protocol))
                self.assertIs(type(value), type(constant))
                self.assertEqual(value, constant)

    def testSizeOf(self):
        for obj in self.objects:
            n1 = MPI._sizeof(obj)
            n2 = MPI._sizeof(type(obj))
            self.assertEqual(n1, n2)
        with self.assertRaises(TypeError):
            MPI._sizeof(None)

    def testAddressOf(self):
        for obj in self.objects:
            addr = MPI._addressof(obj)
            self.assertNotEqual(addr, 0)
        with self.assertRaises(TypeError):
            MPI._addressof(None)

    def testAHandleOf(self):
        for obj in self.objects:
            hdl = MPI._handleof(obj)
            self.assertGreaterEqual(hdl, 0)
        with self.assertRaises(TypeError):
            MPI._handleof(None)

    @unittest.skipUnless(sys.implementation.name == 'cpython', "cpython")
    @unittest.skipUnless(hasattr(MPI, '__pyx_capi__'), "cython")
    def testCAPI(self):
        status = MPI.Status()
        status.source = 0
        status.tag = 1
        status.error = MPI.ERR_OTHER
        extra_objects = [
            status,
            MPI.INT,
            MPI.SUM,
            MPI.INFO_ENV,
            MPI.MESSAGE_NO_PROC,
            MPI.ERRORS_RETURN,
            MPI.GROUP_EMPTY,
            MPI.COMM_SELF,
        ]

        pyapi = ctypes.pythonapi
        PyCapsule_GetPointer = pyapi.PyCapsule_GetPointer
        PyCapsule_GetPointer.restype = ctypes.c_void_p
        PyCapsule_GetPointer.argtypes = [ctypes.py_object, ctypes.c_char_p]

        pyx_capi = MPI.__pyx_capi__

        for obj in self.objects + extra_objects:
            cls = type(obj)
            if issubclass(cls, MPI.Comm):
                cls = MPI.Comm
            typename = cls.__name__
            modifier = ''
            if isinstance(obj, MPI.Status):
                mpi_type = ctypes.c_void_p
                modifier = ' *'
            elif MPI._sizeof(cls) == ctypes.sizeof(ctypes.c_uint32):
                mpi_type = ctypes.c_uint32
            elif MPI._sizeof(cls) == ctypes.sizeof(ctypes.c_uint64):
                mpi_type = ctypes.c_uint64

            new_functype = ctypes.PYFUNCTYPE(ctypes.py_object, mpi_type)
            get_functype = ctypes.PYFUNCTYPE(ctypes.c_void_p, ctypes.py_object)
            new_capsule = pyx_capi[f'PyMPI{typename}_New']
            get_capsule = pyx_capi[f'PyMPI{typename}_Get']
            new_signature = f'PyObject *(MPI_{typename}{modifier})'.encode()
            get_signature = f'MPI_{typename} *(PyObject *)'.encode()
            PyCapsule_GetPointer.restype = new_functype
            pympi_new = PyCapsule_GetPointer(new_capsule, new_signature)
            PyCapsule_GetPointer.restype = get_functype
            pympi_get = PyCapsule_GetPointer(get_capsule, get_signature)
            PyCapsule_GetPointer.restype = ctypes.c_void_p

            objptr = pympi_get(obj)
            if isinstance(obj, MPI.Status):
                newarg = objptr
            else:
                newarg = mpi_type.from_address(objptr).value
            self.assertEqual(objptr, MPI._addressof(obj))
            self.assertEqual(newarg, MPI._handleof(obj))
            newobj = pympi_new(newarg)
            self.assertIs(type(newobj), type(obj))
            self.assertEqual(newobj, obj)


if __name__ == '__main__':
    unittest.main()