File: test_c_spec.py

package info (click to toggle)
python-scipy 0.14.0-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 52,228 kB
  • ctags: 63,719
  • sloc: python: 112,726; fortran: 88,685; cpp: 86,979; ansic: 85,860; makefile: 530; sh: 236
file content (663 lines) | stat: -rw-r--r-- 18,922 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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
from __future__ import absolute_import, print_function

import os
import sys
import tempfile
import string
import time

from numpy.testing import TestCase, dec, assert_, run_module_suite

from scipy.weave import inline_tools,ext_tools,c_spec
from scipy.weave.build_tools import msvc_exists, gcc_exists
from scipy.weave.catalog import unique_file

from weave_test_utils import debug_print


def unique_mod(d,file_name):
    f = os.path.basename(unique_file(d,file_name))
    m = os.path.splitext(f)[0]
    return m


class IntConverter(TestCase):
    compiler = ''

    @dec.slow
    def test_type_match_string(self):
        s = c_spec.int_converter()
        assert_(not s.type_match('string'))

    @dec.slow
    def test_type_match_int(self):
        s = c_spec.int_converter()
        assert_(s.type_match(5))

    @dec.slow
    def test_type_match_float(self):
        s = c_spec.int_converter()
        assert_(not s.type_match(5.))

    @dec.slow
    def test_type_match_complex(self):
        s = c_spec.int_converter()
        assert_(not s.type_match(5.+1j))

    @dec.slow
    def test_var_in(self):
        mod_name = 'int_var_in' + self.compiler
        mod_name = unique_mod(test_dir,mod_name)
        mod = ext_tools.ext_module(mod_name)
        a = 1
        code = "a=2;"
        test = ext_tools.ext_function('test',code,['a'])
        mod.add_function(test)
        mod.compile(location=test_dir, compiler=self.compiler)
        exec('from ' + mod_name + ' import test')
        b = 1
        test(b)
        try:
            b = 1.
            test(b)
        except TypeError:
            pass
        try:
            b = 'abc'
            test(b)
        except TypeError:
            pass

    @dec.slow
    def test_int_return(self):
        mod_name = sys._getframe().f_code.co_name + self.compiler
        mod_name = unique_mod(test_dir,mod_name)
        mod = ext_tools.ext_module(mod_name)
        a = 1
        code = """
               a=a+2;
               return_val = PyInt_FromLong(a);
               """
        test = ext_tools.ext_function('test',code,['a'])
        mod.add_function(test)
        mod.compile(location=test_dir, compiler=self.compiler)
        exec('from ' + mod_name + ' import test')
        b = 1
        c = test(b)

        assert_(c == 3)


class FloatConverter(TestCase):
    compiler = ''

    @dec.slow
    def test_type_match_string(self):
        s = c_spec.float_converter()
        assert_(not s.type_match('string'))

    @dec.slow
    def test_type_match_int(self):
        s = c_spec.float_converter()
        assert_(not s.type_match(5))

    @dec.slow
    def test_type_match_float(self):
        s = c_spec.float_converter()
        assert_(s.type_match(5.))

    @dec.slow
    def test_type_match_complex(self):
        s = c_spec.float_converter()
        assert_(not s.type_match(5.+1j))

    @dec.slow
    def test_float_var_in(self):
        mod_name = sys._getframe().f_code.co_name + self.compiler
        mod_name = unique_mod(test_dir,mod_name)
        mod = ext_tools.ext_module(mod_name)
        a = 1.
        code = "a=2.;"
        test = ext_tools.ext_function('test',code,['a'])
        mod.add_function(test)
        mod.compile(location=test_dir, compiler=self.compiler)
        exec('from ' + mod_name + ' import test')
        b = 1.
        test(b)
        try:
            b = 1.
            test(b)
        except TypeError:
            pass
        try:
            b = 'abc'
            test(b)
        except TypeError:
            pass

    @dec.slow
    def test_float_return(self):
        mod_name = sys._getframe().f_code.co_name + self.compiler
        mod_name = unique_mod(test_dir,mod_name)
        mod = ext_tools.ext_module(mod_name)
        a = 1.
        code = """
               a=a+2.;
               return_val = PyFloat_FromDouble(a);
               """
        test = ext_tools.ext_function('test',code,['a'])
        mod.add_function(test)
        mod.compile(location=test_dir, compiler=self.compiler)
        exec('from ' + mod_name + ' import test')
        b = 1.
        c = test(b)
        assert_(c == 3.)


class ComplexConverter(TestCase):

    compiler = ''

    @dec.slow
    def test_type_match_string(self):
        s = c_spec.complex_converter()
        assert_(not s.type_match('string'))

    @dec.slow
    def test_type_match_int(self):
        s = c_spec.complex_converter()
        assert_(not s.type_match(5))

    @dec.slow
    def test_type_match_float(self):
        s = c_spec.complex_converter()
        assert_(not s.type_match(5.))

    @dec.slow
    def test_type_match_complex(self):
        s = c_spec.complex_converter()
        assert_(s.type_match(5.+1j))

    @dec.slow
    def test_complex_var_in(self):
        mod_name = sys._getframe().f_code.co_name + self.compiler
        mod_name = unique_mod(test_dir,mod_name)
        mod = ext_tools.ext_module(mod_name)
        a = 1.+1j
        code = "a=std::complex<double>(2.,2.);"
        test = ext_tools.ext_function('test',code,['a'])
        mod.add_function(test)
        mod.compile(location=test_dir, compiler=self.compiler)
        exec('from ' + mod_name + ' import test')
        b = 1.+1j
        test(b)
        try:
            b = 1.
            test(b)
        except TypeError:
            pass
        try:
            b = 'abc'
            test(b)
        except TypeError:
            pass

    @dec.slow
    def test_complex_return(self):
        mod_name = sys._getframe().f_code.co_name + self.compiler
        mod_name = unique_mod(test_dir,mod_name)
        mod = ext_tools.ext_module(mod_name)
        a = 1.+1j
        code = """
               a= a + std::complex<double>(2.,2.);
               return_val = PyComplex_FromDoubles(a.real(),a.imag());
               """
        test = ext_tools.ext_function('test',code,['a'])
        mod.add_function(test)
        mod.compile(location=test_dir, compiler=self.compiler)
        exec('from ' + mod_name + ' import test')
        b = 1.+1j
        c = test(b)
        assert_(c == 3.+3j)


#----------------------------------------------------------------------------
# File conversion tests
#----------------------------------------------------------------------------

class FileConverter(TestCase):

    compiler = ''

    @dec.slow
    def test_py_to_file(self):
        file_name = os.path.join(test_dir, "testfile")
        file = open(file_name,'w')
        code = """
               fprintf(file,"hello bob");
               """
        inline_tools.inline(code,['file'],compiler=self.compiler,force=1)
        file.close()
        file = open(file_name,'r')
        assert_(file.read() == "hello bob")

    @dec.slow
    def test_file_to_py(self):
        file_name = os.path.join(test_dir, "testfile")
        # not sure I like Py::String as default -- might move to std::sting
        # or just plain char*
        code = """
               const char* _file_name = file_name.c_str();
               FILE* file = fopen(_file_name, "w");
               return_val = file_to_py(file, _file_name, "w");
               """
        file = inline_tools.inline(code,['file_name'], compiler=self.compiler,
                                   force=1)
        file.write("hello fred")
        file.close()
        file = open(file_name,'r')
        assert_(file.read() == "hello fred")


#----------------------------------------------------------------------------
# Instance conversion tests
#----------------------------------------------------------------------------

class InstanceConverter(TestCase):
    pass


#----------------------------------------------------------------------------
# Callable object conversion tests
#----------------------------------------------------------------------------

class CallableConverter(TestCase):

    compiler = ''

    @dec.slow
    def test_call_function(self):
        func = string.find
        search_str = "hello world hello"
        sub_str = "world"
        # * Not sure about ref counts on search_str and sub_str.
        # * Is the Py::String necessary? (it works anyways...)
        code = """
               py::tuple args(2);
               args[0] = search_str;
               args[1] = sub_str;
               return_val = func.call(args);
               """
        actual = inline_tools.inline(code,['func','search_str','sub_str'],
                                     compiler=self.compiler,force=1)
        desired = func(search_str,sub_str)
        assert_(desired == actual)


class SequenceConverter(TestCase):

    compiler = ''

    @dec.slow
    def test_convert_to_dict(self):
        d = {}
        inline_tools.inline("",['d'],compiler=self.compiler,force=1)

    @dec.slow
    def test_convert_to_list(self):
        l = []
        inline_tools.inline("",['l'],compiler=self.compiler,force=1)

    @dec.slow
    def test_convert_to_string(self):
        s = 'hello'
        inline_tools.inline("",['s'],compiler=self.compiler,force=1)

    @dec.slow
    def test_convert_to_tuple(self):
        t = ()
        inline_tools.inline("",['t'],compiler=self.compiler,force=1)


class StringConverter(TestCase):

    compiler = ''

    @dec.slow
    def test_type_match_string(self):
        s = c_spec.string_converter()
        assert_(s.type_match('string'))

    @dec.slow
    def test_type_match_int(self):
        s = c_spec.string_converter()
        assert_(not s.type_match(5))

    @dec.slow
    def test_type_match_float(self):
        s = c_spec.string_converter()
        assert_(not s.type_match(5.))

    @dec.slow
    def test_type_match_complex(self):
        s = c_spec.string_converter()
        assert_(not s.type_match(5.+1j))

    @dec.slow
    def test_var_in(self):
        mod_name = 'string_var_in'+self.compiler
        mod_name = unique_mod(test_dir,mod_name)
        mod = ext_tools.ext_module(mod_name)
        a = 'string'
        code = 'a=std::string("hello");'
        test = ext_tools.ext_function('test',code,['a'])
        mod.add_function(test)
        mod.compile(location=test_dir, compiler=self.compiler)

        exec('from ' + mod_name + ' import test')
        b = 'bub'
        test(b)
        try:
            b = 1.
            test(b)
        except TypeError:
            pass
        try:
            b = 1
            test(b)
        except TypeError:
            pass

    @dec.slow
    def test_return(self):
        mod_name = 'string_return'+self.compiler
        mod_name = unique_mod(test_dir,mod_name)
        mod = ext_tools.ext_module(mod_name)
        a = 'string'
        code = """
               a= std::string("hello");
               return_val = PyString_FromString(a.c_str());
               """
        test = ext_tools.ext_function('test',code,['a'])
        mod.add_function(test)
        mod.compile(location=test_dir, compiler=self.compiler)
        exec('from ' + mod_name + ' import test')
        b = 'bub'
        c = test(b)
        assert_(c == 'hello')


class ListConverter(TestCase):

    compiler = ''

    @dec.slow
    def test_type_match_bad(self):
        s = c_spec.list_converter()
        objs = [{},(),'',1,1.,1+1j]
        for i in objs:
            assert_(not s.type_match(i))

    @dec.slow
    def test_type_match_good(self):
        s = c_spec.list_converter()
        assert_(s.type_match([]))

    @dec.slow
    def test_var_in(self):
        mod_name = 'list_var_in'+self.compiler
        mod_name = unique_mod(test_dir,mod_name)
        mod = ext_tools.ext_module(mod_name)
        a = [1]
        code = 'a=py::list();'
        test = ext_tools.ext_function('test',code,['a'])
        mod.add_function(test)
        mod.compile(location=test_dir, compiler=self.compiler)
        exec('from ' + mod_name + ' import test')
        b = [1,2]
        test(b)
        try:
            b = 1.
            test(b)
        except TypeError:
            pass
        try:
            b = 'string'
            test(b)
        except TypeError:
            pass

    @dec.slow
    def test_return(self):
        mod_name = 'list_return'+self.compiler
        mod_name = unique_mod(test_dir,mod_name)
        mod = ext_tools.ext_module(mod_name)
        a = [1]
        code = """
               a=py::list();
               a.append("hello");
               return_val = a;
               """
        test = ext_tools.ext_function('test',code,['a'])
        mod.add_function(test)
        mod.compile(location=test_dir, compiler=self.compiler)
        exec('from ' + mod_name + ' import test')
        b = [1,2]
        c = test(b)
        assert_(c == ['hello'])

    @dec.slow
    def test_speed(self):
        mod_name = 'list_speed'+self.compiler
        mod_name = unique_mod(test_dir,mod_name)
        mod = ext_tools.ext_module(mod_name)
        a = range(1000000)
        code = """
               int v, sum = 0;
               for(int i = 0; i < a.len(); i++)
               {
                   v = a[i];
                   if (v % 2)
                    sum += v;
                   else
                    sum -= v;
               }
               return_val = sum;
               """
        with_cxx = ext_tools.ext_function('with_cxx',code,['a'])
        mod.add_function(with_cxx)
        code = """
               int vv, sum = 0;
               PyObject *v;
               for(int i = 0; i < a.len(); i++)
               {
                   v = PyList_GetItem(py_a,i);
                   //didn't set error here -- just speed test
                   vv = py_to_int(v,"list item");
                   if (vv % 2)
                    sum += vv;
                   else
                    sum -= vv;
               }
               return_val = sum;
               """
        no_checking = ext_tools.ext_function('no_checking',code,['a'])
        mod.add_function(no_checking)
        mod.compile(location=test_dir, compiler=self.compiler)
        exec('from ' + mod_name + ' import with_cxx, no_checking')
        t1 = time.time()
        sum1 = with_cxx(a)
        t2 = time.time()
        debug_print('speed test for list access')
        debug_print('compiler:', self.compiler)
        debug_print('scxx:', t2 - t1)
        t1 = time.time()
        sum2 = no_checking(a)
        t2 = time.time()
        debug_print('C, no checking:', t2 - t1)
        sum3 = 0
        t1 = time.time()
        for i in a:
            if i % 2:
                sum3 += i
            else:
                sum3 -= i
        t2 = time.time()
        debug_print('python:', t2 - t1)
        assert_(sum1 == sum2 and sum1 == sum3)


class TupleConverter(TestCase):

    compiler = ''

    @dec.slow
    def test_type_match_bad(self):
        s = c_spec.tuple_converter()
        objs = [{},[],'',1,1.,1+1j]
        for i in objs:
            assert_(not s.type_match(i))

    @dec.slow
    def test_type_match_good(self):
        s = c_spec.tuple_converter()
        assert_(s.type_match((1,)))

    @dec.slow
    def test_var_in(self):
        mod_name = 'tuple_var_in'+self.compiler
        mod_name = unique_mod(test_dir,mod_name)
        mod = ext_tools.ext_module(mod_name)
        a = (1,)
        code = 'a=py::tuple();'
        test = ext_tools.ext_function('test',code,['a'])
        mod.add_function(test)
        mod.compile(location=test_dir, compiler=self.compiler)
        exec('from ' + mod_name + ' import test')
        b = (1,2)
        test(b)
        try:
            b = 1.
            test(b)
        except TypeError:
            pass
        try:
            b = 'string'
            test(b)
        except TypeError:
            pass

    @dec.slow
    def test_return(self):
        mod_name = 'tuple_return'+self.compiler
        mod_name = unique_mod(test_dir,mod_name)
        mod = ext_tools.ext_module(mod_name)
        a = (1,)
        code = """
               a=py::tuple(2);
               a[0] = "hello";
               a.set_item(1,py::None);
               return_val = a;
               """
        test = ext_tools.ext_function('test',code,['a'])
        mod.add_function(test)
        mod.compile(location=test_dir, compiler=self.compiler)
        exec('from ' + mod_name + ' import test')
        b = (1,2)
        c = test(b)
        assert_(c == ('hello',None))


class DictConverter(TestCase):
    """Base Class for dictionary conversion tests."""

    # Default string specifying the compiler to use.  While this is set
    # in all sub-classes, this base test class is found by the test
    # infrastructure and run. Therefore, we give it a default value
    # so that it can run on its own.
    compiler = ''

    @dec.slow
    def test_type_match_bad(self):
        s = c_spec.dict_converter()
        objs = [[],(),'',1,1.,1+1j]
        for i in objs:
            assert_(not s.type_match(i))

    @dec.slow
    def test_type_match_good(self):
        s = c_spec.dict_converter()
        assert_(s.type_match({}))

    @dec.slow
    def test_var_in(self):
        mod_name = 'dict_var_in'+self.compiler
        mod_name = unique_mod(test_dir,mod_name)
        mod = ext_tools.ext_module(mod_name)
        a = {'z':1}
        code = 'a=py::dict();'  # This just checks to make sure the type is correct
        test = ext_tools.ext_function('test',code,['a'])
        mod.add_function(test)
        mod.compile(location=test_dir, compiler=self.compiler)
        exec('from ' + mod_name + ' import test')
        b = {'y':2}
        test(b)
        try:
            b = 1.
            test(b)
        except TypeError:
            pass
        try:
            b = 'string'
            test(b)
        except TypeError:
            pass

    @dec.slow
    def test_return(self):
        mod_name = 'dict_return'+self.compiler
        mod_name = unique_mod(test_dir,mod_name)
        mod = ext_tools.ext_module(mod_name)
        a = {'z':1}
        code = """
               a=py::dict();
               a["hello"] = 5;
               return_val = a;
               """
        test = ext_tools.ext_function('test',code,['a'])
        mod.add_function(test)
        mod.compile(location=test_dir, compiler=self.compiler)
        exec('from ' + mod_name + ' import test')
        b = {'z':2}
        c = test(b)
        assert_(c['hello'] == 5)


for _n in dir():
    if _n[-9:] == 'Converter':
        if msvc_exists():
            exec("class Test%sMsvc(%s):\n    compiler = 'msvc'" % (_n,_n))
        else:
            exec("class Test%sUnix(%s):\n    compiler = ''" % (_n,_n))
        if gcc_exists():
            exec("class Test%sGcc(%s):\n    compiler = 'gcc'" % (_n,_n))


def setup_location():
    test_dir = tempfile.mkdtemp()
    sys.path.insert(0,test_dir)
    return test_dir

test_dir = None

def setUpModule():
    global test_dir
    test_dir = setup_location()

def tearDownModule():
    import shutil
    if test_dir is not None:
        shutil.rmtree(test_dir)

if __name__ == "__main__":
    run_module_suite()