aboutsummaryrefslogtreecommitdiffstats
path: root/3rdparty/pybind11/tests/test_numpy_array.cpp
blob: a84de77f8e8324a95ab9d33e2131cd3f45de80ea (plain)
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
/*
    tests/test_numpy_array.cpp -- test core array functionality

    Copyright (c) 2016 Ivan Smirnov <i.s.smirnov@gmail.com>

    All rights reserved. Use of this source code is governed by a
    BSD-style license that can be found in the LICENSE file.
*/

#include "pybind11_tests.h"

#include <pybind11/numpy.h>
#include <pybind11/stl.h>

#include <cstdint>

// Size / dtype checks.
struct DtypeCheck {
    py::dtype numpy{};
    py::dtype pybind11{};
};

template <typename T>
DtypeCheck get_dtype_check(const char* name) {
    py::module_ np = py::module_::import("numpy");
    DtypeCheck check{};
    check.numpy = np.attr("dtype")(np.attr(name));
    check.pybind11 = py::dtype::of<T>();
    return check;
}

std::vector<DtypeCheck> get_concrete_dtype_checks() {
    return {
        // Normalization
        get_dtype_check<std::int8_t>("int8"),
        get_dtype_check<std::uint8_t>("uint8"),
        get_dtype_check<std::int16_t>("int16"),
        get_dtype_check<std::uint16_t>("uint16"),
        get_dtype_check<std::int32_t>("int32"),
        get_dtype_check<std::uint32_t>("uint32"),
        get_dtype_check<std::int64_t>("int64"),
        get_dtype_check<std::uint64_t>("uint64")
    };
}

struct DtypeSizeCheck {
    std::string name{};
    int size_cpp{};
    int size_numpy{};
    // For debugging.
    py::dtype dtype{};
};

template <typename T>
DtypeSizeCheck get_dtype_size_check() {
    DtypeSizeCheck check{};
    check.name = py::type_id<T>();
    check.size_cpp = sizeof(T);
    check.dtype = py::dtype::of<T>();
    check.size_numpy = check.dtype.attr("itemsize").template cast<int>();
    return check;
}

std::vector<DtypeSizeCheck> get_platform_dtype_size_checks() {
    return {
        get_dtype_size_check<short>(),
        get_dtype_size_check<unsigned short>(),
        get_dtype_size_check<int>(),
        get_dtype_size_check<unsigned int>(),
        get_dtype_size_check<long>(),
        get_dtype_size_check<unsigned long>(),
        get_dtype_size_check<long long>(),
        get_dtype_size_check<unsigned long long>(),
    };
}

// Arrays.
using arr = py::array;
using arr_t = py::array_t<uint16_t, 0>;
static_assert(std::is_same<arr_t::value_type, uint16_t>::value, "");

template<typename... Ix> arr data(const arr& a, Ix... index) {
    return arr(a.nbytes() - a.offset_at(index...), (const uint8_t *) a.data(index...));
}

template<typename... Ix> arr data_t(const arr_t& a, Ix... index) {
    return arr(a.size() - a.index_at(index...), a.data(index...));
}

template<typename... Ix> arr& mutate_data(arr& a, Ix... index) {
    auto ptr = (uint8_t *) a.mutable_data(index...);
    for (py::ssize_t i = 0; i < a.nbytes() - a.offset_at(index...); i++)
        ptr[i] = (uint8_t) (ptr[i] * 2);
    return a;
}

template<typename... Ix> arr_t& mutate_data_t(arr_t& a, Ix... index) {
    auto ptr = a.mutable_data(index...);
    for (py::ssize_t i = 0; i < a.size() - a.index_at(index...); i++)
        ptr[i]++;
    return a;
}

template<typename... Ix> py::ssize_t index_at(const arr& a, Ix... idx) { return a.index_at(idx...); }
template<typename... Ix> py::ssize_t index_at_t(const arr_t& a, Ix... idx) { return a.index_at(idx...); }
template<typename... Ix> py::ssize_t offset_at(const arr& a, Ix... idx) { return a.offset_at(idx...); }
template<typename... Ix> py::ssize_t offset_at_t(const arr_t& a, Ix... idx) { return a.offset_at(idx...); }
template<typename... Ix> py::ssize_t at_t(const arr_t& a, Ix... idx) { return a.at(idx...); }
template<typename... Ix> arr_t& mutate_at_t(arr_t& a, Ix... idx) { a.mutable_at(idx...)++; return a; }

#define def_index_fn(name, type) \
    sm.def(#name, [](type a) { return name(a); }); \
    sm.def(#name, [](type a, int i) { return name(a, i); }); \
    sm.def(#name, [](type a, int i, int j) { return name(a, i, j); }); \
    sm.def(#name, [](type a, int i, int j, int k) { return name(a, i, j, k); });

template <typename T, typename T2> py::handle auxiliaries(T &&r, T2 &&r2) {
    if (r.ndim() != 2) throw std::domain_error("error: ndim != 2");
    py::list l;
    l.append(*r.data(0, 0));
    l.append(*r2.mutable_data(0, 0));
    l.append(r.data(0, 1) == r2.mutable_data(0, 1));
    l.append(r.ndim());
    l.append(r.itemsize());
    l.append(r.shape(0));
    l.append(r.shape(1));
    l.append(r.size());
    l.append(r.nbytes());
    return l.release();
}

// note: declaration at local scope would create a dangling reference!
static int data_i = 42;

TEST_SUBMODULE(numpy_array, sm) {
    try { py::module_::import("numpy"); }
    catch (...) { return; }

    // test_dtypes
    py::class_<DtypeCheck>(sm, "DtypeCheck")
        .def_readonly("numpy", &DtypeCheck::numpy)
        .def_readonly("pybind11", &DtypeCheck::pybind11)
        .def("__repr__", [](const DtypeCheck& self) {
            return py::str("<DtypeCheck numpy={} pybind11={}>").format(
                self.numpy, self.pybind11);
        });
    sm.def("get_concrete_dtype_checks", &get_concrete_dtype_checks);

    py::class_<DtypeSizeCheck>(sm, "DtypeSizeCheck")
        .def_readonly("name", &DtypeSizeCheck::name)
        .def_readonly("size_cpp", &DtypeSizeCheck::size_cpp)
        .def_readonly("size_numpy", &DtypeSizeCheck::size_numpy)
        .def("__repr__", [](const DtypeSizeCheck& self) {
            return py::str("<DtypeSizeCheck name='{}' size_cpp={} size_numpy={} dtype={}>").format(
                self.name, self.size_cpp, self.size_numpy, self.dtype);
        });
    sm.def("get_platform_dtype_size_checks", &get_platform_dtype_size_checks);

    // test_array_attributes
    sm.def("ndim", [](const arr& a) { return a.ndim(); });
    sm.def("shape", [](const arr& a) { return arr(a.ndim(), a.shape()); });
    sm.def("shape", [](const arr& a, py::ssize_t dim) { return a.shape(dim); });
    sm.def("strides", [](const arr& a) { return arr(a.ndim(), a.strides()); });
    sm.def("strides", [](const arr& a, py::ssize_t dim) { return a.strides(dim); });
    sm.def("writeable", [](const arr& a) { return a.writeable(); });
    sm.def("size", [](const arr& a) { return a.size(); });
    sm.def("itemsize", [](const arr& a) { return a.itemsize(); });
    sm.def("nbytes", [](const arr& a) { return a.nbytes(); });
    sm.def("owndata", [](const arr& a) { return a.owndata(); });

    // test_index_offset
    def_index_fn(index_at, const arr&);
    def_index_fn(index_at_t, const arr_t&);
    def_index_fn(offset_at, const arr&);
    def_index_fn(offset_at_t, const arr_t&);
    // test_data
    def_index_fn(data, const arr&);
    def_index_fn(data_t, const arr_t&);
    // test_mutate_data, test_mutate_readonly
    def_index_fn(mutate_data, arr&);
    def_index_fn(mutate_data_t, arr_t&);
    def_index_fn(at_t, const arr_t&);
    def_index_fn(mutate_at_t, arr_t&);

    // test_make_c_f_array
    sm.def("make_f_array", [] { return py::array_t<float>({ 2, 2 }, { 4, 8 }); });
    sm.def("make_c_array", [] { return py::array_t<float>({ 2, 2 }, { 8, 4 }); });

    // test_empty_shaped_array
    sm.def("make_empty_shaped_array", [] { return py::array(py::dtype("f"), {}, {}); });
    // test numpy scalars (empty shape, ndim==0)
    sm.def("scalar_int", []() { return py::array(py::dtype("i"), {}, {}, &data_i); });

    // test_wrap
    sm.def("wrap", [](py::array a) {
        return py::array(
            a.dtype(),
            {a.shape(), a.shape() + a.ndim()},
            {a.strides(), a.strides() + a.ndim()},
            a.data(),
            a
        );
    });

    // test_numpy_view
    struct ArrayClass {
        int data[2] = { 1, 2 };
        ArrayClass() { py::print("ArrayClass()"); }
        ~ArrayClass() { py::print("~ArrayClass()"); }
    };
    py::class_<ArrayClass>(sm, "ArrayClass")
        .def(py::init<>())
        .def("numpy_view", [](py::object &obj) {
            py::print("ArrayClass::numpy_view()");
            auto &a = obj.cast<ArrayClass&>();
            return py::array_t<int>({2}, {4}, a.data, obj);
        }
    );

    // test_cast_numpy_int64_to_uint64
    sm.def("function_taking_uint64", [](uint64_t) { });

    // test_isinstance
    sm.def("isinstance_untyped", [](py::object yes, py::object no) {
        return py::isinstance<py::array>(yes) && !py::isinstance<py::array>(no);
    });
    sm.def("isinstance_typed", [](py::object o) {
        return py::isinstance<py::array_t<double>>(o) && !py::isinstance<py::array_t<int>>(o);
    });

    // test_constructors
    sm.def("default_constructors", []() {
        return py::dict(
            "array"_a=py::array(),
            "array_t<int32>"_a=py::array_t<std::int32_t>(),
            "array_t<double>"_a=py::array_t<double>()
        );
    });
    sm.def("converting_constructors", [](py::object o) {
        return py::dict(
            "array"_a=py::array(o),
            "array_t<int32>"_a=py::array_t<std::int32_t>(o),
            "array_t<double>"_a=py::array_t<double>(o)
        );
    });

    // test_overload_resolution
    sm.def("overloaded", [](py::array_t<double>) { return "double"; });
    sm.def("overloaded", [](py::array_t<float>) { return "float"; });
    sm.def("overloaded", [](py::array_t<int>) { return "int"; });
    sm.def("overloaded", [](py::array_t<unsigned short>) { return "unsigned short"; });
    sm.def("overloaded", [](py::array_t<long long>) { return "long long"; });
    sm.def("overloaded", [](py::array_t<std::complex<double>>) { return "double complex"; });
    sm.def("overloaded", [](py::array_t<std::complex<float>>) { return "float complex"; });

    sm.def("overloaded2", [](py::array_t<std::complex<double>>) { return "double complex"; });
    sm.def("overloaded2", [](py::array_t<double>) { return "double"; });
    sm.def("overloaded2", [](py::array_t<std::complex<float>>) { return "float complex"; });
    sm.def("overloaded2", [](py::array_t<float>) { return "float"; });

    // Only accept the exact types:
    sm.def("overloaded3", [](py::array_t<int>) { return "int"; }, py::arg().noconvert());
    sm.def("overloaded3", [](py::array_t<double>) { return "double"; }, py::arg().noconvert());

    // Make sure we don't do unsafe coercion (e.g. float to int) when not using forcecast, but
    // rather that float gets converted via the safe (conversion to double) overload:
    sm.def("overloaded4", [](py::array_t<long long, 0>) { return "long long"; });
    sm.def("overloaded4", [](py::array_t<double, 0>) { return "double"; });

    // But we do allow conversion to int if forcecast is enabled (but only if no overload matches
    // without conversion)
    sm.def("overloaded5", [](py::array_t<unsigned int>) { return "unsigned int"; });
    sm.def("overloaded5", [](py::array_t<double>) { return "double"; });

    // test_greedy_string_overload
    // Issue 685: ndarray shouldn't go to std::string overload
    sm.def("issue685", [](std::string) { return "string"; });
    sm.def("issue685", [](py::array) { return "array"; });
    sm.def("issue685", [](py::object) { return "other"; });

    // test_array_unchecked_fixed_dims
    sm.def("proxy_add2", [](py::array_t<double> a, double v) {
        auto r = a.mutable_unchecked<2>();
        for (py::ssize_t i = 0; i < r.shape(0); i++)
            for (py::ssize_t j = 0; j < r.shape(1); j++)
                r(i, j) += v;
    }, py::arg().noconvert(), py::arg());

    sm.def("proxy_init3", [](double start) {
        py::array_t<double, py::array::c_style> a({ 3, 3, 3 });
        auto r = a.mutable_unchecked<3>();
        for (py::ssize_t i = 0; i < r.shape(0); i++)
        for (py::ssize_t j = 0; j < r.shape(1); j++)
        for (py::ssize_t k = 0; k < r.shape(2); k++)
            r(i, j, k) = start++;
        return a;
    });
    sm.def("proxy_init3F", [](double start) {
        py::array_t<double, py::array::f_style> a({ 3, 3, 3 });
        auto r = a.mutable_unchecked<3>();
        for (py::ssize_t k = 0; k < r.shape(2); k++)
        for (py::ssize_t j = 0; j < r.shape(1); j++)
        for (py::ssize_t i = 0; i < r.shape(0); i++)
            r(i, j, k) = start++;
        return a;
    });
    sm.def("proxy_squared_L2_norm", [](py::array_t<double> a) {
        auto r = a.unchecked<1>();
        double sumsq = 0;
        for (py::ssize_t i = 0; i < r.shape(0); i++)
            sumsq += r[i] * r(i); // Either notation works for a 1D array
        return sumsq;
    });

    sm.def("proxy_auxiliaries2", [](py::array_t<double> a) {
        auto r = a.unchecked<2>();
        auto r2 = a.mutable_unchecked<2>();
        return auxiliaries(r, r2);
    });

    sm.def("proxy_auxiliaries1_const_ref", [](py::array_t<double> a) {
        const auto &r = a.unchecked<1>();
        const auto &r2 = a.mutable_unchecked<1>();
        return r(0) == r2(0) && r[0] == r2[0];
    });

    sm.def("proxy_auxiliaries2_const_ref", [](py::array_t<double> a) {
        const auto &r = a.unchecked<2>();
        const auto &r2 = a.mutable_unchecked<2>();
        return r(0, 0) == r2(0, 0);
    });

    // test_array_unchecked_dyn_dims
    // Same as the above, but without a compile-time dimensions specification:
    sm.def("proxy_add2_dyn", [](py::array_t<double> a, double v) {
        auto r = a.mutable_unchecked();
        if (r.ndim() != 2) throw std::domain_error("error: ndim != 2");
        for (py::ssize_t i = 0; i < r.shape(0); i++)
            for (py::ssize_t j = 0; j < r.shape(1); j++)
                r(i, j) += v;
    }, py::arg().noconvert(), py::arg());
    sm.def("proxy_init3_dyn", [](double start) {
        py::array_t<double, py::array::c_style> a({ 3, 3, 3 });
        auto r = a.mutable_unchecked();
        if (r.ndim() != 3) throw std::domain_error("error: ndim != 3");
        for (py::ssize_t i = 0; i < r.shape(0); i++)
        for (py::ssize_t j = 0; j < r.shape(1); j++)
        for (py::ssize_t k = 0; k < r.shape(2); k++)
            r(i, j, k) = start++;
        return a;
    });
    sm.def("proxy_auxiliaries2_dyn", [](py::array_t<double> a) {
        return auxiliaries(a.unchecked(), a.mutable_unchecked());
    });

    sm.def("array_auxiliaries2", [](py::array_t<double> a) {
        return auxiliaries(a, a);
    });

    // test_array_failures
    // Issue #785: Uninformative "Unknown internal error" exception when constructing array from empty object:
    sm.def("array_fail_test", []() { return py::array(py::object()); });
    sm.def("array_t_fail_test", []() { return py::array_t<double>(py::object()); });
    // Make sure the error from numpy is being passed through:
    sm.def("array_fail_test_negative_size", []() { int c = 0; return py::array(-1, &c); });

    // test_initializer_list
    // Issue (unnumbered; reported in #788): regression: initializer lists can be ambiguous
    sm.def("array_initializer_list1", []() { return py::array_t<float>(1); }); // { 1 } also works, but clang warns about it
    sm.def("array_initializer_list2", []() { return py::array_t<float>({ 1, 2 }); });
    sm.def("array_initializer_list3", []() { return py::array_t<float>({ 1, 2, 3 }); });
    sm.def("array_initializer_list4", []() { return py::array_t<float>({ 1, 2, 3, 4 }); });

    // test_array_resize
    // reshape array to 2D without changing size
    sm.def("array_reshape2", [](py::array_t<double> a) {
        const auto dim_sz = (py::ssize_t)std::sqrt(a.size());
        if (dim_sz * dim_sz != a.size())
            throw std::domain_error("array_reshape2: input array total size is not a squared integer");
        a.resize({dim_sz, dim_sz});
    });

    // resize to 3D array with each dimension = N
    sm.def("array_resize3", [](py::array_t<double> a, size_t N, bool refcheck) {
        a.resize({N, N, N}, refcheck);
    });

    // test_array_create_and_resize
    // return 2D array with Nrows = Ncols = N
    sm.def("create_and_resize", [](size_t N) {
        py::array_t<double> a;
        a.resize({N, N});
        std::fill(a.mutable_data(), a.mutable_data() + a.size(), 42.);
        return a;
    });

    sm.def("index_using_ellipsis", [](py::array a) {
        return a[py::make_tuple(0, py::ellipsis(), 0)];
    });

    // test_argument_conversions
    sm.def("accept_double",
           [](py::array_t<double, 0>) {},
           py::arg("a"));
    sm.def("accept_double_forcecast",
           [](py::array_t<double, py::array::forcecast>) {},
           py::arg("a"));
    sm.def("accept_double_c_style",
           [](py::array_t<double, py::array::c_style>) {},
           py::arg("a"));
    sm.def("accept_double_c_style_forcecast",
           [](py::array_t<double, py::array::forcecast | py::array::c_style>) {},
           py::arg("a"));
    sm.def("accept_double_f_style",
           [](py::array_t<double, py::array::f_style>) {},
           py::arg("a"));
    sm.def("accept_double_f_style_forcecast",
           [](py::array_t<double, py::array::forcecast | py::array::f_style>) {},
           py::arg("a"));
    sm.def("accept_double_noconvert",
           [](py::array_t<double, 0>) {},
           py::arg("a").noconvert());
    sm.def("accept_double_forcecast_noconvert",
           [](py::array_t<double, py::array::forcecast>) {},
           py::arg("a").noconvert());
    sm.def("accept_double_c_style_noconvert",
           [](py::array_t<double, py::array::c_style>) {},
           py::arg("a").noconvert());
    sm.def("accept_double_c_style_forcecast_noconvert",
           [](py::array_t<double, py::array::forcecast | py::array::c_style>) {},
           py::arg("a").noconvert());
    sm.def("accept_double_f_style_noconvert",
           [](py::array_t<double, py::array::f_style>) {},
           py::arg("a").noconvert());
    sm.def("accept_double_f_style_forcecast_noconvert",
           [](py::array_t<double, py::array::forcecast | py::array::f_style>) {},
           py::arg("a").noconvert());
}
lass="p">(0) type2count = {} type2all = {} for o in obs: all = sys.getrefcount(o) if type(o) is str and o == '<dummy key>': # avoid dictionary madness continue t = type(o) if t in type2count: type2count[t] += 1 type2all[t] += all else: type2count[t] = 1 type2all[t] = all ct = [(type2count[t] - self.type2count.get(t, 0), type2all[t] - self.type2all.get(t, 0), t) for t in type2count.iterkeys()] ct.sort() ct.reverse() printed = False for delta1, delta2, t in ct: if delta1 or delta2: if not printed: print "%-55s %8s %8s" % ('', 'insts', 'refs') printed = True print "%-55s %8d %8d" % (t, delta1, delta2) self.type2count = type2count self.type2all = type2all def runner(files, test_filter, debug): runner = ImmediateTestRunner(verbosity=VERBOSE, debug=DEBUG, progress=PROGRESS, profile=PROFILE, descriptions=False) suite = unittest.TestSuite() for file in files: s = get_suite(file, runner.result) # See if the levels match dolevel = (LEVEL == 0) or LEVEL >= getattr(s, "level", 0) if s is not None and dolevel: s = filter_testcases(s, test_filter) suite.addTest(s) try: r = runner.run(suite) if TIMESFN: r.print_times(open(TIMESFN, "w")) if VERBOSE: print "Wrote timing data to", TIMESFN if TIMETESTS: r.print_times(sys.stdout, TIMETESTS) except: if DEBUGGER: print "%s:" % (sys.exc_info()[0], ) print sys.exc_info()[1] pdb.post_mortem(sys.exc_info()[2]) else: raise def remove_stale_bytecode(arg, dirname, names): names = map(os.path.normcase, names) for name in names: if name.endswith(".pyc") or name.endswith(".pyo"): srcname = name[:-1] if srcname not in names: fullname = os.path.join(dirname, name) print "Removing stale bytecode file", fullname os.unlink(fullname) def main(module_filter, test_filter, libdir): if not KEEP_STALE_BYTECODE: os.path.walk(os.curdir, remove_stale_bytecode, None) configure_logging() # Initialize the path and cwd global pathinit pathinit = PathInit(BUILD, BUILD_INPLACE, libdir) files = find_tests(module_filter) files.sort() if GUI: gui_runner(files, test_filter) elif LOOP: if REFCOUNT: rc = sys.gettotalrefcount() track = TrackRefs() while True: runner(files, test_filter, DEBUG) gc.collect() if gc.garbage: print "GARBAGE:", len(gc.garbage), gc.garbage return if REFCOUNT: prev = rc rc = sys.gettotalrefcount() print "totalrefcount=%-8d change=%-6d" % (rc, rc - prev) track.update() else: runner(files, test_filter, DEBUG) os.chdir(pathinit.org_cwd) def configure_logging(): """Initialize the logging module.""" import logging.config # Get the log.ini file from the current directory instead of possibly # buried in the build directory. XXX This isn't perfect because if # log.ini specifies a log file, it'll be relative to the build directory. # Hmm... logini = os.path.abspath("log.ini") if os.path.exists(logini): logging.config.fileConfig(logini) else: logging.basicConfig() if os.environ.has_key("LOGGING"): level = int(os.environ["LOGGING"]) logging.getLogger().setLevel(level) def process_args(argv=None): import getopt global MODULE_FILTER global TEST_FILTER global VERBOSE global LOOP global GUI global TRACE global REFCOUNT global DEBUG global DEBUGGER global BUILD global LEVEL global LIBDIR global TIMESFN global TIMETESTS global PROGRESS global BUILD_INPLACE global KEEP_STALE_BYTECODE global TEST_DIRS global PROFILE global GC_THRESHOLD global GC_FLAGS global RUN_UNIT global RUN_FUNCTIONAL global PYCHECKER if argv is None: argv = sys.argv MODULE_FILTER = None TEST_FILTER = None VERBOSE = 0 LOOP = False GUI = False TRACE = False REFCOUNT = False DEBUG = False # Don't collect test results; simply let tests crash DEBUGGER = False BUILD = False BUILD_INPLACE = False GC_THRESHOLD = None gcdebug = 0 GC_FLAGS = [] LEVEL = 1 LIBDIR = None PROGRESS = False TIMESFN = None TIMETESTS = 0 KEEP_STALE_BYTECODE = 0 RUN_UNIT = True RUN_FUNCTIONAL = True TEST_DIRS = [] PROFILE = False PYCHECKER = False config_filename = 'test.config' # import the config file if os.path.isfile(config_filename): print 'Configuration file found.' execfile(config_filename, globals()) try: opts, args = getopt.getopt(argv[1:], "a:bBcdDfFg:G:hkl:LmMPprs:tTuUv", ["all", "help", "libdir=", "times=", "keepbytecode", "dir=", "build", "build-inplace", "at-level=", "pychecker", "debug", "pdebug", "gc-threshold=", "gc-option=", "loop", "gui", "minimal-gui", "profile", "progress", "refcount", "trace", "top-fifty", "verbose", ]) # fixme: add the long names # fixme: add the extra documentation # fixme: test for functional first! except getopt.error, msg: print msg print "Try `python %s -h' for more information." % argv[0] sys.exit(2) for k, v in opts: if k in ("-a", "--at-level"): LEVEL = int(v) elif k == "--all": LEVEL = 0 os.environ["COMPLAIN_IF_TESTS_MISSED"]='1' elif k in ("-b", "--build"): BUILD = True elif k in ("-B", "--build-inplace"): BUILD = BUILD_INPLACE = True elif k in("-c", "--pychecker"): PYCHECKER = True elif k in ("-d", "--debug"): DEBUG = True elif k in ("-D", "--pdebug"): DEBUG = True DEBUGGER = True elif k in ("-f", "--skip-unit"): RUN_UNIT = False elif k in ("-u", "--skip-functional"): RUN_FUNCTIONAL = False elif k == "-F": message = 'Unit plus functional is the default behaviour.' warnings.warn(message, DeprecationWarning) RUN_UNIT = True RUN_FUNCTIONAL = True elif k in ("-h", "--help"): print __doc__ sys.exit(0) elif k in ("-g", "--gc-threshold"): GC_THRESHOLD = int(v) elif k in ("-G", "--gc-option"): if not v.startswith("DEBUG_"): print "-G argument must be DEBUG_ flag, not", repr(v) sys.exit(1) GC_FLAGS.append(v) elif k in ('-k', '--keepbytecode'): KEEP_STALE_BYTECODE = 1 elif k in ('-l', '--libdir'): LIBDIR = v elif k in ("-L", "--loop"): LOOP = 1 elif k == "-m": GUI = "minimal" msg = "Use -M or --minimal-gui instead of -m." warnings.warn(msg, DeprecationWarning) elif k in ("-M", "--minimal-gui"): GUI = "minimal" elif k in ("-P", "--profile"): PROFILE = True elif k in ("-p", "--progress"): PROGRESS = True elif k in ("-r", "--refcount"): REFCOUNT = True elif k in ("-T", "--trace"): TRACE = True elif k in ("-t", "--top-fifty"): if not TIMETESTS: TIMETESTS = 50 elif k in ("-u", "--gui"): GUI = 1 elif k in ("-v", "--verbose"): VERBOSE += 1 elif k == "--times": try: TIMETESTS = int(v) except ValueError: # must be a filename to write TIMESFN = v elif k in ('-s', '--dir'): TEST_DIRS.append(v) if PYCHECKER: # make sure you have a recent version of pychecker if not os.environ.get("PYCHECKER"): os.environ["PYCHECKER"] = "-q" import pychecker.checker if REFCOUNT and not hasattr(sys, "gettotalrefcount"): print "-r ignored, because it needs a debug build of Python" REFCOUNT = False if sys.version_info < ( 2,3,2 ): print """\ ERROR: Your python version is not supported by Zope3. Zope3 needs Python 2.3.2 or greater. You are running:""" + sys.version sys.exit(1) if GC_THRESHOLD is not None: if GC_THRESHOLD == 0: gc.disable() print "gc disabled" else: gc.set_threshold(GC_THRESHOLD) print "gc threshold:", gc.get_threshold() if GC_FLAGS: val = 0 for flag in GC_FLAGS: v = getattr(gc, flag, None) if v is None: print "Unknown gc flag", repr(flag) print gc.set_debug.__doc__ sys.exit(1) val |= v gcdebug |= v if gcdebug: gc.set_debug(gcdebug) if BUILD: # Python 2.3 is more sane in its non -q output if sys.hexversion >= 0x02030000: qflag = "" else: qflag = "-q" cmd = sys.executable + " setup.py " + qflag + " build" if BUILD_INPLACE: cmd += "_ext -i" if VERBOSE: print cmd sts = os.system(cmd) if sts: print "Build failed", hex(sts) sys.exit(1) k = [] if RUN_UNIT: k.append(False) if RUN_FUNCTIONAL: k.append(True) global functional for functional in k: if VERBOSE: kind = functional and "FUNCTIONAL" or "UNIT" if LEVEL == 0: print "Running %s tests at all levels" % kind else: print "Running %s tests at level %d" % (kind, LEVEL) # This was to avoid functional tests outside of z3, but this doesn't really # work right. ## if functional: ## try: ## from zope.app.tests.functional import FunctionalTestSetup ## except ImportError: ## raise ## print ('Skipping functional tests: could not import ' ## 'zope.app.tests.functional') ## continue # XXX We want to change *visible* warnings into errors. The next # line changes all warnings into errors, including warnings we # normally never see. In particular, test_datetime does some # short-integer arithmetic that overflows to long ints, and, by # default, Python doesn't display the overflow warning that can # be enabled when this happens. The next line turns that into an # error instead. Guido suggests that a better to get what we're # after is to replace warnings.showwarning() with our own thing # that raises an error. ## warnings.filterwarnings("error") warnings.filterwarnings("ignore", module="logging") if args: if len(args) > 1: TEST_FILTER = args[1] MODULE_FILTER = args[0] try: if TRACE: # if the trace module is used, then we don't exit with # status if on a false return value from main. coverdir = os.path.join(os.getcwd(), "coverage") import trace ignoremods = ["os", "posixpath", "stat"] tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix], ignoremods=ignoremods, trace=False, count=True) tracer.runctx("main(MODULE_FILTER, TEST_FILTER, LIBDIR)", globals=globals(), locals=vars()) r = tracer.results() path = "/tmp/trace.%s" % os.getpid() import cPickle f = open(path, "wb") cPickle.dump(r, f) f.close() print path r.write_results(show_missing=True, summary=True, coverdir=coverdir) else: bad = main(MODULE_FILTER, TEST_FILTER, LIBDIR) if bad: sys.exit(1) except ImportError, err: print err print sys.path raise if __name__ == "__main__": process_args()