keyword
stringclasses
7 values
repo_name
stringlengths
8
98
file_path
stringlengths
4
244
file_extension
stringclasses
29 values
file_size
int64
0
84.1M
line_count
int64
0
1.6M
content
stringlengths
1
84.1M
language
stringclasses
14 values
3D
mcellteam/mcell
libs/pybind11/tests/env.py
.py
1,022
34
# -*- coding: utf-8 -*- import platform import sys import pytest LINUX = sys.platform.startswith("linux") MACOS = sys.platform.startswith("darwin") WIN = sys.platform.startswith("win32") or sys.platform.startswith("cygwin") CPYTHON = platform.python_implementation() == "CPython" PYPY = platform.python_implementation() == "PyPy" PY2 = sys.version_info.major == 2 PY = sys.version_info def deprecated_call(): """ pytest.deprecated_call() seems broken in pytest<3.9.x; concretely, it doesn't work on CPython 3.8.0 with pytest==3.3.2 on Ubuntu 18.04 (#2922). This is a narrowed reimplementation of the following PR :( https://github.com/pytest-dev/pytest/pull/4104 """ # TODO: Remove this when testing requires pytest>=3.9. pieces = pytest.__version__.split(".") pytest_major_minor = (int(pieces[0]), int(pieces[1])) if pytest_major_minor < (3, 9): return pytest.warns((DeprecationWarning, PendingDeprecationWarning)) else: return pytest.deprecated_call()
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_const_name.cpp
.cpp
4,254
71
// Copyright (c) 2021 The Pybind Development Team. // 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" #if defined(_MSC_VER) && _MSC_VER < 1910 // MSVC 2015 fails in bizarre ways. # define PYBIND11_SKIP_TEST_CONST_NAME #else // Only test with MSVC 2017 or newer. // IUT = Implementation Under Test # define CONST_NAME_TESTS(TEST_FUNC, IUT) \ std::string TEST_FUNC(int selector) { \ switch (selector) { \ case 0: \ return IUT("").text; \ case 1: \ return IUT("A").text; \ case 2: \ return IUT("Bd").text; \ case 3: \ return IUT("Cef").text; \ case 4: \ return IUT<int>().text; /*NOLINT(bugprone-macro-parentheses)*/ \ case 5: \ return IUT<std::string>().text; /*NOLINT(bugprone-macro-parentheses)*/ \ case 6: \ return IUT<true>("T1", "T2").text; /*NOLINT(bugprone-macro-parentheses)*/ \ case 7: \ return IUT<false>("U1", "U2").text; /*NOLINT(bugprone-macro-parentheses)*/ \ case 8: \ /*NOLINTNEXTLINE(bugprone-macro-parentheses)*/ \ return IUT<true>(IUT("D1"), IUT("D2")).text; \ case 9: \ /*NOLINTNEXTLINE(bugprone-macro-parentheses)*/ \ return IUT<false>(IUT("E1"), IUT("E2")).text; \ case 10: \ return IUT("KeepAtEnd").text; \ default: \ break; \ } \ throw std::runtime_error("Invalid selector value."); \ } CONST_NAME_TESTS(const_name_tests, py::detail::const_name) # ifdef PYBIND11_DETAIL_UNDERSCORE_BACKWARD_COMPATIBILITY CONST_NAME_TESTS(underscore_tests, py::detail::_) # endif #endif // MSVC >= 2017 TEST_SUBMODULE(const_name, m) { #ifdef PYBIND11_SKIP_TEST_CONST_NAME m.attr("const_name_tests") = "PYBIND11_SKIP_TEST_CONST_NAME"; #else m.def("const_name_tests", const_name_tests); #endif #ifdef PYBIND11_SKIP_TEST_CONST_NAME m.attr("underscore_tests") = "PYBIND11_SKIP_TEST_CONST_NAME"; #elif defined(PYBIND11_DETAIL_UNDERSCORE_BACKWARD_COMPATIBILITY) m.def("underscore_tests", underscore_tests); #else m.attr("underscore_tests") = "PYBIND11_DETAIL_UNDERSCORE_BACKWARD_COMPATIBILITY not defined."; #endif }
C++
3D
mcellteam/mcell
libs/pybind11/tests/test_const_name.py
.py
650
32
# -*- coding: utf-8 -*- import pytest import env from pybind11_tests import const_name as m @pytest.mark.parametrize("func", (m.const_name_tests, m.underscore_tests)) @pytest.mark.parametrize( "selector, expected", enumerate( ( "", "A", "Bd", "Cef", "%", "%", "T1", "U2", "D1", "E2", "KeepAtEnd", ) ), ) def test_const_name(func, selector, expected): if isinstance(func, type(u"") if env.PY2 else str): pytest.skip(func) text = func(selector) assert text == expected
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_factory_constructors.py
.py
16,731
521
# -*- coding: utf-8 -*- import re import pytest import env # noqa: F401 from pybind11_tests import ConstructorStats from pybind11_tests import factory_constructors as m from pybind11_tests.factory_constructors import tag def test_init_factory_basic(): """Tests py::init_factory() wrapper around various ways of returning the object""" cstats = [ ConstructorStats.get(c) for c in [m.TestFactory1, m.TestFactory2, m.TestFactory3] ] cstats[0].alive() # force gc n_inst = ConstructorStats.detail_reg_inst() x1 = m.TestFactory1(tag.unique_ptr, 3) assert x1.value == "3" y1 = m.TestFactory1(tag.pointer) assert y1.value == "(empty)" z1 = m.TestFactory1("hi!") assert z1.value == "hi!" assert ConstructorStats.detail_reg_inst() == n_inst + 3 x2 = m.TestFactory2(tag.move) assert x2.value == "(empty2)" y2 = m.TestFactory2(tag.pointer, 7) assert y2.value == "7" z2 = m.TestFactory2(tag.unique_ptr, "hi again") assert z2.value == "hi again" assert ConstructorStats.detail_reg_inst() == n_inst + 6 x3 = m.TestFactory3(tag.shared_ptr) assert x3.value == "(empty3)" y3 = m.TestFactory3(tag.pointer, 42) assert y3.value == "42" z3 = m.TestFactory3("bye") assert z3.value == "bye" for null_ptr_kind in [tag.null_ptr, tag.null_unique_ptr, tag.null_shared_ptr]: with pytest.raises(TypeError) as excinfo: m.TestFactory3(null_ptr_kind) assert ( str(excinfo.value) == "pybind11::init(): factory function returned nullptr" ) assert [i.alive() for i in cstats] == [3, 3, 3] assert ConstructorStats.detail_reg_inst() == n_inst + 9 del x1, y2, y3, z3 assert [i.alive() for i in cstats] == [2, 2, 1] assert ConstructorStats.detail_reg_inst() == n_inst + 5 del x2, x3, y1, z1, z2 assert [i.alive() for i in cstats] == [0, 0, 0] assert ConstructorStats.detail_reg_inst() == n_inst assert [i.values() for i in cstats] == [ ["3", "hi!"], ["7", "hi again"], ["42", "bye"], ] assert [i.default_constructions for i in cstats] == [1, 1, 1] def test_init_factory_signature(msg): with pytest.raises(TypeError) as excinfo: m.TestFactory1("invalid", "constructor", "arguments") assert ( msg(excinfo.value) == """ __init__(): incompatible constructor arguments. The following argument types are supported: 1. m.factory_constructors.TestFactory1(arg0: m.factory_constructors.tag.unique_ptr_tag, arg1: int) 2. m.factory_constructors.TestFactory1(arg0: str) 3. m.factory_constructors.TestFactory1(arg0: m.factory_constructors.tag.pointer_tag) 4. m.factory_constructors.TestFactory1(arg0: handle, arg1: int, arg2: handle) Invoked with: 'invalid', 'constructor', 'arguments' """ # noqa: E501 line too long ) assert ( msg(m.TestFactory1.__init__.__doc__) == """ __init__(*args, **kwargs) Overloaded function. 1. __init__(self: m.factory_constructors.TestFactory1, arg0: m.factory_constructors.tag.unique_ptr_tag, arg1: int) -> None 2. __init__(self: m.factory_constructors.TestFactory1, arg0: str) -> None 3. __init__(self: m.factory_constructors.TestFactory1, arg0: m.factory_constructors.tag.pointer_tag) -> None 4. __init__(self: m.factory_constructors.TestFactory1, arg0: handle, arg1: int, arg2: handle) -> None """ # noqa: E501 line too long ) def test_init_factory_casting(): """Tests py::init_factory() wrapper with various upcasting and downcasting returns""" cstats = [ ConstructorStats.get(c) for c in [m.TestFactory3, m.TestFactory4, m.TestFactory5] ] cstats[0].alive() # force gc n_inst = ConstructorStats.detail_reg_inst() # Construction from derived references: a = m.TestFactory3(tag.pointer, tag.TF4, 4) assert a.value == "4" b = m.TestFactory3(tag.shared_ptr, tag.TF4, 5) assert b.value == "5" c = m.TestFactory3(tag.pointer, tag.TF5, 6) assert c.value == "6" d = m.TestFactory3(tag.shared_ptr, tag.TF5, 7) assert d.value == "7" assert ConstructorStats.detail_reg_inst() == n_inst + 4 # Shared a lambda with TF3: e = m.TestFactory4(tag.pointer, tag.TF4, 8) assert e.value == "8" assert ConstructorStats.detail_reg_inst() == n_inst + 5 assert [i.alive() for i in cstats] == [5, 3, 2] del a assert [i.alive() for i in cstats] == [4, 2, 2] assert ConstructorStats.detail_reg_inst() == n_inst + 4 del b, c, e assert [i.alive() for i in cstats] == [1, 0, 1] assert ConstructorStats.detail_reg_inst() == n_inst + 1 del d assert [i.alive() for i in cstats] == [0, 0, 0] assert ConstructorStats.detail_reg_inst() == n_inst assert [i.values() for i in cstats] == [ ["4", "5", "6", "7", "8"], ["4", "5", "8"], ["6", "7"], ] def test_init_factory_alias(): """Tests py::init_factory() wrapper with value conversions and alias types""" cstats = [m.TestFactory6.get_cstats(), m.TestFactory6.get_alias_cstats()] cstats[0].alive() # force gc n_inst = ConstructorStats.detail_reg_inst() a = m.TestFactory6(tag.base, 1) assert a.get() == 1 assert not a.has_alias() b = m.TestFactory6(tag.alias, "hi there") assert b.get() == 8 assert b.has_alias() c = m.TestFactory6(tag.alias, 3) assert c.get() == 3 assert c.has_alias() d = m.TestFactory6(tag.alias, tag.pointer, 4) assert d.get() == 4 assert d.has_alias() e = m.TestFactory6(tag.base, tag.pointer, 5) assert e.get() == 5 assert not e.has_alias() f = m.TestFactory6(tag.base, tag.alias, tag.pointer, 6) assert f.get() == 6 assert f.has_alias() assert ConstructorStats.detail_reg_inst() == n_inst + 6 assert [i.alive() for i in cstats] == [6, 4] del a, b, e assert [i.alive() for i in cstats] == [3, 3] assert ConstructorStats.detail_reg_inst() == n_inst + 3 del f, c, d assert [i.alive() for i in cstats] == [0, 0] assert ConstructorStats.detail_reg_inst() == n_inst class MyTest(m.TestFactory6): def __init__(self, *args): m.TestFactory6.__init__(self, *args) def get(self): return -5 + m.TestFactory6.get(self) # Return Class by value, moved into new alias: z = MyTest(tag.base, 123) assert z.get() == 118 assert z.has_alias() # Return alias by value, moved into new alias: y = MyTest(tag.alias, "why hello!") assert y.get() == 5 assert y.has_alias() # Return Class by pointer, moved into new alias then original destroyed: x = MyTest(tag.base, tag.pointer, 47) assert x.get() == 42 assert x.has_alias() assert ConstructorStats.detail_reg_inst() == n_inst + 3 assert [i.alive() for i in cstats] == [3, 3] del x, y, z assert [i.alive() for i in cstats] == [0, 0] assert ConstructorStats.detail_reg_inst() == n_inst assert [i.values() for i in cstats] == [ ["1", "8", "3", "4", "5", "6", "123", "10", "47"], ["hi there", "3", "4", "6", "move", "123", "why hello!", "move", "47"], ] def test_init_factory_dual(): """Tests init factory functions with dual main/alias factory functions""" from pybind11_tests.factory_constructors import TestFactory7 cstats = [TestFactory7.get_cstats(), TestFactory7.get_alias_cstats()] cstats[0].alive() # force gc n_inst = ConstructorStats.detail_reg_inst() class PythFactory7(TestFactory7): def get(self): return 100 + TestFactory7.get(self) a1 = TestFactory7(1) a2 = PythFactory7(2) assert a1.get() == 1 assert a2.get() == 102 assert not a1.has_alias() assert a2.has_alias() b1 = TestFactory7(tag.pointer, 3) b2 = PythFactory7(tag.pointer, 4) assert b1.get() == 3 assert b2.get() == 104 assert not b1.has_alias() assert b2.has_alias() c1 = TestFactory7(tag.mixed, 5) c2 = PythFactory7(tag.mixed, 6) assert c1.get() == 5 assert c2.get() == 106 assert not c1.has_alias() assert c2.has_alias() d1 = TestFactory7(tag.base, tag.pointer, 7) d2 = PythFactory7(tag.base, tag.pointer, 8) assert d1.get() == 7 assert d2.get() == 108 assert not d1.has_alias() assert d2.has_alias() # Both return an alias; the second multiplies the value by 10: e1 = TestFactory7(tag.alias, tag.pointer, 9) e2 = PythFactory7(tag.alias, tag.pointer, 10) assert e1.get() == 9 assert e2.get() == 200 assert e1.has_alias() assert e2.has_alias() f1 = TestFactory7(tag.shared_ptr, tag.base, 11) f2 = PythFactory7(tag.shared_ptr, tag.base, 12) assert f1.get() == 11 assert f2.get() == 112 assert not f1.has_alias() assert f2.has_alias() g1 = TestFactory7(tag.shared_ptr, tag.invalid_base, 13) assert g1.get() == 13 assert not g1.has_alias() with pytest.raises(TypeError) as excinfo: PythFactory7(tag.shared_ptr, tag.invalid_base, 14) assert ( str(excinfo.value) == "pybind11::init(): construction failed: returned holder-wrapped instance is not an " "alias instance" ) assert [i.alive() for i in cstats] == [13, 7] assert ConstructorStats.detail_reg_inst() == n_inst + 13 del a1, a2, b1, d1, e1, e2 assert [i.alive() for i in cstats] == [7, 4] assert ConstructorStats.detail_reg_inst() == n_inst + 7 del b2, c1, c2, d2, f1, f2, g1 assert [i.alive() for i in cstats] == [0, 0] assert ConstructorStats.detail_reg_inst() == n_inst assert [i.values() for i in cstats] == [ ["1", "2", "3", "4", "5", "6", "7", "8", "9", "100", "11", "12", "13", "14"], ["2", "4", "6", "8", "9", "100", "12"], ] def test_no_placement_new(capture): """Prior to 2.2, `py::init<...>` relied on the type supporting placement new; this tests a class without placement new support.""" with capture: a = m.NoPlacementNew(123) found = re.search(r"^operator new called, returning (\d+)\n$", str(capture)) assert found assert a.i == 123 with capture: del a pytest.gc_collect() assert capture == "operator delete called on " + found.group(1) with capture: b = m.NoPlacementNew() found = re.search(r"^operator new called, returning (\d+)\n$", str(capture)) assert found assert b.i == 100 with capture: del b pytest.gc_collect() assert capture == "operator delete called on " + found.group(1) def test_multiple_inheritance(): class MITest(m.TestFactory1, m.TestFactory2): def __init__(self): m.TestFactory1.__init__(self, tag.unique_ptr, 33) m.TestFactory2.__init__(self, tag.move) a = MITest() assert m.TestFactory1.value.fget(a) == "33" assert m.TestFactory2.value.fget(a) == "(empty2)" def create_and_destroy(*args): a = m.NoisyAlloc(*args) print("---") del a pytest.gc_collect() def strip_comments(s): return re.sub(r"\s+#.*", "", s) def test_reallocation_a(capture, msg): """When the constructor is overloaded, previous overloads can require a preallocated value. This test makes sure that such preallocated values only happen when they might be necessary, and that they are deallocated properly.""" pytest.gc_collect() with capture: create_and_destroy(1) assert ( msg(capture) == """ noisy new noisy placement new NoisyAlloc(int 1) --- ~NoisyAlloc() noisy delete """ ) def test_reallocation_b(capture, msg): with capture: create_and_destroy(1.5) assert msg(capture) == strip_comments( """ noisy new # allocation required to attempt first overload noisy delete # have to dealloc before considering factory init overload noisy new # pointer factory calling "new", part 1: allocation NoisyAlloc(double 1.5) # ... part two, invoking constructor --- ~NoisyAlloc() # Destructor noisy delete # operator delete """ ) def test_reallocation_c(capture, msg): with capture: create_and_destroy(2, 3) assert msg(capture) == strip_comments( """ noisy new # pointer factory calling "new", allocation NoisyAlloc(int 2) # constructor --- ~NoisyAlloc() # Destructor noisy delete # operator delete """ ) def test_reallocation_d(capture, msg): with capture: create_and_destroy(2.5, 3) assert msg(capture) == strip_comments( """ NoisyAlloc(double 2.5) # construction (local func variable: operator_new not called) noisy new # return-by-value "new" part 1: allocation ~NoisyAlloc() # moved-away local func variable destruction --- ~NoisyAlloc() # Destructor noisy delete # operator delete """ ) def test_reallocation_e(capture, msg): with capture: create_and_destroy(3.5, 4.5) assert msg(capture) == strip_comments( """ noisy new # preallocation needed before invoking placement-new overload noisy placement new # Placement new NoisyAlloc(double 3.5) # construction --- ~NoisyAlloc() # Destructor noisy delete # operator delete """ ) def test_reallocation_f(capture, msg): with capture: create_and_destroy(4, 0.5) assert msg(capture) == strip_comments( """ noisy new # preallocation needed before invoking placement-new overload noisy delete # deallocation of preallocated storage noisy new # Factory pointer allocation NoisyAlloc(int 4) # factory pointer construction --- ~NoisyAlloc() # Destructor noisy delete # operator delete """ ) def test_reallocation_g(capture, msg): with capture: create_and_destroy(5, "hi") assert msg(capture) == strip_comments( """ noisy new # preallocation needed before invoking first placement new noisy delete # delete before considering new-style constructor noisy new # preallocation for second placement new noisy placement new # Placement new in the second placement new overload NoisyAlloc(int 5) # construction --- ~NoisyAlloc() # Destructor noisy delete # operator delete """ ) @pytest.mark.skipif("env.PY2") def test_invalid_self(): """Tests invocation of the pybind-registered base class with an invalid `self` argument. You can only actually do this on Python 3: Python 2 raises an exception itself if you try.""" class NotPybindDerived(object): pass # Attempts to initialize with an invalid type passed as `self`: class BrokenTF1(m.TestFactory1): def __init__(self, bad): if bad == 1: a = m.TestFactory2(tag.pointer, 1) m.TestFactory1.__init__(a, tag.pointer) elif bad == 2: a = NotPybindDerived() m.TestFactory1.__init__(a, tag.pointer) # Same as above, but for a class with an alias: class BrokenTF6(m.TestFactory6): def __init__(self, bad): if bad == 0: m.TestFactory6.__init__() elif bad == 1: a = m.TestFactory2(tag.pointer, 1) m.TestFactory6.__init__(a, tag.base, 1) elif bad == 2: a = m.TestFactory2(tag.pointer, 1) m.TestFactory6.__init__(a, tag.alias, 1) elif bad == 3: m.TestFactory6.__init__( NotPybindDerived.__new__(NotPybindDerived), tag.base, 1 ) elif bad == 4: m.TestFactory6.__init__( NotPybindDerived.__new__(NotPybindDerived), tag.alias, 1 ) for arg in (1, 2): with pytest.raises(TypeError) as excinfo: BrokenTF1(arg) assert ( str(excinfo.value) == "__init__(self, ...) called with invalid or missing `self` argument" ) for arg in (0, 1, 2, 3, 4): with pytest.raises(TypeError) as excinfo: BrokenTF6(arg) assert ( str(excinfo.value) == "__init__(self, ...) called with invalid or missing `self` argument" )
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_thread.py
.py
875
45
# -*- coding: utf-8 -*- import threading from pybind11_tests import thread as m class Thread(threading.Thread): def __init__(self, fn): super(Thread, self).__init__() self.fn = fn self.e = None def run(self): try: for i in range(10): self.fn(i, i) except Exception as e: self.e = e def join(self): super(Thread, self).join() if self.e: raise self.e def test_implicit_conversion(): a = Thread(m.test) b = Thread(m.test) c = Thread(m.test) for x in [a, b, c]: x.start() for x in [c, b, a]: x.join() def test_implicit_conversion_no_gil(): a = Thread(m.test_no_gil) b = Thread(m.test_no_gil) c = Thread(m.test_no_gil) for x in [a, b, c]: x.start() for x in [c, b, a]: x.join()
Python
3D
mcellteam/mcell
libs/pybind11/tests/cross_module_gil_utils.cpp
.cpp
1,781
65
/* tests/cross_module_gil_utils.cpp -- tools for acquiring GIL from a different module Copyright (c) 2019 Google LLC 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/pybind11.h> #include <cstdint> // This file mimics a DSO that makes pybind11 calls but does not define a // PYBIND11_MODULE. The purpose is to test that such a DSO can create a // py::gil_scoped_acquire when the running thread is in a GIL-released state. // // Note that we define a Python module here for convenience, but in general // this need not be the case. The typical scenario would be a DSO that implements // shared logic used internally by multiple pybind11 modules. namespace { namespace py = pybind11; void gil_acquire() { py::gil_scoped_acquire gil; } constexpr char kModuleName[] = "cross_module_gil_utils"; #if PY_MAJOR_VERSION >= 3 struct PyModuleDef moduledef = {PyModuleDef_HEAD_INIT, kModuleName, NULL, 0, NULL, NULL, NULL, NULL, NULL}; #else PyMethodDef module_methods[] = {{NULL, NULL, 0, NULL}}; #endif } // namespace extern "C" PYBIND11_EXPORT #if PY_MAJOR_VERSION >= 3 PyObject * PyInit_cross_module_gil_utils() #else void initcross_module_gil_utils() #endif { PyObject *m = #if PY_MAJOR_VERSION >= 3 PyModule_Create(&moduledef); #else Py_InitModule(kModuleName, module_methods); #endif if (m != NULL) { static_assert(sizeof(&gil_acquire) == sizeof(void *), "Function pointer must have the same size as void*"); PyModule_AddObject( m, "gil_acquire_funcaddr", PyLong_FromVoidPtr(reinterpret_cast<void *>(&gil_acquire))); } #if PY_MAJOR_VERSION >= 3 return m; #endif }
C++
3D
mcellteam/mcell
libs/pybind11/tests/test_exceptions.cpp
.cpp
10,197
306
/* tests/test_custom-exceptions.cpp -- exception translation Copyright (c) 2016 Pim Schellart <P.Schellart@princeton.edu> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #include "test_exceptions.h" #include "local_bindings.h" #include "pybind11_tests.h" #include <exception> #include <stdexcept> #include <utility> // A type that should be raised as an exception in Python class MyException : public std::exception { public: explicit MyException(const char *m) : message{m} {} const char *what() const noexcept override { return message.c_str(); } private: std::string message = ""; }; // A type that should be translated to a standard Python exception class MyException2 : public std::exception { public: explicit MyException2(const char *m) : message{m} {} const char *what() const noexcept override { return message.c_str(); } private: std::string message = ""; }; // A type that is not derived from std::exception (and is thus unknown) class MyException3 { public: explicit MyException3(const char *m) : message{m} {} virtual const char *what() const noexcept { return message.c_str(); } // Rule of 5 BEGIN: to preempt compiler warnings. MyException3(const MyException3 &) = default; MyException3(MyException3 &&) = default; MyException3 &operator=(const MyException3 &) = default; MyException3 &operator=(MyException3 &&) = default; virtual ~MyException3() = default; // Rule of 5 END. private: std::string message = ""; }; // A type that should be translated to MyException // and delegated to its exception translator class MyException4 : public std::exception { public: explicit MyException4(const char *m) : message{m} {} const char *what() const noexcept override { return message.c_str(); } private: std::string message = ""; }; // Like the above, but declared via the helper function class MyException5 : public std::logic_error { public: explicit MyException5(const std::string &what) : std::logic_error(what) {} }; // Inherits from MyException5 class MyException5_1 : public MyException5 { using MyException5::MyException5; }; // Exception that will be caught via the module local translator. class MyException6 : public std::exception { public: explicit MyException6(const char *m) : message{m} {} const char *what() const noexcept override { return message.c_str(); } private: std::string message = ""; }; struct PythonCallInDestructor { explicit PythonCallInDestructor(const py::dict &d) : d(d) {} ~PythonCallInDestructor() { d["good"] = true; } py::dict d; }; struct PythonAlreadySetInDestructor { explicit PythonAlreadySetInDestructor(const py::str &s) : s(s) {} ~PythonAlreadySetInDestructor() { py::dict foo; try { // Assign to a py::object to force read access of nonexistent dict entry py::object o = foo["bar"]; } catch (py::error_already_set &ex) { ex.discard_as_unraisable(s); } } py::str s; }; TEST_SUBMODULE(exceptions, m) { m.def("throw_std_exception", []() { throw std::runtime_error("This exception was intentionally thrown."); }); // make a new custom exception and use it as a translation target static py::exception<MyException> ex(m, "MyException"); py::register_exception_translator([](std::exception_ptr p) { try { if (p) { std::rethrow_exception(p); } } catch (const MyException &e) { // Set MyException as the active python error ex(e.what()); } }); // register new translator for MyException2 // no need to store anything here because this type will // never by visible from Python py::register_exception_translator([](std::exception_ptr p) { try { if (p) { std::rethrow_exception(p); } } catch (const MyException2 &e) { // Translate this exception to a standard RuntimeError PyErr_SetString(PyExc_RuntimeError, e.what()); } }); // register new translator for MyException4 // which will catch it and delegate to the previously registered // translator for MyException by throwing a new exception py::register_exception_translator([](std::exception_ptr p) { try { if (p) { std::rethrow_exception(p); } } catch (const MyException4 &e) { throw MyException(e.what()); } }); // A simple exception translation: auto ex5 = py::register_exception<MyException5>(m, "MyException5"); // A slightly more complicated one that declares MyException5_1 as a subclass of MyException5 py::register_exception<MyException5_1>(m, "MyException5_1", ex5.ptr()); // py::register_local_exception<LocalSimpleException>(m, "LocalSimpleException") py::register_local_exception_translator([](std::exception_ptr p) { try { if (p) { std::rethrow_exception(p); } } catch (const MyException6 &e) { PyErr_SetString(PyExc_RuntimeError, e.what()); } }); m.def("throws1", []() { throw MyException("this error should go to a custom type"); }); m.def("throws2", []() { throw MyException2("this error should go to a standard Python exception"); }); m.def("throws3", []() { throw MyException3("this error cannot be translated"); }); m.def("throws4", []() { throw MyException4("this error is rethrown"); }); m.def("throws5", []() { throw MyException5("this is a helper-defined translated exception"); }); m.def("throws5_1", []() { throw MyException5_1("MyException5 subclass"); }); m.def("throws6", []() { throw MyException6("MyException6 only handled in this module"); }); m.def("throws_logic_error", []() { throw std::logic_error("this error should fall through to the standard handler"); }); m.def("throws_overflow_error", []() { throw std::overflow_error(""); }); m.def("throws_local_error", []() { throw LocalException("never caught"); }); m.def("throws_local_simple_error", []() { throw LocalSimpleException("this mod"); }); m.def("exception_matches", []() { py::dict foo; try { // Assign to a py::object to force read access of nonexistent dict entry py::object o = foo["bar"]; } catch (py::error_already_set &ex) { if (!ex.matches(PyExc_KeyError)) { throw; } return true; } return false; }); m.def("exception_matches_base", []() { py::dict foo; try { // Assign to a py::object to force read access of nonexistent dict entry py::object o = foo["bar"]; } catch (py::error_already_set &ex) { if (!ex.matches(PyExc_Exception)) { throw; } return true; } return false; }); m.def("modulenotfound_exception_matches_base", []() { try { // On Python >= 3.6, this raises a ModuleNotFoundError, a subclass of ImportError py::module_::import("nonexistent"); } catch (py::error_already_set &ex) { if (!ex.matches(PyExc_ImportError)) { throw; } return true; } return false; }); m.def("throw_already_set", [](bool err) { if (err) { PyErr_SetString(PyExc_ValueError, "foo"); } try { throw py::error_already_set(); } catch (const std::runtime_error &e) { if ((err && e.what() != std::string("ValueError: foo")) || (!err && e.what() != std::string("Unknown internal error occurred"))) { PyErr_Clear(); throw std::runtime_error("error message mismatch"); } } PyErr_Clear(); if (err) { PyErr_SetString(PyExc_ValueError, "foo"); } throw py::error_already_set(); }); m.def("python_call_in_destructor", [](const py::dict &d) { bool retval = false; try { PythonCallInDestructor set_dict_in_destructor(d); PyErr_SetString(PyExc_ValueError, "foo"); throw py::error_already_set(); } catch (const py::error_already_set &) { retval = true; } return retval; }); m.def("python_alreadyset_in_destructor", [](const py::str &s) { PythonAlreadySetInDestructor alreadyset_in_destructor(s); return true; }); // test_nested_throws m.def("try_catch", [m](const py::object &exc_type, const py::function &f, const py::args &args) { try { f(*args); } catch (py::error_already_set &ex) { if (ex.matches(exc_type)) { py::print(ex.what()); } else { throw; } } }); // Test repr that cannot be displayed m.def("simple_bool_passthrough", [](bool x) { return x; }); m.def("throw_should_be_translated_to_key_error", []() { throw shared_exception(); }); #if PY_VERSION_HEX >= 0x03030000 m.def("raise_from", []() { PyErr_SetString(PyExc_ValueError, "inner"); py::raise_from(PyExc_ValueError, "outer"); throw py::error_already_set(); }); m.def("raise_from_already_set", []() { try { PyErr_SetString(PyExc_ValueError, "inner"); throw py::error_already_set(); } catch (py::error_already_set &e) { py::raise_from(e, PyExc_ValueError, "outer"); throw py::error_already_set(); } }); m.def("throw_nested_exception", []() { try { throw std::runtime_error("Inner Exception"); } catch (const std::runtime_error &) { std::throw_with_nested(std::runtime_error("Outer Exception")); } }); #endif }
C++
3D
mcellteam/mcell
libs/pybind11/tests/test_eval_call.py
.py
143
6
# -*- coding: utf-8 -*- # This file is called from 'test_eval.py' if "call_test2" in locals(): call_test2(y) # noqa: F821 undefined name
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_iostream.py
.py
7,958
332
# -*- coding: utf-8 -*- import sys from contextlib import contextmanager from pybind11_tests import iostream as m try: # Python 3 from io import StringIO except ImportError: # Python 2 try: from cStringIO import StringIO except ImportError: from StringIO import StringIO try: # Python 3.4 from contextlib import redirect_stdout except ImportError: @contextmanager def redirect_stdout(target): original = sys.stdout sys.stdout = target yield sys.stdout = original try: # Python 3.5 from contextlib import redirect_stderr except ImportError: @contextmanager def redirect_stderr(target): original = sys.stderr sys.stderr = target yield sys.stderr = original def test_captured(capsys): msg = "I've been redirected to Python, I hope!" m.captured_output(msg) stdout, stderr = capsys.readouterr() assert stdout == msg assert stderr == "" m.captured_output_default(msg) stdout, stderr = capsys.readouterr() assert stdout == msg assert stderr == "" m.captured_err(msg) stdout, stderr = capsys.readouterr() assert stdout == "" assert stderr == msg def test_captured_large_string(capsys): # Make this bigger than the buffer used on the C++ side: 1024 chars msg = "I've been redirected to Python, I hope!" msg = msg * (1024 // len(msg) + 1) m.captured_output_default(msg) stdout, stderr = capsys.readouterr() assert stdout == msg assert stderr == "" def test_captured_utf8_2byte_offset0(capsys): msg = "\u07FF" msg = "" + msg * (1024 // len(msg) + 1) m.captured_output_default(msg) stdout, stderr = capsys.readouterr() assert stdout == msg assert stderr == "" def test_captured_utf8_2byte_offset1(capsys): msg = "\u07FF" msg = "1" + msg * (1024 // len(msg) + 1) m.captured_output_default(msg) stdout, stderr = capsys.readouterr() assert stdout == msg assert stderr == "" def test_captured_utf8_3byte_offset0(capsys): msg = "\uFFFF" msg = "" + msg * (1024 // len(msg) + 1) m.captured_output_default(msg) stdout, stderr = capsys.readouterr() assert stdout == msg assert stderr == "" def test_captured_utf8_3byte_offset1(capsys): msg = "\uFFFF" msg = "1" + msg * (1024 // len(msg) + 1) m.captured_output_default(msg) stdout, stderr = capsys.readouterr() assert stdout == msg assert stderr == "" def test_captured_utf8_3byte_offset2(capsys): msg = "\uFFFF" msg = "12" + msg * (1024 // len(msg) + 1) m.captured_output_default(msg) stdout, stderr = capsys.readouterr() assert stdout == msg assert stderr == "" def test_captured_utf8_4byte_offset0(capsys): msg = "\U0010FFFF" msg = "" + msg * (1024 // len(msg) + 1) m.captured_output_default(msg) stdout, stderr = capsys.readouterr() assert stdout == msg assert stderr == "" def test_captured_utf8_4byte_offset1(capsys): msg = "\U0010FFFF" msg = "1" + msg * (1024 // len(msg) + 1) m.captured_output_default(msg) stdout, stderr = capsys.readouterr() assert stdout == msg assert stderr == "" def test_captured_utf8_4byte_offset2(capsys): msg = "\U0010FFFF" msg = "12" + msg * (1024 // len(msg) + 1) m.captured_output_default(msg) stdout, stderr = capsys.readouterr() assert stdout == msg assert stderr == "" def test_captured_utf8_4byte_offset3(capsys): msg = "\U0010FFFF" msg = "123" + msg * (1024 // len(msg) + 1) m.captured_output_default(msg) stdout, stderr = capsys.readouterr() assert stdout == msg assert stderr == "" def test_guard_capture(capsys): msg = "I've been redirected to Python, I hope!" m.guard_output(msg) stdout, stderr = capsys.readouterr() assert stdout == msg assert stderr == "" def test_series_captured(capture): with capture: m.captured_output("a") m.captured_output("b") assert capture == "ab" def test_flush(capfd): msg = "(not flushed)" msg2 = "(flushed)" with m.ostream_redirect(): m.noisy_function(msg, flush=False) stdout, stderr = capfd.readouterr() assert stdout == "" m.noisy_function(msg2, flush=True) stdout, stderr = capfd.readouterr() assert stdout == msg + msg2 m.noisy_function(msg, flush=False) stdout, stderr = capfd.readouterr() assert stdout == msg def test_not_captured(capfd): msg = "Something that should not show up in log" stream = StringIO() with redirect_stdout(stream): m.raw_output(msg) stdout, stderr = capfd.readouterr() assert stdout == msg assert stderr == "" assert stream.getvalue() == "" stream = StringIO() with redirect_stdout(stream): m.captured_output(msg) stdout, stderr = capfd.readouterr() assert stdout == "" assert stderr == "" assert stream.getvalue() == msg def test_err(capfd): msg = "Something that should not show up in log" stream = StringIO() with redirect_stderr(stream): m.raw_err(msg) stdout, stderr = capfd.readouterr() assert stdout == "" assert stderr == msg assert stream.getvalue() == "" stream = StringIO() with redirect_stderr(stream): m.captured_err(msg) stdout, stderr = capfd.readouterr() assert stdout == "" assert stderr == "" assert stream.getvalue() == msg def test_multi_captured(capfd): stream = StringIO() with redirect_stdout(stream): m.captured_output("a") m.raw_output("b") m.captured_output("c") m.raw_output("d") stdout, stderr = capfd.readouterr() assert stdout == "bd" assert stream.getvalue() == "ac" def test_dual(capsys): m.captured_dual("a", "b") stdout, stderr = capsys.readouterr() assert stdout == "a" assert stderr == "b" def test_redirect(capfd): msg = "Should not be in log!" stream = StringIO() with redirect_stdout(stream): m.raw_output(msg) stdout, stderr = capfd.readouterr() assert stdout == msg assert stream.getvalue() == "" stream = StringIO() with redirect_stdout(stream): with m.ostream_redirect(): m.raw_output(msg) stdout, stderr = capfd.readouterr() assert stdout == "" assert stream.getvalue() == msg stream = StringIO() with redirect_stdout(stream): m.raw_output(msg) stdout, stderr = capfd.readouterr() assert stdout == msg assert stream.getvalue() == "" def test_redirect_err(capfd): msg = "StdOut" msg2 = "StdErr" stream = StringIO() with redirect_stderr(stream): with m.ostream_redirect(stdout=False): m.raw_output(msg) m.raw_err(msg2) stdout, stderr = capfd.readouterr() assert stdout == msg assert stderr == "" assert stream.getvalue() == msg2 def test_redirect_both(capfd): msg = "StdOut" msg2 = "StdErr" stream = StringIO() stream2 = StringIO() with redirect_stdout(stream): with redirect_stderr(stream2): with m.ostream_redirect(): m.raw_output(msg) m.raw_err(msg2) stdout, stderr = capfd.readouterr() assert stdout == "" assert stderr == "" assert stream.getvalue() == msg assert stream2.getvalue() == msg2 def test_threading(): with m.ostream_redirect(stdout=True, stderr=False): # start some threads threads = [] # start some threads for _j in range(20): threads.append(m.TestThread()) # give the threads some time to fail threads[0].sleep() # stop all the threads for t in threads: t.stop() for t in threads: t.join() # if a thread segfaults, we don't get here assert True
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_builtin_casters.cpp
.cpp
15,872
386
/* tests/test_builtin_casters.cpp -- Casters available without any additional headers Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch> 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/complex.h> #include "pybind11_tests.h" struct ConstRefCasted { int tag; }; PYBIND11_NAMESPACE_BEGIN(pybind11) PYBIND11_NAMESPACE_BEGIN(detail) template <> class type_caster<ConstRefCasted> { public: static constexpr auto name = const_name<ConstRefCasted>(); // Input is unimportant, a new value will always be constructed based on the // cast operator. bool load(handle, bool) { return true; } explicit operator ConstRefCasted &&() { value = {1}; // NOLINTNEXTLINE(performance-move-const-arg) return std::move(value); } explicit operator ConstRefCasted &() { value = {2}; return value; } explicit operator ConstRefCasted *() { value = {3}; return &value; } explicit operator const ConstRefCasted &() { value = {4}; return value; } explicit operator const ConstRefCasted *() { value = {5}; return &value; } // custom cast_op to explicitly propagate types to the conversion operators. template <typename T_> using cast_op_type = /// const conditional_t< std::is_same<remove_reference_t<T_>, const ConstRefCasted *>::value, const ConstRefCasted *, conditional_t< std::is_same<T_, const ConstRefCasted &>::value, const ConstRefCasted &, /// non-const conditional_t<std::is_same<remove_reference_t<T_>, ConstRefCasted *>::value, ConstRefCasted *, conditional_t<std::is_same<T_, ConstRefCasted &>::value, ConstRefCasted &, /* else */ ConstRefCasted &&>>>>; private: ConstRefCasted value = {0}; }; PYBIND11_NAMESPACE_END(detail) PYBIND11_NAMESPACE_END(pybind11) TEST_SUBMODULE(builtin_casters, m) { // test_simple_string m.def("string_roundtrip", [](const char *s) { return s; }); // test_unicode_conversion // Some test characters in utf16 and utf32 encodings. The last one (the 𝐀) contains a null // byte char32_t a32 = 0x61 /*a*/, z32 = 0x7a /*z*/, ib32 = 0x203d /*‽*/, cake32 = 0x1f382 /*🎂*/, mathbfA32 = 0x1d400 /*𝐀*/; char16_t b16 = 0x62 /*b*/, z16 = 0x7a, ib16 = 0x203d, cake16_1 = 0xd83c, cake16_2 = 0xdf82, mathbfA16_1 = 0xd835, mathbfA16_2 = 0xdc00; std::wstring wstr; wstr.push_back(0x61); // a wstr.push_back(0x2e18); // ⸘ if (PYBIND11_SILENCE_MSVC_C4127(sizeof(wchar_t) == 2)) { wstr.push_back(mathbfA16_1); wstr.push_back(mathbfA16_2); } // 𝐀, utf16 else { wstr.push_back((wchar_t) mathbfA32); } // 𝐀, utf32 wstr.push_back(0x7a); // z m.def("good_utf8_string", []() { return std::string((const char *) u8"Say utf8\u203d \U0001f382 \U0001d400"); }); // Say utf8‽ 🎂 𝐀 m.def("good_utf16_string", [=]() { return std::u16string({b16, ib16, cake16_1, cake16_2, mathbfA16_1, mathbfA16_2, z16}); }); // b‽🎂𝐀z m.def("good_utf32_string", [=]() { return std::u32string({a32, mathbfA32, cake32, ib32, z32}); }); // a𝐀🎂‽z m.def("good_wchar_string", [=]() { return wstr; }); // a‽𝐀z m.def("bad_utf8_string", []() { return std::string("abc\xd0" "def"); }); m.def("bad_utf16_string", [=]() { return std::u16string({b16, char16_t(0xd800), z16}); }); #if PY_MAJOR_VERSION >= 3 // Under Python 2.7, invalid unicode UTF-32 characters don't appear to trigger // UnicodeDecodeError m.def("bad_utf32_string", [=]() { return std::u32string({a32, char32_t(0xd800), z32}); }); if (PYBIND11_SILENCE_MSVC_C4127(sizeof(wchar_t) == 2)) { m.def("bad_wchar_string", [=]() { return std::wstring({wchar_t(0x61), wchar_t(0xd800)}); }); } #endif m.def("u8_Z", []() -> char { return 'Z'; }); m.def("u8_eacute", []() -> char { return '\xe9'; }); m.def("u16_ibang", [=]() -> char16_t { return ib16; }); m.def("u32_mathbfA", [=]() -> char32_t { return mathbfA32; }); m.def("wchar_heart", []() -> wchar_t { return 0x2665; }); // test_single_char_arguments m.attr("wchar_size") = py::cast(sizeof(wchar_t)); m.def("ord_char", [](char c) -> int { return static_cast<unsigned char>(c); }); m.def("ord_char_lv", [](char &c) -> int { return static_cast<unsigned char>(c); }); m.def("ord_char16", [](char16_t c) -> uint16_t { return c; }); m.def("ord_char16_lv", [](char16_t &c) -> uint16_t { return c; }); m.def("ord_char32", [](char32_t c) -> uint32_t { return c; }); m.def("ord_wchar", [](wchar_t c) -> int { return c; }); // test_bytes_to_string m.def("strlen", [](char *s) { return strlen(s); }); m.def("string_length", [](const std::string &s) { return s.length(); }); #ifdef PYBIND11_HAS_U8STRING m.attr("has_u8string") = true; m.def("good_utf8_u8string", []() { return std::u8string(u8"Say utf8\u203d \U0001f382 \U0001d400"); }); // Say utf8‽ 🎂 𝐀 m.def("bad_utf8_u8string", []() { return std::u8string((const char8_t *) "abc\xd0" "def"); }); m.def("u8_char8_Z", []() -> char8_t { return u8'Z'; }); // test_single_char_arguments m.def("ord_char8", [](char8_t c) -> int { return static_cast<unsigned char>(c); }); m.def("ord_char8_lv", [](char8_t &c) -> int { return static_cast<unsigned char>(c); }); #endif // test_string_view #ifdef PYBIND11_HAS_STRING_VIEW m.attr("has_string_view") = true; m.def("string_view_print", [](std::string_view s) { py::print(s, s.size()); }); m.def("string_view16_print", [](std::u16string_view s) { py::print(s, s.size()); }); m.def("string_view32_print", [](std::u32string_view s) { py::print(s, s.size()); }); m.def("string_view_chars", [](std::string_view s) { py::list l; for (auto c : s) { l.append((std::uint8_t) c); } return l; }); m.def("string_view16_chars", [](std::u16string_view s) { py::list l; for (auto c : s) { l.append((int) c); } return l; }); m.def("string_view32_chars", [](std::u32string_view s) { py::list l; for (auto c : s) { l.append((int) c); } return l; }); m.def("string_view_return", []() { return std::string_view((const char *) u8"utf8 secret \U0001f382"); }); m.def("string_view16_return", []() { return std::u16string_view(u"utf16 secret \U0001f382"); }); m.def("string_view32_return", []() { return std::u32string_view(U"utf32 secret \U0001f382"); }); // The inner lambdas here are to also test implicit conversion using namespace std::literals; m.def("string_view_bytes", []() { return [](py::bytes b) { return b; }("abc \x80\x80 def"sv); }); m.def("string_view_str", []() { return [](py::str s) { return s; }("abc \342\200\275 def"sv); }); m.def("string_view_from_bytes", [](const py::bytes &b) { return [](std::string_view s) { return s; }(b); }); # if PY_MAJOR_VERSION >= 3 m.def("string_view_memoryview", []() { static constexpr auto val = "Have some \360\237\216\202"sv; return py::memoryview::from_memory(val); }); # endif # ifdef PYBIND11_HAS_U8STRING m.def("string_view8_print", [](std::u8string_view s) { py::print(s, s.size()); }); m.def("string_view8_chars", [](std::u8string_view s) { py::list l; for (auto c : s) l.append((std::uint8_t) c); return l; }); m.def("string_view8_return", []() { return std::u8string_view(u8"utf8 secret \U0001f382"); }); m.def("string_view8_str", []() { return py::str{std::u8string_view{u8"abc ‽ def"}}; }); # endif struct TypeWithBothOperatorStringAndStringView { // NOLINTNEXTLINE(google-explicit-constructor) operator std::string() const { return "success"; } // NOLINTNEXTLINE(google-explicit-constructor) operator std::string_view() const { return "failure"; } }; m.def("bytes_from_type_with_both_operator_string_and_string_view", []() { return py::bytes(TypeWithBothOperatorStringAndStringView()); }); m.def("str_from_type_with_both_operator_string_and_string_view", []() { return py::str(TypeWithBothOperatorStringAndStringView()); }); #endif // test_integer_casting m.def("i32_str", [](std::int32_t v) { return std::to_string(v); }); m.def("u32_str", [](std::uint32_t v) { return std::to_string(v); }); m.def("i64_str", [](std::int64_t v) { return std::to_string(v); }); m.def("u64_str", [](std::uint64_t v) { return std::to_string(v); }); // test_int_convert m.def("int_passthrough", [](int arg) { return arg; }); m.def( "int_passthrough_noconvert", [](int arg) { return arg; }, py::arg{}.noconvert()); // test_tuple m.def( "pair_passthrough", [](const std::pair<bool, std::string> &input) { return std::make_pair(input.second, input.first); }, "Return a pair in reversed order"); m.def( "tuple_passthrough", [](std::tuple<bool, std::string, int> input) { return std::make_tuple(std::get<2>(input), std::get<1>(input), std::get<0>(input)); }, "Return a triple in reversed order"); m.def("empty_tuple", []() { return std::tuple<>(); }); static std::pair<RValueCaster, RValueCaster> lvpair; static std::tuple<RValueCaster, RValueCaster, RValueCaster> lvtuple; static std::pair<RValueCaster, std::tuple<RValueCaster, std::pair<RValueCaster, RValueCaster>>> lvnested; m.def("rvalue_pair", []() { return std::make_pair(RValueCaster{}, RValueCaster{}); }); m.def("lvalue_pair", []() -> const decltype(lvpair) & { return lvpair; }); m.def("rvalue_tuple", []() { return std::make_tuple(RValueCaster{}, RValueCaster{}, RValueCaster{}); }); m.def("lvalue_tuple", []() -> const decltype(lvtuple) & { return lvtuple; }); m.def("rvalue_nested", []() { return std::make_pair( RValueCaster{}, std::make_tuple(RValueCaster{}, std::make_pair(RValueCaster{}, RValueCaster{}))); }); m.def("lvalue_nested", []() -> const decltype(lvnested) & { return lvnested; }); static std::pair<int, std::string> int_string_pair{2, "items"}; m.def("int_string_pair", []() { return &int_string_pair; }); // test_builtins_cast_return_none m.def("return_none_string", []() -> std::string * { return nullptr; }); m.def("return_none_char", []() -> const char * { return nullptr; }); m.def("return_none_bool", []() -> bool * { return nullptr; }); m.def("return_none_int", []() -> int * { return nullptr; }); m.def("return_none_float", []() -> float * { return nullptr; }); m.def("return_none_pair", []() -> std::pair<int, int> * { return nullptr; }); // test_none_deferred m.def("defer_none_cstring", [](char *) { return false; }); m.def("defer_none_cstring", [](const py::none &) { return true; }); m.def("defer_none_custom", [](UserType *) { return false; }); m.def("defer_none_custom", [](const py::none &) { return true; }); m.def("nodefer_none_void", [](void *) { return true; }); m.def("nodefer_none_void", [](const py::none &) { return false; }); // test_void_caster m.def("load_nullptr_t", [](std::nullptr_t) {}); // not useful, but it should still compile m.def("cast_nullptr_t", []() { return std::nullptr_t{}; }); // [workaround(intel)] ICC 20/21 breaks with py::arg().stuff, using py::arg{}.stuff works. // test_bool_caster m.def("bool_passthrough", [](bool arg) { return arg; }); m.def( "bool_passthrough_noconvert", [](bool arg) { return arg; }, py::arg{}.noconvert()); // TODO: This should be disabled and fixed in future Intel compilers #if !defined(__INTEL_COMPILER) // Test "bool_passthrough_noconvert" again, but using () instead of {} to construct py::arg // When compiled with the Intel compiler, this results in segmentation faults when importing // the module. Tested with icc (ICC) 2021.1 Beta 20200827, this should be tested again when // a newer version of icc is available. m.def( "bool_passthrough_noconvert2", [](bool arg) { return arg; }, py::arg().noconvert()); #endif // test_reference_wrapper m.def("refwrap_builtin", [](std::reference_wrapper<int> p) { return 10 * p.get(); }); m.def("refwrap_usertype", [](std::reference_wrapper<UserType> p) { return p.get().value(); }); m.def("refwrap_usertype_const", [](std::reference_wrapper<const UserType> p) { return p.get().value(); }); m.def("refwrap_lvalue", []() -> std::reference_wrapper<UserType> { static UserType x(1); return std::ref(x); }); m.def("refwrap_lvalue_const", []() -> std::reference_wrapper<const UserType> { static UserType x(1); return std::cref(x); }); // Not currently supported (std::pair caster has return-by-value cast operator); // triggers static_assert failure. // m.def("refwrap_pair", [](std::reference_wrapper<std::pair<int, int>>) { }); m.def( "refwrap_list", [](bool copy) { static IncType x1(1), x2(2); py::list l; for (const auto &f : {std::ref(x1), std::ref(x2)}) { l.append(py::cast( f, copy ? py::return_value_policy::copy : py::return_value_policy::reference)); } return l; }, "copy"_a); m.def("refwrap_iiw", [](const IncType &w) { return w.value(); }); m.def("refwrap_call_iiw", [](IncType &w, const py::function &f) { py::list l; l.append(f(std::ref(w))); l.append(f(std::cref(w))); IncType x(w.value()); l.append(f(std::ref(x))); IncType y(w.value()); auto r3 = std::ref(y); l.append(f(r3)); return l; }); // test_complex m.def("complex_cast", [](float x) { return "{}"_s.format(x); }); m.def("complex_cast", [](std::complex<float> x) { return "({}, {})"_s.format(x.real(), x.imag()); }); // test int vs. long (Python 2) m.def("int_cast", []() { return (int) 42; }); m.def("long_cast", []() { return (long) 42; }); m.def("longlong_cast", []() { return ULLONG_MAX; }); /// test void* cast operator m.def("test_void_caster", []() -> bool { void *v = (void *) 0xabcd; py::object o = py::cast(v); return py::cast<void *>(o) == v; }); // Tests const/non-const propagation in cast_op. m.def("takes", [](ConstRefCasted x) { return x.tag; }); m.def("takes_move", [](ConstRefCasted &&x) { return x.tag; }); m.def("takes_ptr", [](ConstRefCasted *x) { return x->tag; }); m.def("takes_ref", [](ConstRefCasted &x) { return x.tag; }); m.def("takes_ref_wrap", [](std::reference_wrapper<ConstRefCasted> x) { return x.get().tag; }); m.def("takes_const_ptr", [](const ConstRefCasted *x) { return x->tag; }); m.def("takes_const_ref", [](const ConstRefCasted &x) { return x.tag; }); m.def("takes_const_ref_wrap", [](std::reference_wrapper<const ConstRefCasted> x) { return x.get().tag; }); }
C++
3D
mcellteam/mcell
libs/pybind11/tests/test_enum.cpp
.cpp
5,722
134
/* tests/test_enums.cpp -- enumerations Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> 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" TEST_SUBMODULE(enums, m) { // test_unscoped_enum enum UnscopedEnum { EOne = 1, ETwo, EThree }; py::enum_<UnscopedEnum>(m, "UnscopedEnum", py::arithmetic(), "An unscoped enumeration") .value("EOne", EOne, "Docstring for EOne") .value("ETwo", ETwo, "Docstring for ETwo") .value("EThree", EThree, "Docstring for EThree") .export_values(); // test_scoped_enum enum class ScopedEnum { Two = 2, Three }; py::enum_<ScopedEnum>(m, "ScopedEnum", py::arithmetic()) .value("Two", ScopedEnum::Two) .value("Three", ScopedEnum::Three); m.def("test_scoped_enum", [](ScopedEnum z) { return "ScopedEnum::" + std::string(z == ScopedEnum::Two ? "Two" : "Three"); }); // test_binary_operators enum Flags { Read = 4, Write = 2, Execute = 1 }; py::enum_<Flags>(m, "Flags", py::arithmetic()) .value("Read", Flags::Read) .value("Write", Flags::Write) .value("Execute", Flags::Execute) .export_values(); // test_implicit_conversion class ClassWithUnscopedEnum { public: enum EMode { EFirstMode = 1, ESecondMode }; static EMode test_function(EMode mode) { return mode; } }; py::class_<ClassWithUnscopedEnum> exenum_class(m, "ClassWithUnscopedEnum"); exenum_class.def_static("test_function", &ClassWithUnscopedEnum::test_function); py::enum_<ClassWithUnscopedEnum::EMode>(exenum_class, "EMode") .value("EFirstMode", ClassWithUnscopedEnum::EFirstMode) .value("ESecondMode", ClassWithUnscopedEnum::ESecondMode) .export_values(); // test_enum_to_int m.def("test_enum_to_int", [](int) {}); m.def("test_enum_to_uint", [](uint32_t) {}); m.def("test_enum_to_long_long", [](long long) {}); // test_duplicate_enum_name enum SimpleEnum { ONE, TWO, THREE }; m.def("register_bad_enum", [m]() { py::enum_<SimpleEnum>(m, "SimpleEnum") .value("ONE", SimpleEnum::ONE) // NOTE: all value function calls are called with the // same first parameter value .value("ONE", SimpleEnum::TWO) .value("ONE", SimpleEnum::THREE) .export_values(); }); // test_enum_scalar enum UnscopedUCharEnum : unsigned char {}; enum class ScopedShortEnum : short {}; enum class ScopedLongEnum : long {}; enum UnscopedUInt64Enum : std::uint64_t {}; static_assert( py::detail::all_of< std::is_same<py::enum_<UnscopedUCharEnum>::Scalar, unsigned char>, std::is_same<py::enum_<ScopedShortEnum>::Scalar, short>, std::is_same<py::enum_<ScopedLongEnum>::Scalar, long>, std::is_same<py::enum_<UnscopedUInt64Enum>::Scalar, std::uint64_t>>::value, "Error during the deduction of enum's scalar type with normal integer underlying"); // test_enum_scalar_with_char_underlying enum class ScopedCharEnum : char { Zero, Positive }; enum class ScopedWCharEnum : wchar_t { Zero, Positive }; enum class ScopedChar32Enum : char32_t { Zero, Positive }; enum class ScopedChar16Enum : char16_t { Zero, Positive }; // test the scalar of char type enums according to chapter 'Character types' // from https://en.cppreference.com/w/cpp/language/types static_assert( py::detail::any_of< std::is_same<py::enum_<ScopedCharEnum>::Scalar, signed char>, // e.g. gcc on x86 std::is_same<py::enum_<ScopedCharEnum>::Scalar, unsigned char> // e.g. arm linux >::value, "char should be cast to either signed char or unsigned char"); static_assert(sizeof(py::enum_<ScopedWCharEnum>::Scalar) == 2 || sizeof(py::enum_<ScopedWCharEnum>::Scalar) == 4, "wchar_t should be either 16 bits (Windows) or 32 (everywhere else)"); static_assert( py::detail::all_of< std::is_same<py::enum_<ScopedChar32Enum>::Scalar, std::uint_least32_t>, std::is_same<py::enum_<ScopedChar16Enum>::Scalar, std::uint_least16_t>>::value, "char32_t, char16_t (and char8_t)'s size, signedness, and alignment is determined"); #if defined(PYBIND11_HAS_U8STRING) enum class ScopedChar8Enum : char8_t { Zero, Positive }; static_assert(std::is_same<py::enum_<ScopedChar8Enum>::Scalar, unsigned char>::value); #endif // test_char_underlying_enum py::enum_<ScopedCharEnum>(m, "ScopedCharEnum") .value("Zero", ScopedCharEnum::Zero) .value("Positive", ScopedCharEnum::Positive); py::enum_<ScopedWCharEnum>(m, "ScopedWCharEnum") .value("Zero", ScopedWCharEnum::Zero) .value("Positive", ScopedWCharEnum::Positive); py::enum_<ScopedChar32Enum>(m, "ScopedChar32Enum") .value("Zero", ScopedChar32Enum::Zero) .value("Positive", ScopedChar32Enum::Positive); py::enum_<ScopedChar16Enum>(m, "ScopedChar16Enum") .value("Zero", ScopedChar16Enum::Zero) .value("Positive", ScopedChar16Enum::Positive); // test_bool_underlying_enum enum class ScopedBoolEnum : bool { FALSE, TRUE }; // bool is unsigned (std::is_signed returns false) and 1-byte long, so represented with u8 static_assert(std::is_same<py::enum_<ScopedBoolEnum>::Scalar, std::uint8_t>::value, ""); py::enum_<ScopedBoolEnum>(m, "ScopedBoolEnum") .value("FALSE", ScopedBoolEnum::FALSE) .value("TRUE", ScopedBoolEnum::TRUE); }
C++
3D
mcellteam/mcell
libs/pybind11/tests/pybind11_tests.h
.h
3,018
92
#pragma once #include <pybind11/eval.h> #include <pybind11/pybind11.h> #if defined(_MSC_VER) && _MSC_VER < 1910 // We get some really long type names here which causes MSVC 2015 to emit warnings # pragma warning( \ disable : 4503) // NOLINT: warning C4503: decorated name length exceeded, name was truncated #endif namespace py = pybind11; using namespace pybind11::literals; class test_initializer { using Initializer = void (*)(py::module_ &); public: explicit test_initializer(Initializer init); test_initializer(const char *submodule_name, Initializer init); }; #define TEST_SUBMODULE(name, variable) \ void test_submodule_##name(py::module_ &); \ test_initializer name(#name, test_submodule_##name); \ void test_submodule_##name(py::module_ &(variable)) /// Dummy type which is not exported anywhere -- something to trigger a conversion error struct UnregisteredType {}; /// A user-defined type which is exported and can be used by any test class UserType { public: UserType() = default; explicit UserType(int i) : i(i) {} int value() const { return i; } void set(int set) { i = set; } private: int i = -1; }; /// Like UserType, but increments `value` on copy for quick reference vs. copy tests class IncType : public UserType { public: using UserType::UserType; IncType() = default; IncType(const IncType &other) : IncType(other.value() + 1) {} IncType(IncType &&) = delete; IncType &operator=(const IncType &) = delete; IncType &operator=(IncType &&) = delete; }; /// A simple union for basic testing union IntFloat { int i; float f; }; /// Custom cast-only type that casts to a string "rvalue" or "lvalue" depending on the cast /// context. Used to test recursive casters (e.g. std::tuple, stl containers). struct RValueCaster {}; PYBIND11_NAMESPACE_BEGIN(pybind11) PYBIND11_NAMESPACE_BEGIN(detail) template <> class type_caster<RValueCaster> { public: PYBIND11_TYPE_CASTER(RValueCaster, const_name("RValueCaster")); static handle cast(RValueCaster &&, return_value_policy, handle) { return py::str("rvalue").release(); } static handle cast(const RValueCaster &, return_value_policy, handle) { return py::str("lvalue").release(); } }; PYBIND11_NAMESPACE_END(detail) PYBIND11_NAMESPACE_END(pybind11) template <typename F> void ignoreOldStyleInitWarnings(F &&body) { py::exec(R"( message = "pybind11-bound class '.+' is using an old-style placement-new '(?:__init__|__setstate__)' which has been deprecated" import warnings with warnings.catch_warnings(): warnings.filterwarnings("ignore", message=message, category=FutureWarning) body() )", py::dict(py::arg("body") = py::cpp_function(body))); }
Unknown
3D
mcellteam/mcell
libs/pybind11/tests/test_multiple_inheritance.py
.py
12,034
497
# -*- coding: utf-8 -*- import pytest import env # noqa: F401 from pybind11_tests import ConstructorStats from pybind11_tests import multiple_inheritance as m def test_multiple_inheritance_cpp(): mt = m.MIType(3, 4) assert mt.foo() == 3 assert mt.bar() == 4 @pytest.mark.skipif("env.PYPY and env.PY2") @pytest.mark.xfail("env.PYPY and not env.PY2") def test_multiple_inheritance_mix1(): class Base1: def __init__(self, i): self.i = i def foo(self): return self.i class MITypePy(Base1, m.Base2): def __init__(self, i, j): Base1.__init__(self, i) m.Base2.__init__(self, j) mt = MITypePy(3, 4) assert mt.foo() == 3 assert mt.bar() == 4 def test_multiple_inheritance_mix2(): class Base2: def __init__(self, i): self.i = i def bar(self): return self.i class MITypePy(m.Base1, Base2): def __init__(self, i, j): m.Base1.__init__(self, i) Base2.__init__(self, j) mt = MITypePy(3, 4) assert mt.foo() == 3 assert mt.bar() == 4 @pytest.mark.skipif("env.PYPY and env.PY2") @pytest.mark.xfail("env.PYPY and not env.PY2") def test_multiple_inheritance_python(): class MI1(m.Base1, m.Base2): def __init__(self, i, j): m.Base1.__init__(self, i) m.Base2.__init__(self, j) class B1(object): def v(self): return 1 class MI2(B1, m.Base1, m.Base2): def __init__(self, i, j): B1.__init__(self) m.Base1.__init__(self, i) m.Base2.__init__(self, j) class MI3(MI2): def __init__(self, i, j): MI2.__init__(self, i, j) class MI4(MI3, m.Base2): def __init__(self, i, j): MI3.__init__(self, i, j) # This should be ignored (Base2 is already initialized via MI2): m.Base2.__init__(self, i + 100) class MI5(m.Base2, B1, m.Base1): def __init__(self, i, j): B1.__init__(self) m.Base1.__init__(self, i) m.Base2.__init__(self, j) class MI6(m.Base2, B1): def __init__(self, i): m.Base2.__init__(self, i) B1.__init__(self) class B2(B1): def v(self): return 2 class B3(object): def v(self): return 3 class B4(B3, B2): def v(self): return 4 class MI7(B4, MI6): def __init__(self, i): B4.__init__(self) MI6.__init__(self, i) class MI8(MI6, B3): def __init__(self, i): MI6.__init__(self, i) B3.__init__(self) class MI8b(B3, MI6): def __init__(self, i): B3.__init__(self) MI6.__init__(self, i) mi1 = MI1(1, 2) assert mi1.foo() == 1 assert mi1.bar() == 2 mi2 = MI2(3, 4) assert mi2.v() == 1 assert mi2.foo() == 3 assert mi2.bar() == 4 mi3 = MI3(5, 6) assert mi3.v() == 1 assert mi3.foo() == 5 assert mi3.bar() == 6 mi4 = MI4(7, 8) assert mi4.v() == 1 assert mi4.foo() == 7 assert mi4.bar() == 8 mi5 = MI5(10, 11) assert mi5.v() == 1 assert mi5.foo() == 10 assert mi5.bar() == 11 mi6 = MI6(12) assert mi6.v() == 1 assert mi6.bar() == 12 mi7 = MI7(13) assert mi7.v() == 4 assert mi7.bar() == 13 mi8 = MI8(14) assert mi8.v() == 1 assert mi8.bar() == 14 mi8b = MI8b(15) assert mi8b.v() == 3 assert mi8b.bar() == 15 def test_multiple_inheritance_python_many_bases(): class MIMany14(m.BaseN1, m.BaseN2, m.BaseN3, m.BaseN4): def __init__(self): m.BaseN1.__init__(self, 1) m.BaseN2.__init__(self, 2) m.BaseN3.__init__(self, 3) m.BaseN4.__init__(self, 4) class MIMany58(m.BaseN5, m.BaseN6, m.BaseN7, m.BaseN8): def __init__(self): m.BaseN5.__init__(self, 5) m.BaseN6.__init__(self, 6) m.BaseN7.__init__(self, 7) m.BaseN8.__init__(self, 8) class MIMany916( m.BaseN9, m.BaseN10, m.BaseN11, m.BaseN12, m.BaseN13, m.BaseN14, m.BaseN15, m.BaseN16, ): def __init__(self): m.BaseN9.__init__(self, 9) m.BaseN10.__init__(self, 10) m.BaseN11.__init__(self, 11) m.BaseN12.__init__(self, 12) m.BaseN13.__init__(self, 13) m.BaseN14.__init__(self, 14) m.BaseN15.__init__(self, 15) m.BaseN16.__init__(self, 16) class MIMany19(MIMany14, MIMany58, m.BaseN9): def __init__(self): MIMany14.__init__(self) MIMany58.__init__(self) m.BaseN9.__init__(self, 9) class MIMany117(MIMany14, MIMany58, MIMany916, m.BaseN17): def __init__(self): MIMany14.__init__(self) MIMany58.__init__(self) MIMany916.__init__(self) m.BaseN17.__init__(self, 17) # Inherits from 4 registered C++ classes: can fit in one pointer on any modern arch: a = MIMany14() for i in range(1, 4): assert getattr(a, "f" + str(i))() == 2 * i # Inherits from 8: requires 1/2 pointers worth of holder flags on 32/64-bit arch: b = MIMany916() for i in range(9, 16): assert getattr(b, "f" + str(i))() == 2 * i # Inherits from 9: requires >= 2 pointers worth of holder flags c = MIMany19() for i in range(1, 9): assert getattr(c, "f" + str(i))() == 2 * i # Inherits from 17: requires >= 3 pointers worth of holder flags d = MIMany117() for i in range(1, 17): assert getattr(d, "f" + str(i))() == 2 * i def test_multiple_inheritance_virtbase(): class MITypePy(m.Base12a): def __init__(self, i, j): m.Base12a.__init__(self, i, j) mt = MITypePy(3, 4) assert mt.bar() == 4 assert m.bar_base2a(mt) == 4 assert m.bar_base2a_sharedptr(mt) == 4 def test_mi_static_properties(): """Mixing bases with and without static properties should be possible and the result should be independent of base definition order""" for d in (m.VanillaStaticMix1(), m.VanillaStaticMix2()): assert d.vanilla() == "Vanilla" assert d.static_func1() == "WithStatic1" assert d.static_func2() == "WithStatic2" assert d.static_func() == d.__class__.__name__ m.WithStatic1.static_value1 = 1 m.WithStatic2.static_value2 = 2 assert d.static_value1 == 1 assert d.static_value2 == 2 assert d.static_value == 12 d.static_value1 = 0 assert d.static_value1 == 0 d.static_value2 = 0 assert d.static_value2 == 0 d.static_value = 0 assert d.static_value == 0 # Requires PyPy 6+ def test_mi_dynamic_attributes(): """Mixing bases with and without dynamic attribute support""" for d in (m.VanillaDictMix1(), m.VanillaDictMix2()): d.dynamic = 1 assert d.dynamic == 1 def test_mi_unaligned_base(): """Returning an offset (non-first MI) base class pointer should recognize the instance""" n_inst = ConstructorStats.detail_reg_inst() c = m.I801C() d = m.I801D() # + 4 below because we have the two instances, and each instance has offset base I801B2 assert ConstructorStats.detail_reg_inst() == n_inst + 4 b1c = m.i801b1_c(c) assert b1c is c b2c = m.i801b2_c(c) assert b2c is c b1d = m.i801b1_d(d) assert b1d is d b2d = m.i801b2_d(d) assert b2d is d assert ConstructorStats.detail_reg_inst() == n_inst + 4 # no extra instances del c, b1c, b2c assert ConstructorStats.detail_reg_inst() == n_inst + 2 del d, b1d, b2d assert ConstructorStats.detail_reg_inst() == n_inst def test_mi_base_return(): """Tests returning an offset (non-first MI) base class pointer to a derived instance""" n_inst = ConstructorStats.detail_reg_inst() c1 = m.i801c_b1() assert type(c1) is m.I801C assert c1.a == 1 assert c1.b == 2 d1 = m.i801d_b1() assert type(d1) is m.I801D assert d1.a == 1 assert d1.b == 2 assert ConstructorStats.detail_reg_inst() == n_inst + 4 c2 = m.i801c_b2() assert type(c2) is m.I801C assert c2.a == 1 assert c2.b == 2 d2 = m.i801d_b2() assert type(d2) is m.I801D assert d2.a == 1 assert d2.b == 2 assert ConstructorStats.detail_reg_inst() == n_inst + 8 del c2 assert ConstructorStats.detail_reg_inst() == n_inst + 6 del c1, d1, d2 assert ConstructorStats.detail_reg_inst() == n_inst # Returning an unregistered derived type with a registered base; we won't # pick up the derived type, obviously, but should still work (as an object # of whatever type was returned). e1 = m.i801e_c() assert type(e1) is m.I801C assert e1.a == 1 assert e1.b == 2 e2 = m.i801e_b2() assert type(e2) is m.I801B2 assert e2.b == 2 def test_diamond_inheritance(): """Tests that diamond inheritance works as expected (issue #959)""" # Issue #959: this shouldn't segfault: d = m.D() # Make sure all the various distinct pointers are all recognized as registered instances: assert d is d.c0() assert d is d.c1() assert d is d.b() assert d is d.c0().b() assert d is d.c1().b() assert d is d.c0().c1().b().c0().b() def test_pr3635_diamond_b(): o = m.MVB() assert o.b == 1 assert o.get_b_b() == 1 def test_pr3635_diamond_c(): o = m.MVC() assert o.b == 1 assert o.c == 2 assert o.get_b_b() == 1 assert o.get_c_b() == 1 assert o.get_c_c() == 2 def test_pr3635_diamond_d0(): o = m.MVD0() assert o.b == 1 assert o.c == 2 assert o.d0 == 3 assert o.get_b_b() == 1 assert o.get_c_b() == 1 assert o.get_d0_b() == 1 assert o.get_c_c() == 2 assert o.get_d0_c() == 2 assert o.get_d0_d0() == 3 def test_pr3635_diamond_d1(): o = m.MVD1() assert o.b == 1 assert o.c == 2 assert o.d1 == 4 assert o.get_b_b() == 1 assert o.get_c_b() == 1 assert o.get_d1_b() == 1 assert o.get_c_c() == 2 assert o.get_d1_c() == 2 assert o.get_d1_d1() == 4 def test_pr3635_diamond_e(): o = m.MVE() assert o.b == 1 assert o.c == 2 assert o.d0 == 3 assert o.d1 == 4 assert o.e == 5 assert o.get_b_b() == 1 assert o.get_c_b() == 1 assert o.get_d0_b() == 1 assert o.get_d1_b() == 1 assert o.get_e_b() == 1 assert o.get_c_c() == 2 assert o.get_d0_c() == 2 assert o.get_d1_c() == 2 assert o.get_e_c() == 2 assert o.get_d0_d0() == 3 assert o.get_e_d0() == 3 assert o.get_d1_d1() == 4 assert o.get_e_d1() == 4 assert o.get_e_e() == 5 def test_pr3635_diamond_f(): o = m.MVF() assert o.b == 1 assert o.c == 2 assert o.d0 == 3 assert o.d1 == 4 assert o.e == 5 assert o.f == 6 assert o.get_b_b() == 1 assert o.get_c_b() == 1 assert o.get_d0_b() == 1 assert o.get_d1_b() == 1 assert o.get_e_b() == 1 assert o.get_f_b() == 1 assert o.get_c_c() == 2 assert o.get_d0_c() == 2 assert o.get_d1_c() == 2 assert o.get_e_c() == 2 assert o.get_f_c() == 2 assert o.get_d0_d0() == 3 assert o.get_e_d0() == 3 assert o.get_f_d0() == 3 assert o.get_d1_d1() == 4 assert o.get_e_d1() == 4 assert o.get_f_d1() == 4 assert o.get_e_e() == 5 assert o.get_f_e() == 5 assert o.get_f_f() == 6 def test_python_inherit_from_mi(): """Tests extending a Python class from a single inheritor of a MI class""" class PyMVF(m.MVF): g = 7 def get_g_g(self): return self.g o = PyMVF() assert o.b == 1 assert o.c == 2 assert o.d0 == 3 assert o.d1 == 4 assert o.e == 5 assert o.f == 6 assert o.g == 7 assert o.get_g_g() == 7
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_stl.cpp
.cpp
20,722
529
/* tests/test_stl.cpp -- STL type casters Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch> 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/stl.h> #include "constructor_stats.h" #include "pybind11_tests.h" #ifndef PYBIND11_HAS_FILESYSTEM_IS_OPTIONAL # define PYBIND11_HAS_FILESYSTEM_IS_OPTIONAL #endif #include <pybind11/stl/filesystem.h> #include <string> #include <vector> #if defined(PYBIND11_TEST_BOOST) # include <boost/optional.hpp> namespace pybind11 { namespace detail { template <typename T> struct type_caster<boost::optional<T>> : optional_caster<boost::optional<T>> {}; template <> struct type_caster<boost::none_t> : void_caster<boost::none_t> {}; } // namespace detail } // namespace pybind11 #endif // Test with `std::variant` in C++17 mode, or with `boost::variant` in C++11/14 #if defined(PYBIND11_HAS_VARIANT) using std::variant; #elif defined(PYBIND11_TEST_BOOST) && (!defined(_MSC_VER) || _MSC_VER >= 1910) # include <boost/variant.hpp> # define PYBIND11_HAS_VARIANT 1 using boost::variant; namespace pybind11 { namespace detail { template <typename... Ts> struct type_caster<boost::variant<Ts...>> : variant_caster<boost::variant<Ts...>> {}; template <> struct visit_helper<boost::variant> { template <typename... Args> static auto call(Args &&...args) -> decltype(boost::apply_visitor(args...)) { return boost::apply_visitor(args...); } }; } // namespace detail } // namespace pybind11 #endif PYBIND11_MAKE_OPAQUE(std::vector<std::string, std::allocator<std::string>>); /// Issue #528: templated constructor struct TplCtorClass { template <typename T> explicit TplCtorClass(const T &) {} bool operator==(const TplCtorClass &) const { return true; } }; namespace std { template <> struct hash<TplCtorClass> { size_t operator()(const TplCtorClass &) const { return 0; } }; } // namespace std template <template <typename> class OptionalImpl, typename T> struct OptionalHolder { // NOLINTNEXTLINE(modernize-use-equals-default): breaks GCC 4.8 OptionalHolder(){}; bool member_initialized() const { return member && member->initialized; } OptionalImpl<T> member = T{}; }; enum class EnumType { kSet = 42, kUnset = 85, }; // This is used to test that return-by-ref and return-by-copy policies are // handled properly for optional types. This is a regression test for a dangling // reference issue. The issue seemed to require the enum value type to // reproduce - it didn't seem to happen if the value type is just an integer. template <template <typename> class OptionalImpl> class OptionalProperties { public: using OptionalEnumValue = OptionalImpl<EnumType>; OptionalProperties() : value(EnumType::kSet) {} ~OptionalProperties() { // Reset value to detect use-after-destruction. // This is set to a specific value rather than nullopt to ensure that // the memory that contains the value gets re-written. value = EnumType::kUnset; } OptionalEnumValue &access_by_ref() { return value; } OptionalEnumValue access_by_copy() { return value; } private: OptionalEnumValue value; }; // This type mimics aspects of boost::optional from old versions of Boost, // which exposed a dangling reference bug in Pybind11. Recent versions of // boost::optional, as well as libstdc++'s std::optional, don't seem to be // affected by the same issue. This is meant to be a minimal implementation // required to reproduce the issue, not fully standard-compliant. // See issue #3330 for more details. template <typename T> class ReferenceSensitiveOptional { public: using value_type = T; ReferenceSensitiveOptional() = default; // NOLINTNEXTLINE(google-explicit-constructor) ReferenceSensitiveOptional(const T &value) : storage{value} {} // NOLINTNEXTLINE(google-explicit-constructor) ReferenceSensitiveOptional(T &&value) : storage{std::move(value)} {} ReferenceSensitiveOptional &operator=(const T &value) { storage = {value}; return *this; } ReferenceSensitiveOptional &operator=(T &&value) { storage = {std::move(value)}; return *this; } template <typename... Args> T &emplace(Args &&...args) { storage.clear(); storage.emplace_back(std::forward<Args>(args)...); return storage.back(); } const T &value() const noexcept { assert(!storage.empty()); return storage[0]; } const T &operator*() const noexcept { return value(); } const T *operator->() const noexcept { return &value(); } explicit operator bool() const noexcept { return !storage.empty(); } private: std::vector<T> storage; }; namespace pybind11 { namespace detail { template <typename T> struct type_caster<ReferenceSensitiveOptional<T>> : optional_caster<ReferenceSensitiveOptional<T>> {}; } // namespace detail } // namespace pybind11 TEST_SUBMODULE(stl, m) { // test_vector m.def("cast_vector", []() { return std::vector<int>{1}; }); m.def("load_vector", [](const std::vector<int> &v) { return v.at(0) == 1 && v.at(1) == 2; }); // `std::vector<bool>` is special because it returns proxy objects instead of references m.def("cast_bool_vector", []() { return std::vector<bool>{true, false}; }); m.def("load_bool_vector", [](const std::vector<bool> &v) { return v.at(0) == true && v.at(1) == false; }); // Unnumbered regression (caused by #936): pointers to stl containers aren't castable static std::vector<RValueCaster> lvv{2}; m.def("cast_ptr_vector", []() { return &lvv; }); // test_deque m.def("cast_deque", []() { return std::deque<int>{1}; }); m.def("load_deque", [](const std::deque<int> &v) { return v.at(0) == 1 && v.at(1) == 2; }); // test_array m.def("cast_array", []() { return std::array<int, 2>{{1, 2}}; }); m.def("load_array", [](const std::array<int, 2> &a) { return a[0] == 1 && a[1] == 2; }); // test_valarray m.def("cast_valarray", []() { return std::valarray<int>{1, 4, 9}; }); m.def("load_valarray", [](const std::valarray<int> &v) { return v.size() == 3 && v[0] == 1 && v[1] == 4 && v[2] == 9; }); // test_map m.def("cast_map", []() { return std::map<std::string, std::string>{{"key", "value"}}; }); m.def("load_map", [](const std::map<std::string, std::string> &map) { return map.at("key") == "value" && map.at("key2") == "value2"; }); // test_set m.def("cast_set", []() { return std::set<std::string>{"key1", "key2"}; }); m.def("load_set", [](const std::set<std::string> &set) { return (set.count("key1") != 0u) && (set.count("key2") != 0u) && (set.count("key3") != 0u); }); // test_recursive_casting m.def("cast_rv_vector", []() { return std::vector<RValueCaster>{2}; }); m.def("cast_rv_array", []() { return std::array<RValueCaster, 3>(); }); // NB: map and set keys are `const`, so while we technically do move them (as `const Type &&`), // casters don't typically do anything with that, which means they fall to the `const Type &` // caster. m.def("cast_rv_map", []() { return std::unordered_map<std::string, RValueCaster>{{"a", RValueCaster{}}}; }); m.def("cast_rv_nested", []() { std::vector<std::array<std::list<std::unordered_map<std::string, RValueCaster>>, 2>> v; v.emplace_back(); // add an array v.back()[0].emplace_back(); // add a map to the array v.back()[0].back().emplace("b", RValueCaster{}); v.back()[0].back().emplace("c", RValueCaster{}); v.back()[1].emplace_back(); // add a map to the array v.back()[1].back().emplace("a", RValueCaster{}); return v; }); static std::array<RValueCaster, 2> lva; static std::unordered_map<std::string, RValueCaster> lvm{{"a", RValueCaster{}}, {"b", RValueCaster{}}}; static std::unordered_map<std::string, std::vector<std::list<std::array<RValueCaster, 2>>>> lvn; lvn["a"].emplace_back(); // add a list lvn["a"].back().emplace_back(); // add an array lvn["a"].emplace_back(); // another list lvn["a"].back().emplace_back(); // add an array lvn["b"].emplace_back(); // add a list lvn["b"].back().emplace_back(); // add an array lvn["b"].back().emplace_back(); // add another array m.def("cast_lv_vector", []() -> const decltype(lvv) & { return lvv; }); m.def("cast_lv_array", []() -> const decltype(lva) & { return lva; }); m.def("cast_lv_map", []() -> const decltype(lvm) & { return lvm; }); m.def("cast_lv_nested", []() -> const decltype(lvn) & { return lvn; }); // #853: m.def("cast_unique_ptr_vector", []() { std::vector<std::unique_ptr<UserType>> v; v.emplace_back(new UserType{7}); v.emplace_back(new UserType{42}); return v; }); pybind11::enum_<EnumType>(m, "EnumType") .value("kSet", EnumType::kSet) .value("kUnset", EnumType::kUnset); // test_move_out_container struct MoveOutContainer { struct Value { int value; }; std::list<Value> move_list() const { return {{0}, {1}, {2}}; } }; py::class_<MoveOutContainer::Value>(m, "MoveOutContainerValue") .def_readonly("value", &MoveOutContainer::Value::value); py::class_<MoveOutContainer>(m, "MoveOutContainer") .def(py::init<>()) .def_property_readonly("move_list", &MoveOutContainer::move_list); // Class that can be move- and copy-constructed, but not assigned struct NoAssign { int value; explicit NoAssign(int value = 0) : value(value) {} NoAssign(const NoAssign &) = default; NoAssign(NoAssign &&) = default; NoAssign &operator=(const NoAssign &) = delete; NoAssign &operator=(NoAssign &&) = delete; }; py::class_<NoAssign>(m, "NoAssign", "Class with no C++ assignment operators") .def(py::init<>()) .def(py::init<int>()); struct MoveOutDetector { MoveOutDetector() = default; MoveOutDetector(const MoveOutDetector &) = default; MoveOutDetector(MoveOutDetector &&other) noexcept : initialized(other.initialized) { // steal underlying resource other.initialized = false; } bool initialized = true; }; py::class_<MoveOutDetector>(m, "MoveOutDetector", "Class with move tracking") .def(py::init<>()) .def_readonly("initialized", &MoveOutDetector::initialized); #ifdef PYBIND11_HAS_OPTIONAL // test_optional m.attr("has_optional") = true; using opt_int = std::optional<int>; using opt_no_assign = std::optional<NoAssign>; m.def("double_or_zero", [](const opt_int &x) -> int { return x.value_or(0) * 2; }); m.def("half_or_none", [](int x) -> opt_int { return x != 0 ? opt_int(x / 2) : opt_int(); }); m.def( "test_nullopt", [](opt_int x) { return x.value_or(42); }, py::arg_v("x", std::nullopt, "None")); m.def( "test_no_assign", [](const opt_no_assign &x) { return x ? x->value : 42; }, py::arg_v("x", std::nullopt, "None")); m.def("nodefer_none_optional", [](std::optional<int>) { return true; }); m.def("nodefer_none_optional", [](const py::none &) { return false; }); using opt_holder = OptionalHolder<std::optional, MoveOutDetector>; py::class_<opt_holder>(m, "OptionalHolder", "Class with optional member") .def(py::init<>()) .def_readonly("member", &opt_holder::member) .def("member_initialized", &opt_holder::member_initialized); using opt_props = OptionalProperties<std::optional>; pybind11::class_<opt_props>(m, "OptionalProperties") .def(pybind11::init<>()) .def_property_readonly("access_by_ref", &opt_props::access_by_ref) .def_property_readonly("access_by_copy", &opt_props::access_by_copy); #endif #ifdef PYBIND11_HAS_EXP_OPTIONAL // test_exp_optional m.attr("has_exp_optional") = true; using exp_opt_int = std::experimental::optional<int>; using exp_opt_no_assign = std::experimental::optional<NoAssign>; m.def("double_or_zero_exp", [](const exp_opt_int &x) -> int { return x.value_or(0) * 2; }); m.def("half_or_none_exp", [](int x) -> exp_opt_int { return x ? exp_opt_int(x / 2) : exp_opt_int(); }); m.def( "test_nullopt_exp", [](exp_opt_int x) { return x.value_or(42); }, py::arg_v("x", std::experimental::nullopt, "None")); m.def( "test_no_assign_exp", [](const exp_opt_no_assign &x) { return x ? x->value : 42; }, py::arg_v("x", std::experimental::nullopt, "None")); using opt_exp_holder = OptionalHolder<std::experimental::optional, MoveOutDetector>; py::class_<opt_exp_holder>(m, "OptionalExpHolder", "Class with optional member") .def(py::init<>()) .def_readonly("member", &opt_exp_holder::member) .def("member_initialized", &opt_exp_holder::member_initialized); using opt_exp_props = OptionalProperties<std::experimental::optional>; pybind11::class_<opt_exp_props>(m, "OptionalExpProperties") .def(pybind11::init<>()) .def_property_readonly("access_by_ref", &opt_exp_props::access_by_ref) .def_property_readonly("access_by_copy", &opt_exp_props::access_by_copy); #endif #if defined(PYBIND11_TEST_BOOST) // test_boost_optional m.attr("has_boost_optional") = true; using boost_opt_int = boost::optional<int>; using boost_opt_no_assign = boost::optional<NoAssign>; m.def("double_or_zero_boost", [](const boost_opt_int &x) -> int { return x.value_or(0) * 2; }); m.def("half_or_none_boost", [](int x) -> boost_opt_int { return x != 0 ? boost_opt_int(x / 2) : boost_opt_int(); }); m.def( "test_nullopt_boost", [](boost_opt_int x) { return x.value_or(42); }, py::arg_v("x", boost::none, "None")); m.def( "test_no_assign_boost", [](const boost_opt_no_assign &x) { return x ? x->value : 42; }, py::arg_v("x", boost::none, "None")); using opt_boost_holder = OptionalHolder<boost::optional, MoveOutDetector>; py::class_<opt_boost_holder>(m, "OptionalBoostHolder", "Class with optional member") .def(py::init<>()) .def_readonly("member", &opt_boost_holder::member) .def("member_initialized", &opt_boost_holder::member_initialized); using opt_boost_props = OptionalProperties<boost::optional>; pybind11::class_<opt_boost_props>(m, "OptionalBoostProperties") .def(pybind11::init<>()) .def_property_readonly("access_by_ref", &opt_boost_props::access_by_ref) .def_property_readonly("access_by_copy", &opt_boost_props::access_by_copy); #endif // test_refsensitive_optional using refsensitive_opt_int = ReferenceSensitiveOptional<int>; using refsensitive_opt_no_assign = ReferenceSensitiveOptional<NoAssign>; m.def("double_or_zero_refsensitive", [](const refsensitive_opt_int &x) -> int { return (x ? x.value() : 0) * 2; }); m.def("half_or_none_refsensitive", [](int x) -> refsensitive_opt_int { return x != 0 ? refsensitive_opt_int(x / 2) : refsensitive_opt_int(); }); m.def( "test_nullopt_refsensitive", // NOLINTNEXTLINE(performance-unnecessary-value-param) [](refsensitive_opt_int x) { return x ? x.value() : 42; }, py::arg_v("x", refsensitive_opt_int(), "None")); m.def( "test_no_assign_refsensitive", [](const refsensitive_opt_no_assign &x) { return x ? x->value : 42; }, py::arg_v("x", refsensitive_opt_no_assign(), "None")); using opt_refsensitive_holder = OptionalHolder<ReferenceSensitiveOptional, MoveOutDetector>; py::class_<opt_refsensitive_holder>( m, "OptionalRefSensitiveHolder", "Class with optional member") .def(py::init<>()) .def_readonly("member", &opt_refsensitive_holder::member) .def("member_initialized", &opt_refsensitive_holder::member_initialized); using opt_refsensitive_props = OptionalProperties<ReferenceSensitiveOptional>; pybind11::class_<opt_refsensitive_props>(m, "OptionalRefSensitiveProperties") .def(pybind11::init<>()) .def_property_readonly("access_by_ref", &opt_refsensitive_props::access_by_ref) .def_property_readonly("access_by_copy", &opt_refsensitive_props::access_by_copy); #ifdef PYBIND11_HAS_FILESYSTEM // test_fs_path m.attr("has_filesystem") = true; m.def("parent_path", [](const std::filesystem::path &p) { return p.parent_path(); }); #endif #ifdef PYBIND11_HAS_VARIANT static_assert(std::is_same<py::detail::variant_caster_visitor::result_type, py::handle>::value, "visitor::result_type is required by boost::variant in C++11 mode"); struct visitor { using result_type = const char *; result_type operator()(int) { return "int"; } result_type operator()(const std::string &) { return "std::string"; } result_type operator()(double) { return "double"; } result_type operator()(std::nullptr_t) { return "std::nullptr_t"; } }; // test_variant m.def("load_variant", [](const variant<int, std::string, double, std::nullptr_t> &v) { return py::detail::visit_helper<variant>::call(visitor(), v); }); m.def("load_variant_2pass", [](variant<double, int> v) { return py::detail::visit_helper<variant>::call(visitor(), v); }); m.def("cast_variant", []() { using V = variant<int, std::string>; return py::make_tuple(V(5), V("Hello")); }); #endif // #528: templated constructor // (no python tests: the test here is that this compiles) m.def("tpl_ctor_vector", [](std::vector<TplCtorClass> &) {}); m.def("tpl_ctor_map", [](std::unordered_map<TplCtorClass, TplCtorClass> &) {}); m.def("tpl_ctor_set", [](std::unordered_set<TplCtorClass> &) {}); #if defined(PYBIND11_HAS_OPTIONAL) m.def("tpl_constr_optional", [](std::optional<TplCtorClass> &) {}); #endif #if defined(PYBIND11_HAS_EXP_OPTIONAL) m.def("tpl_constr_optional_exp", [](std::experimental::optional<TplCtorClass> &) {}); #endif #if defined(PYBIND11_TEST_BOOST) m.def("tpl_constr_optional_boost", [](boost::optional<TplCtorClass> &) {}); #endif // test_vec_of_reference_wrapper // #171: Can't return STL structures containing reference wrapper m.def("return_vec_of_reference_wrapper", [](std::reference_wrapper<UserType> p4) { static UserType p1{1}, p2{2}, p3{3}; return std::vector<std::reference_wrapper<UserType>>{ std::ref(p1), std::ref(p2), std::ref(p3), p4}; }); // test_stl_pass_by_pointer m.def( "stl_pass_by_pointer", [](std::vector<int> *v) { return *v; }, "v"_a = nullptr); // #1258: pybind11/stl.h converts string to vector<string> m.def("func_with_string_or_vector_string_arg_overload", [](const std::vector<std::string> &) { return 1; }); m.def("func_with_string_or_vector_string_arg_overload", [](const std::list<std::string> &) { return 2; }); m.def("func_with_string_or_vector_string_arg_overload", [](const std::string &) { return 3; }); class Placeholder { public: Placeholder() { print_created(this); } Placeholder(const Placeholder &) = delete; ~Placeholder() { print_destroyed(this); } }; py::class_<Placeholder>(m, "Placeholder"); /// test_stl_vector_ownership m.def( "test_stl_ownership", []() { std::vector<Placeholder *> result; result.push_back(new Placeholder()); return result; }, py::return_value_policy::take_ownership); m.def("array_cast_sequence", [](std::array<int, 3> x) { return x; }); /// test_issue_1561 struct Issue1561Inner { std::string data; }; struct Issue1561Outer { std::vector<Issue1561Inner> list; }; py::class_<Issue1561Inner>(m, "Issue1561Inner") .def(py::init<std::string>()) .def_readwrite("data", &Issue1561Inner::data); py::class_<Issue1561Outer>(m, "Issue1561Outer") .def(py::init<>()) .def_readwrite("list", &Issue1561Outer::list); m.def( "return_vector_bool_raw_ptr", []() { return new std::vector<bool>(4513); }, // Without explicitly specifying `take_ownership`, this function leaks. py::return_value_policy::take_ownership); }
C++
3D
mcellteam/mcell
libs/pybind11/tests/test_numpy_vectorize.py
.py
9,710
268
# -*- coding: utf-8 -*- import pytest from pybind11_tests import numpy_vectorize as m np = pytest.importorskip("numpy") def test_vectorize(capture): assert np.isclose(m.vectorized_func3(np.array(3 + 7j)), [6 + 14j]) for f in [m.vectorized_func, m.vectorized_func2]: with capture: assert np.isclose(f(1, 2, 3), 6) assert capture == "my_func(x:int=1, y:float=2, z:float=3)" with capture: assert np.isclose(f(np.array(1), np.array(2), 3), 6) assert capture == "my_func(x:int=1, y:float=2, z:float=3)" with capture: assert np.allclose(f(np.array([1, 3]), np.array([2, 4]), 3), [6, 36]) assert ( capture == """ my_func(x:int=1, y:float=2, z:float=3) my_func(x:int=3, y:float=4, z:float=3) """ ) with capture: a = np.array([[1, 2], [3, 4]], order="F") b = np.array([[10, 20], [30, 40]], order="F") c = 3 result = f(a, b, c) assert np.allclose(result, a * b * c) assert result.flags.f_contiguous # All inputs are F order and full or singletons, so we the result is in col-major order: assert ( capture == """ my_func(x:int=1, y:float=10, z:float=3) my_func(x:int=3, y:float=30, z:float=3) my_func(x:int=2, y:float=20, z:float=3) my_func(x:int=4, y:float=40, z:float=3) """ ) with capture: a, b, c = ( np.array([[1, 3, 5], [7, 9, 11]]), np.array([[2, 4, 6], [8, 10, 12]]), 3, ) assert np.allclose(f(a, b, c), a * b * c) assert ( capture == """ my_func(x:int=1, y:float=2, z:float=3) my_func(x:int=3, y:float=4, z:float=3) my_func(x:int=5, y:float=6, z:float=3) my_func(x:int=7, y:float=8, z:float=3) my_func(x:int=9, y:float=10, z:float=3) my_func(x:int=11, y:float=12, z:float=3) """ ) with capture: a, b, c = np.array([[1, 2, 3], [4, 5, 6]]), np.array([2, 3, 4]), 2 assert np.allclose(f(a, b, c), a * b * c) assert ( capture == """ my_func(x:int=1, y:float=2, z:float=2) my_func(x:int=2, y:float=3, z:float=2) my_func(x:int=3, y:float=4, z:float=2) my_func(x:int=4, y:float=2, z:float=2) my_func(x:int=5, y:float=3, z:float=2) my_func(x:int=6, y:float=4, z:float=2) """ ) with capture: a, b, c = np.array([[1, 2, 3], [4, 5, 6]]), np.array([[2], [3]]), 2 assert np.allclose(f(a, b, c), a * b * c) assert ( capture == """ my_func(x:int=1, y:float=2, z:float=2) my_func(x:int=2, y:float=2, z:float=2) my_func(x:int=3, y:float=2, z:float=2) my_func(x:int=4, y:float=3, z:float=2) my_func(x:int=5, y:float=3, z:float=2) my_func(x:int=6, y:float=3, z:float=2) """ ) with capture: a, b, c = ( np.array([[1, 2, 3], [4, 5, 6]], order="F"), np.array([[2], [3]]), 2, ) assert np.allclose(f(a, b, c), a * b * c) assert ( capture == """ my_func(x:int=1, y:float=2, z:float=2) my_func(x:int=2, y:float=2, z:float=2) my_func(x:int=3, y:float=2, z:float=2) my_func(x:int=4, y:float=3, z:float=2) my_func(x:int=5, y:float=3, z:float=2) my_func(x:int=6, y:float=3, z:float=2) """ ) with capture: a, b, c = np.array([[1, 2, 3], [4, 5, 6]])[::, ::2], np.array([[2], [3]]), 2 assert np.allclose(f(a, b, c), a * b * c) assert ( capture == """ my_func(x:int=1, y:float=2, z:float=2) my_func(x:int=3, y:float=2, z:float=2) my_func(x:int=4, y:float=3, z:float=2) my_func(x:int=6, y:float=3, z:float=2) """ ) with capture: a, b, c = ( np.array([[1, 2, 3], [4, 5, 6]], order="F")[::, ::2], np.array([[2], [3]]), 2, ) assert np.allclose(f(a, b, c), a * b * c) assert ( capture == """ my_func(x:int=1, y:float=2, z:float=2) my_func(x:int=3, y:float=2, z:float=2) my_func(x:int=4, y:float=3, z:float=2) my_func(x:int=6, y:float=3, z:float=2) """ ) def test_type_selection(): assert m.selective_func(np.array([1], dtype=np.int32)) == "Int branch taken." assert m.selective_func(np.array([1.0], dtype=np.float32)) == "Float branch taken." assert ( m.selective_func(np.array([1.0j], dtype=np.complex64)) == "Complex float branch taken." ) def test_docs(doc): assert ( doc(m.vectorized_func) == """ vectorized_func(arg0: numpy.ndarray[numpy.int32], arg1: numpy.ndarray[numpy.float32], arg2: numpy.ndarray[numpy.float64]) -> object """ # noqa: E501 line too long ) def test_trivial_broadcasting(): trivial, vectorized_is_trivial = m.trivial, m.vectorized_is_trivial assert vectorized_is_trivial(1, 2, 3) == trivial.c_trivial assert vectorized_is_trivial(np.array(1), np.array(2), 3) == trivial.c_trivial assert ( vectorized_is_trivial(np.array([1, 3]), np.array([2, 4]), 3) == trivial.c_trivial ) assert trivial.c_trivial == vectorized_is_trivial( np.array([[1, 3, 5], [7, 9, 11]]), np.array([[2, 4, 6], [8, 10, 12]]), 3 ) assert ( vectorized_is_trivial(np.array([[1, 2, 3], [4, 5, 6]]), np.array([2, 3, 4]), 2) == trivial.non_trivial ) assert ( vectorized_is_trivial(np.array([[1, 2, 3], [4, 5, 6]]), np.array([[2], [3]]), 2) == trivial.non_trivial ) z1 = np.array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype="int32") z2 = np.array(z1, dtype="float32") z3 = np.array(z1, dtype="float64") assert vectorized_is_trivial(z1, z2, z3) == trivial.c_trivial assert vectorized_is_trivial(1, z2, z3) == trivial.c_trivial assert vectorized_is_trivial(z1, 1, z3) == trivial.c_trivial assert vectorized_is_trivial(z1, z2, 1) == trivial.c_trivial assert vectorized_is_trivial(z1[::2, ::2], 1, 1) == trivial.non_trivial assert vectorized_is_trivial(1, 1, z1[::2, ::2]) == trivial.c_trivial assert vectorized_is_trivial(1, 1, z3[::2, ::2]) == trivial.non_trivial assert vectorized_is_trivial(z1, 1, z3[1::4, 1::4]) == trivial.c_trivial y1 = np.array(z1, order="F") y2 = np.array(y1) y3 = np.array(y1) assert vectorized_is_trivial(y1, y2, y3) == trivial.f_trivial assert vectorized_is_trivial(y1, 1, 1) == trivial.f_trivial assert vectorized_is_trivial(1, y2, 1) == trivial.f_trivial assert vectorized_is_trivial(1, 1, y3) == trivial.f_trivial assert vectorized_is_trivial(y1, z2, 1) == trivial.non_trivial assert vectorized_is_trivial(z1[1::4, 1::4], y2, 1) == trivial.f_trivial assert vectorized_is_trivial(y1[1::4, 1::4], z2, 1) == trivial.c_trivial assert m.vectorized_func(z1, z2, z3).flags.c_contiguous assert m.vectorized_func(y1, y2, y3).flags.f_contiguous assert m.vectorized_func(z1, 1, 1).flags.c_contiguous assert m.vectorized_func(1, y2, 1).flags.f_contiguous assert m.vectorized_func(z1[1::4, 1::4], y2, 1).flags.f_contiguous assert m.vectorized_func(y1[1::4, 1::4], z2, 1).flags.c_contiguous def test_passthrough_arguments(doc): assert doc(m.vec_passthrough) == ( "vec_passthrough(" + ", ".join( [ "arg0: float", "arg1: numpy.ndarray[numpy.float64]", "arg2: numpy.ndarray[numpy.float64]", "arg3: numpy.ndarray[numpy.int32]", "arg4: int", "arg5: m.numpy_vectorize.NonPODClass", "arg6: numpy.ndarray[numpy.float64]", ] ) + ") -> object" ) b = np.array([[10, 20, 30]], dtype="float64") c = np.array([100, 200]) # NOT a vectorized argument d = np.array([[1000], [2000], [3000]], dtype="int") g = np.array([[1000000, 2000000, 3000000]], dtype="int") # requires casting assert np.all( m.vec_passthrough(1, b, c, d, 10000, m.NonPODClass(100000), g) == np.array( [ [1111111, 2111121, 3111131], [1112111, 2112121, 3112131], [1113111, 2113121, 3113131], ] ) ) def test_method_vectorization(): o = m.VectorizeTestClass(3) x = np.array([1, 2], dtype="int") y = np.array([[10], [20]], dtype="float32") assert np.all(o.method(x, y) == [[14, 15], [24, 25]]) def test_array_collapse(): assert not isinstance(m.vectorized_func(1, 2, 3), np.ndarray) assert not isinstance(m.vectorized_func(np.array(1), 2, 3), np.ndarray) z = m.vectorized_func([1], 2, 3) assert isinstance(z, np.ndarray) assert z.shape == (1,) z = m.vectorized_func(1, [[[2]]], 3) assert isinstance(z, np.ndarray) assert z.shape == (1, 1, 1) def test_vectorized_noreturn(): x = m.NonPODClass(0) assert x.value == 0 m.add_to(x, [1, 2, 3, 4]) assert x.value == 10 m.add_to(x, 1) assert x.value == 11 m.add_to(x, [[1, 1], [2, 3]]) assert x.value == 18
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_iostream.cpp
.cpp
4,122
131
/* tests/test_iostream.cpp -- Usage of scoped_output_redirect Copyright (c) 2017 Henry F. Schreiner All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #if defined(_MSC_VER) && _MSC_VER < 1910 // VS 2015's MSVC # pragma warning(disable : 4702) // unreachable code in system header (xatomic.h(382)) #endif #include <pybind11/iostream.h> #include "pybind11_tests.h" #include <atomic> #include <iostream> #include <mutex> #include <string> #include <thread> void noisy_function(const std::string &msg, bool flush) { std::cout << msg; if (flush) { std::cout << std::flush; } } void noisy_funct_dual(const std::string &msg, const std::string &emsg) { std::cout << msg; std::cerr << emsg; } // object to manage C++ thread // simply repeatedly write to std::cerr until stopped // redirect is called at some point to test the safety of scoped_estream_redirect struct TestThread { TestThread() : stop_{false} { auto thread_f = [this] { static std::mutex cout_mutex; while (!stop_) { { // #HelpAppreciated: Work on iostream.h thread safety. // Without this lock, the clang ThreadSanitizer (tsan) reliably reports a // data race, and this test is predictably flakey on Windows. // For more background see the discussion under // https://github.com/pybind/pybind11/pull/2982 and // https://github.com/pybind/pybind11/pull/2995. const std::lock_guard<std::mutex> lock(cout_mutex); std::cout << "x" << std::flush; } std::this_thread::sleep_for(std::chrono::microseconds(50)); } }; t_ = new std::thread(std::move(thread_f)); } ~TestThread() { delete t_; } void stop() { stop_ = true; } void join() const { py::gil_scoped_release gil_lock; t_->join(); } void sleep() { py::gil_scoped_release gil_lock; std::this_thread::sleep_for(std::chrono::milliseconds(50)); } std::thread *t_{nullptr}; std::atomic<bool> stop_; }; TEST_SUBMODULE(iostream, m) { add_ostream_redirect(m); // test_evals m.def("captured_output_default", [](const std::string &msg) { py::scoped_ostream_redirect redir; std::cout << msg << std::flush; }); m.def("captured_output", [](const std::string &msg) { py::scoped_ostream_redirect redir(std::cout, py::module_::import("sys").attr("stdout")); std::cout << msg << std::flush; }); m.def("guard_output", &noisy_function, py::call_guard<py::scoped_ostream_redirect>(), py::arg("msg"), py::arg("flush") = true); m.def("captured_err", [](const std::string &msg) { py::scoped_ostream_redirect redir(std::cerr, py::module_::import("sys").attr("stderr")); std::cerr << msg << std::flush; }); m.def("noisy_function", &noisy_function, py::arg("msg"), py::arg("flush") = true); m.def("dual_guard", &noisy_funct_dual, py::call_guard<py::scoped_ostream_redirect, py::scoped_estream_redirect>(), py::arg("msg"), py::arg("emsg")); m.def("raw_output", [](const std::string &msg) { std::cout << msg << std::flush; }); m.def("raw_err", [](const std::string &msg) { std::cerr << msg << std::flush; }); m.def("captured_dual", [](const std::string &msg, const std::string &emsg) { py::scoped_ostream_redirect redirout(std::cout, py::module_::import("sys").attr("stdout")); py::scoped_ostream_redirect redirerr(std::cerr, py::module_::import("sys").attr("stderr")); std::cout << msg << std::flush; std::cerr << emsg << std::flush; }); py::class_<TestThread>(m, "TestThread") .def(py::init<>()) .def("stop", &TestThread::stop) .def("join", &TestThread::join) .def("sleep", &TestThread::sleep); }
C++
3D
mcellteam/mcell
libs/pybind11/tests/test_numpy_array.py
.py
20,339
594
# -*- coding: utf-8 -*- import pytest import env # noqa: F401 from pybind11_tests import numpy_array as m np = pytest.importorskip("numpy") def test_dtypes(): # See issue #1328. # - Platform-dependent sizes. for size_check in m.get_platform_dtype_size_checks(): print(size_check) assert size_check.size_cpp == size_check.size_numpy, size_check # - Concrete sizes. for check in m.get_concrete_dtype_checks(): print(check) assert check.numpy == check.pybind11, check if check.numpy.num != check.pybind11.num: print( "NOTE: typenum mismatch for {}: {} != {}".format( check, check.numpy.num, check.pybind11.num ) ) @pytest.fixture(scope="function") def arr(): return np.array([[1, 2, 3], [4, 5, 6]], "=u2") def test_array_attributes(): a = np.array(0, "f8") assert m.ndim(a) == 0 assert all(m.shape(a) == []) assert all(m.strides(a) == []) with pytest.raises(IndexError) as excinfo: m.shape(a, 0) assert str(excinfo.value) == "invalid axis: 0 (ndim = 0)" with pytest.raises(IndexError) as excinfo: m.strides(a, 0) assert str(excinfo.value) == "invalid axis: 0 (ndim = 0)" assert m.writeable(a) assert m.size(a) == 1 assert m.itemsize(a) == 8 assert m.nbytes(a) == 8 assert m.owndata(a) a = np.array([[1, 2, 3], [4, 5, 6]], "u2").view() a.flags.writeable = False assert m.ndim(a) == 2 assert all(m.shape(a) == [2, 3]) assert m.shape(a, 0) == 2 assert m.shape(a, 1) == 3 assert all(m.strides(a) == [6, 2]) assert m.strides(a, 0) == 6 assert m.strides(a, 1) == 2 with pytest.raises(IndexError) as excinfo: m.shape(a, 2) assert str(excinfo.value) == "invalid axis: 2 (ndim = 2)" with pytest.raises(IndexError) as excinfo: m.strides(a, 2) assert str(excinfo.value) == "invalid axis: 2 (ndim = 2)" assert not m.writeable(a) assert m.size(a) == 6 assert m.itemsize(a) == 2 assert m.nbytes(a) == 12 assert not m.owndata(a) @pytest.mark.parametrize( "args, ret", [([], 0), ([0], 0), ([1], 3), ([0, 1], 1), ([1, 2], 5)] ) def test_index_offset(arr, args, ret): assert m.index_at(arr, *args) == ret assert m.index_at_t(arr, *args) == ret assert m.offset_at(arr, *args) == ret * arr.dtype.itemsize assert m.offset_at_t(arr, *args) == ret * arr.dtype.itemsize def test_dim_check_fail(arr): for func in ( m.index_at, m.index_at_t, m.offset_at, m.offset_at_t, m.data, m.data_t, m.mutate_data, m.mutate_data_t, ): with pytest.raises(IndexError) as excinfo: func(arr, 1, 2, 3) assert str(excinfo.value) == "too many indices for an array: 3 (ndim = 2)" @pytest.mark.parametrize( "args, ret", [ ([], [1, 2, 3, 4, 5, 6]), ([1], [4, 5, 6]), ([0, 1], [2, 3, 4, 5, 6]), ([1, 2], [6]), ], ) def test_data(arr, args, ret): from sys import byteorder assert all(m.data_t(arr, *args) == ret) assert all(m.data(arr, *args)[(0 if byteorder == "little" else 1) :: 2] == ret) assert all(m.data(arr, *args)[(1 if byteorder == "little" else 0) :: 2] == 0) @pytest.mark.parametrize("dim", [0, 1, 3]) def test_at_fail(arr, dim): for func in m.at_t, m.mutate_at_t: with pytest.raises(IndexError) as excinfo: func(arr, *([0] * dim)) assert str(excinfo.value) == "index dimension mismatch: {} (ndim = 2)".format( dim ) def test_at(arr): assert m.at_t(arr, 0, 2) == 3 assert m.at_t(arr, 1, 0) == 4 assert all(m.mutate_at_t(arr, 0, 2).ravel() == [1, 2, 4, 4, 5, 6]) assert all(m.mutate_at_t(arr, 1, 0).ravel() == [1, 2, 4, 5, 5, 6]) def test_mutate_readonly(arr): arr.flags.writeable = False for func, args in ( (m.mutate_data, ()), (m.mutate_data_t, ()), (m.mutate_at_t, (0, 0)), ): with pytest.raises(ValueError) as excinfo: func(arr, *args) assert str(excinfo.value) == "array is not writeable" def test_mutate_data(arr): assert all(m.mutate_data(arr).ravel() == [2, 4, 6, 8, 10, 12]) assert all(m.mutate_data(arr).ravel() == [4, 8, 12, 16, 20, 24]) assert all(m.mutate_data(arr, 1).ravel() == [4, 8, 12, 32, 40, 48]) assert all(m.mutate_data(arr, 0, 1).ravel() == [4, 16, 24, 64, 80, 96]) assert all(m.mutate_data(arr, 1, 2).ravel() == [4, 16, 24, 64, 80, 192]) assert all(m.mutate_data_t(arr).ravel() == [5, 17, 25, 65, 81, 193]) assert all(m.mutate_data_t(arr).ravel() == [6, 18, 26, 66, 82, 194]) assert all(m.mutate_data_t(arr, 1).ravel() == [6, 18, 26, 67, 83, 195]) assert all(m.mutate_data_t(arr, 0, 1).ravel() == [6, 19, 27, 68, 84, 196]) assert all(m.mutate_data_t(arr, 1, 2).ravel() == [6, 19, 27, 68, 84, 197]) def test_bounds_check(arr): for func in ( m.index_at, m.index_at_t, m.data, m.data_t, m.mutate_data, m.mutate_data_t, m.at_t, m.mutate_at_t, ): with pytest.raises(IndexError) as excinfo: func(arr, 2, 0) assert str(excinfo.value) == "index 2 is out of bounds for axis 0 with size 2" with pytest.raises(IndexError) as excinfo: func(arr, 0, 4) assert str(excinfo.value) == "index 4 is out of bounds for axis 1 with size 3" def test_make_c_f_array(): assert m.make_c_array().flags.c_contiguous assert not m.make_c_array().flags.f_contiguous assert m.make_f_array().flags.f_contiguous assert not m.make_f_array().flags.c_contiguous def test_make_empty_shaped_array(): m.make_empty_shaped_array() # empty shape means numpy scalar, PEP 3118 assert m.scalar_int().ndim == 0 assert m.scalar_int().shape == () assert m.scalar_int() == 42 def test_wrap(): def assert_references(a, b, base=None): from distutils.version import LooseVersion if base is None: base = a assert a is not b assert a.__array_interface__["data"][0] == b.__array_interface__["data"][0] assert a.shape == b.shape assert a.strides == b.strides assert a.flags.c_contiguous == b.flags.c_contiguous assert a.flags.f_contiguous == b.flags.f_contiguous assert a.flags.writeable == b.flags.writeable assert a.flags.aligned == b.flags.aligned if LooseVersion(np.__version__) >= LooseVersion("1.14.0"): assert a.flags.writebackifcopy == b.flags.writebackifcopy else: assert a.flags.updateifcopy == b.flags.updateifcopy assert np.all(a == b) assert not b.flags.owndata assert b.base is base if a.flags.writeable and a.ndim == 2: a[0, 0] = 1234 assert b[0, 0] == 1234 a1 = np.array([1, 2], dtype=np.int16) assert a1.flags.owndata and a1.base is None a2 = m.wrap(a1) assert_references(a1, a2) a1 = np.array([[1, 2], [3, 4]], dtype=np.float32, order="F") assert a1.flags.owndata and a1.base is None a2 = m.wrap(a1) assert_references(a1, a2) a1 = np.array([[1, 2], [3, 4]], dtype=np.float32, order="C") a1.flags.writeable = False a2 = m.wrap(a1) assert_references(a1, a2) a1 = np.random.random((4, 4, 4)) a2 = m.wrap(a1) assert_references(a1, a2) a1t = a1.transpose() a2 = m.wrap(a1t) assert_references(a1t, a2, a1) a1d = a1.diagonal() a2 = m.wrap(a1d) assert_references(a1d, a2, a1) a1m = a1[::-1, ::-1, ::-1] a2 = m.wrap(a1m) assert_references(a1m, a2, a1) def test_numpy_view(capture): with capture: ac = m.ArrayClass() ac_view_1 = ac.numpy_view() ac_view_2 = ac.numpy_view() assert np.all(ac_view_1 == np.array([1, 2], dtype=np.int32)) del ac pytest.gc_collect() assert ( capture == """ ArrayClass() ArrayClass::numpy_view() ArrayClass::numpy_view() """ ) ac_view_1[0] = 4 ac_view_1[1] = 3 assert ac_view_2[0] == 4 assert ac_view_2[1] == 3 with capture: del ac_view_1 del ac_view_2 pytest.gc_collect() pytest.gc_collect() assert ( capture == """ ~ArrayClass() """ ) def test_cast_numpy_int64_to_uint64(): m.function_taking_uint64(123) m.function_taking_uint64(np.uint64(123)) def test_isinstance(): assert m.isinstance_untyped(np.array([1, 2, 3]), "not an array") assert m.isinstance_typed(np.array([1.0, 2.0, 3.0])) def test_constructors(): defaults = m.default_constructors() for a in defaults.values(): assert a.size == 0 assert defaults["array"].dtype == np.array([]).dtype assert defaults["array_t<int32>"].dtype == np.int32 assert defaults["array_t<double>"].dtype == np.float64 results = m.converting_constructors([1, 2, 3]) for a in results.values(): np.testing.assert_array_equal(a, [1, 2, 3]) assert results["array"].dtype == np.int_ assert results["array_t<int32>"].dtype == np.int32 assert results["array_t<double>"].dtype == np.float64 def test_overload_resolution(msg): # Exact overload matches: assert m.overloaded(np.array([1], dtype="float64")) == "double" assert m.overloaded(np.array([1], dtype="float32")) == "float" assert m.overloaded(np.array([1], dtype="ushort")) == "unsigned short" assert m.overloaded(np.array([1], dtype="intc")) == "int" assert m.overloaded(np.array([1], dtype="longlong")) == "long long" assert m.overloaded(np.array([1], dtype="complex")) == "double complex" assert m.overloaded(np.array([1], dtype="csingle")) == "float complex" # No exact match, should call first convertible version: assert m.overloaded(np.array([1], dtype="uint8")) == "double" with pytest.raises(TypeError) as excinfo: m.overloaded("not an array") assert ( msg(excinfo.value) == """ overloaded(): incompatible function arguments. The following argument types are supported: 1. (arg0: numpy.ndarray[numpy.float64]) -> str 2. (arg0: numpy.ndarray[numpy.float32]) -> str 3. (arg0: numpy.ndarray[numpy.int32]) -> str 4. (arg0: numpy.ndarray[numpy.uint16]) -> str 5. (arg0: numpy.ndarray[numpy.int64]) -> str 6. (arg0: numpy.ndarray[numpy.complex128]) -> str 7. (arg0: numpy.ndarray[numpy.complex64]) -> str Invoked with: 'not an array' """ ) assert m.overloaded2(np.array([1], dtype="float64")) == "double" assert m.overloaded2(np.array([1], dtype="float32")) == "float" assert m.overloaded2(np.array([1], dtype="complex64")) == "float complex" assert m.overloaded2(np.array([1], dtype="complex128")) == "double complex" assert m.overloaded2(np.array([1], dtype="float32")) == "float" assert m.overloaded3(np.array([1], dtype="float64")) == "double" assert m.overloaded3(np.array([1], dtype="intc")) == "int" expected_exc = """ overloaded3(): incompatible function arguments. The following argument types are supported: 1. (arg0: numpy.ndarray[numpy.int32]) -> str 2. (arg0: numpy.ndarray[numpy.float64]) -> str Invoked with: """ with pytest.raises(TypeError) as excinfo: m.overloaded3(np.array([1], dtype="uintc")) assert msg(excinfo.value) == expected_exc + repr(np.array([1], dtype="uint32")) with pytest.raises(TypeError) as excinfo: m.overloaded3(np.array([1], dtype="float32")) assert msg(excinfo.value) == expected_exc + repr(np.array([1.0], dtype="float32")) with pytest.raises(TypeError) as excinfo: m.overloaded3(np.array([1], dtype="complex")) assert msg(excinfo.value) == expected_exc + repr(np.array([1.0 + 0.0j])) # Exact matches: assert m.overloaded4(np.array([1], dtype="double")) == "double" assert m.overloaded4(np.array([1], dtype="longlong")) == "long long" # Non-exact matches requiring conversion. Since float to integer isn't a # save conversion, it should go to the double overload, but short can go to # either (and so should end up on the first-registered, the long long). assert m.overloaded4(np.array([1], dtype="float32")) == "double" assert m.overloaded4(np.array([1], dtype="short")) == "long long" assert m.overloaded5(np.array([1], dtype="double")) == "double" assert m.overloaded5(np.array([1], dtype="uintc")) == "unsigned int" assert m.overloaded5(np.array([1], dtype="float32")) == "unsigned int" def test_greedy_string_overload(): """Tests fix for #685 - ndarray shouldn't go to std::string overload""" assert m.issue685("abc") == "string" assert m.issue685(np.array([97, 98, 99], dtype="b")) == "array" assert m.issue685(123) == "other" def test_array_unchecked_fixed_dims(msg): z1 = np.array([[1, 2], [3, 4]], dtype="float64") m.proxy_add2(z1, 10) assert np.all(z1 == [[11, 12], [13, 14]]) with pytest.raises(ValueError) as excinfo: m.proxy_add2(np.array([1.0, 2, 3]), 5.0) assert ( msg(excinfo.value) == "array has incorrect number of dimensions: 1; expected 2" ) expect_c = np.ndarray(shape=(3, 3, 3), buffer=np.array(range(3, 30)), dtype="int") assert np.all(m.proxy_init3(3.0) == expect_c) expect_f = np.transpose(expect_c) assert np.all(m.proxy_init3F(3.0) == expect_f) assert m.proxy_squared_L2_norm(np.array(range(6))) == 55 assert m.proxy_squared_L2_norm(np.array(range(6), dtype="float64")) == 55 assert m.proxy_auxiliaries2(z1) == [11, 11, True, 2, 8, 2, 2, 4, 32] assert m.proxy_auxiliaries2(z1) == m.array_auxiliaries2(z1) assert m.proxy_auxiliaries1_const_ref(z1[0, :]) assert m.proxy_auxiliaries2_const_ref(z1) def test_array_unchecked_dyn_dims(): z1 = np.array([[1, 2], [3, 4]], dtype="float64") m.proxy_add2_dyn(z1, 10) assert np.all(z1 == [[11, 12], [13, 14]]) expect_c = np.ndarray(shape=(3, 3, 3), buffer=np.array(range(3, 30)), dtype="int") assert np.all(m.proxy_init3_dyn(3.0) == expect_c) assert m.proxy_auxiliaries2_dyn(z1) == [11, 11, True, 2, 8, 2, 2, 4, 32] assert m.proxy_auxiliaries2_dyn(z1) == m.array_auxiliaries2(z1) def test_array_failure(): with pytest.raises(ValueError) as excinfo: m.array_fail_test() assert str(excinfo.value) == "cannot create a pybind11::array from a nullptr" with pytest.raises(ValueError) as excinfo: m.array_t_fail_test() assert str(excinfo.value) == "cannot create a pybind11::array_t from a nullptr" with pytest.raises(ValueError) as excinfo: m.array_fail_test_negative_size() assert str(excinfo.value) == "negative dimensions are not allowed" def test_initializer_list(): assert m.array_initializer_list1().shape == (1,) assert m.array_initializer_list2().shape == (1, 2) assert m.array_initializer_list3().shape == (1, 2, 3) assert m.array_initializer_list4().shape == (1, 2, 3, 4) def test_array_resize(): a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype="float64") m.array_reshape2(a) assert a.size == 9 assert np.all(a == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # total size change should succced with refcheck off m.array_resize3(a, 4, False) assert a.size == 64 # ... and fail with refcheck on try: m.array_resize3(a, 3, True) except ValueError as e: assert str(e).startswith("cannot resize an array") # transposed array doesn't own data b = a.transpose() try: m.array_resize3(b, 3, False) except ValueError as e: assert str(e).startswith("cannot resize this array: it does not own its data") # ... but reshape should be fine m.array_reshape2(b) assert b.shape == (8, 8) @pytest.mark.xfail("env.PYPY") def test_array_create_and_resize(): a = m.create_and_resize(2) assert a.size == 4 assert np.all(a == 42.0) def test_array_view(): a = np.ones(100 * 4).astype("uint8") a_float_view = m.array_view(a, "float32") assert a_float_view.shape == (100 * 1,) # 1 / 4 bytes = 8 / 32 a_int16_view = m.array_view(a, "int16") # 1 / 2 bytes = 16 / 32 assert a_int16_view.shape == (100 * 2,) def test_array_view_invalid(): a = np.ones(100 * 4).astype("uint8") with pytest.raises(TypeError): m.array_view(a, "deadly_dtype") def test_reshape_initializer_list(): a = np.arange(2 * 7 * 3) + 1 x = m.reshape_initializer_list(a, 2, 7, 3) assert x.shape == (2, 7, 3) assert list(x[1][4]) == [34, 35, 36] with pytest.raises(ValueError) as excinfo: m.reshape_initializer_list(a, 1, 7, 3) assert str(excinfo.value) == "cannot reshape array of size 42 into shape (1,7,3)" def test_reshape_tuple(): a = np.arange(3 * 7 * 2) + 1 x = m.reshape_tuple(a, (3, 7, 2)) assert x.shape == (3, 7, 2) assert list(x[1][4]) == [23, 24] y = m.reshape_tuple(x, (x.size,)) assert y.shape == (42,) with pytest.raises(ValueError) as excinfo: m.reshape_tuple(a, (3, 7, 1)) assert str(excinfo.value) == "cannot reshape array of size 42 into shape (3,7,1)" with pytest.raises(ValueError) as excinfo: m.reshape_tuple(a, ()) assert str(excinfo.value) == "cannot reshape array of size 42 into shape ()" def test_index_using_ellipsis(): a = m.index_using_ellipsis(np.zeros((5, 6, 7))) assert a.shape == (6,) @pytest.mark.parametrize( "test_func", [ m.test_fmt_desc_float, m.test_fmt_desc_double, m.test_fmt_desc_const_float, m.test_fmt_desc_const_double, ], ) def test_format_descriptors_for_floating_point_types(test_func): assert "numpy.ndarray[numpy.float" in test_func.__doc__ @pytest.mark.parametrize("forcecast", [False, True]) @pytest.mark.parametrize("contiguity", [None, "C", "F"]) @pytest.mark.parametrize("noconvert", [False, True]) @pytest.mark.filterwarnings( "ignore:Casting complex values to real discards the imaginary part:numpy.ComplexWarning" ) def test_argument_conversions(forcecast, contiguity, noconvert): function_name = "accept_double" if contiguity == "C": function_name += "_c_style" elif contiguity == "F": function_name += "_f_style" if forcecast: function_name += "_forcecast" if noconvert: function_name += "_noconvert" function = getattr(m, function_name) for dtype in [np.dtype("float32"), np.dtype("float64"), np.dtype("complex128")]: for order in ["C", "F"]: for shape in [(2, 2), (1, 3, 1, 1), (1, 1, 1), (0,)]: if not noconvert: # If noconvert is not passed, only complex128 needs to be truncated and # "cannot be safely obtained". So without `forcecast`, the argument shouldn't # be accepted. should_raise = dtype.name == "complex128" and not forcecast else: # If noconvert is passed, only float64 and the matching order is accepted. # If at most one dimension has a size greater than 1, the array is also # trivially contiguous. trivially_contiguous = sum(1 for d in shape if d > 1) <= 1 should_raise = dtype.name != "float64" or ( contiguity is not None and contiguity != order and not trivially_contiguous ) array = np.zeros(shape, dtype=dtype, order=order) if not should_raise: function(array) else: with pytest.raises( TypeError, match="incompatible function arguments" ): function(array) @pytest.mark.xfail("env.PYPY") def test_dtype_refcount_leak(): from sys import getrefcount dtype = np.dtype(np.float_) a = np.array([1], dtype=dtype) before = getrefcount(dtype) m.ndim(a) after = getrefcount(dtype) assert after == before
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_union.py
.py
172
10
# -*- coding: utf-8 -*- from pybind11_tests import union_ as m def test_union(): instance = m.TestUnion() instance.as_uint = 10 assert instance.as_int == 10
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_buffers.cpp
.cpp
8,567
225
/* tests/test_buffers.cpp -- supporting Pythons' buffer protocol Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> 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/stl.h> #include "constructor_stats.h" #include "pybind11_tests.h" TEST_SUBMODULE(buffers, m) { // test_from_python / test_to_python: class Matrix { public: Matrix(py::ssize_t rows, py::ssize_t cols) : m_rows(rows), m_cols(cols) { print_created(this, std::to_string(m_rows) + "x" + std::to_string(m_cols) + " matrix"); // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer) m_data = new float[(size_t) (rows * cols)]; memset(m_data, 0, sizeof(float) * (size_t) (rows * cols)); } Matrix(const Matrix &s) : m_rows(s.m_rows), m_cols(s.m_cols) { print_copy_created(this, std::to_string(m_rows) + "x" + std::to_string(m_cols) + " matrix"); // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer) m_data = new float[(size_t) (m_rows * m_cols)]; memcpy(m_data, s.m_data, sizeof(float) * (size_t) (m_rows * m_cols)); } Matrix(Matrix &&s) noexcept : m_rows(s.m_rows), m_cols(s.m_cols), m_data(s.m_data) { print_move_created(this); s.m_rows = 0; s.m_cols = 0; s.m_data = nullptr; } ~Matrix() { print_destroyed(this, std::to_string(m_rows) + "x" + std::to_string(m_cols) + " matrix"); delete[] m_data; } Matrix &operator=(const Matrix &s) { if (this == &s) { return *this; } print_copy_assigned(this, std::to_string(m_rows) + "x" + std::to_string(m_cols) + " matrix"); delete[] m_data; m_rows = s.m_rows; m_cols = s.m_cols; m_data = new float[(size_t) (m_rows * m_cols)]; memcpy(m_data, s.m_data, sizeof(float) * (size_t) (m_rows * m_cols)); return *this; } Matrix &operator=(Matrix &&s) noexcept { print_move_assigned(this, std::to_string(m_rows) + "x" + std::to_string(m_cols) + " matrix"); if (&s != this) { delete[] m_data; m_rows = s.m_rows; m_cols = s.m_cols; m_data = s.m_data; s.m_rows = 0; s.m_cols = 0; s.m_data = nullptr; } return *this; } float operator()(py::ssize_t i, py::ssize_t j) const { return m_data[(size_t) (i * m_cols + j)]; } float &operator()(py::ssize_t i, py::ssize_t j) { return m_data[(size_t) (i * m_cols + j)]; } float *data() { return m_data; } py::ssize_t rows() const { return m_rows; } py::ssize_t cols() const { return m_cols; } private: py::ssize_t m_rows; py::ssize_t m_cols; float *m_data; }; py::class_<Matrix>(m, "Matrix", py::buffer_protocol()) .def(py::init<py::ssize_t, py::ssize_t>()) /// Construct from a buffer .def(py::init([](const py::buffer &b) { py::buffer_info info = b.request(); if (info.format != py::format_descriptor<float>::format() || info.ndim != 2) { throw std::runtime_error("Incompatible buffer format!"); } auto *v = new Matrix(info.shape[0], info.shape[1]); memcpy(v->data(), info.ptr, sizeof(float) * (size_t) (v->rows() * v->cols())); return v; })) .def("rows", &Matrix::rows) .def("cols", &Matrix::cols) /// Bare bones interface .def("__getitem__", [](const Matrix &m, std::pair<py::ssize_t, py::ssize_t> i) { if (i.first >= m.rows() || i.second >= m.cols()) { throw py::index_error(); } return m(i.first, i.second); }) .def("__setitem__", [](Matrix &m, std::pair<py::ssize_t, py::ssize_t> i, float v) { if (i.first >= m.rows() || i.second >= m.cols()) { throw py::index_error(); } m(i.first, i.second) = v; }) /// Provide buffer access .def_buffer([](Matrix &m) -> py::buffer_info { return py::buffer_info( m.data(), /* Pointer to buffer */ {m.rows(), m.cols()}, /* Buffer dimensions */ {sizeof(float) * size_t(m.cols()), /* Strides (in bytes) for each index */ sizeof(float)}); }); // test_inherited_protocol class SquareMatrix : public Matrix { public: explicit SquareMatrix(py::ssize_t n) : Matrix(n, n) {} }; // Derived classes inherit the buffer protocol and the buffer access function py::class_<SquareMatrix, Matrix>(m, "SquareMatrix").def(py::init<py::ssize_t>()); // test_pointer_to_member_fn // Tests that passing a pointer to member to the base class works in // the derived class. struct Buffer { int32_t value = 0; py::buffer_info get_buffer_info() { return py::buffer_info( &value, sizeof(value), py::format_descriptor<int32_t>::format(), 1); } }; py::class_<Buffer>(m, "Buffer", py::buffer_protocol()) .def(py::init<>()) .def_readwrite("value", &Buffer::value) .def_buffer(&Buffer::get_buffer_info); class ConstBuffer { std::unique_ptr<int32_t> value; public: int32_t get_value() const { return *value; } void set_value(int32_t v) { *value = v; } py::buffer_info get_buffer_info() const { return py::buffer_info( value.get(), sizeof(*value), py::format_descriptor<int32_t>::format(), 1); } ConstBuffer() : value(new int32_t{0}) {} }; py::class_<ConstBuffer>(m, "ConstBuffer", py::buffer_protocol()) .def(py::init<>()) .def_property("value", &ConstBuffer::get_value, &ConstBuffer::set_value) .def_buffer(&ConstBuffer::get_buffer_info); struct DerivedBuffer : public Buffer {}; py::class_<DerivedBuffer>(m, "DerivedBuffer", py::buffer_protocol()) .def(py::init<>()) .def_readwrite("value", (int32_t DerivedBuffer::*) &DerivedBuffer::value) .def_buffer(&DerivedBuffer::get_buffer_info); struct BufferReadOnly { const uint8_t value = 0; explicit BufferReadOnly(uint8_t value) : value(value) {} py::buffer_info get_buffer_info() { return py::buffer_info(&value, 1); } }; py::class_<BufferReadOnly>(m, "BufferReadOnly", py::buffer_protocol()) .def(py::init<uint8_t>()) .def_buffer(&BufferReadOnly::get_buffer_info); struct BufferReadOnlySelect { uint8_t value = 0; bool readonly = false; py::buffer_info get_buffer_info() { return py::buffer_info(&value, 1, readonly); } }; py::class_<BufferReadOnlySelect>(m, "BufferReadOnlySelect", py::buffer_protocol()) .def(py::init<>()) .def_readwrite("value", &BufferReadOnlySelect::value) .def_readwrite("readonly", &BufferReadOnlySelect::readonly) .def_buffer(&BufferReadOnlySelect::get_buffer_info); // Expose buffer_info for testing. py::class_<py::buffer_info>(m, "buffer_info") .def(py::init<>()) .def_readonly("itemsize", &py::buffer_info::itemsize) .def_readonly("size", &py::buffer_info::size) .def_readonly("format", &py::buffer_info::format) .def_readonly("ndim", &py::buffer_info::ndim) .def_readonly("shape", &py::buffer_info::shape) .def_readonly("strides", &py::buffer_info::strides) .def_readonly("readonly", &py::buffer_info::readonly) .def("__repr__", [](py::handle self) { return py::str("itemsize={0.itemsize!r}, size={0.size!r}, format={0.format!r}, " "ndim={0.ndim!r}, shape={0.shape!r}, strides={0.strides!r}, " "readonly={0.readonly!r}") .format(self); }); m.def("get_buffer_info", [](const py::buffer &buffer) { return buffer.request(); }); }
C++
3D
mcellteam/mcell
libs/pybind11/tests/test_constants_and_functions.cpp
.cpp
5,934
163
/* tests/test_constants_and_functions.cpp -- global constants and functions, enumerations, raw byte strings Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> 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" enum MyEnum { EFirstEntry = 1, ESecondEntry }; std::string test_function1() { return "test_function()"; } std::string test_function2(MyEnum k) { return "test_function(enum=" + std::to_string(k) + ")"; } std::string test_function3(int i) { return "test_function(" + std::to_string(i) + ")"; } py::str test_function4() { return "test_function()"; } py::str test_function4(char *) { return "test_function(char *)"; } py::str test_function4(int, float) { return "test_function(int, float)"; } py::str test_function4(float, int) { return "test_function(float, int)"; } py::bytes return_bytes() { const char *data = "\x01\x00\x02\x00"; return std::string(data, 4); } std::string print_bytes(const py::bytes &bytes) { std::string ret = "bytes["; const auto value = static_cast<std::string>(bytes); for (size_t i = 0; i < value.length(); ++i) { ret += std::to_string(static_cast<int>(value[i])) + " "; } ret.back() = ']'; return ret; } // Test that we properly handle C++17 exception specifiers (which are part of the function // signature in C++17). These should all still work before C++17, but don't affect the function // signature. namespace test_exc_sp { // [workaround(intel)] Unable to use noexcept instead of noexcept(true) // Make the f1 test basically the same as the f2 test in C++17 mode for the Intel compiler as // it fails to compile with a plain noexcept (tested with icc (ICC) 2021.1 Beta 20200827). #if defined(__INTEL_COMPILER) && defined(PYBIND11_CPP17) int f1(int x) noexcept(true) { return x + 1; } #else int f1(int x) noexcept { return x + 1; } #endif int f2(int x) noexcept(true) { return x + 2; } int f3(int x) noexcept(false) { return x + 3; } #if defined(__GNUG__) && !defined(__INTEL_COMPILER) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated" #endif // NOLINTNEXTLINE(modernize-use-noexcept) int f4(int x) throw() { return x + 4; } // Deprecated equivalent to noexcept(true) #if defined(__GNUG__) && !defined(__INTEL_COMPILER) # pragma GCC diagnostic pop #endif struct C { int m1(int x) noexcept { return x - 1; } int m2(int x) const noexcept { return x - 2; } int m3(int x) noexcept(true) { return x - 3; } int m4(int x) const noexcept(true) { return x - 4; } int m5(int x) noexcept(false) { return x - 5; } int m6(int x) const noexcept(false) { return x - 6; } #if defined(__GNUG__) && !defined(__INTEL_COMPILER) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated" #endif // NOLINTNEXTLINE(modernize-use-noexcept) int m7(int x) throw() { return x - 7; } // NOLINTNEXTLINE(modernize-use-noexcept) int m8(int x) const throw() { return x - 8; } #if defined(__GNUG__) && !defined(__INTEL_COMPILER) # pragma GCC diagnostic pop #endif }; } // namespace test_exc_sp TEST_SUBMODULE(constants_and_functions, m) { // test_constants m.attr("some_constant") = py::int_(14); // test_function_overloading m.def("test_function", &test_function1); m.def("test_function", &test_function2); m.def("test_function", &test_function3); #if defined(PYBIND11_OVERLOAD_CAST) m.def("test_function", py::overload_cast<>(&test_function4)); m.def("test_function", py::overload_cast<char *>(&test_function4)); m.def("test_function", py::overload_cast<int, float>(&test_function4)); m.def("test_function", py::overload_cast<float, int>(&test_function4)); #else m.def("test_function", static_cast<py::str (*)()>(&test_function4)); m.def("test_function", static_cast<py::str (*)(char *)>(&test_function4)); m.def("test_function", static_cast<py::str (*)(int, float)>(&test_function4)); m.def("test_function", static_cast<py::str (*)(float, int)>(&test_function4)); #endif py::enum_<MyEnum>(m, "MyEnum") .value("EFirstEntry", EFirstEntry) .value("ESecondEntry", ESecondEntry) .export_values(); // test_bytes m.def("return_bytes", &return_bytes); m.def("print_bytes", &print_bytes); // test_exception_specifiers using namespace test_exc_sp; py::class_<C>(m, "C") .def(py::init<>()) .def("m1", &C::m1) .def("m2", &C::m2) .def("m3", &C::m3) .def("m4", &C::m4) .def("m5", &C::m5) .def("m6", &C::m6) .def("m7", &C::m7) .def("m8", &C::m8); m.def("f1", f1); m.def("f2", f2); #if defined(__INTEL_COMPILER) # pragma warning push # pragma warning disable 878 // incompatible exception specifications #endif m.def("f3", f3); #if defined(__INTEL_COMPILER) # pragma warning pop #endif m.def("f4", f4); // test_function_record_leaks struct LargeCapture { // This should always be enough to trigger the alternative branch // where `sizeof(capture) > sizeof(rec->data)` uint64_t zeros[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; }; m.def("register_large_capture_with_invalid_arguments", [](py::module_ m) { LargeCapture capture; // VS 2015's MSVC is acting up if we create the array here m.def( "should_raise", [capture](int) { return capture.zeros[9] + 33; }, py::kw_only(), py::arg()); }); m.def("register_with_raising_repr", [](py::module_ m, const py::object &default_value) { m.def( "should_raise", [](int, int, const py::object &) { return 42; }, "some docstring", py::arg_v("x", 42), py::arg_v("y", 42, "<the answer>"), py::arg_v("z", default_value)); }); }
C++
3D
mcellteam/mcell
libs/pybind11/tests/test_eval.cpp
.cpp
3,168
119
/* tests/test_eval.cpp -- Usage of eval() and eval_file() Copyright (c) 2016 Klemens D. Morgenstern 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/eval.h> #include "pybind11_tests.h" #include <utility> TEST_SUBMODULE(eval_, m) { // test_evals auto global = py::dict(py::module_::import("__main__").attr("__dict__")); m.def("test_eval_statements", [global]() { auto local = py::dict(); local["call_test"] = py::cpp_function([&]() -> int { return 42; }); // Regular string literal py::exec("message = 'Hello World!'\n" "x = call_test()", global, local); // Multi-line raw string literal py::exec(R"( if x == 42: print(message) else: raise RuntimeError )", global, local); auto x = local["x"].cast<int>(); return x == 42; }); m.def("test_eval", [global]() { auto local = py::dict(); local["x"] = py::int_(42); auto x = py::eval("x", global, local); return x.cast<int>() == 42; }); m.def("test_eval_single_statement", []() { auto local = py::dict(); local["call_test"] = py::cpp_function([&]() -> int { return 42; }); auto result = py::eval<py::eval_single_statement>("x = call_test()", py::dict(), local); auto x = local["x"].cast<int>(); return result.is_none() && x == 42; }); m.def("test_eval_file", [global](py::str filename) { auto local = py::dict(); local["y"] = py::int_(43); int val_out = 0; local["call_test2"] = py::cpp_function([&](int value) { val_out = value; }); auto result = py::eval_file(std::move(filename), global, local); return val_out == 43 && result.is_none(); }); m.def("test_eval_failure", []() { try { py::eval("nonsense code ..."); } catch (py::error_already_set &) { return true; } return false; }); m.def("test_eval_file_failure", []() { try { py::eval_file("non-existing file"); } catch (std::exception &) { return true; } return false; }); // test_eval_empty_globals m.def("eval_empty_globals", [](py::object global) { if (global.is_none()) { global = py::dict(); } auto int_class = py::eval("isinstance(42, int)", global); return global; }); // test_eval_closure m.def("test_eval_closure", []() { py::dict global; global["closure_value"] = 42; py::dict local; local["closure_value"] = 0; py::exec(R"( local_value = closure_value def func_global(): return closure_value def func_local(): return local_value )", global, local); return std::make_pair(global, local); }); }
C++
3D
mcellteam/mcell
libs/pybind11/tests/pybind11_cross_module_tests.cpp
.cpp
6,264
150
/* tests/pybind11_cross_module_tests.cpp -- contains tests that require multiple modules Copyright (c) 2017 Jason Rhinelander <jason@imaginary.ca> 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/stl_bind.h> #include "local_bindings.h" #include "pybind11_tests.h" #include "test_exceptions.h" #include <numeric> #include <utility> PYBIND11_MODULE(pybind11_cross_module_tests, m) { m.doc() = "pybind11 cross-module test module"; // test_local_bindings.py tests: // // Definitions here are tested by importing both this module and the // relevant pybind11_tests submodule from a test_whatever.py // test_load_external bind_local<ExternalType1>(m, "ExternalType1", py::module_local()); bind_local<ExternalType2>(m, "ExternalType2", py::module_local()); // test_exceptions.py py::register_local_exception<LocalSimpleException>(m, "LocalSimpleException"); m.def("raise_runtime_error", []() { PyErr_SetString(PyExc_RuntimeError, "My runtime error"); throw py::error_already_set(); }); m.def("raise_value_error", []() { PyErr_SetString(PyExc_ValueError, "My value error"); throw py::error_already_set(); }); m.def("throw_pybind_value_error", []() { throw py::value_error("pybind11 value error"); }); m.def("throw_pybind_type_error", []() { throw py::type_error("pybind11 type error"); }); m.def("throw_stop_iteration", []() { throw py::stop_iteration(); }); m.def("throw_local_error", []() { throw LocalException("just local"); }); m.def("throw_local_simple_error", []() { throw LocalSimpleException("external mod"); }); py::register_exception_translator([](std::exception_ptr p) { try { if (p) { std::rethrow_exception(p); } } catch (const shared_exception &e) { PyErr_SetString(PyExc_KeyError, e.what()); } }); // translate the local exception into a key error but only in this module py::register_local_exception_translator([](std::exception_ptr p) { try { if (p) { std::rethrow_exception(p); } } catch (const LocalException &e) { PyErr_SetString(PyExc_KeyError, e.what()); } }); // test_local_bindings.py // Local to both: bind_local<LocalType, 1>(m, "LocalType", py::module_local()).def("get2", [](LocalType &t) { return t.i + 2; }); // Can only be called with our python type: m.def("local_value", [](LocalType &l) { return l.i; }); // test_nonlocal_failure // This registration will fail (global registration when LocalFail is already registered // globally in the main test module): m.def("register_nonlocal", [m]() { bind_local<NonLocalType, 0>(m, "NonLocalType"); }); // test_stl_bind_local // stl_bind.h binders defaults to py::module_local if the types are local or converting: py::bind_vector<LocalVec>(m, "LocalVec"); py::bind_map<LocalMap>(m, "LocalMap"); // test_stl_bind_global // and global if the type (or one of the types, for the map) is global (so these will fail, // assuming pybind11_tests is already loaded): m.def("register_nonlocal_vec", [m]() { py::bind_vector<NonLocalVec>(m, "NonLocalVec"); }); m.def("register_nonlocal_map", [m]() { py::bind_map<NonLocalMap>(m, "NonLocalMap"); }); // The default can, however, be overridden to global using `py::module_local()` or // `py::module_local(false)`. // Explicitly made local: py::bind_vector<NonLocalVec2>(m, "NonLocalVec2", py::module_local()); // Explicitly made global (and so will fail to bind): m.def("register_nonlocal_map2", [m]() { py::bind_map<NonLocalMap2>(m, "NonLocalMap2", py::module_local(false)); }); // test_mixed_local_global // We try this both with the global type registered first and vice versa (the order shouldn't // matter). m.def("register_mixed_global_local", [m]() { bind_local<MixedGlobalLocal, 200>(m, "MixedGlobalLocal", py::module_local()); }); m.def("register_mixed_local_global", [m]() { bind_local<MixedLocalGlobal, 2000>(m, "MixedLocalGlobal", py::module_local(false)); }); m.def("get_mixed_gl", [](int i) { return MixedGlobalLocal(i); }); m.def("get_mixed_lg", [](int i) { return MixedLocalGlobal(i); }); // test_internal_locals_differ m.def("local_cpp_types_addr", []() { return (uintptr_t) &py::detail::get_local_internals().registered_types_cpp; }); // test_stl_caster_vs_stl_bind py::bind_vector<std::vector<int>>(m, "VectorInt"); m.def("load_vector_via_binding", [](std::vector<int> &v) { return std::accumulate(v.begin(), v.end(), 0); }); // test_cross_module_calls m.def("return_self", [](LocalVec *v) { return v; }); m.def("return_copy", [](const LocalVec &v) { return LocalVec(v); }); class Dog : public pets::Pet { public: explicit Dog(std::string name) : Pet(std::move(name)) {} }; py::class_<pets::Pet>(m, "Pet", py::module_local()).def("name", &pets::Pet::name); // Binding for local extending class: py::class_<Dog, pets::Pet>(m, "Dog").def(py::init<std::string>()); m.def("pet_name", [](pets::Pet &p) { return p.name(); }); py::class_<MixGL>(m, "MixGL", py::module_local()).def(py::init<int>()); m.def("get_gl_value", [](MixGL &o) { return o.i + 100; }); py::class_<MixGL2>(m, "MixGL2", py::module_local()).def(py::init<int>()); // test_vector_bool // We can't test both stl.h and stl_bind.h conversions of `std::vector<bool>` within // the same module (it would be an ODR violation). Therefore `bind_vector` of `bool` // is defined here and tested in `test_stl_binders.py`. py::bind_vector<std::vector<bool>>(m, "VectorBool"); // test_missing_header_message // The main module already includes stl.h, but we need to test the error message // which appears when this header is missing. m.def("missing_header_arg", [](const std::vector<float> &) {}); m.def("missing_header_return", []() { return std::vector<float>(); }); }
C++
3D
mcellteam/mcell
libs/pybind11/tests/test_call_policies.py
.py
6,573
249
# -*- coding: utf-8 -*- import pytest import env # noqa: F401 from pybind11_tests import ConstructorStats from pybind11_tests import call_policies as m @pytest.mark.xfail("env.PYPY", reason="sometimes comes out 1 off on PyPy", strict=False) def test_keep_alive_argument(capture): n_inst = ConstructorStats.detail_reg_inst() with capture: p = m.Parent() assert capture == "Allocating parent." with capture: p.addChild(m.Child()) assert ConstructorStats.detail_reg_inst() == n_inst + 1 assert ( capture == """ Allocating child. Releasing child. """ ) with capture: del p assert ConstructorStats.detail_reg_inst() == n_inst assert capture == "Releasing parent." with capture: p = m.Parent() assert capture == "Allocating parent." with capture: p.addChildKeepAlive(m.Child()) assert ConstructorStats.detail_reg_inst() == n_inst + 2 assert capture == "Allocating child." with capture: del p assert ConstructorStats.detail_reg_inst() == n_inst assert ( capture == """ Releasing parent. Releasing child. """ ) p = m.Parent() c = m.Child() assert ConstructorStats.detail_reg_inst() == n_inst + 2 m.free_function(p, c) del c assert ConstructorStats.detail_reg_inst() == n_inst + 2 del p assert ConstructorStats.detail_reg_inst() == n_inst with pytest.raises(RuntimeError) as excinfo: m.invalid_arg_index() assert str(excinfo.value) == "Could not activate keep_alive!" def test_keep_alive_return_value(capture): n_inst = ConstructorStats.detail_reg_inst() with capture: p = m.Parent() assert capture == "Allocating parent." with capture: p.returnChild() assert ConstructorStats.detail_reg_inst() == n_inst + 1 assert ( capture == """ Allocating child. Releasing child. """ ) with capture: del p assert ConstructorStats.detail_reg_inst() == n_inst assert capture == "Releasing parent." with capture: p = m.Parent() assert capture == "Allocating parent." with capture: p.returnChildKeepAlive() assert ConstructorStats.detail_reg_inst() == n_inst + 2 assert capture == "Allocating child." with capture: del p assert ConstructorStats.detail_reg_inst() == n_inst assert ( capture == """ Releasing parent. Releasing child. """ ) p = m.Parent() assert ConstructorStats.detail_reg_inst() == n_inst + 1 with capture: m.Parent.staticFunction(p) assert ConstructorStats.detail_reg_inst() == n_inst + 2 assert capture == "Allocating child." with capture: del p assert ConstructorStats.detail_reg_inst() == n_inst assert ( capture == """ Releasing parent. Releasing child. """ ) # https://foss.heptapod.net/pypy/pypy/-/issues/2447 @pytest.mark.xfail("env.PYPY", reason="_PyObject_GetDictPtr is unimplemented") def test_alive_gc(capture): n_inst = ConstructorStats.detail_reg_inst() p = m.ParentGC() p.addChildKeepAlive(m.Child()) assert ConstructorStats.detail_reg_inst() == n_inst + 2 lst = [p] lst.append(lst) # creates a circular reference with capture: del p, lst assert ConstructorStats.detail_reg_inst() == n_inst assert ( capture == """ Releasing parent. Releasing child. """ ) def test_alive_gc_derived(capture): class Derived(m.Parent): pass n_inst = ConstructorStats.detail_reg_inst() p = Derived() p.addChildKeepAlive(m.Child()) assert ConstructorStats.detail_reg_inst() == n_inst + 2 lst = [p] lst.append(lst) # creates a circular reference with capture: del p, lst assert ConstructorStats.detail_reg_inst() == n_inst assert ( capture == """ Releasing parent. Releasing child. """ ) def test_alive_gc_multi_derived(capture): class Derived(m.Parent, m.Child): def __init__(self): m.Parent.__init__(self) m.Child.__init__(self) n_inst = ConstructorStats.detail_reg_inst() p = Derived() p.addChildKeepAlive(m.Child()) # +3 rather than +2 because Derived corresponds to two registered instances assert ConstructorStats.detail_reg_inst() == n_inst + 3 lst = [p] lst.append(lst) # creates a circular reference with capture: del p, lst assert ConstructorStats.detail_reg_inst() == n_inst assert ( capture == """ Releasing parent. Releasing child. Releasing child. """ ) def test_return_none(capture): n_inst = ConstructorStats.detail_reg_inst() with capture: p = m.Parent() assert capture == "Allocating parent." with capture: p.returnNullChildKeepAliveChild() assert ConstructorStats.detail_reg_inst() == n_inst + 1 assert capture == "" with capture: del p assert ConstructorStats.detail_reg_inst() == n_inst assert capture == "Releasing parent." with capture: p = m.Parent() assert capture == "Allocating parent." with capture: p.returnNullChildKeepAliveParent() assert ConstructorStats.detail_reg_inst() == n_inst + 1 assert capture == "" with capture: del p assert ConstructorStats.detail_reg_inst() == n_inst assert capture == "Releasing parent." def test_keep_alive_constructor(capture): n_inst = ConstructorStats.detail_reg_inst() with capture: p = m.Parent(m.Child()) assert ConstructorStats.detail_reg_inst() == n_inst + 2 assert ( capture == """ Allocating child. Allocating parent. """ ) with capture: del p assert ConstructorStats.detail_reg_inst() == n_inst assert ( capture == """ Releasing parent. Releasing child. """ ) def test_call_guard(): assert m.unguarded_call() == "unguarded" assert m.guarded_call() == "guarded" assert m.multiple_guards_correct_order() == "guarded & guarded" assert m.multiple_guards_wrong_order() == "unguarded & guarded" if hasattr(m, "with_gil"): assert m.with_gil() == "GIL held" assert m.without_gil() == "GIL released"
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_opaque_types.py
.py
1,907
60
# -*- coding: utf-8 -*- import pytest from pybind11_tests import ConstructorStats, UserType from pybind11_tests import opaque_types as m def test_string_list(): lst = m.StringList() lst.push_back("Element 1") lst.push_back("Element 2") assert m.print_opaque_list(lst) == "Opaque list: [Element 1, Element 2]" assert lst.back() == "Element 2" for i, k in enumerate(lst, start=1): assert k == "Element {}".format(i) lst.pop_back() assert m.print_opaque_list(lst) == "Opaque list: [Element 1]" cvp = m.ClassWithSTLVecProperty() assert m.print_opaque_list(cvp.stringList) == "Opaque list: []" cvp.stringList = lst cvp.stringList.push_back("Element 3") assert m.print_opaque_list(cvp.stringList) == "Opaque list: [Element 1, Element 3]" def test_pointers(msg): living_before = ConstructorStats.get(UserType).alive() assert m.get_void_ptr_value(m.return_void_ptr()) == 0x1234 assert m.get_void_ptr_value(UserType()) # Should also work for other C++ types assert ConstructorStats.get(UserType).alive() == living_before with pytest.raises(TypeError) as excinfo: m.get_void_ptr_value([1, 2, 3]) # This should not work assert ( msg(excinfo.value) == """ get_void_ptr_value(): incompatible function arguments. The following argument types are supported: 1. (arg0: capsule) -> int Invoked with: [1, 2, 3] """ # noqa: E501 line too long ) assert m.return_null_str() is None assert m.get_null_str_value(m.return_null_str()) is not None ptr = m.return_unique_ptr() assert "StringList" in repr(ptr) assert m.print_opaque_list(ptr) == "Opaque list: [some value]" def test_unions(): int_float_union = m.IntFloat() int_float_union.i = 42 assert int_float_union.i == 42 int_float_union.f = 3.0 assert int_float_union.f == 3.0
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_constants_and_functions.py
.py
1,522
54
# -*- coding: utf-8 -*- import pytest m = pytest.importorskip("pybind11_tests.constants_and_functions") def test_constants(): assert m.some_constant == 14 def test_function_overloading(): assert m.test_function() == "test_function()" assert m.test_function(7) == "test_function(7)" assert m.test_function(m.MyEnum.EFirstEntry) == "test_function(enum=1)" assert m.test_function(m.MyEnum.ESecondEntry) == "test_function(enum=2)" assert m.test_function() == "test_function()" assert m.test_function("abcd") == "test_function(char *)" assert m.test_function(1, 1.0) == "test_function(int, float)" assert m.test_function(1, 1.0) == "test_function(int, float)" assert m.test_function(2.0, 2) == "test_function(float, int)" def test_bytes(): assert m.print_bytes(m.return_bytes()) == "bytes[1 0 2 0]" def test_exception_specifiers(): c = m.C() assert c.m1(2) == 1 assert c.m2(3) == 1 assert c.m3(5) == 2 assert c.m4(7) == 3 assert c.m5(10) == 5 assert c.m6(14) == 8 assert c.m7(20) == 13 assert c.m8(29) == 21 assert m.f1(33) == 34 assert m.f2(53) == 55 assert m.f3(86) == 89 assert m.f4(140) == 144 def test_function_record_leaks(): class RaisingRepr: def __repr__(self): raise RuntimeError("Surprise!") with pytest.raises(RuntimeError): m.register_large_capture_with_invalid_arguments(m) with pytest.raises(RuntimeError): m.register_with_raising_repr(m, RaisingRepr())
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_custom_type_setup.cpp
.cpp
1,259
42
/* tests/test_custom_type_setup.cpp -- Tests `pybind11::custom_type_setup` Copyright (c) Google LLC 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/pybind11.h> #include "pybind11_tests.h" namespace py = pybind11; namespace { struct OwnsPythonObjects { py::object value = py::none(); }; } // namespace TEST_SUBMODULE(custom_type_setup, m) { py::class_<OwnsPythonObjects> cls( m, "OwnsPythonObjects", py::custom_type_setup([](PyHeapTypeObject *heap_type) { auto *type = &heap_type->ht_type; type->tp_flags |= Py_TPFLAGS_HAVE_GC; type->tp_traverse = [](PyObject *self_base, visitproc visit, void *arg) { auto &self = py::cast<OwnsPythonObjects &>(py::handle(self_base)); Py_VISIT(self.value.ptr()); return 0; }; type->tp_clear = [](PyObject *self_base) { auto &self = py::cast<OwnsPythonObjects &>(py::handle(self_base)); self.value = py::none(); return 0; }; })); cls.def(py::init<>()); cls.def_readwrite("value", &OwnsPythonObjects::value); }
C++
3D
mcellteam/mcell
libs/pybind11/tests/test_builtin_casters.py
.py
18,372
551
# -*- coding: utf-8 -*- import pytest import env from pybind11_tests import IncType, UserType from pybind11_tests import builtin_casters as m def test_simple_string(): assert m.string_roundtrip("const char *") == "const char *" def test_unicode_conversion(): """Tests unicode conversion and error reporting.""" assert m.good_utf8_string() == u"Say utf8‽ 🎂 𝐀" assert m.good_utf16_string() == u"b‽🎂𝐀z" assert m.good_utf32_string() == u"a𝐀🎂‽z" assert m.good_wchar_string() == u"a⸘𝐀z" if hasattr(m, "has_u8string"): assert m.good_utf8_u8string() == u"Say utf8‽ 🎂 𝐀" with pytest.raises(UnicodeDecodeError): m.bad_utf8_string() with pytest.raises(UnicodeDecodeError): m.bad_utf16_string() # These are provided only if they actually fail (they don't when 32-bit and under Python 2.7) if hasattr(m, "bad_utf32_string"): with pytest.raises(UnicodeDecodeError): m.bad_utf32_string() if hasattr(m, "bad_wchar_string"): with pytest.raises(UnicodeDecodeError): m.bad_wchar_string() if hasattr(m, "has_u8string"): with pytest.raises(UnicodeDecodeError): m.bad_utf8_u8string() assert m.u8_Z() == "Z" assert m.u8_eacute() == u"é" assert m.u16_ibang() == u"‽" assert m.u32_mathbfA() == u"𝐀" assert m.wchar_heart() == u"♥" if hasattr(m, "has_u8string"): assert m.u8_char8_Z() == "Z" def test_single_char_arguments(): """Tests failures for passing invalid inputs to char-accepting functions""" def toobig_message(r): return "Character code point not in range({:#x})".format(r) toolong_message = "Expected a character, but multi-character string found" assert m.ord_char(u"a") == 0x61 # simple ASCII assert m.ord_char_lv(u"b") == 0x62 assert ( m.ord_char(u"é") == 0xE9 ) # requires 2 bytes in utf-8, but can be stuffed in a char with pytest.raises(ValueError) as excinfo: assert m.ord_char(u"Ā") == 0x100 # requires 2 bytes, doesn't fit in a char assert str(excinfo.value) == toobig_message(0x100) with pytest.raises(ValueError) as excinfo: assert m.ord_char(u"ab") assert str(excinfo.value) == toolong_message assert m.ord_char16(u"a") == 0x61 assert m.ord_char16(u"é") == 0xE9 assert m.ord_char16_lv(u"ê") == 0xEA assert m.ord_char16(u"Ā") == 0x100 assert m.ord_char16(u"‽") == 0x203D assert m.ord_char16(u"♥") == 0x2665 assert m.ord_char16_lv(u"♡") == 0x2661 with pytest.raises(ValueError) as excinfo: assert m.ord_char16(u"🎂") == 0x1F382 # requires surrogate pair assert str(excinfo.value) == toobig_message(0x10000) with pytest.raises(ValueError) as excinfo: assert m.ord_char16(u"aa") assert str(excinfo.value) == toolong_message assert m.ord_char32(u"a") == 0x61 assert m.ord_char32(u"é") == 0xE9 assert m.ord_char32(u"Ā") == 0x100 assert m.ord_char32(u"‽") == 0x203D assert m.ord_char32(u"♥") == 0x2665 assert m.ord_char32(u"🎂") == 0x1F382 with pytest.raises(ValueError) as excinfo: assert m.ord_char32(u"aa") assert str(excinfo.value) == toolong_message assert m.ord_wchar(u"a") == 0x61 assert m.ord_wchar(u"é") == 0xE9 assert m.ord_wchar(u"Ā") == 0x100 assert m.ord_wchar(u"‽") == 0x203D assert m.ord_wchar(u"♥") == 0x2665 if m.wchar_size == 2: with pytest.raises(ValueError) as excinfo: assert m.ord_wchar(u"🎂") == 0x1F382 # requires surrogate pair assert str(excinfo.value) == toobig_message(0x10000) else: assert m.ord_wchar(u"🎂") == 0x1F382 with pytest.raises(ValueError) as excinfo: assert m.ord_wchar(u"aa") assert str(excinfo.value) == toolong_message if hasattr(m, "has_u8string"): assert m.ord_char8(u"a") == 0x61 # simple ASCII assert m.ord_char8_lv(u"b") == 0x62 assert ( m.ord_char8(u"é") == 0xE9 ) # requires 2 bytes in utf-8, but can be stuffed in a char with pytest.raises(ValueError) as excinfo: assert m.ord_char8(u"Ā") == 0x100 # requires 2 bytes, doesn't fit in a char assert str(excinfo.value) == toobig_message(0x100) with pytest.raises(ValueError) as excinfo: assert m.ord_char8(u"ab") assert str(excinfo.value) == toolong_message def test_bytes_to_string(): """Tests the ability to pass bytes to C++ string-accepting functions. Note that this is one-way: the only way to return bytes to Python is via the pybind11::bytes class.""" # Issue #816 def to_bytes(s): b = s if env.PY2 else s.encode("utf8") assert isinstance(b, bytes) return b assert m.strlen(to_bytes("hi")) == 2 assert m.string_length(to_bytes("world")) == 5 assert m.string_length(to_bytes("a\x00b")) == 3 assert m.strlen(to_bytes("a\x00b")) == 1 # C-string limitation # passing in a utf8 encoded string should work assert m.string_length(u"💩".encode("utf8")) == 4 @pytest.mark.skipif(not hasattr(m, "has_string_view"), reason="no <string_view>") def test_string_view(capture): """Tests support for C++17 string_view arguments and return values""" assert m.string_view_chars("Hi") == [72, 105] assert m.string_view_chars("Hi 🎂") == [72, 105, 32, 0xF0, 0x9F, 0x8E, 0x82] assert m.string_view16_chars(u"Hi 🎂") == [72, 105, 32, 0xD83C, 0xDF82] assert m.string_view32_chars(u"Hi 🎂") == [72, 105, 32, 127874] if hasattr(m, "has_u8string"): assert m.string_view8_chars("Hi") == [72, 105] assert m.string_view8_chars(u"Hi 🎂") == [72, 105, 32, 0xF0, 0x9F, 0x8E, 0x82] assert m.string_view_return() == u"utf8 secret 🎂" assert m.string_view16_return() == u"utf16 secret 🎂" assert m.string_view32_return() == u"utf32 secret 🎂" if hasattr(m, "has_u8string"): assert m.string_view8_return() == u"utf8 secret 🎂" with capture: m.string_view_print("Hi") m.string_view_print("utf8 🎂") m.string_view16_print(u"utf16 🎂") m.string_view32_print(u"utf32 🎂") assert ( capture == u""" Hi 2 utf8 🎂 9 utf16 🎂 8 utf32 🎂 7 """ ) if hasattr(m, "has_u8string"): with capture: m.string_view8_print("Hi") m.string_view8_print(u"utf8 🎂") assert ( capture == u""" Hi 2 utf8 🎂 9 """ ) with capture: m.string_view_print("Hi, ascii") m.string_view_print("Hi, utf8 🎂") m.string_view16_print(u"Hi, utf16 🎂") m.string_view32_print(u"Hi, utf32 🎂") assert ( capture == u""" Hi, ascii 9 Hi, utf8 🎂 13 Hi, utf16 🎂 12 Hi, utf32 🎂 11 """ ) if hasattr(m, "has_u8string"): with capture: m.string_view8_print("Hi, ascii") m.string_view8_print(u"Hi, utf8 🎂") assert ( capture == u""" Hi, ascii 9 Hi, utf8 🎂 13 """ ) assert m.string_view_bytes() == b"abc \x80\x80 def" assert m.string_view_str() == u"abc ‽ def" assert m.string_view_from_bytes(u"abc ‽ def".encode("utf-8")) == u"abc ‽ def" if hasattr(m, "has_u8string"): assert m.string_view8_str() == u"abc ‽ def" if not env.PY2: assert m.string_view_memoryview() == "Have some 🎂".encode() assert m.bytes_from_type_with_both_operator_string_and_string_view() == b"success" assert m.str_from_type_with_both_operator_string_and_string_view() == "success" def test_integer_casting(): """Issue #929 - out-of-range integer values shouldn't be accepted""" assert m.i32_str(-1) == "-1" assert m.i64_str(-1) == "-1" assert m.i32_str(2000000000) == "2000000000" assert m.u32_str(2000000000) == "2000000000" if env.PY2: assert m.i32_str(long(-1)) == "-1" # noqa: F821 undefined name 'long' assert m.i64_str(long(-1)) == "-1" # noqa: F821 undefined name 'long' assert ( m.i64_str(long(-999999999999)) # noqa: F821 undefined name 'long' == "-999999999999" ) assert ( m.u64_str(long(999999999999)) # noqa: F821 undefined name 'long' == "999999999999" ) else: assert m.i64_str(-999999999999) == "-999999999999" assert m.u64_str(999999999999) == "999999999999" with pytest.raises(TypeError) as excinfo: m.u32_str(-1) assert "incompatible function arguments" in str(excinfo.value) with pytest.raises(TypeError) as excinfo: m.u64_str(-1) assert "incompatible function arguments" in str(excinfo.value) with pytest.raises(TypeError) as excinfo: m.i32_str(-3000000000) assert "incompatible function arguments" in str(excinfo.value) with pytest.raises(TypeError) as excinfo: m.i32_str(3000000000) assert "incompatible function arguments" in str(excinfo.value) if env.PY2: with pytest.raises(TypeError) as excinfo: m.u32_str(long(-1)) # noqa: F821 undefined name 'long' assert "incompatible function arguments" in str(excinfo.value) with pytest.raises(TypeError) as excinfo: m.u64_str(long(-1)) # noqa: F821 undefined name 'long' assert "incompatible function arguments" in str(excinfo.value) def test_int_convert(): class Int(object): def __int__(self): return 42 class NotInt(object): pass class Float(object): def __float__(self): return 41.99999 class Index(object): def __index__(self): return 42 class IntAndIndex(object): def __int__(self): return 42 def __index__(self): return 0 class RaisingTypeErrorOnIndex(object): def __index__(self): raise TypeError def __int__(self): return 42 class RaisingValueErrorOnIndex(object): def __index__(self): raise ValueError def __int__(self): return 42 convert, noconvert = m.int_passthrough, m.int_passthrough_noconvert def requires_conversion(v): pytest.raises(TypeError, noconvert, v) def cant_convert(v): pytest.raises(TypeError, convert, v) assert convert(7) == 7 assert noconvert(7) == 7 cant_convert(3.14159) # TODO: Avoid DeprecationWarning in `PyLong_AsLong` (and similar) # TODO: PyPy 3.8 does not behave like CPython 3.8 here yet (7.3.7) if (3, 8) <= env.PY < (3, 10) and env.CPYTHON: with env.deprecated_call(): assert convert(Int()) == 42 else: assert convert(Int()) == 42 requires_conversion(Int()) cant_convert(NotInt()) cant_convert(Float()) # Before Python 3.8, `PyLong_AsLong` does not pick up on `obj.__index__`, # but pybind11 "backports" this behavior. assert convert(Index()) == 42 assert noconvert(Index()) == 42 assert convert(IntAndIndex()) == 0 # Fishy; `int(DoubleThought)` == 42 assert noconvert(IntAndIndex()) == 0 assert convert(RaisingTypeErrorOnIndex()) == 42 requires_conversion(RaisingTypeErrorOnIndex()) assert convert(RaisingValueErrorOnIndex()) == 42 requires_conversion(RaisingValueErrorOnIndex()) def test_numpy_int_convert(): np = pytest.importorskip("numpy") convert, noconvert = m.int_passthrough, m.int_passthrough_noconvert def require_implicit(v): pytest.raises(TypeError, noconvert, v) # `np.intc` is an alias that corresponds to a C++ `int` assert convert(np.intc(42)) == 42 assert noconvert(np.intc(42)) == 42 # The implicit conversion from np.float32 is undesirable but currently accepted. # TODO: Avoid DeprecationWarning in `PyLong_AsLong` (and similar) # TODO: PyPy 3.8 does not behave like CPython 3.8 here yet (7.3.7) # https://github.com/pybind/pybind11/issues/3408 if (3, 8) <= env.PY < (3, 10) and env.CPYTHON: with env.deprecated_call(): assert convert(np.float32(3.14159)) == 3 else: assert convert(np.float32(3.14159)) == 3 require_implicit(np.float32(3.14159)) def test_tuple(doc): """std::pair <-> tuple & std::tuple <-> tuple""" assert m.pair_passthrough((True, "test")) == ("test", True) assert m.tuple_passthrough((True, "test", 5)) == (5, "test", True) # Any sequence can be cast to a std::pair or std::tuple assert m.pair_passthrough([True, "test"]) == ("test", True) assert m.tuple_passthrough([True, "test", 5]) == (5, "test", True) assert m.empty_tuple() == () assert ( doc(m.pair_passthrough) == """ pair_passthrough(arg0: Tuple[bool, str]) -> Tuple[str, bool] Return a pair in reversed order """ ) assert ( doc(m.tuple_passthrough) == """ tuple_passthrough(arg0: Tuple[bool, str, int]) -> Tuple[int, str, bool] Return a triple in reversed order """ ) assert m.rvalue_pair() == ("rvalue", "rvalue") assert m.lvalue_pair() == ("lvalue", "lvalue") assert m.rvalue_tuple() == ("rvalue", "rvalue", "rvalue") assert m.lvalue_tuple() == ("lvalue", "lvalue", "lvalue") assert m.rvalue_nested() == ("rvalue", ("rvalue", ("rvalue", "rvalue"))) assert m.lvalue_nested() == ("lvalue", ("lvalue", ("lvalue", "lvalue"))) assert m.int_string_pair() == (2, "items") def test_builtins_cast_return_none(): """Casters produced with PYBIND11_TYPE_CASTER() should convert nullptr to None""" assert m.return_none_string() is None assert m.return_none_char() is None assert m.return_none_bool() is None assert m.return_none_int() is None assert m.return_none_float() is None assert m.return_none_pair() is None def test_none_deferred(): """None passed as various argument types should defer to other overloads""" assert not m.defer_none_cstring("abc") assert m.defer_none_cstring(None) assert not m.defer_none_custom(UserType()) assert m.defer_none_custom(None) assert m.nodefer_none_void(None) def test_void_caster(): assert m.load_nullptr_t(None) is None assert m.cast_nullptr_t() is None def test_reference_wrapper(): """std::reference_wrapper for builtin and user types""" assert m.refwrap_builtin(42) == 420 assert m.refwrap_usertype(UserType(42)) == 42 assert m.refwrap_usertype_const(UserType(42)) == 42 with pytest.raises(TypeError) as excinfo: m.refwrap_builtin(None) assert "incompatible function arguments" in str(excinfo.value) with pytest.raises(TypeError) as excinfo: m.refwrap_usertype(None) assert "incompatible function arguments" in str(excinfo.value) assert m.refwrap_lvalue().value == 1 assert m.refwrap_lvalue_const().value == 1 a1 = m.refwrap_list(copy=True) a2 = m.refwrap_list(copy=True) assert [x.value for x in a1] == [2, 3] assert [x.value for x in a2] == [2, 3] assert not a1[0] is a2[0] and not a1[1] is a2[1] b1 = m.refwrap_list(copy=False) b2 = m.refwrap_list(copy=False) assert [x.value for x in b1] == [1, 2] assert [x.value for x in b2] == [1, 2] assert b1[0] is b2[0] and b1[1] is b2[1] assert m.refwrap_iiw(IncType(5)) == 5 assert m.refwrap_call_iiw(IncType(10), m.refwrap_iiw) == [10, 10, 10, 10] def test_complex_cast(): """std::complex casts""" assert m.complex_cast(1) == "1.0" assert m.complex_cast(2j) == "(0.0, 2.0)" def test_bool_caster(): """Test bool caster implicit conversions.""" convert, noconvert = m.bool_passthrough, m.bool_passthrough_noconvert def require_implicit(v): pytest.raises(TypeError, noconvert, v) def cant_convert(v): pytest.raises(TypeError, convert, v) # straight up bool assert convert(True) is True assert convert(False) is False assert noconvert(True) is True assert noconvert(False) is False # None requires implicit conversion require_implicit(None) assert convert(None) is False class A(object): def __init__(self, x): self.x = x def __nonzero__(self): return self.x def __bool__(self): return self.x class B(object): pass # Arbitrary objects are not accepted cant_convert(object()) cant_convert(B()) # Objects with __nonzero__ / __bool__ defined can be converted require_implicit(A(True)) assert convert(A(True)) is True assert convert(A(False)) is False def test_numpy_bool(): np = pytest.importorskip("numpy") convert, noconvert = m.bool_passthrough, m.bool_passthrough_noconvert def cant_convert(v): pytest.raises(TypeError, convert, v) # np.bool_ is not considered implicit assert convert(np.bool_(True)) is True assert convert(np.bool_(False)) is False assert noconvert(np.bool_(True)) is True assert noconvert(np.bool_(False)) is False cant_convert(np.zeros(2, dtype="int")) def test_int_long(): """In Python 2, a C++ int should return a Python int rather than long if possible: longs are not always accepted where ints are used (such as the argument to sys.exit()). A C++ long long is always a Python long.""" import sys must_be_long = type(getattr(sys, "maxint", 1) + 1) assert isinstance(m.int_cast(), int) assert isinstance(m.long_cast(), int) assert isinstance(m.longlong_cast(), must_be_long) def test_void_caster_2(): assert m.test_void_caster() def test_const_ref_caster(): """Verifies that const-ref is propagated through type_caster cast_op. The returned ConstRefCasted type is a minimal type that is constructed to reference the casting mode used. """ x = False assert m.takes(x) == 1 assert m.takes_move(x) == 1 assert m.takes_ptr(x) == 3 assert m.takes_ref(x) == 2 assert m.takes_ref_wrap(x) == 2 assert m.takes_const_ptr(x) == 5 assert m.takes_const_ref(x) == 4 assert m.takes_const_ref_wrap(x) == 4
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_callbacks.cpp
.cpp
9,243
244
/* tests/test_callbacks.cpp -- callbacks Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> 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/functional.h> #include "constructor_stats.h" #include "pybind11_tests.h" #include <thread> int dummy_function(int i) { return i + 1; } TEST_SUBMODULE(callbacks, m) { // test_callbacks, test_function_signatures m.def("test_callback1", [](const py::object &func) { return func(); }); m.def("test_callback2", [](const py::object &func) { return func("Hello", 'x', true, 5); }); m.def("test_callback3", [](const std::function<int(int)> &func) { return "func(43) = " + std::to_string(func(43)); }); m.def("test_callback4", []() -> std::function<int(int)> { return [](int i) { return i + 1; }; }); m.def("test_callback5", []() { return py::cpp_function([](int i) { return i + 1; }, py::arg("number")); }); // test_keyword_args_and_generalized_unpacking m.def("test_tuple_unpacking", [](const py::function &f) { auto t1 = py::make_tuple(2, 3); auto t2 = py::make_tuple(5, 6); return f("positional", 1, *t1, 4, *t2); }); m.def("test_dict_unpacking", [](const py::function &f) { auto d1 = py::dict("key"_a = "value", "a"_a = 1); auto d2 = py::dict(); auto d3 = py::dict("b"_a = 2); return f("positional", 1, **d1, **d2, **d3); }); m.def("test_keyword_args", [](const py::function &f) { return f("x"_a = 10, "y"_a = 20); }); m.def("test_unpacking_and_keywords1", [](const py::function &f) { auto args = py::make_tuple(2); auto kwargs = py::dict("d"_a = 4); return f(1, *args, "c"_a = 3, **kwargs); }); m.def("test_unpacking_and_keywords2", [](const py::function &f) { auto kwargs1 = py::dict("a"_a = 1); auto kwargs2 = py::dict("c"_a = 3, "d"_a = 4); return f("positional", *py::make_tuple(1), 2, *py::make_tuple(3, 4), 5, "key"_a = "value", **kwargs1, "b"_a = 2, **kwargs2, "e"_a = 5); }); m.def("test_unpacking_error1", [](const py::function &f) { auto kwargs = py::dict("x"_a = 3); return f("x"_a = 1, "y"_a = 2, **kwargs); // duplicate ** after keyword }); m.def("test_unpacking_error2", [](const py::function &f) { auto kwargs = py::dict("x"_a = 3); return f(**kwargs, "x"_a = 1); // duplicate keyword after ** }); m.def("test_arg_conversion_error1", [](const py::function &f) { f(234, UnregisteredType(), "kw"_a = 567); }); m.def("test_arg_conversion_error2", [](const py::function &f) { f(234, "expected_name"_a = UnregisteredType(), "kw"_a = 567); }); // test_lambda_closure_cleanup struct Payload { Payload() { print_default_created(this); } ~Payload() { print_destroyed(this); } Payload(const Payload &) { print_copy_created(this); } Payload(Payload &&) noexcept { print_move_created(this); } }; // Export the payload constructor statistics for testing purposes: m.def("payload_cstats", &ConstructorStats::get<Payload>); m.def("test_lambda_closure_cleanup", []() -> std::function<void()> { Payload p; // In this situation, `Func` in the implementation of // `cpp_function::initialize` is NOT trivially destructible. return [p]() { /* p should be cleaned up when the returned function is garbage collected */ (void) p; }; }); class CppCallable { public: CppCallable() { track_default_created(this); } ~CppCallable() { track_destroyed(this); } CppCallable(const CppCallable &) { track_copy_created(this); } CppCallable(CppCallable &&) noexcept { track_move_created(this); } void operator()() {} }; m.def("test_cpp_callable_cleanup", []() { // Related issue: https://github.com/pybind/pybind11/issues/3228 // Related PR: https://github.com/pybind/pybind11/pull/3229 py::list alive_counts; ConstructorStats &stat = ConstructorStats::get<CppCallable>(); alive_counts.append(stat.alive()); { CppCallable cpp_callable; alive_counts.append(stat.alive()); { // In this situation, `Func` in the implementation of // `cpp_function::initialize` IS trivially destructible, // only `capture` is not. py::cpp_function py_func(cpp_callable); py::detail::silence_unused_warnings(py_func); alive_counts.append(stat.alive()); } alive_counts.append(stat.alive()); { py::cpp_function py_func(std::move(cpp_callable)); py::detail::silence_unused_warnings(py_func); alive_counts.append(stat.alive()); } alive_counts.append(stat.alive()); } alive_counts.append(stat.alive()); return alive_counts; }); // test_cpp_function_roundtrip /* Test if passing a function pointer from C++ -> Python -> C++ yields the original pointer */ m.def("dummy_function", &dummy_function); m.def("dummy_function_overloaded", [](int i, int j) { return i + j; }); m.def("dummy_function_overloaded", &dummy_function); m.def("dummy_function2", [](int i, int j) { return i + j; }); m.def( "roundtrip", [](std::function<int(int)> f, bool expect_none = false) { if (expect_none && f) { throw std::runtime_error("Expected None to be converted to empty std::function"); } return f; }, py::arg("f"), py::arg("expect_none") = false); m.def("test_dummy_function", [](const std::function<int(int)> &f) -> std::string { using fn_type = int (*)(int); const auto *result = f.target<fn_type>(); if (!result) { auto r = f(1); return "can't convert to function pointer: eval(1) = " + std::to_string(r); } if (*result == dummy_function) { auto r = (*result)(1); return "matches dummy_function: eval(1) = " + std::to_string(r); } return "argument does NOT match dummy_function. This should never happen!"; }); class AbstractBase { public: // [workaround(intel)] = default does not work here // Defaulting this destructor results in linking errors with the Intel compiler // (in Debug builds only, tested with icpc (ICC) 2021.1 Beta 20200827) virtual ~AbstractBase() {} // NOLINT(modernize-use-equals-default) virtual unsigned int func() = 0; }; m.def("func_accepting_func_accepting_base", [](const std::function<double(AbstractBase &)> &) {}); struct MovableObject { bool valid = true; MovableObject() = default; MovableObject(const MovableObject &) = default; MovableObject &operator=(const MovableObject &) = default; MovableObject(MovableObject &&o) noexcept : valid(o.valid) { o.valid = false; } MovableObject &operator=(MovableObject &&o) noexcept { valid = o.valid; o.valid = false; return *this; } }; py::class_<MovableObject>(m, "MovableObject"); // test_movable_object m.def("callback_with_movable", [](const std::function<void(MovableObject &)> &f) { auto x = MovableObject(); f(x); // lvalue reference shouldn't move out object return x.valid; // must still return `true` }); // test_bound_method_callback struct CppBoundMethodTest {}; py::class_<CppBoundMethodTest>(m, "CppBoundMethodTest") .def(py::init<>()) .def("triple", [](CppBoundMethodTest &, int val) { return 3 * val; }); // This checks that builtin functions can be passed as callbacks // rather than throwing RuntimeError due to trying to extract as capsule m.def("test_sum_builtin", [](const std::function<double(py::iterable)> &sum_builtin, const py::iterable &i) { return sum_builtin(i); }); // test async Python callbacks using callback_f = std::function<void(int)>; m.def("test_async_callback", [](const callback_f &f, const py::list &work) { // make detached thread that calls `f` with piece of work after a little delay auto start_f = [f](int j) { auto invoke_f = [f, j] { std::this_thread::sleep_for(std::chrono::milliseconds(50)); f(j); }; auto t = std::thread(std::move(invoke_f)); t.detach(); }; // spawn worker threads for (auto i : work) { start_f(py::cast<int>(i)); } }); m.def("callback_num_times", [](const py::function &f, std::size_t num) { for (std::size_t i = 0; i < num; i++) { f(); } }); }
C++
3D
mcellteam/mcell
libs/pybind11/tests/test_docstring_options.py
.py
1,630
43
# -*- coding: utf-8 -*- from pybind11_tests import docstring_options as m def test_docstring_options(): # options.disable_function_signatures() assert not m.test_function1.__doc__ assert m.test_function2.__doc__ == "A custom docstring" # docstring specified on just the first overload definition: assert m.test_overloaded1.__doc__ == "Overload docstring" # docstring on both overloads: assert m.test_overloaded2.__doc__ == "overload docstring 1\noverload docstring 2" # docstring on only second overload: assert m.test_overloaded3.__doc__ == "Overload docstr" # options.enable_function_signatures() assert m.test_function3.__doc__.startswith("test_function3(a: int, b: int) -> None") assert m.test_function4.__doc__.startswith("test_function4(a: int, b: int) -> None") assert m.test_function4.__doc__.endswith("A custom docstring\n") # options.disable_function_signatures() # options.disable_user_defined_docstrings() assert not m.test_function5.__doc__ # nested options.enable_user_defined_docstrings() assert m.test_function6.__doc__ == "A custom docstring" # RAII destructor assert m.test_function7.__doc__.startswith("test_function7(a: int, b: int) -> None") assert m.test_function7.__doc__.endswith("A custom docstring\n") # when all options are disabled, no docstring (instead of an empty one) should be generated assert m.test_function8.__doc__ is None # Suppression of user-defined docstrings for non-function objects assert not m.DocstringTestFoo.__doc__ assert not m.DocstringTestFoo.value_prop.__doc__
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_pickling.py
.py
2,286
83
# -*- coding: utf-8 -*- import pytest import env from pybind11_tests import pickling as m try: import cPickle as pickle # Use cPickle on Python 2.7 except ImportError: import pickle @pytest.mark.parametrize("cls_name", ["Pickleable", "PickleableNew"]) def test_roundtrip(cls_name): cls = getattr(m, cls_name) p = cls("test_value") p.setExtra1(15) p.setExtra2(48) data = pickle.dumps(p, 2) # Must use pickle protocol >= 2 p2 = pickle.loads(data) assert p2.value() == p.value() assert p2.extra1() == p.extra1() assert p2.extra2() == p.extra2() @pytest.mark.xfail("env.PYPY") @pytest.mark.parametrize("cls_name", ["PickleableWithDict", "PickleableWithDictNew"]) def test_roundtrip_with_dict(cls_name): cls = getattr(m, cls_name) p = cls("test_value") p.extra = 15 p.dynamic = "Attribute" data = pickle.dumps(p, pickle.HIGHEST_PROTOCOL) p2 = pickle.loads(data) assert p2.value == p.value assert p2.extra == p.extra assert p2.dynamic == p.dynamic def test_enum_pickle(): from pybind11_tests import enums as e data = pickle.dumps(e.EOne, 2) assert e.EOne == pickle.loads(data) # # exercise_trampoline # class SimplePyDerived(m.SimpleBase): pass def test_roundtrip_simple_py_derived(): p = SimplePyDerived() p.num = 202 p.stored_in_dict = 303 data = pickle.dumps(p, pickle.HIGHEST_PROTOCOL) p2 = pickle.loads(data) assert isinstance(p2, SimplePyDerived) assert p2.num == 202 assert p2.stored_in_dict == 303 def test_roundtrip_simple_cpp_derived(): p = m.make_SimpleCppDerivedAsBase() assert m.check_dynamic_cast_SimpleCppDerived(p) p.num = 404 if not env.PYPY: # To ensure that this unit test is not accidentally invalidated. with pytest.raises(AttributeError): # Mimics the `setstate` C++ implementation. setattr(p, "__dict__", {}) # noqa: B010 data = pickle.dumps(p, pickle.HIGHEST_PROTOCOL) p2 = pickle.loads(data) assert isinstance(p2, m.SimpleBase) assert p2.num == 404 # Issue #3062: pickleable base C++ classes can incur object slicing # if derived typeid is not registered with pybind11 assert not m.check_dynamic_cast_SimpleCppDerived(p2)
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_methods_and_attributes.cpp
.cpp
21,327
460
/* tests/test_methods_and_attributes.cpp -- constructors, deconstructors, attribute access, __str__, argument and return value conventions Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #include "constructor_stats.h" #include "pybind11_tests.h" #if !defined(PYBIND11_OVERLOAD_CAST) template <typename... Args> using overload_cast_ = pybind11::detail::overload_cast_impl<Args...>; #endif class ExampleMandA { public: ExampleMandA() { print_default_created(this); } explicit ExampleMandA(int value) : value(value) { print_created(this, value); } ExampleMandA(const ExampleMandA &e) : value(e.value) { print_copy_created(this); } explicit ExampleMandA(std::string &&) {} ExampleMandA(ExampleMandA &&e) noexcept : value(e.value) { print_move_created(this); } ~ExampleMandA() { print_destroyed(this); } std::string toString() const { return "ExampleMandA[value=" + std::to_string(value) + "]"; } void operator=(const ExampleMandA &e) { print_copy_assigned(this); value = e.value; } void operator=(ExampleMandA &&e) noexcept { print_move_assigned(this); value = e.value; } // NOLINTNEXTLINE(performance-unnecessary-value-param) void add1(ExampleMandA other) { value += other.value; } // passing by value void add2(ExampleMandA &other) { value += other.value; } // passing by reference void add3(const ExampleMandA &other) { value += other.value; } // passing by const reference void add4(ExampleMandA *other) { value += other->value; } // passing by pointer void add5(const ExampleMandA *other) { value += other->value; } // passing by const pointer void add6(int other) { value += other; } // passing by value void add7(int &other) { value += other; } // passing by reference void add8(const int &other) { value += other; } // passing by const reference // NOLINTNEXTLINE(readability-non-const-parameter) Deliberately non-const for testing void add9(int *other) { value += *other; } // passing by pointer void add10(const int *other) { value += *other; } // passing by const pointer void consume_str(std::string &&) {} ExampleMandA self1() { return *this; } // return by value ExampleMandA &self2() { return *this; } // return by reference const ExampleMandA &self3() const { return *this; } // return by const reference ExampleMandA *self4() { return this; } // return by pointer const ExampleMandA *self5() const { return this; } // return by const pointer int internal1() const { return value; } // return by value int &internal2() { return value; } // return by reference const int &internal3() const { return value; } // return by const reference int *internal4() { return &value; } // return by pointer const int *internal5() { return &value; } // return by const pointer py::str overloaded() { return "()"; } py::str overloaded(int) { return "(int)"; } py::str overloaded(int, float) { return "(int, float)"; } py::str overloaded(float, int) { return "(float, int)"; } py::str overloaded(int, int) { return "(int, int)"; } py::str overloaded(float, float) { return "(float, float)"; } py::str overloaded(int) const { return "(int) const"; } py::str overloaded(int, float) const { return "(int, float) const"; } py::str overloaded(float, int) const { return "(float, int) const"; } py::str overloaded(int, int) const { return "(int, int) const"; } py::str overloaded(float, float) const { return "(float, float) const"; } static py::str overloaded(float) { return "static float"; } int value = 0; }; struct TestProperties { int value = 1; static int static_value; int get() const { return value; } void set(int v) { value = v; } static int static_get() { return static_value; } static void static_set(int v) { static_value = v; } }; int TestProperties::static_value = 1; struct TestPropertiesOverride : TestProperties { int value = 99; static int static_value; }; int TestPropertiesOverride::static_value = 99; struct TestPropRVP { UserType v1{1}; UserType v2{1}; static UserType sv1; static UserType sv2; const UserType &get1() const { return v1; } const UserType &get2() const { return v2; } UserType get_rvalue() const { return v2; } void set1(int v) { v1.set(v); } void set2(int v) { v2.set(v); } }; UserType TestPropRVP::sv1(1); UserType TestPropRVP::sv2(1); // Test None-allowed py::arg argument policy class NoneTester { public: int answer = 42; }; int none1(const NoneTester &obj) { return obj.answer; } int none2(NoneTester *obj) { return obj ? obj->answer : -1; } int none3(std::shared_ptr<NoneTester> &obj) { return obj ? obj->answer : -1; } int none4(std::shared_ptr<NoneTester> *obj) { return obj && *obj ? (*obj)->answer : -1; } int none5(const std::shared_ptr<NoneTester> &obj) { return obj ? obj->answer : -1; } // Issue #2778: implicit casting from None to object (not pointer) class NoneCastTester { public: int answer = -1; NoneCastTester() = default; explicit NoneCastTester(int v) : answer(v) {} }; struct StrIssue { int val = -1; StrIssue() = default; explicit StrIssue(int i) : val{i} {} }; // Issues #854, #910: incompatible function args when member function/pointer is in unregistered // base class class UnregisteredBase { public: void do_nothing() const {} void increase_value() { rw_value++; ro_value += 0.25; } void set_int(int v) { rw_value = v; } int get_int() const { return rw_value; } double get_double() const { return ro_value; } int rw_value = 42; double ro_value = 1.25; }; class RegisteredDerived : public UnregisteredBase { public: using UnregisteredBase::UnregisteredBase; double sum() const { return rw_value + ro_value; } }; // Test explicit lvalue ref-qualification struct RefQualified { int value = 0; void refQualified(int other) & { value += other; } int constRefQualified(int other) const & { return value + other; } }; // Test rvalue ref param struct RValueRefParam { std::size_t func1(std::string &&s) { return s.size(); } std::size_t func2(std::string &&s) const { return s.size(); } std::size_t func3(std::string &&s) & { return s.size(); } std::size_t func4(std::string &&s) const & { return s.size(); } }; TEST_SUBMODULE(methods_and_attributes, m) { // test_methods_and_attributes py::class_<ExampleMandA> emna(m, "ExampleMandA"); emna.def(py::init<>()) .def(py::init<int>()) .def(py::init<std::string &&>()) .def(py::init<const ExampleMandA &>()) .def("add1", &ExampleMandA::add1) .def("add2", &ExampleMandA::add2) .def("add3", &ExampleMandA::add3) .def("add4", &ExampleMandA::add4) .def("add5", &ExampleMandA::add5) .def("add6", &ExampleMandA::add6) .def("add7", &ExampleMandA::add7) .def("add8", &ExampleMandA::add8) .def("add9", &ExampleMandA::add9) .def("add10", &ExampleMandA::add10) .def("consume_str", &ExampleMandA::consume_str) .def("self1", &ExampleMandA::self1) .def("self2", &ExampleMandA::self2) .def("self3", &ExampleMandA::self3) .def("self4", &ExampleMandA::self4) .def("self5", &ExampleMandA::self5) .def("internal1", &ExampleMandA::internal1) .def("internal2", &ExampleMandA::internal2) .def("internal3", &ExampleMandA::internal3) .def("internal4", &ExampleMandA::internal4) .def("internal5", &ExampleMandA::internal5) #if defined(PYBIND11_OVERLOAD_CAST) .def("overloaded", py::overload_cast<>(&ExampleMandA::overloaded)) .def("overloaded", py::overload_cast<int>(&ExampleMandA::overloaded)) .def("overloaded", py::overload_cast<int, float>(&ExampleMandA::overloaded)) .def("overloaded", py::overload_cast<float, int>(&ExampleMandA::overloaded)) .def("overloaded", py::overload_cast<int, int>(&ExampleMandA::overloaded)) .def("overloaded", py::overload_cast<float, float>(&ExampleMandA::overloaded)) .def("overloaded_float", py::overload_cast<float, float>(&ExampleMandA::overloaded)) .def("overloaded_const", py::overload_cast<int>(&ExampleMandA::overloaded, py::const_)) .def("overloaded_const", py::overload_cast<int, float>(&ExampleMandA::overloaded, py::const_)) .def("overloaded_const", py::overload_cast<float, int>(&ExampleMandA::overloaded, py::const_)) .def("overloaded_const", py::overload_cast<int, int>(&ExampleMandA::overloaded, py::const_)) .def("overloaded_const", py::overload_cast<float, float>(&ExampleMandA::overloaded, py::const_)) #else // Use both the traditional static_cast method and the C++11 compatible overload_cast_ .def("overloaded", overload_cast_<>()(&ExampleMandA::overloaded)) .def("overloaded", overload_cast_<int>()(&ExampleMandA::overloaded)) .def("overloaded", overload_cast_<int, float>()(&ExampleMandA::overloaded)) .def("overloaded", static_cast<py::str (ExampleMandA::*)(float, int)>(&ExampleMandA::overloaded)) .def("overloaded", static_cast<py::str (ExampleMandA::*)(int, int)>(&ExampleMandA::overloaded)) .def("overloaded", static_cast<py::str (ExampleMandA::*)(float, float)>(&ExampleMandA::overloaded)) .def("overloaded_float", overload_cast_<float, float>()(&ExampleMandA::overloaded)) .def("overloaded_const", overload_cast_<int >()(&ExampleMandA::overloaded, py::const_)) .def("overloaded_const", overload_cast_<int, float>()(&ExampleMandA::overloaded, py::const_)) .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(float, int) const>(&ExampleMandA::overloaded)) .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(int, int) const>(&ExampleMandA::overloaded)) .def("overloaded_const", static_cast<py::str (ExampleMandA::*)(float, float) const>(&ExampleMandA::overloaded)) #endif // test_no_mixed_overloads // Raise error if trying to mix static/non-static overloads on the same name: .def_static("add_mixed_overloads1", []() { auto emna = py::reinterpret_borrow<py::class_<ExampleMandA>>( py::module_::import("pybind11_tests.methods_and_attributes") .attr("ExampleMandA")); emna.def("overload_mixed1", static_cast<py::str (ExampleMandA::*)(int, int)>( &ExampleMandA::overloaded)) .def_static( "overload_mixed1", static_cast<py::str (*)(float)>(&ExampleMandA::overloaded)); }) .def_static("add_mixed_overloads2", []() { auto emna = py::reinterpret_borrow<py::class_<ExampleMandA>>( py::module_::import("pybind11_tests.methods_and_attributes") .attr("ExampleMandA")); emna.def_static("overload_mixed2", static_cast<py::str (*)(float)>(&ExampleMandA::overloaded)) .def("overload_mixed2", static_cast<py::str (ExampleMandA::*)(int, int)>( &ExampleMandA::overloaded)); }) .def("__str__", &ExampleMandA::toString) .def_readwrite("value", &ExampleMandA::value); // test_copy_method // Issue #443: can't call copied methods in Python 3 emna.attr("add2b") = emna.attr("add2"); // test_properties, test_static_properties, test_static_cls py::class_<TestProperties>(m, "TestProperties") .def(py::init<>()) .def_readonly("def_readonly", &TestProperties::value) .def_readwrite("def_readwrite", &TestProperties::value) .def_property("def_writeonly", nullptr, [](TestProperties &s, int v) { s.value = v; }) .def_property("def_property_writeonly", nullptr, &TestProperties::set) .def_property_readonly("def_property_readonly", &TestProperties::get) .def_property("def_property", &TestProperties::get, &TestProperties::set) .def_property("def_property_impossible", nullptr, nullptr) .def_readonly_static("def_readonly_static", &TestProperties::static_value) .def_readwrite_static("def_readwrite_static", &TestProperties::static_value) .def_property_static("def_writeonly_static", nullptr, [](const py::object &, int v) { TestProperties::static_value = v; }) .def_property_readonly_static( "def_property_readonly_static", [](const py::object &) { return TestProperties::static_get(); }) .def_property_static( "def_property_writeonly_static", nullptr, [](const py::object &, int v) { return TestProperties::static_set(v); }) .def_property_static( "def_property_static", [](const py::object &) { return TestProperties::static_get(); }, [](const py::object &, int v) { TestProperties::static_set(v); }) .def_property_static( "static_cls", [](py::object cls) { return cls; }, [](const py::object &cls, const py::function &f) { f(cls); }); py::class_<TestPropertiesOverride, TestProperties>(m, "TestPropertiesOverride") .def(py::init<>()) .def_readonly("def_readonly", &TestPropertiesOverride::value) .def_readonly_static("def_readonly_static", &TestPropertiesOverride::static_value); auto static_get1 = [](const py::object &) -> const UserType & { return TestPropRVP::sv1; }; auto static_get2 = [](const py::object &) -> const UserType & { return TestPropRVP::sv2; }; auto static_set1 = [](const py::object &, int v) { TestPropRVP::sv1.set(v); }; auto static_set2 = [](const py::object &, int v) { TestPropRVP::sv2.set(v); }; auto rvp_copy = py::return_value_policy::copy; // test_property_return_value_policies py::class_<TestPropRVP>(m, "TestPropRVP") .def(py::init<>()) .def_property_readonly("ro_ref", &TestPropRVP::get1) .def_property_readonly("ro_copy", &TestPropRVP::get2, rvp_copy) .def_property_readonly("ro_func", py::cpp_function(&TestPropRVP::get2, rvp_copy)) .def_property("rw_ref", &TestPropRVP::get1, &TestPropRVP::set1) .def_property("rw_copy", &TestPropRVP::get2, &TestPropRVP::set2, rvp_copy) .def_property( "rw_func", py::cpp_function(&TestPropRVP::get2, rvp_copy), &TestPropRVP::set2) .def_property_readonly_static("static_ro_ref", static_get1) .def_property_readonly_static("static_ro_copy", static_get2, rvp_copy) .def_property_readonly_static("static_ro_func", py::cpp_function(static_get2, rvp_copy)) .def_property_static("static_rw_ref", static_get1, static_set1) .def_property_static("static_rw_copy", static_get2, static_set2, rvp_copy) .def_property_static( "static_rw_func", py::cpp_function(static_get2, rvp_copy), static_set2) // test_property_rvalue_policy .def_property_readonly("rvalue", &TestPropRVP::get_rvalue) .def_property_readonly_static("static_rvalue", [](const py::object &) { return UserType(1); }); // test_metaclass_override struct MetaclassOverride {}; py::class_<MetaclassOverride>(m, "MetaclassOverride", py::metaclass((PyObject *) &PyType_Type)) .def_property_readonly_static("readonly", [](const py::object &) { return 1; }); // test_overload_ordering m.def("overload_order", [](const std::string &) { return 1; }); m.def("overload_order", [](const std::string &) { return 2; }); m.def("overload_order", [](int) { return 3; }); m.def( "overload_order", [](int) { return 4; }, py::prepend{}); #if !defined(PYPY_VERSION) // test_dynamic_attributes class DynamicClass { public: DynamicClass() { print_default_created(this); } DynamicClass(const DynamicClass &) = delete; ~DynamicClass() { print_destroyed(this); } }; py::class_<DynamicClass>(m, "DynamicClass", py::dynamic_attr()).def(py::init()); class CppDerivedDynamicClass : public DynamicClass {}; py::class_<CppDerivedDynamicClass, DynamicClass>(m, "CppDerivedDynamicClass").def(py::init()); #endif // test_bad_arg_default // Issue/PR #648: bad arg default debugging output #if !defined(NDEBUG) m.attr("debug_enabled") = true; #else m.attr("debug_enabled") = false; #endif m.def("bad_arg_def_named", [] { auto m = py::module_::import("pybind11_tests"); m.def( "should_fail", [](int, UnregisteredType) {}, py::arg(), py::arg("a") = UnregisteredType()); }); m.def("bad_arg_def_unnamed", [] { auto m = py::module_::import("pybind11_tests"); m.def( "should_fail", [](int, UnregisteredType) {}, py::arg(), py::arg() = UnregisteredType()); }); // [workaround(intel)] ICC 20/21 breaks with py::arg().stuff, using py::arg{}.stuff works. // test_accepts_none py::class_<NoneTester, std::shared_ptr<NoneTester>>(m, "NoneTester").def(py::init<>()); m.def("no_none1", &none1, py::arg{}.none(false)); m.def("no_none2", &none2, py::arg{}.none(false)); m.def("no_none3", &none3, py::arg{}.none(false)); m.def("no_none4", &none4, py::arg{}.none(false)); m.def("no_none5", &none5, py::arg{}.none(false)); m.def("ok_none1", &none1); m.def("ok_none2", &none2, py::arg{}.none(true)); m.def("ok_none3", &none3); m.def("ok_none4", &none4, py::arg{}.none(true)); m.def("ok_none5", &none5); m.def("no_none_kwarg", &none2, "a"_a.none(false)); m.def("no_none_kwarg_kw_only", &none2, py::kw_only(), "a"_a.none(false)); // test_casts_none // Issue #2778: implicit casting from None to object (not pointer) py::class_<NoneCastTester>(m, "NoneCastTester") .def(py::init<>()) .def(py::init<int>()) .def(py::init([](py::none const &) { return NoneCastTester{}; })); py::implicitly_convertible<py::none, NoneCastTester>(); m.def("ok_obj_or_none", [](NoneCastTester const &foo) { return foo.answer; }); // test_str_issue // Issue #283: __str__ called on uninitialized instance when constructor arguments invalid py::class_<StrIssue>(m, "StrIssue") .def(py::init<int>()) .def(py::init<>()) .def("__str__", [](const StrIssue &si) { return "StrIssue[" + std::to_string(si.val) + "]"; }); // test_unregistered_base_implementations // // Issues #854/910: incompatible function args when member function/pointer is in unregistered // base class The methods and member pointers below actually resolve to members/pointers in // UnregisteredBase; before this test/fix they would be registered via lambda with a first // argument of an unregistered type, and thus uncallable. py::class_<RegisteredDerived>(m, "RegisteredDerived") .def(py::init<>()) .def("do_nothing", &RegisteredDerived::do_nothing) .def("increase_value", &RegisteredDerived::increase_value) .def_readwrite("rw_value", &RegisteredDerived::rw_value) .def_readonly("ro_value", &RegisteredDerived::ro_value) // Uncommenting the next line should trigger a static_assert: // .def_readwrite("fails", &UserType::value) // Uncommenting the next line should trigger a static_assert: // .def_readonly("fails", &UserType::value) .def_property("rw_value_prop", &RegisteredDerived::get_int, &RegisteredDerived::set_int) .def_property_readonly("ro_value_prop", &RegisteredDerived::get_double) // This one is in the registered class: .def("sum", &RegisteredDerived::sum); using Adapted = decltype(py::method_adaptor<RegisteredDerived>(&RegisteredDerived::do_nothing)); static_assert(std::is_same<Adapted, void (RegisteredDerived::*)() const>::value, ""); // test_methods_and_attributes py::class_<RefQualified>(m, "RefQualified") .def(py::init<>()) .def_readonly("value", &RefQualified::value) .def("refQualified", &RefQualified::refQualified) .def("constRefQualified", &RefQualified::constRefQualified); py::class_<RValueRefParam>(m, "RValueRefParam") .def(py::init<>()) .def("func1", &RValueRefParam::func1) .def("func2", &RValueRefParam::func2) .def("func3", &RValueRefParam::func3) .def("func4", &RValueRefParam::func4); }
C++
3D
mcellteam/mcell
libs/pybind11/tests/test_numpy_array.cpp
.cpp
19,774
525
/* 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/numpy.h> #include <pybind11/stl.h> #include "pybind11_tests.h" #include <cstdint> #include <utility> // 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", [](const 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>(std::move(yes)) && !py::isinstance<py::array>(std::move(no)); }); sm.def("isinstance_typed", [](const 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", [](const 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", [](const py::array_t<double> &) { return "double"; }); sm.def("overloaded", [](const py::array_t<float> &) { return "float"; }); sm.def("overloaded", [](const py::array_t<int> &) { return "int"; }); sm.def("overloaded", [](const py::array_t<unsigned short> &) { return "unsigned short"; }); sm.def("overloaded", [](const py::array_t<long long> &) { return "long long"; }); sm.def("overloaded", [](const py::array_t<std::complex<double>> &) { return "double complex"; }); sm.def("overloaded", [](const py::array_t<std::complex<float>> &) { return "float complex"; }); sm.def("overloaded2", [](const py::array_t<std::complex<double>> &) { return "double complex"; }); sm.def("overloaded2", [](const py::array_t<double> &) { return "double"; }); sm.def("overloaded2", [](const py::array_t<std::complex<float>> &) { return "float complex"; }); sm.def("overloaded2", [](const py::array_t<float> &) { return "float"; }); // [workaround(intel)] ICC 20/21 breaks with py::arg().stuff, using py::arg{}.stuff works. // Only accept the exact types: sm.def( "overloaded3", [](const py::array_t<int> &) { return "int"; }, py::arg{}.noconvert()); sm.def( "overloaded3", [](const 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", [](const py::array_t<long long, 0> &) { return "long long"; }); sm.def("overloaded4", [](const 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", [](const py::array_t<unsigned int> &) { return "unsigned int"; }); sm.def("overloaded5", [](const py::array_t<double> &) { return "double"; }); // test_greedy_string_overload // Issue 685: ndarray shouldn't go to std::string overload sm.def("issue685", [](const std::string &) { return "string"; }); sm.def("issue685", [](const py::array &) { return "array"; }); sm.def("issue685", [](const 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", [](const 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 for the above, 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("array_view", [](py::array_t<uint8_t> a, const std::string &dtype) { return a.view(dtype); }); sm.def("reshape_initializer_list", [](py::array_t<int> a, size_t N, size_t M, size_t O) { return a.reshape({N, M, O}); }); sm.def("reshape_tuple", [](py::array_t<int> a, const std::vector<int> &new_shape) { return a.reshape(new_shape); }); sm.def("index_using_ellipsis", [](const py::array &a) { return a[py::make_tuple(0, py::ellipsis(), 0)]; }); // test_argument_conversions sm.def( "accept_double", [](const py::array_t<double, 0> &) {}, py::arg("a")); sm.def( "accept_double_forcecast", [](const py::array_t<double, py::array::forcecast> &) {}, py::arg("a")); sm.def( "accept_double_c_style", [](const py::array_t<double, py::array::c_style> &) {}, py::arg("a")); sm.def( "accept_double_c_style_forcecast", [](const py::array_t<double, py::array::forcecast | py::array::c_style> &) {}, py::arg("a")); sm.def( "accept_double_f_style", [](const py::array_t<double, py::array::f_style> &) {}, py::arg("a")); sm.def( "accept_double_f_style_forcecast", [](const py::array_t<double, py::array::forcecast | py::array::f_style> &) {}, py::arg("a")); sm.def( "accept_double_noconvert", [](const py::array_t<double, 0> &) {}, "a"_a.noconvert()); sm.def( "accept_double_forcecast_noconvert", [](const py::array_t<double, py::array::forcecast> &) {}, "a"_a.noconvert()); sm.def( "accept_double_c_style_noconvert", [](const py::array_t<double, py::array::c_style> &) {}, "a"_a.noconvert()); sm.def( "accept_double_c_style_forcecast_noconvert", [](const py::array_t<double, py::array::forcecast | py::array::c_style> &) {}, "a"_a.noconvert()); sm.def( "accept_double_f_style_noconvert", [](const py::array_t<double, py::array::f_style> &) {}, "a"_a.noconvert()); sm.def( "accept_double_f_style_forcecast_noconvert", [](const py::array_t<double, py::array::forcecast | py::array::f_style> &) {}, "a"_a.noconvert()); // Check that types returns correct npy format descriptor sm.def("test_fmt_desc_float", [](const py::array_t<float> &) {}); sm.def("test_fmt_desc_double", [](const py::array_t<double> &) {}); sm.def("test_fmt_desc_const_float", [](const py::array_t<const float> &) {}); sm.def("test_fmt_desc_const_double", [](const py::array_t<const double> &) {}); }
C++
3D
mcellteam/mcell
libs/pybind11/tests/test_docstring_options.cpp
.cpp
2,816
89
/* tests/test_docstring_options.cpp -- generation of docstrings and signatures Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> 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" TEST_SUBMODULE(docstring_options, m) { // test_docstring_options { py::options options; options.disable_function_signatures(); m.def( "test_function1", [](int, int) {}, py::arg("a"), py::arg("b")); m.def( "test_function2", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring"); m.def( "test_overloaded1", [](int) {}, py::arg("i"), "Overload docstring"); m.def( "test_overloaded1", [](double) {}, py::arg("d")); m.def( "test_overloaded2", [](int) {}, py::arg("i"), "overload docstring 1"); m.def( "test_overloaded2", [](double) {}, py::arg("d"), "overload docstring 2"); m.def( "test_overloaded3", [](int) {}, py::arg("i")); m.def( "test_overloaded3", [](double) {}, py::arg("d"), "Overload docstr"); options.enable_function_signatures(); m.def( "test_function3", [](int, int) {}, py::arg("a"), py::arg("b")); m.def( "test_function4", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring"); options.disable_function_signatures().disable_user_defined_docstrings(); m.def( "test_function5", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring"); { py::options nested_options; nested_options.enable_user_defined_docstrings(); m.def( "test_function6", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring"); } } m.def( "test_function7", [](int, int) {}, py::arg("a"), py::arg("b"), "A custom docstring"); { py::options options; options.disable_user_defined_docstrings(); options.disable_function_signatures(); m.def("test_function8", []() {}); } { py::options options; options.disable_user_defined_docstrings(); struct DocstringTestFoo { int value; void setValue(int v) { value = v; } int getValue() const { return value; } }; py::class_<DocstringTestFoo>(m, "DocstringTestFoo", "This is a class docstring") .def_property("value_prop", &DocstringTestFoo::getValue, &DocstringTestFoo::setValue, "This is a property docstring"); } }
C++
3D
mcellteam/mcell
libs/pybind11/tests/test_eval.py
.py
1,183
52
# -*- coding: utf-8 -*- import os import pytest import env # noqa: F401 from pybind11_tests import eval_ as m def test_evals(capture): with capture: assert m.test_eval_statements() assert capture == "Hello World!" assert m.test_eval() assert m.test_eval_single_statement() assert m.test_eval_failure() @pytest.mark.xfail("env.PYPY and not env.PY2", raises=RuntimeError) def test_eval_file(): filename = os.path.join(os.path.dirname(__file__), "test_eval_call.py") assert m.test_eval_file(filename) assert m.test_eval_file_failure() def test_eval_empty_globals(): assert "__builtins__" in m.eval_empty_globals(None) g = {} assert "__builtins__" in m.eval_empty_globals(g) assert "__builtins__" in g def test_eval_closure(): global_, local = m.test_eval_closure() assert global_["closure_value"] == 42 assert local["closure_value"] == 0 assert "local_value" not in global_ assert local["local_value"] == 0 assert "func_global" not in global_ assert local["func_global"]() == 42 assert "func_local" not in global_ with pytest.raises(NameError): local["func_local"]()
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_modules.py
.py
2,843
93
# -*- coding: utf-8 -*- from pybind11_tests import ConstructorStats from pybind11_tests import modules as m from pybind11_tests.modules import subsubmodule as ms def test_nested_modules(): import pybind11_tests assert pybind11_tests.__name__ == "pybind11_tests" assert pybind11_tests.modules.__name__ == "pybind11_tests.modules" assert ( pybind11_tests.modules.subsubmodule.__name__ == "pybind11_tests.modules.subsubmodule" ) assert m.__name__ == "pybind11_tests.modules" assert ms.__name__ == "pybind11_tests.modules.subsubmodule" assert ms.submodule_func() == "submodule_func()" def test_reference_internal(): b = ms.B() assert str(b.get_a1()) == "A[1]" assert str(b.a1) == "A[1]" assert str(b.get_a2()) == "A[2]" assert str(b.a2) == "A[2]" b.a1 = ms.A(42) b.a2 = ms.A(43) assert str(b.get_a1()) == "A[42]" assert str(b.a1) == "A[42]" assert str(b.get_a2()) == "A[43]" assert str(b.a2) == "A[43]" astats, bstats = ConstructorStats.get(ms.A), ConstructorStats.get(ms.B) assert astats.alive() == 2 assert bstats.alive() == 1 del b assert astats.alive() == 0 assert bstats.alive() == 0 assert astats.values() == ["1", "2", "42", "43"] assert bstats.values() == [] assert astats.default_constructions == 0 assert bstats.default_constructions == 1 assert astats.copy_constructions == 0 assert bstats.copy_constructions == 0 # assert astats.move_constructions >= 0 # Don't invoke any # assert bstats.move_constructions >= 0 # Don't invoke any assert astats.copy_assignments == 2 assert bstats.copy_assignments == 0 assert astats.move_assignments == 0 assert bstats.move_assignments == 0 def test_importing(): from collections import OrderedDict from pybind11_tests.modules import OD assert OD is OrderedDict assert str(OD([(1, "a"), (2, "b")])) == "OrderedDict([(1, 'a'), (2, 'b')])" def test_pydoc(): """Pydoc needs to be able to provide help() for everything inside a pybind11 module""" import pydoc import pybind11_tests assert pybind11_tests.__name__ == "pybind11_tests" assert pybind11_tests.__doc__ == "pybind11 test module" assert pydoc.text.docmodule(pybind11_tests) def test_duplicate_registration(): """Registering two things with the same name""" assert m.duplicate_registration() == [] def test_builtin_key_type(): """Test that all the keys in the builtin modules have type str. Previous versions of pybind11 would add a unicode key in python 2. """ if hasattr(__builtins__, "keys"): keys = __builtins__.keys() else: # this is to make pypy happy since builtins is different there. keys = __builtins__.__dict__.keys() assert {type(k) for k in keys} == {str}
Python
3D
mcellteam/mcell
libs/pybind11/tests/local_bindings.h
.h
2,847
93
#pragma once #include "pybind11_tests.h" #include <utility> /// Simple class used to test py::local: template <int> class LocalBase { public: explicit LocalBase(int i) : i(i) {} int i = -1; }; /// Registered with py::module_local in both main and secondary modules: using LocalType = LocalBase<0>; /// Registered without py::module_local in both modules: using NonLocalType = LocalBase<1>; /// A second non-local type (for stl_bind tests): using NonLocal2 = LocalBase<2>; /// Tests within-module, different-compilation-unit local definition conflict: using LocalExternal = LocalBase<3>; /// Mixed: registered local first, then global using MixedLocalGlobal = LocalBase<4>; /// Mixed: global first, then local using MixedGlobalLocal = LocalBase<5>; /// Registered with py::module_local only in the secondary module: using ExternalType1 = LocalBase<6>; using ExternalType2 = LocalBase<7>; using LocalVec = std::vector<LocalType>; using LocalVec2 = std::vector<NonLocal2>; using LocalMap = std::unordered_map<std::string, LocalType>; using NonLocalVec = std::vector<NonLocalType>; using NonLocalVec2 = std::vector<NonLocal2>; using NonLocalMap = std::unordered_map<std::string, NonLocalType>; using NonLocalMap2 = std::unordered_map<std::string, uint8_t>; // Exception that will be caught via the module local translator. class LocalException : public std::exception { public: explicit LocalException(const char *m) : message{m} {} const char *what() const noexcept override { return message.c_str(); } private: std::string message = ""; }; // Exception that will be registered with register_local_exception_translator class LocalSimpleException : public std::exception { public: explicit LocalSimpleException(const char *m) : message{m} {} const char *what() const noexcept override { return message.c_str(); } private: std::string message = ""; }; PYBIND11_MAKE_OPAQUE(LocalVec); PYBIND11_MAKE_OPAQUE(LocalVec2); PYBIND11_MAKE_OPAQUE(LocalMap); PYBIND11_MAKE_OPAQUE(NonLocalVec); // PYBIND11_MAKE_OPAQUE(NonLocalVec2); // same type as LocalVec2 PYBIND11_MAKE_OPAQUE(NonLocalMap); PYBIND11_MAKE_OPAQUE(NonLocalMap2); // Simple bindings (used with the above): template <typename T, int Adjust = 0, typename... Args> py::class_<T> bind_local(Args &&...args) { return py::class_<T>(std::forward<Args>(args)...).def(py::init<int>()).def("get", [](T &i) { return i.i + Adjust; }); }; // Simulate a foreign library base class (to match the example in the docs): namespace pets { class Pet { public: explicit Pet(std::string name) : name_(std::move(name)) {} std::string name_; const std::string &name() const { return name_; } }; } // namespace pets struct MixGL { int i; explicit MixGL(int i) : i{i} {} }; struct MixGL2 { int i; explicit MixGL2(int i) : i{i} {} };
Unknown
3D
mcellteam/mcell
libs/pybind11/tests/test_sequences_and_iterators.py
.py
8,059
254
# -*- coding: utf-8 -*- import pytest from pybind11_tests import ConstructorStats from pybind11_tests import sequences_and_iterators as m def isclose(a, b, rel_tol=1e-05, abs_tol=0.0): """Like math.isclose() from Python 3.5""" return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) def allclose(a_list, b_list, rel_tol=1e-05, abs_tol=0.0): return all( isclose(a, b, rel_tol=rel_tol, abs_tol=abs_tol) for a, b in zip(a_list, b_list) ) def test_slice_constructors(): assert m.make_forward_slice_size_t() == slice(0, -1, 1) assert m.make_reversed_slice_object() == slice(None, None, -1) @pytest.mark.skipif(not m.has_optional, reason="no <optional>") def test_slice_constructors_explicit_optional(): assert m.make_reversed_slice_size_t_optional() == slice(None, None, -1) assert m.make_reversed_slice_size_t_optional_verbose() == slice(None, None, -1) def test_generalized_iterators(): assert list(m.IntPairs([(1, 2), (3, 4), (0, 5)]).nonzero()) == [(1, 2), (3, 4)] assert list(m.IntPairs([(1, 2), (2, 0), (0, 3), (4, 5)]).nonzero()) == [(1, 2)] assert list(m.IntPairs([(0, 3), (1, 2), (3, 4)]).nonzero()) == [] assert list(m.IntPairs([(1, 2), (3, 4), (0, 5)]).nonzero_keys()) == [1, 3] assert list(m.IntPairs([(1, 2), (2, 0), (0, 3), (4, 5)]).nonzero_keys()) == [1] assert list(m.IntPairs([(0, 3), (1, 2), (3, 4)]).nonzero_keys()) == [] assert list(m.IntPairs([(1, 2), (3, 4), (0, 5)]).nonzero_values()) == [2, 4] assert list(m.IntPairs([(1, 2), (2, 0), (0, 3), (4, 5)]).nonzero_values()) == [2] assert list(m.IntPairs([(0, 3), (1, 2), (3, 4)]).nonzero_values()) == [] # __next__ must continue to raise StopIteration it = m.IntPairs([(0, 0)]).nonzero() for _ in range(3): with pytest.raises(StopIteration): next(it) it = m.IntPairs([(0, 0)]).nonzero_keys() for _ in range(3): with pytest.raises(StopIteration): next(it) def test_nonref_iterators(): pairs = m.IntPairs([(1, 2), (3, 4), (0, 5)]) assert list(pairs.nonref()) == [(1, 2), (3, 4), (0, 5)] assert list(pairs.nonref_keys()) == [1, 3, 0] assert list(pairs.nonref_values()) == [2, 4, 5] def test_generalized_iterators_simple(): assert list(m.IntPairs([(1, 2), (3, 4), (0, 5)]).simple_iterator()) == [ (1, 2), (3, 4), (0, 5), ] assert list(m.IntPairs([(1, 2), (3, 4), (0, 5)]).simple_keys()) == [1, 3, 0] assert list(m.IntPairs([(1, 2), (3, 4), (0, 5)]).simple_values()) == [2, 4, 5] def test_iterator_referencing(): """Test that iterators reference rather than copy their referents.""" vec = m.VectorNonCopyableInt() vec.append(3) vec.append(5) assert [int(x) for x in vec] == [3, 5] # Increment everything to make sure the referents can be mutated for x in vec: x.set(int(x) + 1) assert [int(x) for x in vec] == [4, 6] vec = m.VectorNonCopyableIntPair() vec.append([3, 4]) vec.append([5, 7]) assert [int(x) for x in vec.keys()] == [3, 5] assert [int(x) for x in vec.values()] == [4, 7] for x in vec.keys(): x.set(int(x) + 1) for x in vec.values(): x.set(int(x) + 10) assert [int(x) for x in vec.keys()] == [4, 6] assert [int(x) for x in vec.values()] == [14, 17] def test_sliceable(): sliceable = m.Sliceable(100) assert sliceable[::] == (0, 100, 1) assert sliceable[10::] == (10, 100, 1) assert sliceable[:10:] == (0, 10, 1) assert sliceable[::10] == (0, 100, 10) assert sliceable[-10::] == (90, 100, 1) assert sliceable[:-10:] == (0, 90, 1) assert sliceable[::-10] == (99, -1, -10) assert sliceable[50:60:1] == (50, 60, 1) assert sliceable[50:60:-1] == (50, 60, -1) def test_sequence(): cstats = ConstructorStats.get(m.Sequence) s = m.Sequence(5) assert cstats.values() == ["of size", "5"] assert "Sequence" in repr(s) assert len(s) == 5 assert s[0] == 0 and s[3] == 0 assert 12.34 not in s s[0], s[3] = 12.34, 56.78 assert 12.34 in s assert isclose(s[0], 12.34) and isclose(s[3], 56.78) rev = reversed(s) assert cstats.values() == ["of size", "5"] rev2 = s[::-1] assert cstats.values() == ["of size", "5"] it = iter(m.Sequence(0)) for _ in range(3): # __next__ must continue to raise StopIteration with pytest.raises(StopIteration): next(it) assert cstats.values() == ["of size", "0"] expected = [0, 56.78, 0, 0, 12.34] assert allclose(rev, expected) assert allclose(rev2, expected) assert rev == rev2 rev[0::2] = m.Sequence([2.0, 2.0, 2.0]) assert cstats.values() == ["of size", "3", "from std::vector"] assert allclose(rev, [2, 56.78, 2, 0, 2]) assert cstats.alive() == 4 del it assert cstats.alive() == 3 del s assert cstats.alive() == 2 del rev assert cstats.alive() == 1 del rev2 assert cstats.alive() == 0 assert cstats.values() == [] assert cstats.default_constructions == 0 assert cstats.copy_constructions == 0 assert cstats.move_constructions >= 1 assert cstats.copy_assignments == 0 assert cstats.move_assignments == 0 def test_sequence_length(): """#2076: Exception raised by len(arg) should be propagated""" class BadLen(RuntimeError): pass class SequenceLike: def __getitem__(self, i): return None def __len__(self): raise BadLen() with pytest.raises(BadLen): m.sequence_length(SequenceLike()) assert m.sequence_length([1, 2, 3]) == 3 assert m.sequence_length("hello") == 5 def test_map_iterator(): sm = m.StringMap({"hi": "bye", "black": "white"}) assert sm["hi"] == "bye" assert len(sm) == 2 assert sm["black"] == "white" with pytest.raises(KeyError): assert sm["orange"] sm["orange"] = "banana" assert sm["orange"] == "banana" expected = {"hi": "bye", "black": "white", "orange": "banana"} for k in sm: assert sm[k] == expected[k] for k, v in sm.items(): assert v == expected[k] assert list(sm.values()) == [expected[k] for k in sm] it = iter(m.StringMap({})) for _ in range(3): # __next__ must continue to raise StopIteration with pytest.raises(StopIteration): next(it) def test_python_iterator_in_cpp(): t = (1, 2, 3) assert m.object_to_list(t) == [1, 2, 3] assert m.object_to_list(iter(t)) == [1, 2, 3] assert m.iterator_to_list(iter(t)) == [1, 2, 3] with pytest.raises(TypeError) as excinfo: m.object_to_list(1) assert "object is not iterable" in str(excinfo.value) with pytest.raises(TypeError) as excinfo: m.iterator_to_list(1) assert "incompatible function arguments" in str(excinfo.value) def bad_next_call(): raise RuntimeError("py::iterator::advance() should propagate errors") with pytest.raises(RuntimeError) as excinfo: m.iterator_to_list(iter(bad_next_call, None)) assert str(excinfo.value) == "py::iterator::advance() should propagate errors" lst = [1, None, 0, None] assert m.count_none(lst) == 2 assert m.find_none(lst) is True assert m.count_nonzeros({"a": 0, "b": 1, "c": 2}) == 2 r = range(5) assert all(m.tuple_iterator(tuple(r))) assert all(m.list_iterator(list(r))) assert all(m.sequence_iterator(r)) def test_iterator_passthrough(): """#181: iterator passthrough did not compile""" from pybind11_tests.sequences_and_iterators import iterator_passthrough values = [3, 5, 7, 9, 11, 13, 15] assert list(iterator_passthrough(iter(values))) == values def test_iterator_rvp(): """#388: Can't make iterators via make_iterator() with different r/v policies""" import pybind11_tests.sequences_and_iterators as m assert list(m.make_iterator_1()) == [1, 2, 3] assert list(m.make_iterator_2()) == [1, 2, 3] assert not isinstance(m.make_iterator_1(), type(m.make_iterator_2()))
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_local_bindings.py
.py
8,101
258
# -*- coding: utf-8 -*- import pytest import env # noqa: F401 from pybind11_tests import local_bindings as m def test_load_external(): """Load a `py::module_local` type that's only registered in an external module""" import pybind11_cross_module_tests as cm assert m.load_external1(cm.ExternalType1(11)) == 11 assert m.load_external2(cm.ExternalType2(22)) == 22 with pytest.raises(TypeError) as excinfo: assert m.load_external2(cm.ExternalType1(21)) == 21 assert "incompatible function arguments" in str(excinfo.value) with pytest.raises(TypeError) as excinfo: assert m.load_external1(cm.ExternalType2(12)) == 12 assert "incompatible function arguments" in str(excinfo.value) def test_local_bindings(): """Tests that duplicate `py::module_local` class bindings work across modules""" # Make sure we can load the second module with the conflicting (but local) definition: import pybind11_cross_module_tests as cm i1 = m.LocalType(5) assert i1.get() == 4 assert i1.get3() == 8 i2 = cm.LocalType(10) assert i2.get() == 11 assert i2.get2() == 12 assert not hasattr(i1, "get2") assert not hasattr(i2, "get3") # Loading within the local module assert m.local_value(i1) == 5 assert cm.local_value(i2) == 10 # Cross-module loading works as well (on failure, the type loader looks for # external module-local converters): assert m.local_value(i2) == 10 assert cm.local_value(i1) == 5 def test_nonlocal_failure(): """Tests that attempting to register a non-local type in multiple modules fails""" import pybind11_cross_module_tests as cm with pytest.raises(RuntimeError) as excinfo: cm.register_nonlocal() assert ( str(excinfo.value) == 'generic_type: type "NonLocalType" is already registered!' ) def test_duplicate_local(): """Tests expected failure when registering a class twice with py::local in the same module""" with pytest.raises(RuntimeError) as excinfo: m.register_local_external() import pybind11_tests assert str(excinfo.value) == ( 'generic_type: type "LocalExternal" is already registered!' if hasattr(pybind11_tests, "class_") else "test_class not enabled" ) def test_stl_bind_local(): import pybind11_cross_module_tests as cm v1, v2 = m.LocalVec(), cm.LocalVec() v1.append(m.LocalType(1)) v1.append(m.LocalType(2)) v2.append(cm.LocalType(1)) v2.append(cm.LocalType(2)) # Cross module value loading: v1.append(cm.LocalType(3)) v2.append(m.LocalType(3)) assert [i.get() for i in v1] == [0, 1, 2] assert [i.get() for i in v2] == [2, 3, 4] v3, v4 = m.NonLocalVec(), cm.NonLocalVec2() v3.append(m.NonLocalType(1)) v3.append(m.NonLocalType(2)) v4.append(m.NonLocal2(3)) v4.append(m.NonLocal2(4)) assert [i.get() for i in v3] == [1, 2] assert [i.get() for i in v4] == [13, 14] d1, d2 = m.LocalMap(), cm.LocalMap() d1["a"] = v1[0] d1["b"] = v1[1] d2["c"] = v2[0] d2["d"] = v2[1] assert {i: d1[i].get() for i in d1} == {"a": 0, "b": 1} assert {i: d2[i].get() for i in d2} == {"c": 2, "d": 3} def test_stl_bind_global(): import pybind11_cross_module_tests as cm with pytest.raises(RuntimeError) as excinfo: cm.register_nonlocal_map() assert ( str(excinfo.value) == 'generic_type: type "NonLocalMap" is already registered!' ) with pytest.raises(RuntimeError) as excinfo: cm.register_nonlocal_vec() assert ( str(excinfo.value) == 'generic_type: type "NonLocalVec" is already registered!' ) with pytest.raises(RuntimeError) as excinfo: cm.register_nonlocal_map2() assert ( str(excinfo.value) == 'generic_type: type "NonLocalMap2" is already registered!' ) def test_mixed_local_global(): """Local types take precedence over globally registered types: a module with a `module_local` type can be registered even if the type is already registered globally. With the module, casting will go to the local type; outside the module casting goes to the global type.""" import pybind11_cross_module_tests as cm m.register_mixed_global() m.register_mixed_local() a = [] a.append(m.MixedGlobalLocal(1)) a.append(m.MixedLocalGlobal(2)) a.append(m.get_mixed_gl(3)) a.append(m.get_mixed_lg(4)) assert [x.get() for x in a] == [101, 1002, 103, 1004] cm.register_mixed_global_local() cm.register_mixed_local_global() a.append(m.MixedGlobalLocal(5)) a.append(m.MixedLocalGlobal(6)) a.append(cm.MixedGlobalLocal(7)) a.append(cm.MixedLocalGlobal(8)) a.append(m.get_mixed_gl(9)) a.append(m.get_mixed_lg(10)) a.append(cm.get_mixed_gl(11)) a.append(cm.get_mixed_lg(12)) assert [x.get() for x in a] == [ 101, 1002, 103, 1004, 105, 1006, 207, 2008, 109, 1010, 211, 2012, ] def test_internal_locals_differ(): """Makes sure the internal local type map differs across the two modules""" import pybind11_cross_module_tests as cm assert m.local_cpp_types_addr() != cm.local_cpp_types_addr() @pytest.mark.xfail("env.PYPY and sys.pypy_version_info < (7, 3, 2)") def test_stl_caster_vs_stl_bind(msg): """One module uses a generic vector caster from `<pybind11/stl.h>` while the other exports `std::vector<int>` via `py:bind_vector` and `py::module_local`""" import pybind11_cross_module_tests as cm v1 = cm.VectorInt([1, 2, 3]) assert m.load_vector_via_caster(v1) == 6 assert cm.load_vector_via_binding(v1) == 6 v2 = [1, 2, 3] assert m.load_vector_via_caster(v2) == 6 with pytest.raises(TypeError) as excinfo: cm.load_vector_via_binding(v2) assert ( msg(excinfo.value) == """ load_vector_via_binding(): incompatible function arguments. The following argument types are supported: 1. (arg0: pybind11_cross_module_tests.VectorInt) -> int Invoked with: [1, 2, 3] """ # noqa: E501 line too long ) def test_cross_module_calls(): import pybind11_cross_module_tests as cm v1 = m.LocalVec() v1.append(m.LocalType(1)) v2 = cm.LocalVec() v2.append(cm.LocalType(2)) # Returning the self pointer should get picked up as returning an existing # instance (even when that instance is of a foreign, non-local type). assert m.return_self(v1) is v1 assert cm.return_self(v2) is v2 assert m.return_self(v2) is v2 assert cm.return_self(v1) is v1 assert m.LocalVec is not cm.LocalVec # Returning a copy, on the other hand, always goes to the local type, # regardless of where the source type came from. assert type(m.return_copy(v1)) is m.LocalVec assert type(m.return_copy(v2)) is m.LocalVec assert type(cm.return_copy(v1)) is cm.LocalVec assert type(cm.return_copy(v2)) is cm.LocalVec # Test the example given in the documentation (which also tests inheritance casting): mycat = m.Cat("Fluffy") mydog = cm.Dog("Rover") assert mycat.get_name() == "Fluffy" assert mydog.name() == "Rover" assert m.Cat.__base__.__name__ == "Pet" assert cm.Dog.__base__.__name__ == "Pet" assert m.Cat.__base__ is not cm.Dog.__base__ assert m.pet_name(mycat) == "Fluffy" assert m.pet_name(mydog) == "Rover" assert cm.pet_name(mycat) == "Fluffy" assert cm.pet_name(mydog) == "Rover" assert m.MixGL is not cm.MixGL a = m.MixGL(1) b = cm.MixGL(2) assert m.get_gl_value(a) == 11 assert m.get_gl_value(b) == 12 assert cm.get_gl_value(a) == 101 assert cm.get_gl_value(b) == 102 c, d = m.MixGL2(3), cm.MixGL2(4) with pytest.raises(TypeError) as excinfo: m.get_gl_value(c) assert "incompatible function arguments" in str(excinfo.value) with pytest.raises(TypeError) as excinfo: m.get_gl_value(d) assert "incompatible function arguments" in str(excinfo.value)
Python
3D
mcellteam/mcell
libs/pybind11/tests/object.h
.h
5,743
206
#if !defined(__OBJECT_H) # define __OBJECT_H # include "constructor_stats.h" # include <atomic> /// Reference counted object base class class Object { public: /// Default constructor Object() { print_default_created(this); } /// Copy constructor Object(const Object &) : m_refCount(0) { print_copy_created(this); } /// Return the current reference count int getRefCount() const { return m_refCount; }; /// Increase the object's reference count by one void incRef() const { ++m_refCount; } /** \brief Decrease the reference count of * the object and possibly deallocate it. * * The object will automatically be deallocated once * the reference count reaches zero. */ void decRef(bool dealloc = true) const { --m_refCount; if (m_refCount == 0 && dealloc) { delete this; } else if (m_refCount < 0) { throw std::runtime_error("Internal error: reference count < 0!"); } } virtual std::string toString() const = 0; protected: /** \brief Virtual protected deconstructor. * (Will only be called by \ref ref) */ virtual ~Object() { print_destroyed(this); } private: mutable std::atomic<int> m_refCount{0}; }; // Tag class used to track constructions of ref objects. When we track constructors, below, we // track and print out the actual class (e.g. ref<MyObject>), and *also* add a fake tracker for // ref_tag. This lets us check that the total number of ref<Anything> constructors/destructors is // correct without having to check each individual ref<Whatever> type individually. class ref_tag {}; /** * \brief Reference counting helper * * The \a ref refeference template is a simple wrapper to store a * pointer to an object. It takes care of increasing and decreasing * the reference count of the object. When the last reference goes * out of scope, the associated object will be deallocated. * * \ingroup libcore */ template <typename T> class ref { public: /// Create a nullptr reference ref() : m_ptr(nullptr) { print_default_created(this); track_default_created((ref_tag *) this); } /// Construct a reference from a pointer explicit ref(T *ptr) : m_ptr(ptr) { if (m_ptr) { ((Object *) m_ptr)->incRef(); } print_created(this, "from pointer", m_ptr); track_created((ref_tag *) this, "from pointer"); } /// Copy constructor ref(const ref &r) : m_ptr(r.m_ptr) { if (m_ptr) { ((Object *) m_ptr)->incRef(); } print_copy_created(this, "with pointer", m_ptr); track_copy_created((ref_tag *) this); } /// Move constructor ref(ref &&r) noexcept : m_ptr(r.m_ptr) { r.m_ptr = nullptr; print_move_created(this, "with pointer", m_ptr); track_move_created((ref_tag *) this); } /// Destroy this reference ~ref() { if (m_ptr) { ((Object *) m_ptr)->decRef(); } print_destroyed(this); track_destroyed((ref_tag *) this); } /// Move another reference into the current one ref &operator=(ref &&r) noexcept { print_move_assigned(this, "pointer", r.m_ptr); track_move_assigned((ref_tag *) this); if (*this == r) { return *this; } if (m_ptr) { ((Object *) m_ptr)->decRef(); } m_ptr = r.m_ptr; r.m_ptr = nullptr; return *this; } /// Overwrite this reference with another reference ref &operator=(const ref &r) { if (this == &r) { return *this; } print_copy_assigned(this, "pointer", r.m_ptr); track_copy_assigned((ref_tag *) this); if (m_ptr == r.m_ptr) { return *this; } if (m_ptr) { ((Object *) m_ptr)->decRef(); } m_ptr = r.m_ptr; if (m_ptr) { ((Object *) m_ptr)->incRef(); } return *this; } /// Overwrite this reference with a pointer to another object ref &operator=(T *ptr) { print_values(this, "assigned pointer"); track_values((ref_tag *) this, "assigned pointer"); if (m_ptr == ptr) { return *this; } if (m_ptr) { ((Object *) m_ptr)->decRef(); } m_ptr = ptr; if (m_ptr) { ((Object *) m_ptr)->incRef(); } return *this; } /// Compare this reference with another reference bool operator==(const ref &r) const { return m_ptr == r.m_ptr; } /// Compare this reference with another reference bool operator!=(const ref &r) const { return m_ptr != r.m_ptr; } /// Compare this reference with a pointer bool operator==(const T *ptr) const { return m_ptr == ptr; } /// Compare this reference with a pointer bool operator!=(const T *ptr) const { return m_ptr != ptr; } /// Access the object referenced by this reference T *operator->() { return m_ptr; } /// Access the object referenced by this reference const T *operator->() const { return m_ptr; } /// Return a C++ reference to the referenced object T &operator*() { return *m_ptr; } /// Return a const C++ reference to the referenced object const T &operator*() const { return *m_ptr; } /// Return a pointer to the referenced object explicit operator T *() { return m_ptr; } /// Return a const pointer to the referenced object T *get_ptr() { return m_ptr; } /// Return a pointer to the referenced object const T *get_ptr() const { return m_ptr; } private: T *m_ptr; }; #endif /* __OBJECT_H */
Unknown
3D
mcellteam/mcell
libs/pybind11/tests/test_custom_type_casters.cpp
.cpp
7,210
210
/* tests/test_custom_type_casters.cpp -- tests type_caster<T> Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #include "constructor_stats.h" #include "pybind11_tests.h" // py::arg/py::arg_v testing: these arguments just record their argument when invoked class ArgInspector1 { public: std::string arg = "(default arg inspector 1)"; }; class ArgInspector2 { public: std::string arg = "(default arg inspector 2)"; }; class ArgAlwaysConverts {}; namespace pybind11 { namespace detail { template <> struct type_caster<ArgInspector1> { public: // Classic #ifdef PYBIND11_DETAIL_UNDERSCORE_BACKWARD_COMPATIBILITY PYBIND11_TYPE_CASTER(ArgInspector1, _("ArgInspector1")); #else PYBIND11_TYPE_CASTER(ArgInspector1, const_name("ArgInspector1")); #endif bool load(handle src, bool convert) { value.arg = "loading ArgInspector1 argument " + std::string(convert ? "WITH" : "WITHOUT") + " conversion allowed. " "Argument value = " + (std::string) str(src); return true; } static handle cast(const ArgInspector1 &src, return_value_policy, handle) { return str(src.arg).release(); } }; template <> struct type_caster<ArgInspector2> { public: PYBIND11_TYPE_CASTER(ArgInspector2, const_name("ArgInspector2")); bool load(handle src, bool convert) { value.arg = "loading ArgInspector2 argument " + std::string(convert ? "WITH" : "WITHOUT") + " conversion allowed. " "Argument value = " + (std::string) str(src); return true; } static handle cast(const ArgInspector2 &src, return_value_policy, handle) { return str(src.arg).release(); } }; template <> struct type_caster<ArgAlwaysConverts> { public: PYBIND11_TYPE_CASTER(ArgAlwaysConverts, const_name("ArgAlwaysConverts")); bool load(handle, bool convert) { return convert; } static handle cast(const ArgAlwaysConverts &, return_value_policy, handle) { return py::none().release(); } }; } // namespace detail } // namespace pybind11 // test_custom_caster_destruction class DestructionTester { public: DestructionTester() { print_default_created(this); } ~DestructionTester() { print_destroyed(this); } DestructionTester(const DestructionTester &) { print_copy_created(this); } DestructionTester(DestructionTester &&) noexcept { print_move_created(this); } DestructionTester &operator=(const DestructionTester &) { print_copy_assigned(this); return *this; } DestructionTester &operator=(DestructionTester &&) noexcept { print_move_assigned(this); return *this; } }; namespace pybind11 { namespace detail { template <> struct type_caster<DestructionTester> { PYBIND11_TYPE_CASTER(DestructionTester, const_name("DestructionTester")); bool load(handle, bool) { return true; } static handle cast(const DestructionTester &, return_value_policy, handle) { return py::bool_(true).release(); } }; } // namespace detail } // namespace pybind11 // Define type caster outside of `pybind11::detail` and then alias it. namespace other_lib { struct MyType {}; // Corrupt `py` shorthand alias for surrounding context. namespace py {} // Corrupt unqualified relative `pybind11` namespace. namespace pybind11 {} // Correct alias. namespace py_ = ::pybind11; // Define caster. This is effectively no-op, we only ensure it compiles and we // don't have any symbol collision when using macro mixin. struct my_caster { PYBIND11_TYPE_CASTER(MyType, py_::detail::const_name("MyType")); bool load(py_::handle, bool) { return true; } static py_::handle cast(const MyType &, py_::return_value_policy, py_::handle) { return py_::bool_(true).release(); } }; } // namespace other_lib // Effectively "alias" it into correct namespace (via inheritance). namespace pybind11 { namespace detail { template <> struct type_caster<other_lib::MyType> : public other_lib::my_caster {}; } // namespace detail } // namespace pybind11 TEST_SUBMODULE(custom_type_casters, m) { // test_custom_type_casters // test_noconvert_args // // Test converting. The ArgAlwaysConverts is just there to make the first no-conversion pass // fail so that our call always ends up happening via the second dispatch (the one that allows // some conversion). class ArgInspector { public: ArgInspector1 f(ArgInspector1 a, ArgAlwaysConverts) { return a; } std::string g(const ArgInspector1 &a, const ArgInspector1 &b, int c, ArgInspector2 *d, ArgAlwaysConverts) { return a.arg + "\n" + b.arg + "\n" + std::to_string(c) + "\n" + d->arg; } static ArgInspector2 h(ArgInspector2 a, ArgAlwaysConverts) { return a; } }; // [workaround(intel)] ICC 20/21 breaks with py::arg().stuff, using py::arg{}.stuff works. py::class_<ArgInspector>(m, "ArgInspector") .def(py::init<>()) .def("f", &ArgInspector::f, py::arg(), py::arg() = ArgAlwaysConverts()) .def("g", &ArgInspector::g, "a"_a.noconvert(), "b"_a, "c"_a.noconvert() = 13, "d"_a = ArgInspector2(), py::arg() = ArgAlwaysConverts()) .def_static("h", &ArgInspector::h, py::arg{}.noconvert(), py::arg() = ArgAlwaysConverts()); m.def( "arg_inspect_func", [](const ArgInspector2 &a, const ArgInspector1 &b, ArgAlwaysConverts) { return a.arg + "\n" + b.arg; }, py::arg{}.noconvert(false), py::arg_v(nullptr, ArgInspector1()).noconvert(true), py::arg() = ArgAlwaysConverts()); m.def( "floats_preferred", [](double f) { return 0.5 * f; }, "f"_a); m.def( "floats_only", [](double f) { return 0.5 * f; }, "f"_a.noconvert()); m.def( "ints_preferred", [](int i) { return i / 2; }, "i"_a); m.def( "ints_only", [](int i) { return i / 2; }, "i"_a.noconvert()); // test_custom_caster_destruction // Test that `take_ownership` works on types with a custom type caster when given a pointer // default policy: don't take ownership: m.def("custom_caster_no_destroy", []() { static auto *dt = new DestructionTester(); return dt; }); m.def( "custom_caster_destroy", []() { return new DestructionTester(); }, py::return_value_policy::take_ownership); // Takes ownership: destroy when finished m.def( "custom_caster_destroy_const", []() -> const DestructionTester * { return new DestructionTester(); }, py::return_value_policy::take_ownership); // Likewise (const doesn't inhibit destruction) m.def("destruction_tester_cstats", &ConstructorStats::get<DestructionTester>, py::return_value_policy::reference); m.def("other_lib_type", [](other_lib::MyType x) { return x; }); }
C++
3D
mcellteam/mcell
libs/pybind11/tests/test_numpy_dtypes.py
.py
14,036
442
# -*- coding: utf-8 -*- import re import pytest import env # noqa: F401 from pybind11_tests import numpy_dtypes as m np = pytest.importorskip("numpy") @pytest.fixture(scope="module") def simple_dtype(): ld = np.dtype("longdouble") return np.dtype( { "names": ["bool_", "uint_", "float_", "ldbl_"], "formats": ["?", "u4", "f4", "f{}".format(ld.itemsize)], "offsets": [0, 4, 8, (16 if ld.alignment > 4 else 12)], } ) @pytest.fixture(scope="module") def packed_dtype(): return np.dtype([("bool_", "?"), ("uint_", "u4"), ("float_", "f4"), ("ldbl_", "g")]) def dt_fmt(): from sys import byteorder e = "<" if byteorder == "little" else ">" return ( "{{'names':['bool_','uint_','float_','ldbl_']," "'formats':['?','" + e + "u4','" + e + "f4','" + e + "f{}']," "'offsets':[0,4,8,{}],'itemsize':{}}}" ) def simple_dtype_fmt(): ld = np.dtype("longdouble") simple_ld_off = 12 + 4 * (ld.alignment > 4) return dt_fmt().format(ld.itemsize, simple_ld_off, simple_ld_off + ld.itemsize) def packed_dtype_fmt(): from sys import byteorder return "[('bool_','?'),('uint_','{e}u4'),('float_','{e}f4'),('ldbl_','{e}f{}')]".format( np.dtype("longdouble").itemsize, e="<" if byteorder == "little" else ">" ) def partial_ld_offset(): return ( 12 + 4 * (np.dtype("uint64").alignment > 4) + 8 + 8 * (np.dtype("longdouble").alignment > 8) ) def partial_dtype_fmt(): ld = np.dtype("longdouble") partial_ld_off = partial_ld_offset() partial_size = partial_ld_off + ld.itemsize partial_end_padding = partial_size % np.dtype("uint64").alignment return dt_fmt().format( ld.itemsize, partial_ld_off, partial_size + partial_end_padding ) def partial_nested_fmt(): ld = np.dtype("longdouble") partial_nested_off = 8 + 8 * (ld.alignment > 8) partial_ld_off = partial_ld_offset() partial_size = partial_ld_off + ld.itemsize partial_end_padding = partial_size % np.dtype("uint64").alignment partial_nested_size = partial_nested_off * 2 + partial_size + partial_end_padding return "{{'names':['a'],'formats':[{}],'offsets':[{}],'itemsize':{}}}".format( partial_dtype_fmt(), partial_nested_off, partial_nested_size ) def assert_equal(actual, expected_data, expected_dtype): np.testing.assert_equal(actual, np.array(expected_data, dtype=expected_dtype)) def test_format_descriptors(): with pytest.raises(RuntimeError) as excinfo: m.get_format_unbound() assert re.match( "^NumPy type info missing for .*UnboundStruct.*$", str(excinfo.value) ) ld = np.dtype("longdouble") ldbl_fmt = ("4x" if ld.alignment > 4 else "") + ld.char ss_fmt = "^T{?:bool_:3xI:uint_:f:float_:" + ldbl_fmt + ":ldbl_:}" dbl = np.dtype("double") end_padding = ld.itemsize % np.dtype("uint64").alignment partial_fmt = ( "^T{?:bool_:3xI:uint_:f:float_:" + str(4 * (dbl.alignment > 4) + dbl.itemsize + 8 * (ld.alignment > 8)) + "xg:ldbl_:" + (str(end_padding) + "x}" if end_padding > 0 else "}") ) nested_extra = str(max(8, ld.alignment)) assert m.print_format_descriptors() == [ ss_fmt, "^T{?:bool_:I:uint_:f:float_:g:ldbl_:}", "^T{" + ss_fmt + ":a:^T{?:bool_:I:uint_:f:float_:g:ldbl_:}:b:}", partial_fmt, "^T{" + nested_extra + "x" + partial_fmt + ":a:" + nested_extra + "x}", "^T{3s:a:3s:b:}", "^T{(3)4s:a:(2)i:b:(3)B:c:1x(4, 2)f:d:}", "^T{q:e1:B:e2:}", "^T{Zf:cflt:Zd:cdbl:}", ] def test_dtype(simple_dtype): from sys import byteorder e = "<" if byteorder == "little" else ">" assert [x.replace(" ", "") for x in m.print_dtypes()] == [ simple_dtype_fmt(), packed_dtype_fmt(), "[('a',{}),('b',{})]".format(simple_dtype_fmt(), packed_dtype_fmt()), partial_dtype_fmt(), partial_nested_fmt(), "[('a','S3'),('b','S3')]", ( "{{'names':['a','b','c','d']," + "'formats':[('S4',(3,)),('" + e + "i4',(2,)),('u1',(3,)),('" + e + "f4',(4,2))]," + "'offsets':[0,12,20,24],'itemsize':56}}" ).format(e=e), "[('e1','" + e + "i8'),('e2','u1')]", "[('x','i1'),('y','" + e + "u8')]", "[('cflt','" + e + "c8'),('cdbl','" + e + "c16')]", ] d1 = np.dtype( { "names": ["a", "b"], "formats": ["int32", "float64"], "offsets": [1, 10], "itemsize": 20, } ) d2 = np.dtype([("a", "i4"), ("b", "f4")]) assert m.test_dtype_ctors() == [ np.dtype("int32"), np.dtype("float64"), np.dtype("bool"), d1, d1, np.dtype("uint32"), d2, ] assert m.test_dtype_methods() == [ np.dtype("int32"), simple_dtype, False, True, np.dtype("int32").itemsize, simple_dtype.itemsize, ] assert m.trailing_padding_dtype() == m.buffer_to_dtype( np.zeros(1, m.trailing_padding_dtype()) ) assert m.test_dtype_kind() == list("iiiiiuuuuuffffcccbMmO") assert m.test_dtype_char_() == list("bhilqBHILQefdgFDG?MmO") def test_recarray(simple_dtype, packed_dtype): elements = [(False, 0, 0.0, -0.0), (True, 1, 1.5, -2.5), (False, 2, 3.0, -5.0)] for func, dtype in [ (m.create_rec_simple, simple_dtype), (m.create_rec_packed, packed_dtype), ]: arr = func(0) assert arr.dtype == dtype assert_equal(arr, [], simple_dtype) assert_equal(arr, [], packed_dtype) arr = func(3) assert arr.dtype == dtype assert_equal(arr, elements, simple_dtype) assert_equal(arr, elements, packed_dtype) # Show what recarray's look like in NumPy. assert type(arr[0]) == np.void assert type(arr[0].item()) == tuple if dtype == simple_dtype: assert m.print_rec_simple(arr) == [ "s:0,0,0,-0", "s:1,1,1.5,-2.5", "s:0,2,3,-5", ] else: assert m.print_rec_packed(arr) == [ "p:0,0,0,-0", "p:1,1,1.5,-2.5", "p:0,2,3,-5", ] nested_dtype = np.dtype([("a", simple_dtype), ("b", packed_dtype)]) arr = m.create_rec_nested(0) assert arr.dtype == nested_dtype assert_equal(arr, [], nested_dtype) arr = m.create_rec_nested(3) assert arr.dtype == nested_dtype assert_equal( arr, [ ((False, 0, 0.0, -0.0), (True, 1, 1.5, -2.5)), ((True, 1, 1.5, -2.5), (False, 2, 3.0, -5.0)), ((False, 2, 3.0, -5.0), (True, 3, 4.5, -7.5)), ], nested_dtype, ) assert m.print_rec_nested(arr) == [ "n:a=s:0,0,0,-0;b=p:1,1,1.5,-2.5", "n:a=s:1,1,1.5,-2.5;b=p:0,2,3,-5", "n:a=s:0,2,3,-5;b=p:1,3,4.5,-7.5", ] arr = m.create_rec_partial(3) assert str(arr.dtype).replace(" ", "") == partial_dtype_fmt() partial_dtype = arr.dtype assert "" not in arr.dtype.fields assert partial_dtype.itemsize > simple_dtype.itemsize assert_equal(arr, elements, simple_dtype) assert_equal(arr, elements, packed_dtype) arr = m.create_rec_partial_nested(3) assert str(arr.dtype).replace(" ", "") == partial_nested_fmt() assert "" not in arr.dtype.fields assert "" not in arr.dtype.fields["a"][0].fields assert arr.dtype.itemsize > partial_dtype.itemsize np.testing.assert_equal(arr["a"], m.create_rec_partial(3)) def test_array_constructors(): data = np.arange(1, 7, dtype="int32") for i in range(8): np.testing.assert_array_equal(m.test_array_ctors(10 + i), data.reshape((3, 2))) np.testing.assert_array_equal(m.test_array_ctors(20 + i), data.reshape((3, 2))) for i in range(5): np.testing.assert_array_equal(m.test_array_ctors(30 + i), data) np.testing.assert_array_equal(m.test_array_ctors(40 + i), data) def test_string_array(): arr = m.create_string_array(True) assert str(arr.dtype) == "[('a', 'S3'), ('b', 'S3')]" assert m.print_string_array(arr) == [ "a='',b=''", "a='a',b='a'", "a='ab',b='ab'", "a='abc',b='abc'", ] dtype = arr.dtype assert arr["a"].tolist() == [b"", b"a", b"ab", b"abc"] assert arr["b"].tolist() == [b"", b"a", b"ab", b"abc"] arr = m.create_string_array(False) assert dtype == arr.dtype def test_array_array(): from sys import byteorder e = "<" if byteorder == "little" else ">" arr = m.create_array_array(3) assert str(arr.dtype).replace(" ", "") == ( "{{'names':['a','b','c','d']," + "'formats':[('S4',(3,)),('" + e + "i4',(2,)),('u1',(3,)),('{e}f4',(4,2))]," + "'offsets':[0,12,20,24],'itemsize':56}}" ).format(e=e) assert m.print_array_array(arr) == [ "a={{A,B,C,D},{K,L,M,N},{U,V,W,X}},b={0,1}," + "c={0,1,2},d={{0,1},{10,11},{20,21},{30,31}}", "a={{W,X,Y,Z},{G,H,I,J},{Q,R,S,T}},b={1000,1001}," + "c={10,11,12},d={{100,101},{110,111},{120,121},{130,131}}", "a={{S,T,U,V},{C,D,E,F},{M,N,O,P}},b={2000,2001}," + "c={20,21,22},d={{200,201},{210,211},{220,221},{230,231}}", ] assert arr["a"].tolist() == [ [b"ABCD", b"KLMN", b"UVWX"], [b"WXYZ", b"GHIJ", b"QRST"], [b"STUV", b"CDEF", b"MNOP"], ] assert arr["b"].tolist() == [[0, 1], [1000, 1001], [2000, 2001]] assert m.create_array_array(0).dtype == arr.dtype def test_enum_array(): from sys import byteorder e = "<" if byteorder == "little" else ">" arr = m.create_enum_array(3) dtype = arr.dtype assert dtype == np.dtype([("e1", e + "i8"), ("e2", "u1")]) assert m.print_enum_array(arr) == ["e1=A,e2=X", "e1=B,e2=Y", "e1=A,e2=X"] assert arr["e1"].tolist() == [-1, 1, -1] assert arr["e2"].tolist() == [1, 2, 1] assert m.create_enum_array(0).dtype == dtype def test_complex_array(): from sys import byteorder e = "<" if byteorder == "little" else ">" arr = m.create_complex_array(3) dtype = arr.dtype assert dtype == np.dtype([("cflt", e + "c8"), ("cdbl", e + "c16")]) assert m.print_complex_array(arr) == [ "c:(0,0.25),(0.5,0.75)", "c:(1,1.25),(1.5,1.75)", "c:(2,2.25),(2.5,2.75)", ] assert arr["cflt"].tolist() == [0.0 + 0.25j, 1.0 + 1.25j, 2.0 + 2.25j] assert arr["cdbl"].tolist() == [0.5 + 0.75j, 1.5 + 1.75j, 2.5 + 2.75j] assert m.create_complex_array(0).dtype == dtype def test_signature(doc): assert ( doc(m.create_rec_nested) == "create_rec_nested(arg0: int) -> numpy.ndarray[NestedStruct]" ) def test_scalar_conversion(): n = 3 arrays = [ m.create_rec_simple(n), m.create_rec_packed(n), m.create_rec_nested(n), m.create_enum_array(n), ] funcs = [m.f_simple, m.f_packed, m.f_nested] for i, func in enumerate(funcs): for j, arr in enumerate(arrays): if i == j and i < 2: assert [func(arr[k]) for k in range(n)] == [k * 10 for k in range(n)] else: with pytest.raises(TypeError) as excinfo: func(arr[0]) assert "incompatible function arguments" in str(excinfo.value) def test_vectorize(): n = 3 array = m.create_rec_simple(n) values = m.f_simple_vectorized(array) np.testing.assert_array_equal(values, [0, 10, 20]) array_2 = m.f_simple_pass_thru_vectorized(array) np.testing.assert_array_equal(array, array_2) def test_cls_and_dtype_conversion(simple_dtype): s = m.SimpleStruct() assert s.astuple() == (False, 0, 0.0, 0.0) assert m.SimpleStruct.fromtuple(s.astuple()).astuple() == s.astuple() s.uint_ = 2 assert m.f_simple(s) == 20 # Try as recarray of shape==(1,). s_recarray = np.array([(False, 2, 0.0, 0.0)], dtype=simple_dtype) # Show that this will work for vectorized case. np.testing.assert_array_equal(m.f_simple_vectorized(s_recarray), [20]) # Show as a scalar that inherits from np.generic. s_scalar = s_recarray[0] assert isinstance(s_scalar, np.void) assert m.f_simple(s_scalar) == 20 # Show that an *array* scalar (np.ndarray.shape == ()) does not convert. # More specifically, conversion to SimpleStruct is not implicit. s_recarray_scalar = s_recarray.reshape(()) assert isinstance(s_recarray_scalar, np.ndarray) assert s_recarray_scalar.dtype == simple_dtype with pytest.raises(TypeError) as excinfo: m.f_simple(s_recarray_scalar) assert "incompatible function arguments" in str(excinfo.value) # Explicitly convert to m.SimpleStruct. assert m.f_simple(m.SimpleStruct.fromtuple(s_recarray_scalar.item())) == 20 # Show that an array of dtype=object does *not* convert. s_array_object = np.array([s]) assert s_array_object.dtype == object with pytest.raises(TypeError) as excinfo: m.f_simple_vectorized(s_array_object) assert "incompatible function arguments" in str(excinfo.value) # Explicitly convert to `np.array(..., dtype=simple_dtype)` s_array = np.array([s.astuple()], dtype=simple_dtype) np.testing.assert_array_equal(m.f_simple_vectorized(s_array), [20]) def test_register_dtype(): with pytest.raises(RuntimeError) as excinfo: m.register_dtype() assert "dtype is already registered" in str(excinfo.value) @pytest.mark.xfail("env.PYPY") def test_str_leak(): from sys import getrefcount fmt = "f4" pytest.gc_collect() start = getrefcount(fmt) d = m.dtype_wrapper(fmt) assert d is np.dtype("f4") del d pytest.gc_collect() assert getrefcount(fmt) == start def test_compare_buffer_info(): assert all(m.compare_buffer_info())
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_custom_type_casters.py
.py
4,088
122
# -*- coding: utf-8 -*- import pytest from pybind11_tests import custom_type_casters as m def test_noconvert_args(msg): a = m.ArgInspector() assert ( msg(a.f("hi")) == """ loading ArgInspector1 argument WITH conversion allowed. Argument value = hi """ ) assert ( msg(a.g("this is a", "this is b")) == """ loading ArgInspector1 argument WITHOUT conversion allowed. Argument value = this is a loading ArgInspector1 argument WITH conversion allowed. Argument value = this is b 13 loading ArgInspector2 argument WITH conversion allowed. Argument value = (default arg inspector 2) """ # noqa: E501 line too long ) assert ( msg(a.g("this is a", "this is b", 42)) == """ loading ArgInspector1 argument WITHOUT conversion allowed. Argument value = this is a loading ArgInspector1 argument WITH conversion allowed. Argument value = this is b 42 loading ArgInspector2 argument WITH conversion allowed. Argument value = (default arg inspector 2) """ # noqa: E501 line too long ) assert ( msg(a.g("this is a", "this is b", 42, "this is d")) == """ loading ArgInspector1 argument WITHOUT conversion allowed. Argument value = this is a loading ArgInspector1 argument WITH conversion allowed. Argument value = this is b 42 loading ArgInspector2 argument WITH conversion allowed. Argument value = this is d """ ) assert ( a.h("arg 1") == "loading ArgInspector2 argument WITHOUT conversion allowed. Argument value = arg 1" ) assert ( msg(m.arg_inspect_func("A1", "A2")) == """ loading ArgInspector2 argument WITH conversion allowed. Argument value = A1 loading ArgInspector1 argument WITHOUT conversion allowed. Argument value = A2 """ ) assert m.floats_preferred(4) == 2.0 assert m.floats_only(4.0) == 2.0 with pytest.raises(TypeError) as excinfo: m.floats_only(4) assert ( msg(excinfo.value) == """ floats_only(): incompatible function arguments. The following argument types are supported: 1. (f: float) -> float Invoked with: 4 """ ) assert m.ints_preferred(4) == 2 assert m.ints_preferred(True) == 0 with pytest.raises(TypeError) as excinfo: m.ints_preferred(4.0) assert ( msg(excinfo.value) == """ ints_preferred(): incompatible function arguments. The following argument types are supported: 1. (i: int) -> int Invoked with: 4.0 """ # noqa: E501 line too long ) assert m.ints_only(4) == 2 with pytest.raises(TypeError) as excinfo: m.ints_only(4.0) assert ( msg(excinfo.value) == """ ints_only(): incompatible function arguments. The following argument types are supported: 1. (i: int) -> int Invoked with: 4.0 """ ) def test_custom_caster_destruction(): """Tests that returning a pointer to a type that gets converted with a custom type caster gets destroyed when the function has py::return_value_policy::take_ownership policy applied.""" cstats = m.destruction_tester_cstats() # This one *doesn't* have take_ownership: the pointer should be used but not destroyed: z = m.custom_caster_no_destroy() assert cstats.alive() == 1 and cstats.default_constructions == 1 assert z # take_ownership applied: this constructs a new object, casts it, then destroys it: z = m.custom_caster_destroy() assert z assert cstats.default_constructions == 2 # Same, but with a const pointer return (which should *not* inhibit destruction): z = m.custom_caster_destroy_const() assert z assert cstats.default_constructions == 3 # Make sure we still only have the original object (from ..._no_destroy()) alive: assert cstats.alive() == 1 def test_custom_caster_other_lib(): assert m.other_lib_type(True)
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_kwargs_and_defaults.cpp
.cpp
9,236
274
/* tests/test_kwargs_and_defaults.cpp -- keyword arguments and default values Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> 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/stl.h> #include "constructor_stats.h" #include "pybind11_tests.h" #include <utility> TEST_SUBMODULE(kwargs_and_defaults, m) { auto kw_func = [](int x, int y) { return "x=" + std::to_string(x) + ", y=" + std::to_string(y); }; // test_named_arguments m.def("kw_func0", kw_func); m.def("kw_func1", kw_func, py::arg("x"), py::arg("y")); m.def("kw_func2", kw_func, py::arg("x") = 100, py::arg("y") = 200); m.def( "kw_func3", [](const char *) {}, py::arg("data") = std::string("Hello world!")); /* A fancier default argument */ std::vector<int> list{{13, 17}}; m.def( "kw_func4", [](const std::vector<int> &entries) { std::string ret = "{"; for (int i : entries) { ret += std::to_string(i) + " "; } ret.back() = '}'; return ret; }, py::arg("myList") = list); m.def("kw_func_udl", kw_func, "x"_a, "y"_a = 300); m.def("kw_func_udl_z", kw_func, "x"_a, "y"_a = 0); // test_args_and_kwargs m.def("args_function", [](py::args args) -> py::tuple { return std::move(args); }); m.def("args_kwargs_function", [](const py::args &args, const py::kwargs &kwargs) { return py::make_tuple(args, kwargs); }); // test_mixed_args_and_kwargs m.def("mixed_plus_args", [](int i, double j, const py::args &args) { return py::make_tuple(i, j, args); }); m.def("mixed_plus_kwargs", [](int i, double j, const py::kwargs &kwargs) { return py::make_tuple(i, j, kwargs); }); auto mixed_plus_both = [](int i, double j, const py::args &args, const py::kwargs &kwargs) { return py::make_tuple(i, j, args, kwargs); }; m.def("mixed_plus_args_kwargs", mixed_plus_both); m.def("mixed_plus_args_kwargs_defaults", mixed_plus_both, py::arg("i") = 1, py::arg("j") = 3.14159); m.def( "args_kwonly", [](int i, double j, const py::args &args, int z) { return py::make_tuple(i, j, args, z); }, "i"_a, "j"_a, "z"_a); m.def( "args_kwonly_kwargs", [](int i, double j, const py::args &args, int z, const py::kwargs &kwargs) { return py::make_tuple(i, j, args, z, kwargs); }, "i"_a, "j"_a, py::kw_only{}, "z"_a); m.def( "args_kwonly_kwargs_defaults", [](int i, double j, const py::args &args, int z, const py::kwargs &kwargs) { return py::make_tuple(i, j, args, z, kwargs); }, "i"_a = 1, "j"_a = 3.14159, "z"_a = 42); m.def( "args_kwonly_full_monty", [](int h, int i, double j, const py::args &args, int z, const py::kwargs &kwargs) { return py::make_tuple(h, i, j, args, z, kwargs); }, py::arg() = 1, py::arg() = 2, py::pos_only{}, "j"_a = 3.14159, "z"_a = 42); // test_args_refcount // PyPy needs a garbage collection to get the reference count values to match CPython's behaviour #ifdef PYPY_VERSION # define GC_IF_NEEDED ConstructorStats::gc() #else # define GC_IF_NEEDED #endif m.def("arg_refcount_h", [](py::handle h) { GC_IF_NEEDED; return h.ref_count(); }); m.def("arg_refcount_h", [](py::handle h, py::handle, py::handle) { GC_IF_NEEDED; return h.ref_count(); }); m.def("arg_refcount_o", [](const py::object &o) { GC_IF_NEEDED; return o.ref_count(); }); m.def("args_refcount", [](py::args a) { GC_IF_NEEDED; py::tuple t(a.size()); for (size_t i = 0; i < a.size(); i++) { // Use raw Python API here to avoid an extra, intermediate incref on the tuple item: t[i] = (int) Py_REFCNT(PyTuple_GET_ITEM(a.ptr(), static_cast<py::ssize_t>(i))); } return t; }); m.def("mixed_args_refcount", [](const py::object &o, py::args a) { GC_IF_NEEDED; py::tuple t(a.size() + 1); t[0] = o.ref_count(); for (size_t i = 0; i < a.size(); i++) { // Use raw Python API here to avoid an extra, intermediate incref on the tuple item: t[i + 1] = (int) Py_REFCNT(PyTuple_GET_ITEM(a.ptr(), static_cast<py::ssize_t>(i))); } return t; }); // pybind11 won't allow these to be bound: args and kwargs, if present, must be at the end. // Uncomment these to test that the static_assert is indeed working: // m.def("bad_args1", [](py::args, int) {}); // m.def("bad_args2", [](py::kwargs, int) {}); // m.def("bad_args3", [](py::kwargs, py::args) {}); // m.def("bad_args4", [](py::args, int, py::kwargs) {}); // m.def("bad_args5", [](py::args, py::kwargs, int) {}); // m.def("bad_args6", [](py::args, py::args) {}); // m.def("bad_args7", [](py::kwargs, py::kwargs) {}); // test_keyword_only_args m.def( "kw_only_all", [](int i, int j) { return py::make_tuple(i, j); }, py::kw_only(), py::arg("i"), py::arg("j")); m.def( "kw_only_some", [](int i, int j, int k) { return py::make_tuple(i, j, k); }, py::arg(), py::kw_only(), py::arg("j"), py::arg("k")); m.def( "kw_only_with_defaults", [](int i, int j, int k, int z) { return py::make_tuple(i, j, k, z); }, py::arg() = 3, "j"_a = 4, py::kw_only(), "k"_a = 5, "z"_a); m.def( "kw_only_mixed", [](int i, int j) { return py::make_tuple(i, j); }, "i"_a, py::kw_only(), "j"_a); m.def( "kw_only_plus_more", [](int i, int j, int k, const py::kwargs &kwargs) { return py::make_tuple(i, j, k, kwargs); }, py::arg() /* positional */, py::arg("j") = -1 /* both */, py::kw_only(), py::arg("k") /* kw-only */); m.def("register_invalid_kw_only", [](py::module_ m) { m.def( "bad_kw_only", [](int i, int j) { return py::make_tuple(i, j); }, py::kw_only(), py::arg() /* invalid unnamed argument */, "j"_a); }); // test_positional_only_args m.def( "pos_only_all", [](int i, int j) { return py::make_tuple(i, j); }, py::arg("i"), py::arg("j"), py::pos_only()); m.def( "pos_only_mix", [](int i, int j) { return py::make_tuple(i, j); }, py::arg("i"), py::pos_only(), py::arg("j")); m.def( "pos_kw_only_mix", [](int i, int j, int k) { return py::make_tuple(i, j, k); }, py::arg("i"), py::pos_only(), py::arg("j"), py::kw_only(), py::arg("k")); m.def( "pos_only_def_mix", [](int i, int j, int k) { return py::make_tuple(i, j, k); }, py::arg("i"), py::arg("j") = 2, py::pos_only(), py::arg("k") = 3); // These should fail to compile: #ifdef PYBIND11_NEVER_DEFINED_EVER // argument annotations are required when using kw_only m.def( "bad_kw_only1", [](int) {}, py::kw_only()); // can't specify both `py::kw_only` and a `py::args` argument m.def( "bad_kw_only2", [](int i, py::args) {}, py::kw_only(), "i"_a); #endif // test_function_signatures (along with most of the above) struct KWClass { void foo(int, float) {} }; py::class_<KWClass>(m, "KWClass") .def("foo0", &KWClass::foo) .def("foo1", &KWClass::foo, "x"_a, "y"_a); // Make sure a class (not an instance) can be used as a default argument. // The return value doesn't matter, only that the module is importable. m.def( "class_default_argument", [](py::object a) { return py::repr(std::move(a)); }, "a"_a = py::module_::import("decimal").attr("Decimal")); // Initial implementation of kw_only was broken when used on a method/constructor before any // other arguments // https://github.com/pybind/pybind11/pull/3402#issuecomment-963341987 struct first_arg_kw_only {}; py::class_<first_arg_kw_only>(m, "first_arg_kw_only") .def(py::init([](int) { return first_arg_kw_only(); }), py::kw_only(), // This being before any args was broken py::arg("i") = 0) .def( "method", [](first_arg_kw_only &, int, int) {}, py::kw_only(), // and likewise here py::arg("i") = 1, py::arg("j") = 2) // Closely related: pos_only marker didn't show up properly when it was before any other // arguments (although that is fairly useless in practice). .def( "pos_only", [](first_arg_kw_only &, int, int) {}, py::pos_only{}, py::arg("i"), py::arg("j")); }
C++
3D
mcellteam/mcell
libs/pybind11/tests/test_stl_binders.py
.py
8,071
319
# -*- coding: utf-8 -*- import pytest import env from pybind11_tests import stl_binders as m def test_vector_int(): v_int = m.VectorInt([0, 0]) assert len(v_int) == 2 assert bool(v_int) is True # test construction from a generator v_int1 = m.VectorInt(x for x in range(5)) assert v_int1 == m.VectorInt([0, 1, 2, 3, 4]) v_int2 = m.VectorInt([0, 0]) assert v_int == v_int2 v_int2[1] = 1 assert v_int != v_int2 v_int2.append(2) v_int2.insert(0, 1) v_int2.insert(0, 2) v_int2.insert(0, 3) v_int2.insert(6, 3) assert str(v_int2) == "VectorInt[3, 2, 1, 0, 1, 2, 3]" with pytest.raises(IndexError): v_int2.insert(8, 4) v_int.append(99) v_int2[2:-2] = v_int assert v_int2 == m.VectorInt([3, 2, 0, 0, 99, 2, 3]) del v_int2[1:3] assert v_int2 == m.VectorInt([3, 0, 99, 2, 3]) del v_int2[0] assert v_int2 == m.VectorInt([0, 99, 2, 3]) v_int2.extend(m.VectorInt([4, 5])) assert v_int2 == m.VectorInt([0, 99, 2, 3, 4, 5]) v_int2.extend([6, 7]) assert v_int2 == m.VectorInt([0, 99, 2, 3, 4, 5, 6, 7]) # test error handling, and that the vector is unchanged with pytest.raises(RuntimeError): v_int2.extend([8, "a"]) assert v_int2 == m.VectorInt([0, 99, 2, 3, 4, 5, 6, 7]) # test extending from a generator v_int2.extend(x for x in range(5)) assert v_int2 == m.VectorInt([0, 99, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4]) # test negative indexing assert v_int2[-1] == 4 # insert with negative index v_int2.insert(-1, 88) assert v_int2 == m.VectorInt([0, 99, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 88, 4]) # delete negative index del v_int2[-1] assert v_int2 == m.VectorInt([0, 99, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 88]) v_int2.clear() assert len(v_int2) == 0 # Older PyPy's failed here, related to the PyPy's buffer protocol. def test_vector_buffer(): b = bytearray([1, 2, 3, 4]) v = m.VectorUChar(b) assert v[1] == 2 v[2] = 5 mv = memoryview(v) # We expose the buffer interface if not env.PY2: assert mv[2] == 5 mv[2] = 6 else: assert mv[2] == "\x05" mv[2] = "\x06" assert v[2] == 6 if not env.PY2: mv = memoryview(b) v = m.VectorUChar(mv[::2]) assert v[1] == 3 with pytest.raises(RuntimeError) as excinfo: m.create_undeclstruct() # Undeclared struct contents, no buffer interface assert "NumPy type info missing for " in str(excinfo.value) def test_vector_buffer_numpy(): np = pytest.importorskip("numpy") a = np.array([1, 2, 3, 4], dtype=np.int32) with pytest.raises(TypeError): m.VectorInt(a) a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], dtype=np.uintc) v = m.VectorInt(a[0, :]) assert len(v) == 4 assert v[2] == 3 ma = np.asarray(v) ma[2] = 5 assert v[2] == 5 v = m.VectorInt(a[:, 1]) assert len(v) == 3 assert v[2] == 10 v = m.get_vectorstruct() assert v[0].x == 5 ma = np.asarray(v) ma[1]["x"] = 99 assert v[1].x == 99 v = m.VectorStruct( np.zeros( 3, dtype=np.dtype( [("w", "bool"), ("x", "I"), ("y", "float64"), ("z", "bool")], align=True ), ) ) assert len(v) == 3 b = np.array([1, 2, 3, 4], dtype=np.uint8) v = m.VectorUChar(b[::2]) assert v[1] == 3 def test_vector_bool(): import pybind11_cross_module_tests as cm vv_c = cm.VectorBool() for i in range(10): vv_c.append(i % 2 == 0) for i in range(10): assert vv_c[i] == (i % 2 == 0) assert str(vv_c) == "VectorBool[1, 0, 1, 0, 1, 0, 1, 0, 1, 0]" def test_vector_custom(): v_a = m.VectorEl() v_a.append(m.El(1)) v_a.append(m.El(2)) assert str(v_a) == "VectorEl[El{1}, El{2}]" vv_a = m.VectorVectorEl() vv_a.append(v_a) vv_b = vv_a[0] assert str(vv_b) == "VectorEl[El{1}, El{2}]" def test_map_string_double(): mm = m.MapStringDouble() mm["a"] = 1 mm["b"] = 2.5 assert list(mm) == ["a", "b"] assert str(mm) == "MapStringDouble{a: 1, b: 2.5}" assert "b" in mm assert "c" not in mm assert 123 not in mm # Check that keys, values, items are views, not merely iterable keys = mm.keys() values = mm.values() items = mm.items() assert list(keys) == ["a", "b"] assert len(keys) == 2 assert "a" in keys assert "c" not in keys assert 123 not in keys assert list(items) == [("a", 1), ("b", 2.5)] assert len(items) == 2 assert ("b", 2.5) in items assert "hello" not in items assert ("b", 2.5, None) not in items assert list(values) == [1, 2.5] assert len(values) == 2 assert 1 in values assert 2 not in values # Check that views update when the map is updated mm["c"] = -1 assert list(keys) == ["a", "b", "c"] assert list(values) == [1, 2.5, -1] assert list(items) == [("a", 1), ("b", 2.5), ("c", -1)] um = m.UnorderedMapStringDouble() um["ua"] = 1.1 um["ub"] = 2.6 assert sorted(list(um)) == ["ua", "ub"] assert list(um.keys()) == list(um) assert sorted(list(um.items())) == [("ua", 1.1), ("ub", 2.6)] assert list(zip(um.keys(), um.values())) == list(um.items()) assert "UnorderedMapStringDouble" in str(um) def test_map_string_double_const(): mc = m.MapStringDoubleConst() mc["a"] = 10 mc["b"] = 20.5 assert str(mc) == "MapStringDoubleConst{a: 10, b: 20.5}" umc = m.UnorderedMapStringDoubleConst() umc["a"] = 11 umc["b"] = 21.5 str(umc) def test_noncopyable_containers(): # std::vector vnc = m.get_vnc(5) for i in range(0, 5): assert vnc[i].value == i + 1 for i, j in enumerate(vnc, start=1): assert j.value == i # std::deque dnc = m.get_dnc(5) for i in range(0, 5): assert dnc[i].value == i + 1 i = 1 for j in dnc: assert j.value == i i += 1 # std::map mnc = m.get_mnc(5) for i in range(1, 6): assert mnc[i].value == 10 * i vsum = 0 for k, v in mnc.items(): assert v.value == 10 * k vsum += v.value assert vsum == 150 # std::unordered_map mnc = m.get_umnc(5) for i in range(1, 6): assert mnc[i].value == 10 * i vsum = 0 for k, v in mnc.items(): assert v.value == 10 * k vsum += v.value assert vsum == 150 # nested std::map<std::vector> nvnc = m.get_nvnc(5) for i in range(1, 6): for j in range(0, 5): assert nvnc[i][j].value == j + 1 # Note: maps do not have .values() for _, v in nvnc.items(): for i, j in enumerate(v, start=1): assert j.value == i # nested std::map<std::map> nmnc = m.get_nmnc(5) for i in range(1, 6): for j in range(10, 60, 10): assert nmnc[i][j].value == 10 * j vsum = 0 for _, v_o in nmnc.items(): for k_i, v_i in v_o.items(): assert v_i.value == 10 * k_i vsum += v_i.value assert vsum == 7500 # nested std::unordered_map<std::unordered_map> numnc = m.get_numnc(5) for i in range(1, 6): for j in range(10, 60, 10): assert numnc[i][j].value == 10 * j vsum = 0 for _, v_o in numnc.items(): for k_i, v_i in v_o.items(): assert v_i.value == 10 * k_i vsum += v_i.value assert vsum == 7500 def test_map_delitem(): mm = m.MapStringDouble() mm["a"] = 1 mm["b"] = 2.5 assert list(mm) == ["a", "b"] assert list(mm.items()) == [("a", 1), ("b", 2.5)] del mm["a"] assert list(mm) == ["b"] assert list(mm.items()) == [("b", 2.5)] um = m.UnorderedMapStringDouble() um["ua"] = 1.1 um["ub"] = 2.6 assert sorted(list(um)) == ["ua", "ub"] assert sorted(list(um.items())) == [("ua", 1.1), ("ub", 2.6)] del um["ua"] assert sorted(list(um)) == ["ub"] assert sorted(list(um.items())) == [("ub", 2.6)]
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_pickling.cpp
.cpp
6,646
196
// clang-format off /* tests/test_pickling.cpp -- pickle support Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> Copyright (c) 2021 The Pybind Development Team. 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" // clang-format on #include <memory> #include <stdexcept> #include <utility> namespace exercise_trampoline { struct SimpleBase { int num = 0; virtual ~SimpleBase() = default; // For compatibility with old clang versions: SimpleBase() = default; SimpleBase(const SimpleBase &) = default; }; struct SimpleBaseTrampoline : SimpleBase {}; struct SimpleCppDerived : SimpleBase {}; void wrap(py::module m) { py::class_<SimpleBase, SimpleBaseTrampoline>(m, "SimpleBase") .def(py::init<>()) .def_readwrite("num", &SimpleBase::num) .def(py::pickle( [](const py::object &self) { py::dict d; if (py::hasattr(self, "__dict__")) { d = self.attr("__dict__"); } return py::make_tuple(self.attr("num"), d); }, [](const py::tuple &t) { if (t.size() != 2) { throw std::runtime_error("Invalid state!"); } auto cpp_state = std::unique_ptr<SimpleBase>(new SimpleBaseTrampoline); cpp_state->num = t[0].cast<int>(); auto py_state = t[1].cast<py::dict>(); return std::make_pair(std::move(cpp_state), py_state); })); m.def("make_SimpleCppDerivedAsBase", []() { return std::unique_ptr<SimpleBase>(new SimpleCppDerived); }); m.def("check_dynamic_cast_SimpleCppDerived", [](const SimpleBase *base_ptr) { return dynamic_cast<const SimpleCppDerived *>(base_ptr) != nullptr; }); } } // namespace exercise_trampoline // clang-format off TEST_SUBMODULE(pickling, m) { // test_roundtrip class Pickleable { public: explicit Pickleable(const std::string &value) : m_value(value) { } const std::string &value() const { return m_value; } void setExtra1(int extra1) { m_extra1 = extra1; } void setExtra2(int extra2) { m_extra2 = extra2; } int extra1() const { return m_extra1; } int extra2() const { return m_extra2; } private: std::string m_value; int m_extra1 = 0; int m_extra2 = 0; }; class PickleableNew : public Pickleable { public: using Pickleable::Pickleable; }; py::class_<Pickleable> pyPickleable(m, "Pickleable"); pyPickleable .def(py::init<std::string>()) .def("value", &Pickleable::value) .def("extra1", &Pickleable::extra1) .def("extra2", &Pickleable::extra2) .def("setExtra1", &Pickleable::setExtra1) .def("setExtra2", &Pickleable::setExtra2) // For details on the methods below, refer to // http://docs.python.org/3/library/pickle.html#pickling-class-instances .def("__getstate__", [](const Pickleable &p) { /* Return a tuple that fully encodes the state of the object */ return py::make_tuple(p.value(), p.extra1(), p.extra2()); }); ignoreOldStyleInitWarnings([&pyPickleable]() { pyPickleable.def("__setstate__", [](Pickleable &p, const py::tuple &t) { if (t.size() != 3) { throw std::runtime_error("Invalid state!"); } /* Invoke the constructor (need to use in-place version) */ new (&p) Pickleable(t[0].cast<std::string>()); /* Assign any additional state */ p.setExtra1(t[1].cast<int>()); p.setExtra2(t[2].cast<int>()); }); }); py::class_<PickleableNew, Pickleable>(m, "PickleableNew") .def(py::init<std::string>()) .def(py::pickle( [](const PickleableNew &p) { return py::make_tuple(p.value(), p.extra1(), p.extra2()); }, [](const py::tuple &t) { if (t.size() != 3) { throw std::runtime_error("Invalid state!"); } auto p = PickleableNew(t[0].cast<std::string>()); p.setExtra1(t[1].cast<int>()); p.setExtra2(t[2].cast<int>()); return p; })); #if !defined(PYPY_VERSION) // test_roundtrip_with_dict class PickleableWithDict { public: explicit PickleableWithDict(const std::string &value) : value(value) { } std::string value; int extra; }; class PickleableWithDictNew : public PickleableWithDict { public: using PickleableWithDict::PickleableWithDict; }; py::class_<PickleableWithDict> pyPickleableWithDict(m, "PickleableWithDict", py::dynamic_attr()); pyPickleableWithDict.def(py::init<std::string>()) .def_readwrite("value", &PickleableWithDict::value) .def_readwrite("extra", &PickleableWithDict::extra) .def("__getstate__", [](const py::object &self) { /* Also include __dict__ in state */ return py::make_tuple(self.attr("value"), self.attr("extra"), self.attr("__dict__")); }); ignoreOldStyleInitWarnings([&pyPickleableWithDict]() { pyPickleableWithDict.def("__setstate__", [](const py::object &self, const py::tuple &t) { if (t.size() != 3) { throw std::runtime_error("Invalid state!"); } /* Cast and construct */ auto &p = self.cast<PickleableWithDict &>(); new (&p) PickleableWithDict(t[0].cast<std::string>()); /* Assign C++ state */ p.extra = t[1].cast<int>(); /* Assign Python state */ self.attr("__dict__") = t[2]; }); }); py::class_<PickleableWithDictNew, PickleableWithDict>(m, "PickleableWithDictNew") .def(py::init<std::string>()) .def(py::pickle( [](const py::object &self) { return py::make_tuple(self.attr("value"), self.attr("extra"), self.attr("__dict__")); }, [](const py::tuple &t) { if (t.size() != 3) { throw std::runtime_error("Invalid state!"); } auto cpp_state = PickleableWithDictNew(t[0].cast<std::string>()); cpp_state.extra = t[1].cast<int>(); auto py_state = t[2].cast<py::dict>(); return std::make_pair(cpp_state, py_state); })); #endif exercise_trampoline::wrap(m); }
C++
3D
mcellteam/mcell
libs/pybind11/tests/test_tagbased_polymorphic.py
.py
765
30
# -*- coding: utf-8 -*- from pybind11_tests import tagbased_polymorphic as m def test_downcast(): zoo = m.create_zoo() assert [type(animal) for animal in zoo] == [ m.Labrador, m.Dog, m.Chihuahua, m.Cat, m.Panther, ] assert [animal.name for animal in zoo] == [ "Fido", "Ginger", "Hertzl", "Tiger", "Leo", ] zoo[1].sound = "woooooo" assert [dog.bark() for dog in zoo[:3]] == [ "Labrador Fido goes WOOF!", "Dog Ginger goes woooooo", "Chihuahua Hertzl goes iyiyiyiyiyi and runs in circles", ] assert [cat.purr() for cat in zoo[3:]] == ["mrowr", "mrrrRRRRRR"] zoo[0].excitement -= 1000 assert zoo[0].excitement == 14000
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_smart_ptr.py
.py
9,620
319
# -*- coding: utf-8 -*- import pytest m = pytest.importorskip("pybind11_tests.smart_ptr") from pybind11_tests import ConstructorStats # noqa: E402 def test_smart_ptr(capture): # Object1 for i, o in enumerate( [m.make_object_1(), m.make_object_2(), m.MyObject1(3)], start=1 ): assert o.getRefCount() == 1 with capture: m.print_object_1(o) m.print_object_2(o) m.print_object_3(o) m.print_object_4(o) assert capture == "MyObject1[{i}]\n".format(i=i) * 4 for i, o in enumerate( [m.make_myobject1_1(), m.make_myobject1_2(), m.MyObject1(6), 7], start=4 ): print(o) with capture: if not isinstance(o, int): m.print_object_1(o) m.print_object_2(o) m.print_object_3(o) m.print_object_4(o) m.print_myobject1_1(o) m.print_myobject1_2(o) m.print_myobject1_3(o) m.print_myobject1_4(o) times = 4 if isinstance(o, int) else 8 assert capture == "MyObject1[{i}]\n".format(i=i) * times cstats = ConstructorStats.get(m.MyObject1) assert cstats.alive() == 0 expected_values = ["MyObject1[{}]".format(i) for i in range(1, 7)] + [ "MyObject1[7]" ] * 4 assert cstats.values() == expected_values assert cstats.default_constructions == 0 assert cstats.copy_constructions == 0 # assert cstats.move_constructions >= 0 # Doesn't invoke any assert cstats.copy_assignments == 0 assert cstats.move_assignments == 0 # Object2 for i, o in zip( [8, 6, 7], [m.MyObject2(8), m.make_myobject2_1(), m.make_myobject2_2()] ): print(o) with capture: m.print_myobject2_1(o) m.print_myobject2_2(o) m.print_myobject2_3(o) m.print_myobject2_4(o) assert capture == "MyObject2[{i}]\n".format(i=i) * 4 cstats = ConstructorStats.get(m.MyObject2) assert cstats.alive() == 1 o = None assert cstats.alive() == 0 assert cstats.values() == ["MyObject2[8]", "MyObject2[6]", "MyObject2[7]"] assert cstats.default_constructions == 0 assert cstats.copy_constructions == 0 # assert cstats.move_constructions >= 0 # Doesn't invoke any assert cstats.copy_assignments == 0 assert cstats.move_assignments == 0 # Object3 for i, o in zip( [9, 8, 9], [m.MyObject3(9), m.make_myobject3_1(), m.make_myobject3_2()] ): print(o) with capture: m.print_myobject3_1(o) m.print_myobject3_2(o) m.print_myobject3_3(o) m.print_myobject3_4(o) assert capture == "MyObject3[{i}]\n".format(i=i) * 4 cstats = ConstructorStats.get(m.MyObject3) assert cstats.alive() == 1 o = None assert cstats.alive() == 0 assert cstats.values() == ["MyObject3[9]", "MyObject3[8]", "MyObject3[9]"] assert cstats.default_constructions == 0 assert cstats.copy_constructions == 0 # assert cstats.move_constructions >= 0 # Doesn't invoke any assert cstats.copy_assignments == 0 assert cstats.move_assignments == 0 # Object cstats = ConstructorStats.get(m.Object) assert cstats.alive() == 0 assert cstats.values() == [] assert cstats.default_constructions == 10 assert cstats.copy_constructions == 0 # assert cstats.move_constructions >= 0 # Doesn't invoke any assert cstats.copy_assignments == 0 assert cstats.move_assignments == 0 # ref<> cstats = m.cstats_ref() assert cstats.alive() == 0 assert cstats.values() == ["from pointer"] * 10 assert cstats.default_constructions == 30 assert cstats.copy_constructions == 12 # assert cstats.move_constructions >= 0 # Doesn't invoke any assert cstats.copy_assignments == 30 assert cstats.move_assignments == 0 def test_smart_ptr_refcounting(): assert m.test_object1_refcounting() def test_unique_nodelete(): o = m.MyObject4(23) assert o.value == 23 cstats = ConstructorStats.get(m.MyObject4) assert cstats.alive() == 1 del o assert cstats.alive() == 1 m.MyObject4.cleanup_all_instances() assert cstats.alive() == 0 def test_unique_nodelete4a(): o = m.MyObject4a(23) assert o.value == 23 cstats = ConstructorStats.get(m.MyObject4a) assert cstats.alive() == 1 del o assert cstats.alive() == 1 m.MyObject4a.cleanup_all_instances() assert cstats.alive() == 0 def test_unique_deleter(): m.MyObject4a(0) o = m.MyObject4b(23) assert o.value == 23 cstats4a = ConstructorStats.get(m.MyObject4a) assert cstats4a.alive() == 2 cstats4b = ConstructorStats.get(m.MyObject4b) assert cstats4b.alive() == 1 del o assert cstats4a.alive() == 1 # Should now only be one leftover assert cstats4b.alive() == 0 # Should be deleted m.MyObject4a.cleanup_all_instances() assert cstats4a.alive() == 0 assert cstats4b.alive() == 0 def test_large_holder(): o = m.MyObject5(5) assert o.value == 5 cstats = ConstructorStats.get(m.MyObject5) assert cstats.alive() == 1 del o assert cstats.alive() == 0 def test_shared_ptr_and_references(): s = m.SharedPtrRef() stats = ConstructorStats.get(m.A) assert stats.alive() == 2 ref = s.ref # init_holder_helper(holder_ptr=false, owned=false) assert stats.alive() == 2 assert s.set_ref(ref) with pytest.raises(RuntimeError) as excinfo: assert s.set_holder(ref) assert "Unable to cast from non-held to held instance" in str(excinfo.value) copy = s.copy # init_holder_helper(holder_ptr=false, owned=true) assert stats.alive() == 3 assert s.set_ref(copy) assert s.set_holder(copy) holder_ref = s.holder_ref # init_holder_helper(holder_ptr=true, owned=false) assert stats.alive() == 3 assert s.set_ref(holder_ref) assert s.set_holder(holder_ref) holder_copy = s.holder_copy # init_holder_helper(holder_ptr=true, owned=true) assert stats.alive() == 3 assert s.set_ref(holder_copy) assert s.set_holder(holder_copy) del ref, copy, holder_ref, holder_copy, s assert stats.alive() == 0 def test_shared_ptr_from_this_and_references(): s = m.SharedFromThisRef() stats = ConstructorStats.get(m.B) assert stats.alive() == 2 ref = s.ref # init_holder_helper(holder_ptr=false, owned=false, bad_wp=false) assert stats.alive() == 2 assert s.set_ref(ref) assert s.set_holder( ref ) # std::enable_shared_from_this can create a holder from a reference bad_wp = s.bad_wp # init_holder_helper(holder_ptr=false, owned=false, bad_wp=true) assert stats.alive() == 2 assert s.set_ref(bad_wp) with pytest.raises(RuntimeError) as excinfo: assert s.set_holder(bad_wp) assert "Unable to cast from non-held to held instance" in str(excinfo.value) copy = s.copy # init_holder_helper(holder_ptr=false, owned=true, bad_wp=false) assert stats.alive() == 3 assert s.set_ref(copy) assert s.set_holder(copy) holder_ref = ( s.holder_ref ) # init_holder_helper(holder_ptr=true, owned=false, bad_wp=false) assert stats.alive() == 3 assert s.set_ref(holder_ref) assert s.set_holder(holder_ref) holder_copy = ( s.holder_copy ) # init_holder_helper(holder_ptr=true, owned=true, bad_wp=false) assert stats.alive() == 3 assert s.set_ref(holder_copy) assert s.set_holder(holder_copy) del ref, bad_wp, copy, holder_ref, holder_copy, s assert stats.alive() == 0 z = m.SharedFromThisVirt.get() y = m.SharedFromThisVirt.get() assert y is z def test_move_only_holder(): a = m.TypeWithMoveOnlyHolder.make() b = m.TypeWithMoveOnlyHolder.make_as_object() stats = ConstructorStats.get(m.TypeWithMoveOnlyHolder) assert stats.alive() == 2 del b assert stats.alive() == 1 del a assert stats.alive() == 0 def test_holder_with_addressof_operator(): # this test must not throw exception from c++ a = m.TypeForHolderWithAddressOf.make() a.print_object_1() a.print_object_2() a.print_object_3() a.print_object_4() stats = ConstructorStats.get(m.TypeForHolderWithAddressOf) assert stats.alive() == 1 np = m.TypeForHolderWithAddressOf.make() assert stats.alive() == 2 del a assert stats.alive() == 1 del np assert stats.alive() == 0 b = m.TypeForHolderWithAddressOf.make() c = b assert b.get() is c.get() assert stats.alive() == 1 del b assert stats.alive() == 1 del c assert stats.alive() == 0 def test_move_only_holder_with_addressof_operator(): a = m.TypeForMoveOnlyHolderWithAddressOf.make() a.print_object() stats = ConstructorStats.get(m.TypeForMoveOnlyHolderWithAddressOf) assert stats.alive() == 1 a.value = 42 assert a.value == 42 del a assert stats.alive() == 0 def test_smart_ptr_from_default(): instance = m.HeldByDefaultHolder() with pytest.raises(RuntimeError) as excinfo: m.HeldByDefaultHolder.load_shared_ptr(instance) assert ( "Unable to load a custom holder type from a " "default-holder instance" in str(excinfo.value) ) def test_shared_ptr_gc(): """#187: issue involving std::shared_ptr<> return value policy & garbage collection""" el = m.ElementList() for i in range(10): el.add(m.ElementA(i)) pytest.gc_collect() for i, v in enumerate(el.get()): assert i == v.value()
Python
3D
mcellteam/mcell
libs/pybind11/tests/conftest.py
.py
4,841
209
# -*- coding: utf-8 -*- """pytest configuration Extends output capture as needed by pybind11: ignore constructors, optional unordered lines. Adds docstring and exceptions message sanitizers: ignore Python 2 vs 3 differences. """ import contextlib import difflib import gc import re import textwrap import pytest import env # Early diagnostic for failed imports import pybind11_tests # noqa: F401 _unicode_marker = re.compile(r"u(\'[^\']*\')") _long_marker = re.compile(r"([0-9])L") _hexadecimal = re.compile(r"0x[0-9a-fA-F]+") # Avoid collecting Python3 only files collect_ignore = [] if env.PY2: collect_ignore.append("test_async.py") def _strip_and_dedent(s): """For triple-quote strings""" return textwrap.dedent(s.lstrip("\n").rstrip()) def _split_and_sort(s): """For output which does not require specific line order""" return sorted(_strip_and_dedent(s).splitlines()) def _make_explanation(a, b): """Explanation for a failed assert -- the a and b arguments are List[str]""" return ["--- actual / +++ expected"] + [ line.strip("\n") for line in difflib.ndiff(a, b) ] class Output(object): """Basic output post-processing and comparison""" def __init__(self, string): self.string = string self.explanation = [] def __str__(self): return self.string def __eq__(self, other): # Ignore constructor/destructor output which is prefixed with "###" a = [ line for line in self.string.strip().splitlines() if not line.startswith("###") ] b = _strip_and_dedent(other).splitlines() if a == b: return True else: self.explanation = _make_explanation(a, b) return False class Unordered(Output): """Custom comparison for output without strict line ordering""" def __eq__(self, other): a = _split_and_sort(self.string) b = _split_and_sort(other) if a == b: return True else: self.explanation = _make_explanation(a, b) return False class Capture(object): def __init__(self, capfd): self.capfd = capfd self.out = "" self.err = "" def __enter__(self): self.capfd.readouterr() return self def __exit__(self, *args): self.out, self.err = self.capfd.readouterr() def __eq__(self, other): a = Output(self.out) b = other if a == b: return True else: self.explanation = a.explanation return False def __str__(self): return self.out def __contains__(self, item): return item in self.out @property def unordered(self): return Unordered(self.out) @property def stderr(self): return Output(self.err) @pytest.fixture def capture(capsys): """Extended `capsys` with context manager and custom equality operators""" return Capture(capsys) class SanitizedString(object): def __init__(self, sanitizer): self.sanitizer = sanitizer self.string = "" self.explanation = [] def __call__(self, thing): self.string = self.sanitizer(thing) return self def __eq__(self, other): a = self.string b = _strip_and_dedent(other) if a == b: return True else: self.explanation = _make_explanation(a.splitlines(), b.splitlines()) return False def _sanitize_general(s): s = s.strip() s = s.replace("pybind11_tests.", "m.") s = s.replace("unicode", "str") s = _long_marker.sub(r"\1", s) s = _unicode_marker.sub(r"\1", s) return s def _sanitize_docstring(thing): s = thing.__doc__ s = _sanitize_general(s) return s @pytest.fixture def doc(): """Sanitize docstrings and add custom failure explanation""" return SanitizedString(_sanitize_docstring) def _sanitize_message(thing): s = str(thing) s = _sanitize_general(s) s = _hexadecimal.sub("0", s) return s @pytest.fixture def msg(): """Sanitize messages and add custom failure explanation""" return SanitizedString(_sanitize_message) # noinspection PyUnusedLocal def pytest_assertrepr_compare(op, left, right): """Hook to insert custom failure explanation""" if hasattr(left, "explanation"): return left.explanation @contextlib.contextmanager def suppress(exception): """Suppress the desired exception""" try: yield except exception: pass def gc_collect(): """Run the garbage collector twice (needed when running reference counting tests with PyPy)""" gc.collect() gc.collect() def pytest_configure(): pytest.suppress = suppress pytest.gc_collect = gc_collect
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_smart_ptr.cpp
.cpp
19,040
475
/* tests/test_smart_ptr.cpp -- binding classes with custom reference counting, implicit conversions between types Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #if defined(_MSC_VER) && _MSC_VER < 1910 // VS 2015's MSVC # pragma warning(disable : 4702) // unreachable code in system header (xatomic.h(382)) #endif #include "object.h" #include "pybind11_tests.h" namespace { // This is just a wrapper around unique_ptr, but with extra fields to deliberately bloat up the // holder size to trigger the non-simple-layout internal instance layout for single inheritance // with large holder type: template <typename T> class huge_unique_ptr { std::unique_ptr<T> ptr; uint64_t padding[10]; public: explicit huge_unique_ptr(T *p) : ptr(p) {} T *get() { return ptr.get(); } }; // Simple custom holder that works like unique_ptr template <typename T> class custom_unique_ptr { std::unique_ptr<T> impl; public: explicit custom_unique_ptr(T *p) : impl(p) {} T *get() const { return impl.get(); } T *release_ptr() { return impl.release(); } }; // Simple custom holder that works like shared_ptr and has operator& overload // To obtain address of an instance of this holder pybind should use std::addressof // Attempt to get address via operator& may leads to segmentation fault template <typename T> class shared_ptr_with_addressof_operator { std::shared_ptr<T> impl; public: shared_ptr_with_addressof_operator() = default; explicit shared_ptr_with_addressof_operator(T *p) : impl(p) {} T *get() const { return impl.get(); } T **operator&() { throw std::logic_error("Call of overloaded operator& is not expected"); } }; // Simple custom holder that works like unique_ptr and has operator& overload // To obtain address of an instance of this holder pybind should use std::addressof // Attempt to get address via operator& may leads to segmentation fault template <typename T> class unique_ptr_with_addressof_operator { std::unique_ptr<T> impl; public: unique_ptr_with_addressof_operator() = default; explicit unique_ptr_with_addressof_operator(T *p) : impl(p) {} T *get() const { return impl.get(); } T *release_ptr() { return impl.release(); } T **operator&() { throw std::logic_error("Call of overloaded operator& is not expected"); } }; // Custom object with builtin reference counting (see 'object.h' for the implementation) class MyObject1 : public Object { public: explicit MyObject1(int value) : value(value) { print_created(this, toString()); } std::string toString() const override { return "MyObject1[" + std::to_string(value) + "]"; } protected: ~MyObject1() override { print_destroyed(this); } private: int value; }; // Object managed by a std::shared_ptr<> class MyObject2 { public: MyObject2(const MyObject2 &) = default; explicit MyObject2(int value) : value(value) { print_created(this, toString()); } std::string toString() const { return "MyObject2[" + std::to_string(value) + "]"; } virtual ~MyObject2() { print_destroyed(this); } private: int value; }; // Object managed by a std::shared_ptr<>, additionally derives from std::enable_shared_from_this<> class MyObject3 : public std::enable_shared_from_this<MyObject3> { public: MyObject3(const MyObject3 &) = default; explicit MyObject3(int value) : value(value) { print_created(this, toString()); } std::string toString() const { return "MyObject3[" + std::to_string(value) + "]"; } virtual ~MyObject3() { print_destroyed(this); } private: int value; }; // test_unique_nodelete // Object with a private destructor class MyObject4; std::unordered_set<MyObject4 *> myobject4_instances; class MyObject4 { public: explicit MyObject4(int value) : value{value} { print_created(this); myobject4_instances.insert(this); } int value; static void cleanupAllInstances() { auto tmp = std::move(myobject4_instances); myobject4_instances.clear(); for (auto *o : tmp) { delete o; } } private: ~MyObject4() { myobject4_instances.erase(this); print_destroyed(this); } }; // test_unique_deleter // Object with std::unique_ptr<T, D> where D is not matching the base class // Object with a protected destructor class MyObject4a; std::unordered_set<MyObject4a *> myobject4a_instances; class MyObject4a { public: explicit MyObject4a(int i) : value{i} { print_created(this); myobject4a_instances.insert(this); }; int value; static void cleanupAllInstances() { auto tmp = std::move(myobject4a_instances); myobject4a_instances.clear(); for (auto *o : tmp) { delete o; } } protected: virtual ~MyObject4a() { myobject4a_instances.erase(this); print_destroyed(this); } }; // Object derived but with public destructor and no Deleter in default holder class MyObject4b : public MyObject4a { public: explicit MyObject4b(int i) : MyObject4a(i) { print_created(this); } ~MyObject4b() override { print_destroyed(this); } }; // test_large_holder class MyObject5 { // managed by huge_unique_ptr public: explicit MyObject5(int value) : value{value} { print_created(this); } ~MyObject5() { print_destroyed(this); } int value; }; // test_shared_ptr_and_references struct SharedPtrRef { struct A { A() { print_created(this); } A(const A &) { print_copy_created(this); } A(A &&) noexcept { print_move_created(this); } ~A() { print_destroyed(this); } }; A value = {}; std::shared_ptr<A> shared = std::make_shared<A>(); }; // test_shared_ptr_from_this_and_references struct SharedFromThisRef { struct B : std::enable_shared_from_this<B> { B() { print_created(this); } // NOLINTNEXTLINE(bugprone-copy-constructor-init) B(const B &) : std::enable_shared_from_this<B>() { print_copy_created(this); } B(B &&) noexcept : std::enable_shared_from_this<B>() { print_move_created(this); } ~B() { print_destroyed(this); } }; B value = {}; std::shared_ptr<B> shared = std::make_shared<B>(); }; // Issue #865: shared_from_this doesn't work with virtual inheritance struct SharedFromThisVBase : std::enable_shared_from_this<SharedFromThisVBase> { SharedFromThisVBase() = default; SharedFromThisVBase(const SharedFromThisVBase &) = default; virtual ~SharedFromThisVBase() = default; }; struct SharedFromThisVirt : virtual SharedFromThisVBase {}; // test_move_only_holder struct C { C() { print_created(this); } ~C() { print_destroyed(this); } }; // test_holder_with_addressof_operator struct TypeForHolderWithAddressOf { TypeForHolderWithAddressOf() { print_created(this); } TypeForHolderWithAddressOf(const TypeForHolderWithAddressOf &) { print_copy_created(this); } TypeForHolderWithAddressOf(TypeForHolderWithAddressOf &&) noexcept { print_move_created(this); } ~TypeForHolderWithAddressOf() { print_destroyed(this); } std::string toString() const { return "TypeForHolderWithAddressOf[" + std::to_string(value) + "]"; } int value = 42; }; // test_move_only_holder_with_addressof_operator struct TypeForMoveOnlyHolderWithAddressOf { explicit TypeForMoveOnlyHolderWithAddressOf(int value) : value{value} { print_created(this); } ~TypeForMoveOnlyHolderWithAddressOf() { print_destroyed(this); } std::string toString() const { return "MoveOnlyHolderWithAddressOf[" + std::to_string(value) + "]"; } int value; }; // test_smart_ptr_from_default struct HeldByDefaultHolder {}; // test_shared_ptr_gc // #187: issue involving std::shared_ptr<> return value policy & garbage collection struct ElementBase { virtual ~ElementBase() = default; /* Force creation of virtual table */ ElementBase() = default; ElementBase(const ElementBase &) = delete; }; struct ElementA : ElementBase { explicit ElementA(int v) : v(v) {} int value() const { return v; } int v; }; struct ElementList { void add(const std::shared_ptr<ElementBase> &e) { l.push_back(e); } std::vector<std::shared_ptr<ElementBase>> l; }; } // namespace // ref<T> is a wrapper for 'Object' which uses intrusive reference counting // It is always possible to construct a ref<T> from an Object* pointer without // possible inconsistencies, hence the 'true' argument at the end. // Make pybind11 aware of the non-standard getter member function namespace pybind11 { namespace detail { template <typename T> struct holder_helper<ref<T>> { static const T *get(const ref<T> &p) { return p.get_ptr(); } }; } // namespace detail } // namespace pybind11 // Make pybind aware of the ref-counted wrapper type (s): PYBIND11_DECLARE_HOLDER_TYPE(T, ref<T>, true); // The following is not required anymore for std::shared_ptr, but it should compile without error: PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>); PYBIND11_DECLARE_HOLDER_TYPE(T, huge_unique_ptr<T>); PYBIND11_DECLARE_HOLDER_TYPE(T, custom_unique_ptr<T>); PYBIND11_DECLARE_HOLDER_TYPE(T, shared_ptr_with_addressof_operator<T>); PYBIND11_DECLARE_HOLDER_TYPE(T, unique_ptr_with_addressof_operator<T>); TEST_SUBMODULE(smart_ptr, m) { // Please do not interleave `struct` and `class` definitions with bindings code, // but implement `struct`s and `class`es in the anonymous namespace above. // This helps keeping the smart_holder branch in sync with master. // test_smart_ptr // Object implementation in `object.h` py::class_<Object, ref<Object>> obj(m, "Object"); obj.def("getRefCount", &Object::getRefCount); py::class_<MyObject1, ref<MyObject1>>(m, "MyObject1", obj).def(py::init<int>()); py::implicitly_convertible<py::int_, MyObject1>(); m.def("make_object_1", []() -> Object * { return new MyObject1(1); }); m.def("make_object_2", []() -> ref<Object> { return ref<Object>(new MyObject1(2)); }); m.def("make_myobject1_1", []() -> MyObject1 * { return new MyObject1(4); }); m.def("make_myobject1_2", []() -> ref<MyObject1> { return ref<MyObject1>(new MyObject1(5)); }); m.def("print_object_1", [](const Object *obj) { py::print(obj->toString()); }); m.def("print_object_2", [](ref<Object> obj) { py::print(obj->toString()); }); m.def("print_object_3", [](const ref<Object> &obj) { py::print(obj->toString()); }); m.def("print_object_4", [](const ref<Object> *obj) { py::print((*obj)->toString()); }); m.def("print_myobject1_1", [](const MyObject1 *obj) { py::print(obj->toString()); }); m.def("print_myobject1_2", [](ref<MyObject1> obj) { py::print(obj->toString()); }); m.def("print_myobject1_3", [](const ref<MyObject1> &obj) { py::print(obj->toString()); }); m.def("print_myobject1_4", [](const ref<MyObject1> *obj) { py::print((*obj)->toString()); }); // Expose constructor stats for the ref type m.def("cstats_ref", &ConstructorStats::get<ref_tag>); py::class_<MyObject2, std::shared_ptr<MyObject2>>(m, "MyObject2").def(py::init<int>()); m.def("make_myobject2_1", []() { return new MyObject2(6); }); m.def("make_myobject2_2", []() { return std::make_shared<MyObject2>(7); }); m.def("print_myobject2_1", [](const MyObject2 *obj) { py::print(obj->toString()); }); // NOLINTNEXTLINE(performance-unnecessary-value-param) m.def("print_myobject2_2", [](std::shared_ptr<MyObject2> obj) { py::print(obj->toString()); }); m.def("print_myobject2_3", [](const std::shared_ptr<MyObject2> &obj) { py::print(obj->toString()); }); m.def("print_myobject2_4", [](const std::shared_ptr<MyObject2> *obj) { py::print((*obj)->toString()); }); py::class_<MyObject3, std::shared_ptr<MyObject3>>(m, "MyObject3").def(py::init<int>()); m.def("make_myobject3_1", []() { return new MyObject3(8); }); m.def("make_myobject3_2", []() { return std::make_shared<MyObject3>(9); }); m.def("print_myobject3_1", [](const MyObject3 *obj) { py::print(obj->toString()); }); // NOLINTNEXTLINE(performance-unnecessary-value-param) m.def("print_myobject3_2", [](std::shared_ptr<MyObject3> obj) { py::print(obj->toString()); }); m.def("print_myobject3_3", [](const std::shared_ptr<MyObject3> &obj) { py::print(obj->toString()); }); m.def("print_myobject3_4", [](const std::shared_ptr<MyObject3> *obj) { py::print((*obj)->toString()); }); // test_smart_ptr_refcounting m.def("test_object1_refcounting", []() { auto o = ref<MyObject1>(new MyObject1(0)); bool good = o->getRefCount() == 1; py::object o2 = py::cast(o, py::return_value_policy::reference); // always request (partial) ownership for objects with intrusive // reference counting even when using the 'reference' RVP good &= o->getRefCount() == 2; return good; }); // test_unique_nodelete py::class_<MyObject4, std::unique_ptr<MyObject4, py::nodelete>>(m, "MyObject4") .def(py::init<int>()) .def_readwrite("value", &MyObject4::value) .def_static("cleanup_all_instances", &MyObject4::cleanupAllInstances); // test_unique_deleter py::class_<MyObject4a, std::unique_ptr<MyObject4a, py::nodelete>>(m, "MyObject4a") .def(py::init<int>()) .def_readwrite("value", &MyObject4a::value) .def_static("cleanup_all_instances", &MyObject4a::cleanupAllInstances); py::class_<MyObject4b, MyObject4a, std::unique_ptr<MyObject4b>>(m, "MyObject4b") .def(py::init<int>()); // test_large_holder py::class_<MyObject5, huge_unique_ptr<MyObject5>>(m, "MyObject5") .def(py::init<int>()) .def_readwrite("value", &MyObject5::value); // test_shared_ptr_and_references using A = SharedPtrRef::A; py::class_<A, std::shared_ptr<A>>(m, "A"); py::class_<SharedPtrRef, std::unique_ptr<SharedPtrRef>>(m, "SharedPtrRef") .def(py::init<>()) .def_readonly("ref", &SharedPtrRef::value) .def_property_readonly( "copy", [](const SharedPtrRef &s) { return s.value; }, py::return_value_policy::copy) .def_readonly("holder_ref", &SharedPtrRef::shared) .def_property_readonly( "holder_copy", [](const SharedPtrRef &s) { return s.shared; }, py::return_value_policy::copy) .def("set_ref", [](SharedPtrRef &, const A &) { return true; }) // NOLINTNEXTLINE(performance-unnecessary-value-param) .def("set_holder", [](SharedPtrRef &, std::shared_ptr<A>) { return true; }); // test_shared_ptr_from_this_and_references using B = SharedFromThisRef::B; py::class_<B, std::shared_ptr<B>>(m, "B"); py::class_<SharedFromThisRef, std::unique_ptr<SharedFromThisRef>>(m, "SharedFromThisRef") .def(py::init<>()) .def_readonly("bad_wp", &SharedFromThisRef::value) .def_property_readonly("ref", [](const SharedFromThisRef &s) -> const B & { return *s.shared; }) .def_property_readonly( "copy", [](const SharedFromThisRef &s) { return s.value; }, py::return_value_policy::copy) .def_readonly("holder_ref", &SharedFromThisRef::shared) .def_property_readonly( "holder_copy", [](const SharedFromThisRef &s) { return s.shared; }, py::return_value_policy::copy) .def("set_ref", [](SharedFromThisRef &, const B &) { return true; }) // NOLINTNEXTLINE(performance-unnecessary-value-param) .def("set_holder", [](SharedFromThisRef &, std::shared_ptr<B>) { return true; }); // Issue #865: shared_from_this doesn't work with virtual inheritance static std::shared_ptr<SharedFromThisVirt> sft(new SharedFromThisVirt()); py::class_<SharedFromThisVirt, std::shared_ptr<SharedFromThisVirt>>(m, "SharedFromThisVirt") .def_static("get", []() { return sft.get(); }); // test_move_only_holder py::class_<C, custom_unique_ptr<C>>(m, "TypeWithMoveOnlyHolder") .def_static("make", []() { return custom_unique_ptr<C>(new C); }) .def_static("make_as_object", []() { return py::cast(custom_unique_ptr<C>(new C)); }); // test_holder_with_addressof_operator using HolderWithAddressOf = shared_ptr_with_addressof_operator<TypeForHolderWithAddressOf>; py::class_<TypeForHolderWithAddressOf, HolderWithAddressOf>(m, "TypeForHolderWithAddressOf") .def_static("make", []() { return HolderWithAddressOf(new TypeForHolderWithAddressOf); }) .def("get", [](const HolderWithAddressOf &self) { return self.get(); }) .def("print_object_1", [](const TypeForHolderWithAddressOf *obj) { py::print(obj->toString()); }) // NOLINTNEXTLINE(performance-unnecessary-value-param) .def("print_object_2", [](HolderWithAddressOf obj) { py::print(obj.get()->toString()); }) .def("print_object_3", [](const HolderWithAddressOf &obj) { py::print(obj.get()->toString()); }) .def("print_object_4", [](const HolderWithAddressOf *obj) { py::print((*obj).get()->toString()); }); // test_move_only_holder_with_addressof_operator using MoveOnlyHolderWithAddressOf = unique_ptr_with_addressof_operator<TypeForMoveOnlyHolderWithAddressOf>; py::class_<TypeForMoveOnlyHolderWithAddressOf, MoveOnlyHolderWithAddressOf>( m, "TypeForMoveOnlyHolderWithAddressOf") .def_static("make", []() { return MoveOnlyHolderWithAddressOf( new TypeForMoveOnlyHolderWithAddressOf(0)); }) .def_readwrite("value", &TypeForMoveOnlyHolderWithAddressOf::value) .def("print_object", [](const TypeForMoveOnlyHolderWithAddressOf *obj) { py::print(obj->toString()); }); // test_smart_ptr_from_default py::class_<HeldByDefaultHolder, std::unique_ptr<HeldByDefaultHolder>>(m, "HeldByDefaultHolder") .def(py::init<>()) // NOLINTNEXTLINE(performance-unnecessary-value-param) .def_static("load_shared_ptr", [](std::shared_ptr<HeldByDefaultHolder>) {}); // test_shared_ptr_gc // #187: issue involving std::shared_ptr<> return value policy & garbage collection py::class_<ElementBase, std::shared_ptr<ElementBase>>(m, "ElementBase"); py::class_<ElementA, ElementBase, std::shared_ptr<ElementA>>(m, "ElementA") .def(py::init<int>()) .def("value", &ElementA::value); py::class_<ElementList, std::shared_ptr<ElementList>>(m, "ElementList") .def(py::init<>()) .def("add", &ElementList::add) .def("get", [](ElementList &el) { py::list list; for (auto &e : el.l) { list.append(py::cast(e)); } return list; }); }
C++
3D
mcellteam/mcell
libs/pybind11/tests/pybind11_tests.cpp
.cpp
3,686
93
/* tests/pybind11_tests.cpp -- pybind example plugin Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> 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 "constructor_stats.h" #include <functional> #include <list> /* For testing purposes, we define a static global variable here in a function that each individual test .cpp calls with its initialization lambda. It's convenient here because we can just not compile some test files to disable/ignore some of the test code. It is NOT recommended as a way to use pybind11 in practice, however: the initialization order will be essentially random, which is okay for our test scripts (there are no dependencies between the individual pybind11 test .cpp files), but most likely not what you want when using pybind11 productively. Instead, see the "How can I reduce the build time?" question in the "Frequently asked questions" section of the documentation for good practice on splitting binding code over multiple files. */ std::list<std::function<void(py::module_ &)>> &initializers() { static std::list<std::function<void(py::module_ &)>> inits; return inits; } test_initializer::test_initializer(Initializer init) { initializers().emplace_back(init); } test_initializer::test_initializer(const char *submodule_name, Initializer init) { initializers().emplace_back([=](py::module_ &parent) { auto m = parent.def_submodule(submodule_name); init(m); }); } void bind_ConstructorStats(py::module_ &m) { py::class_<ConstructorStats>(m, "ConstructorStats") .def("alive", &ConstructorStats::alive) .def("values", &ConstructorStats::values) .def_readwrite("default_constructions", &ConstructorStats::default_constructions) .def_readwrite("copy_assignments", &ConstructorStats::copy_assignments) .def_readwrite("move_assignments", &ConstructorStats::move_assignments) .def_readwrite("copy_constructions", &ConstructorStats::copy_constructions) .def_readwrite("move_constructions", &ConstructorStats::move_constructions) .def_static("get", (ConstructorStats & (*) (py::object)) & ConstructorStats::get, py::return_value_policy::reference_internal) // Not exactly ConstructorStats, but related: expose the internal pybind number of // registered instances to allow instance cleanup checks (invokes a GC first) .def_static("detail_reg_inst", []() { ConstructorStats::gc(); return py::detail::get_internals().registered_instances.size(); }); } PYBIND11_MODULE(pybind11_tests, m) { m.doc() = "pybind11 test module"; bind_ConstructorStats(m); #if !defined(NDEBUG) m.attr("debug_enabled") = true; #else m.attr("debug_enabled") = false; #endif py::class_<UserType>(m, "UserType", "A `py::class_` type for testing") .def(py::init<>()) .def(py::init<int>()) .def("get_value", &UserType::value, "Get value using a method") .def("set_value", &UserType::set, "Set value using a method") .def_property("value", &UserType::value, &UserType::set, "Get/set value using a property") .def("__repr__", [](const UserType &u) { return "UserType({})"_s.format(u.value()); }); py::class_<IncType, UserType>(m, "IncType") .def(py::init<>()) .def(py::init<int>()) .def("__repr__", [](const IncType &u) { return "IncType({})"_s.format(u.value()); }); for (const auto &initializer : initializers()) { initializer(m); } }
C++
3D
mcellteam/mcell
libs/pybind11/tests/test_custom_type_setup.py
.py
1,114
51
# -*- coding: utf-8 -*- import gc import weakref import pytest import env # noqa: F401 from pybind11_tests import custom_type_setup as m @pytest.fixture def gc_tester(): """Tests that an object is garbage collected. Assumes that any unreferenced objects are fully collected after calling `gc.collect()`. That is true on CPython, but does not appear to reliably hold on PyPy. """ weak_refs = [] def add_ref(obj): # PyPy does not support `gc.is_tracked`. if hasattr(gc, "is_tracked"): assert gc.is_tracked(obj) weak_refs.append(weakref.ref(obj)) yield add_ref gc.collect() for ref in weak_refs: assert ref() is None # PyPy does not seem to reliably garbage collect. @pytest.mark.skipif("env.PYPY") def test_self_cycle(gc_tester): obj = m.OwnsPythonObjects() obj.value = obj gc_tester(obj) # PyPy does not seem to reliably garbage collect. @pytest.mark.skipif("env.PYPY") def test_indirect_cycle(gc_tester): obj = m.OwnsPythonObjects() obj_list = [obj] obj.value = obj_list gc_tester(obj)
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_gil_scoped.cpp
.cpp
1,673
48
/* tests/test_gil_scoped.cpp -- acquire and release gil Copyright (c) 2017 Borja Zarco (Google LLC) <bzarco@google.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/functional.h> #include "pybind11_tests.h" class VirtClass { public: virtual ~VirtClass() = default; VirtClass() = default; VirtClass(const VirtClass &) = delete; virtual void virtual_func() {} virtual void pure_virtual_func() = 0; }; class PyVirtClass : public VirtClass { void virtual_func() override { PYBIND11_OVERRIDE(void, VirtClass, virtual_func, ); } void pure_virtual_func() override { PYBIND11_OVERRIDE_PURE(void, VirtClass, pure_virtual_func, ); } }; TEST_SUBMODULE(gil_scoped, m) { py::class_<VirtClass, PyVirtClass>(m, "VirtClass") .def(py::init<>()) .def("virtual_func", &VirtClass::virtual_func) .def("pure_virtual_func", &VirtClass::pure_virtual_func); m.def("test_callback_py_obj", [](py::object &func) { func(); }); m.def("test_callback_std_func", [](const std::function<void()> &func) { func(); }); m.def("test_callback_virtual_func", [](VirtClass &virt) { virt.virtual_func(); }); m.def("test_callback_pure_virtual_func", [](VirtClass &virt) { virt.pure_virtual_func(); }); m.def("test_cross_module_gil", []() { auto cm = py::module_::import("cross_module_gil_utils"); auto gil_acquire = reinterpret_cast<void (*)()>( PyLong_AsVoidPtr(cm.attr("gil_acquire_funcaddr").ptr())); py::gil_scoped_release gil_release; gil_acquire(); }); }
C++
3D
mcellteam/mcell
libs/pybind11/tests/test_operator_overloading.py
.py
4,392
156
# -*- coding: utf-8 -*- import pytest import env from pybind11_tests import ConstructorStats from pybind11_tests import operators as m def test_operator_overloading(): v1 = m.Vector2(1, 2) v2 = m.Vector(3, -1) v3 = m.Vector2(1, 2) # Same value as v1, but different instance. assert v1 is not v3 assert str(v1) == "[1.000000, 2.000000]" assert str(v2) == "[3.000000, -1.000000]" assert str(-v2) == "[-3.000000, 1.000000]" assert str(v1 + v2) == "[4.000000, 1.000000]" assert str(v1 - v2) == "[-2.000000, 3.000000]" assert str(v1 - 8) == "[-7.000000, -6.000000]" assert str(v1 + 8) == "[9.000000, 10.000000]" assert str(v1 * 8) == "[8.000000, 16.000000]" assert str(v1 / 8) == "[0.125000, 0.250000]" assert str(8 - v1) == "[7.000000, 6.000000]" assert str(8 + v1) == "[9.000000, 10.000000]" assert str(8 * v1) == "[8.000000, 16.000000]" assert str(8 / v1) == "[8.000000, 4.000000]" assert str(v1 * v2) == "[3.000000, -2.000000]" assert str(v2 / v1) == "[3.000000, -0.500000]" assert v1 == v3 assert v1 != v2 assert hash(v1) == 4 # TODO(eric.cousineau): Make this work. # assert abs(v1) == "abs(Vector2)" v1 += 2 * v2 assert str(v1) == "[7.000000, 0.000000]" v1 -= v2 assert str(v1) == "[4.000000, 1.000000]" v1 *= 2 assert str(v1) == "[8.000000, 2.000000]" v1 /= 16 assert str(v1) == "[0.500000, 0.125000]" v1 *= v2 assert str(v1) == "[1.500000, -0.125000]" v2 /= v1 assert str(v2) == "[2.000000, 8.000000]" cstats = ConstructorStats.get(m.Vector2) assert cstats.alive() == 3 del v1 assert cstats.alive() == 2 del v2 assert cstats.alive() == 1 del v3 assert cstats.alive() == 0 assert cstats.values() == [ "[1.000000, 2.000000]", "[3.000000, -1.000000]", "[1.000000, 2.000000]", "[-3.000000, 1.000000]", "[4.000000, 1.000000]", "[-2.000000, 3.000000]", "[-7.000000, -6.000000]", "[9.000000, 10.000000]", "[8.000000, 16.000000]", "[0.125000, 0.250000]", "[7.000000, 6.000000]", "[9.000000, 10.000000]", "[8.000000, 16.000000]", "[8.000000, 4.000000]", "[3.000000, -2.000000]", "[3.000000, -0.500000]", "[6.000000, -2.000000]", ] assert cstats.default_constructions == 0 assert cstats.copy_constructions == 0 assert cstats.move_constructions >= 10 assert cstats.copy_assignments == 0 assert cstats.move_assignments == 0 def test_operators_notimplemented(): """#393: need to return NotSupported to ensure correct arithmetic operator behavior""" c1, c2 = m.C1(), m.C2() assert c1 + c1 == 11 assert c2 + c2 == 22 assert c2 + c1 == 21 assert c1 + c2 == 12 def test_nested(): """#328: first member in a class can't be used in operators""" a = m.NestA() b = m.NestB() c = m.NestC() a += 10 assert m.get_NestA(a) == 13 b.a += 100 assert m.get_NestA(b.a) == 103 c.b.a += 1000 assert m.get_NestA(c.b.a) == 1003 b -= 1 assert m.get_NestB(b) == 3 c.b -= 3 assert m.get_NestB(c.b) == 1 c *= 7 assert m.get_NestC(c) == 35 abase = a.as_base() assert abase.value == -2 a.as_base().value += 44 assert abase.value == 42 assert c.b.a.as_base().value == -2 c.b.a.as_base().value += 44 assert c.b.a.as_base().value == 42 del c pytest.gc_collect() del a # Shouldn't delete while abase is still alive pytest.gc_collect() assert abase.value == 42 del abase, b pytest.gc_collect() def test_overriding_eq_reset_hash(): assert m.Comparable(15) is not m.Comparable(15) assert m.Comparable(15) == m.Comparable(15) with pytest.raises(TypeError) as excinfo: hash(m.Comparable(15)) assert str(excinfo.value).startswith("unhashable type:") for hashable in (m.Hashable, m.Hashable2): assert hashable(15) is not hashable(15) assert hashable(15) == hashable(15) assert hash(hashable(15)) == 15 assert hash(hashable(15)) == hash(hashable(15)) def test_return_set_of_unhashable(): with pytest.raises(TypeError) as excinfo: m.get_unhashable_HashMe_set() if not env.PY2: assert str(excinfo.value.__cause__).startswith("unhashable type:")
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_call_policies.cpp
.cpp
4,118
116
/* tests/test_call_policies.cpp -- keep_alive and call_guard Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> 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" struct CustomGuard { static bool enabled; CustomGuard() { enabled = true; } ~CustomGuard() { enabled = false; } static const char *report_status() { return enabled ? "guarded" : "unguarded"; } }; bool CustomGuard::enabled = false; struct DependentGuard { static bool enabled; DependentGuard() { enabled = CustomGuard::enabled; } ~DependentGuard() { enabled = false; } static const char *report_status() { return enabled ? "guarded" : "unguarded"; } }; bool DependentGuard::enabled = false; TEST_SUBMODULE(call_policies, m) { // Parent/Child are used in: // test_keep_alive_argument, test_keep_alive_return_value, test_alive_gc_derived, // test_alive_gc_multi_derived, test_return_none, test_keep_alive_constructor class Child { public: Child() { py::print("Allocating child."); } Child(const Child &) = default; Child(Child &&) = default; ~Child() { py::print("Releasing child."); } }; py::class_<Child>(m, "Child").def(py::init<>()); class Parent { public: Parent() { py::print("Allocating parent."); } Parent(const Parent &parent) = default; ~Parent() { py::print("Releasing parent."); } void addChild(Child *) {} Child *returnChild() { return new Child(); } Child *returnNullChild() { return nullptr; } static Child *staticFunction(Parent *) { return new Child(); } }; py::class_<Parent>(m, "Parent") .def(py::init<>()) .def(py::init([](Child *) { return new Parent(); }), py::keep_alive<1, 2>()) .def("addChild", &Parent::addChild) .def("addChildKeepAlive", &Parent::addChild, py::keep_alive<1, 2>()) .def("returnChild", &Parent::returnChild) .def("returnChildKeepAlive", &Parent::returnChild, py::keep_alive<1, 0>()) .def("returnNullChildKeepAliveChild", &Parent::returnNullChild, py::keep_alive<1, 0>()) .def("returnNullChildKeepAliveParent", &Parent::returnNullChild, py::keep_alive<0, 1>()) .def_static("staticFunction", &Parent::staticFunction, py::keep_alive<1, 0>()); m.def( "free_function", [](Parent *, Child *) {}, py::keep_alive<1, 2>()); m.def( "invalid_arg_index", [] {}, py::keep_alive<0, 1>()); #if !defined(PYPY_VERSION) // test_alive_gc class ParentGC : public Parent { public: using Parent::Parent; }; py::class_<ParentGC, Parent>(m, "ParentGC", py::dynamic_attr()).def(py::init<>()); #endif // test_call_guard m.def("unguarded_call", &CustomGuard::report_status); m.def("guarded_call", &CustomGuard::report_status, py::call_guard<CustomGuard>()); m.def( "multiple_guards_correct_order", []() { return CustomGuard::report_status() + std::string(" & ") + DependentGuard::report_status(); }, py::call_guard<CustomGuard, DependentGuard>()); m.def( "multiple_guards_wrong_order", []() { return DependentGuard::report_status() + std::string(" & ") + CustomGuard::report_status(); }, py::call_guard<DependentGuard, CustomGuard>()); #if defined(WITH_THREAD) && !defined(PYPY_VERSION) // `py::call_guard<py::gil_scoped_release>()` should work in PyPy as well, // but it's unclear how to test it without `PyGILState_GetThisThreadState`. auto report_gil_status = []() { auto is_gil_held = false; if (auto *tstate = py::detail::get_thread_state_unchecked()) { is_gil_held = (tstate == PyGILState_GetThisThreadState()); } return is_gil_held ? "GIL held" : "GIL released"; }; m.def("with_gil", report_gil_status); m.def("without_gil", report_gil_status, py::call_guard<py::gil_scoped_release>()); #endif }
C++
3D
mcellteam/mcell
libs/pybind11/tests/test_stl.py
.py
11,662
359
# -*- coding: utf-8 -*- import pytest from pybind11_tests import ConstructorStats, UserType from pybind11_tests import stl as m def test_vector(doc): """std::vector <-> list""" lst = m.cast_vector() assert lst == [1] lst.append(2) assert m.load_vector(lst) assert m.load_vector(tuple(lst)) assert m.cast_bool_vector() == [True, False] assert m.load_bool_vector([True, False]) assert doc(m.cast_vector) == "cast_vector() -> List[int]" assert doc(m.load_vector) == "load_vector(arg0: List[int]) -> bool" # Test regression caused by 936: pointers to stl containers weren't castable assert m.cast_ptr_vector() == ["lvalue", "lvalue"] def test_deque(doc): """std::deque <-> list""" lst = m.cast_deque() assert lst == [1] lst.append(2) assert m.load_deque(lst) assert m.load_deque(tuple(lst)) def test_array(doc): """std::array <-> list""" lst = m.cast_array() assert lst == [1, 2] assert m.load_array(lst) assert doc(m.cast_array) == "cast_array() -> List[int[2]]" assert doc(m.load_array) == "load_array(arg0: List[int[2]]) -> bool" def test_valarray(doc): """std::valarray <-> list""" lst = m.cast_valarray() assert lst == [1, 4, 9] assert m.load_valarray(lst) assert doc(m.cast_valarray) == "cast_valarray() -> List[int]" assert doc(m.load_valarray) == "load_valarray(arg0: List[int]) -> bool" def test_map(doc): """std::map <-> dict""" d = m.cast_map() assert d == {"key": "value"} assert "key" in d d["key2"] = "value2" assert "key2" in d assert m.load_map(d) assert doc(m.cast_map) == "cast_map() -> Dict[str, str]" assert doc(m.load_map) == "load_map(arg0: Dict[str, str]) -> bool" def test_set(doc): """std::set <-> set""" s = m.cast_set() assert s == {"key1", "key2"} s.add("key3") assert m.load_set(s) assert doc(m.cast_set) == "cast_set() -> Set[str]" assert doc(m.load_set) == "load_set(arg0: Set[str]) -> bool" def test_recursive_casting(): """Tests that stl casters preserve lvalue/rvalue context for container values""" assert m.cast_rv_vector() == ["rvalue", "rvalue"] assert m.cast_lv_vector() == ["lvalue", "lvalue"] assert m.cast_rv_array() == ["rvalue", "rvalue", "rvalue"] assert m.cast_lv_array() == ["lvalue", "lvalue"] assert m.cast_rv_map() == {"a": "rvalue"} assert m.cast_lv_map() == {"a": "lvalue", "b": "lvalue"} assert m.cast_rv_nested() == [[[{"b": "rvalue", "c": "rvalue"}], [{"a": "rvalue"}]]] assert m.cast_lv_nested() == { "a": [[["lvalue", "lvalue"]], [["lvalue", "lvalue"]]], "b": [[["lvalue", "lvalue"], ["lvalue", "lvalue"]]], } # Issue #853 test case: z = m.cast_unique_ptr_vector() assert z[0].value == 7 and z[1].value == 42 def test_move_out_container(): """Properties use the `reference_internal` policy by default. If the underlying function returns an rvalue, the policy is automatically changed to `move` to avoid referencing a temporary. In case the return value is a container of user-defined types, the policy also needs to be applied to the elements, not just the container.""" c = m.MoveOutContainer() moved_out_list = c.move_list assert [x.value for x in moved_out_list] == [0, 1, 2] @pytest.mark.skipif(not hasattr(m, "has_optional"), reason="no <optional>") def test_optional(): assert m.double_or_zero(None) == 0 assert m.double_or_zero(42) == 84 pytest.raises(TypeError, m.double_or_zero, "foo") assert m.half_or_none(0) is None assert m.half_or_none(42) == 21 pytest.raises(TypeError, m.half_or_none, "foo") assert m.test_nullopt() == 42 assert m.test_nullopt(None) == 42 assert m.test_nullopt(42) == 42 assert m.test_nullopt(43) == 43 assert m.test_no_assign() == 42 assert m.test_no_assign(None) == 42 assert m.test_no_assign(m.NoAssign(43)) == 43 pytest.raises(TypeError, m.test_no_assign, 43) assert m.nodefer_none_optional(None) holder = m.OptionalHolder() mvalue = holder.member assert mvalue.initialized assert holder.member_initialized() props = m.OptionalProperties() assert int(props.access_by_ref) == 42 assert int(props.access_by_copy) == 42 @pytest.mark.skipif( not hasattr(m, "has_exp_optional"), reason="no <experimental/optional>" ) def test_exp_optional(): assert m.double_or_zero_exp(None) == 0 assert m.double_or_zero_exp(42) == 84 pytest.raises(TypeError, m.double_or_zero_exp, "foo") assert m.half_or_none_exp(0) is None assert m.half_or_none_exp(42) == 21 pytest.raises(TypeError, m.half_or_none_exp, "foo") assert m.test_nullopt_exp() == 42 assert m.test_nullopt_exp(None) == 42 assert m.test_nullopt_exp(42) == 42 assert m.test_nullopt_exp(43) == 43 assert m.test_no_assign_exp() == 42 assert m.test_no_assign_exp(None) == 42 assert m.test_no_assign_exp(m.NoAssign(43)) == 43 pytest.raises(TypeError, m.test_no_assign_exp, 43) holder = m.OptionalExpHolder() mvalue = holder.member assert mvalue.initialized assert holder.member_initialized() props = m.OptionalExpProperties() assert int(props.access_by_ref) == 42 assert int(props.access_by_copy) == 42 @pytest.mark.skipif(not hasattr(m, "has_boost_optional"), reason="no <boost/optional>") def test_boost_optional(): assert m.double_or_zero_boost(None) == 0 assert m.double_or_zero_boost(42) == 84 pytest.raises(TypeError, m.double_or_zero_boost, "foo") assert m.half_or_none_boost(0) is None assert m.half_or_none_boost(42) == 21 pytest.raises(TypeError, m.half_or_none_boost, "foo") assert m.test_nullopt_boost() == 42 assert m.test_nullopt_boost(None) == 42 assert m.test_nullopt_boost(42) == 42 assert m.test_nullopt_boost(43) == 43 assert m.test_no_assign_boost() == 42 assert m.test_no_assign_boost(None) == 42 assert m.test_no_assign_boost(m.NoAssign(43)) == 43 pytest.raises(TypeError, m.test_no_assign_boost, 43) holder = m.OptionalBoostHolder() mvalue = holder.member assert mvalue.initialized assert holder.member_initialized() props = m.OptionalBoostProperties() assert int(props.access_by_ref) == 42 assert int(props.access_by_copy) == 42 def test_reference_sensitive_optional(): assert m.double_or_zero_refsensitive(None) == 0 assert m.double_or_zero_refsensitive(42) == 84 pytest.raises(TypeError, m.double_or_zero_refsensitive, "foo") assert m.half_or_none_refsensitive(0) is None assert m.half_or_none_refsensitive(42) == 21 pytest.raises(TypeError, m.half_or_none_refsensitive, "foo") assert m.test_nullopt_refsensitive() == 42 assert m.test_nullopt_refsensitive(None) == 42 assert m.test_nullopt_refsensitive(42) == 42 assert m.test_nullopt_refsensitive(43) == 43 assert m.test_no_assign_refsensitive() == 42 assert m.test_no_assign_refsensitive(None) == 42 assert m.test_no_assign_refsensitive(m.NoAssign(43)) == 43 pytest.raises(TypeError, m.test_no_assign_refsensitive, 43) holder = m.OptionalRefSensitiveHolder() mvalue = holder.member assert mvalue.initialized assert holder.member_initialized() props = m.OptionalRefSensitiveProperties() assert int(props.access_by_ref) == 42 assert int(props.access_by_copy) == 42 @pytest.mark.skipif(not hasattr(m, "has_filesystem"), reason="no <filesystem>") def test_fs_path(): from pathlib import Path class PseudoStrPath: def __fspath__(self): return "foo/bar" class PseudoBytesPath: def __fspath__(self): return b"foo/bar" assert m.parent_path(Path("foo/bar")) == Path("foo") assert m.parent_path("foo/bar") == Path("foo") assert m.parent_path(b"foo/bar") == Path("foo") assert m.parent_path(PseudoStrPath()) == Path("foo") assert m.parent_path(PseudoBytesPath()) == Path("foo") @pytest.mark.skipif(not hasattr(m, "load_variant"), reason="no <variant>") def test_variant(doc): assert m.load_variant(1) == "int" assert m.load_variant("1") == "std::string" assert m.load_variant(1.0) == "double" assert m.load_variant(None) == "std::nullptr_t" assert m.load_variant_2pass(1) == "int" assert m.load_variant_2pass(1.0) == "double" assert m.cast_variant() == (5, "Hello") assert ( doc(m.load_variant) == "load_variant(arg0: Union[int, str, float, None]) -> str" ) def test_vec_of_reference_wrapper(): """#171: Can't return reference wrappers (or STL structures containing them)""" assert ( str(m.return_vec_of_reference_wrapper(UserType(4))) == "[UserType(1), UserType(2), UserType(3), UserType(4)]" ) def test_stl_pass_by_pointer(msg): """Passing nullptr or None to an STL container pointer is not expected to work""" with pytest.raises(TypeError) as excinfo: m.stl_pass_by_pointer() # default value is `nullptr` assert ( msg(excinfo.value) == """ stl_pass_by_pointer(): incompatible function arguments. The following argument types are supported: 1. (v: List[int] = None) -> List[int] Invoked with: """ # noqa: E501 line too long ) with pytest.raises(TypeError) as excinfo: m.stl_pass_by_pointer(None) assert ( msg(excinfo.value) == """ stl_pass_by_pointer(): incompatible function arguments. The following argument types are supported: 1. (v: List[int] = None) -> List[int] Invoked with: None """ # noqa: E501 line too long ) assert m.stl_pass_by_pointer([1, 2, 3]) == [1, 2, 3] def test_missing_header_message(): """Trying convert `list` to a `std::vector`, or vice versa, without including <pybind11/stl.h> should result in a helpful suggestion in the error message""" import pybind11_cross_module_tests as cm expected_message = ( "Did you forget to `#include <pybind11/stl.h>`? Or <pybind11/complex.h>,\n" "<pybind11/functional.h>, <pybind11/chrono.h>, etc. Some automatic\n" "conversions are optional and require extra headers to be included\n" "when compiling your pybind11 module." ) with pytest.raises(TypeError) as excinfo: cm.missing_header_arg([1.0, 2.0, 3.0]) assert expected_message in str(excinfo.value) with pytest.raises(TypeError) as excinfo: cm.missing_header_return() assert expected_message in str(excinfo.value) def test_function_with_string_and_vector_string_arg(): """Check if a string is NOT implicitly converted to a list, which was the behavior before fix of issue #1258""" assert m.func_with_string_or_vector_string_arg_overload(("A", "B")) == 2 assert m.func_with_string_or_vector_string_arg_overload(["A", "B"]) == 2 assert m.func_with_string_or_vector_string_arg_overload("A") == 3 def test_stl_ownership(): cstats = ConstructorStats.get(m.Placeholder) assert cstats.alive() == 0 r = m.test_stl_ownership() assert len(r) == 1 del r assert cstats.alive() == 0 def test_array_cast_sequence(): assert m.array_cast_sequence((1, 2, 3)) == [1, 2, 3] def test_issue_1561(): """check fix for issue #1561""" bar = m.Issue1561Outer() bar.list = [m.Issue1561Inner("bar")] bar.list assert bar.list[0].data == "bar" def test_return_vector_bool_raw_ptr(): # Add `while True:` for manual leak checking. v = m.return_vector_bool_raw_ptr() assert isinstance(v, list) assert len(v) == 4513
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_numpy_vectorize.cpp
.cpp
4,461
108
/* tests/test_numpy_vectorize.cpp -- auto-vectorize functions over NumPy array arguments Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> 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/numpy.h> #include "pybind11_tests.h" #include <utility> double my_func(int x, float y, double z) { py::print("my_func(x:int={}, y:float={:.0f}, z:float={:.0f})"_s.format(x, y, z)); return (float) x * y * z; } TEST_SUBMODULE(numpy_vectorize, m) { try { py::module_::import("numpy"); } catch (...) { return; } // test_vectorize, test_docs, test_array_collapse // Vectorize all arguments of a function (though non-vector arguments are also allowed) m.def("vectorized_func", py::vectorize(my_func)); // Vectorize a lambda function with a capture object (e.g. to exclude some arguments from the // vectorization) m.def("vectorized_func2", [](py::array_t<int> x, py::array_t<float> y, float z) { return py::vectorize([z](int x, float y) { return my_func(x, y, z); })(std::move(x), std::move(y)); }); // Vectorize a complex-valued function m.def("vectorized_func3", py::vectorize([](std::complex<double> c) { return c * std::complex<double>(2.f); })); // test_type_selection // NumPy function which only accepts specific data types // A lot of these no lints could be replaced with const refs, and probably should at some // point. m.def("selective_func", [](const py::array_t<int, py::array::c_style> &) { return "Int branch taken."; }); m.def("selective_func", [](const py::array_t<float, py::array::c_style> &) { return "Float branch taken."; }); m.def("selective_func", [](const py::array_t<std::complex<float>, py::array::c_style> &) { return "Complex float branch taken."; }); // test_passthrough_arguments // Passthrough test: references and non-pod types should be automatically passed through (in // the function definition below, only `b`, `d`, and `g` are vectorized): struct NonPODClass { explicit NonPODClass(int v) : value{v} {} int value; }; py::class_<NonPODClass>(m, "NonPODClass") .def(py::init<int>()) .def_readwrite("value", &NonPODClass::value); m.def("vec_passthrough", py::vectorize([](const double *a, double b, // Changing this broke things // NOLINTNEXTLINE(performance-unnecessary-value-param) py::array_t<double> c, const int &d, int &e, NonPODClass f, const double g) { return *a + b + c.at(0) + d + e + f.value + g; })); // test_method_vectorization struct VectorizeTestClass { explicit VectorizeTestClass(int v) : value{v} {}; float method(int x, float y) const { return y + (float) (x + value); } int value = 0; }; py::class_<VectorizeTestClass> vtc(m, "VectorizeTestClass"); vtc.def(py::init<int>()).def_readwrite("value", &VectorizeTestClass::value); // Automatic vectorizing of methods vtc.def("method", py::vectorize(&VectorizeTestClass::method)); // test_trivial_broadcasting // Internal optimization test for whether the input is trivially broadcastable: py::enum_<py::detail::broadcast_trivial>(m, "trivial") .value("f_trivial", py::detail::broadcast_trivial::f_trivial) .value("c_trivial", py::detail::broadcast_trivial::c_trivial) .value("non_trivial", py::detail::broadcast_trivial::non_trivial); m.def("vectorized_is_trivial", [](const py::array_t<int, py::array::forcecast> &arg1, const py::array_t<float, py::array::forcecast> &arg2, const py::array_t<double, py::array::forcecast> &arg3) { py::ssize_t ndim = 0; std::vector<py::ssize_t> shape; std::array<py::buffer_info, 3> buffers{ {arg1.request(), arg2.request(), arg3.request()}}; return py::detail::broadcast(buffers, ndim, shape); }); m.def("add_to", py::vectorize([](NonPODClass &x, int a) { x.value += a; })); }
C++
3D
mcellteam/mcell
libs/pybind11/tests/test_embed/external_module.cpp
.cpp
543
21
#include <pybind11/pybind11.h> namespace py = pybind11; /* Simple test module/test class to check that the referenced internals data of external pybind11 * modules aren't preserved over a finalize/initialize. */ PYBIND11_MODULE(external_module, m) { class A { public: explicit A(int value) : v{value} {}; int v; }; py::class_<A>(m, "A").def(py::init<int>()).def_readwrite("value", &A::v); m.def("internals_at", []() { return reinterpret_cast<uintptr_t>(&py::detail::get_internals()); }); }
C++
3D
mcellteam/mcell
libs/pybind11/tests/test_embed/catch.cpp
.cpp
733
28
// The Catch implementation is compiled here. This is a standalone // translation unit to avoid recompiling it for every test change. #include <pybind11/embed.h> #ifdef _MSC_VER // Silence MSVC C++17 deprecation warning from Catch regarding std::uncaught_exceptions (up to // catch 2.0.1; this should be fixed in the next catch release after 2.0.1). # pragma warning(disable : 4996) #endif // Catch uses _ internally, which breaks gettext style defines #ifdef _ # undef _ #endif #define CATCH_CONFIG_RUNNER #include <catch.hpp> namespace py = pybind11; int main(int argc, char *argv[]) { py::scoped_interpreter guard{}; auto result = Catch::Session().run(argc, argv); return result < 0xff ? result : 0xff; }
C++
3D
mcellteam/mcell
libs/pybind11/tests/test_embed/test_interpreter.py
.py
280
16
# -*- coding: utf-8 -*- import sys from widget_module import Widget class DerivedWidget(Widget): def __init__(self, message): super(DerivedWidget, self).__init__(message) def the_answer(self): return 42 def argv0(self): return sys.argv[0]
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_embed/test_trampoline.py
.py
300
19
# -*- coding: utf-8 -*- import trampoline_module def func(): class Test(trampoline_module.test_override_cache_helper): def func(self): return 42 return Test() def func2(): class Test(trampoline_module.test_override_cache_helper): pass return Test()
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_embed/test_interpreter.cpp
.cpp
14,173
401
#include <pybind11/embed.h> #ifdef _MSC_VER // Silence MSVC C++17 deprecation warning from Catch regarding std::uncaught_exceptions (up to // catch 2.0.1; this should be fixed in the next catch release after 2.0.1). # pragma warning(disable : 4996) #endif #include <catch.hpp> #include <cstdlib> #include <fstream> #include <functional> #include <thread> #include <utility> namespace py = pybind11; using namespace py::literals; class Widget { public: explicit Widget(std::string message) : message(std::move(message)) {} virtual ~Widget() = default; std::string the_message() const { return message; } virtual int the_answer() const = 0; virtual std::string argv0() const = 0; private: std::string message; }; class PyWidget final : public Widget { using Widget::Widget; int the_answer() const override { PYBIND11_OVERRIDE_PURE(int, Widget, the_answer); } std::string argv0() const override { PYBIND11_OVERRIDE_PURE(std::string, Widget, argv0); } }; class test_override_cache_helper { public: virtual int func() { return 0; } test_override_cache_helper() = default; virtual ~test_override_cache_helper() = default; // Non-copyable test_override_cache_helper &operator=(test_override_cache_helper const &Right) = delete; test_override_cache_helper(test_override_cache_helper const &Copy) = delete; }; class test_override_cache_helper_trampoline : public test_override_cache_helper { int func() override { PYBIND11_OVERRIDE(int, test_override_cache_helper, func); } }; PYBIND11_EMBEDDED_MODULE(widget_module, m) { py::class_<Widget, PyWidget>(m, "Widget") .def(py::init<std::string>()) .def_property_readonly("the_message", &Widget::the_message); m.def("add", [](int i, int j) { return i + j; }); } PYBIND11_EMBEDDED_MODULE(trampoline_module, m) { py::class_<test_override_cache_helper, test_override_cache_helper_trampoline, std::shared_ptr<test_override_cache_helper>>(m, "test_override_cache_helper") .def(py::init_alias<>()) .def("func", &test_override_cache_helper::func); } PYBIND11_EMBEDDED_MODULE(throw_exception, ) { throw std::runtime_error("C++ Error"); } PYBIND11_EMBEDDED_MODULE(throw_error_already_set, ) { auto d = py::dict(); d["missing"].cast<py::object>(); } TEST_CASE("Pass classes and data between modules defined in C++ and Python") { auto module_ = py::module_::import("test_interpreter"); REQUIRE(py::hasattr(module_, "DerivedWidget")); auto locals = py::dict("hello"_a = "Hello, World!", "x"_a = 5, **module_.attr("__dict__")); py::exec(R"( widget = DerivedWidget("{} - {}".format(hello, x)) message = widget.the_message )", py::globals(), locals); REQUIRE(locals["message"].cast<std::string>() == "Hello, World! - 5"); auto py_widget = module_.attr("DerivedWidget")("The question"); auto message = py_widget.attr("the_message"); REQUIRE(message.cast<std::string>() == "The question"); const auto &cpp_widget = py_widget.cast<const Widget &>(); REQUIRE(cpp_widget.the_answer() == 42); } TEST_CASE("Override cache") { auto module_ = py::module_::import("test_trampoline"); REQUIRE(py::hasattr(module_, "func")); REQUIRE(py::hasattr(module_, "func2")); auto locals = py::dict(**module_.attr("__dict__")); int i = 0; for (; i < 1500; ++i) { std::shared_ptr<test_override_cache_helper> p_obj; std::shared_ptr<test_override_cache_helper> p_obj2; py::object loc_inst = locals["func"](); p_obj = py::cast<std::shared_ptr<test_override_cache_helper>>(loc_inst); int ret = p_obj->func(); REQUIRE(ret == 42); loc_inst = locals["func2"](); p_obj2 = py::cast<std::shared_ptr<test_override_cache_helper>>(loc_inst); p_obj2->func(); } } TEST_CASE("Import error handling") { REQUIRE_NOTHROW(py::module_::import("widget_module")); REQUIRE_THROWS_WITH(py::module_::import("throw_exception"), "ImportError: C++ Error"); #if PY_VERSION_HEX >= 0x03030000 REQUIRE_THROWS_WITH(py::module_::import("throw_error_already_set"), Catch::Contains("ImportError: initialization failed")); auto locals = py::dict("is_keyerror"_a = false, "message"_a = "not set"); py::exec(R"( try: import throw_error_already_set except ImportError as e: is_keyerror = type(e.__cause__) == KeyError message = str(e.__cause__) )", py::globals(), locals); REQUIRE(locals["is_keyerror"].cast<bool>() == true); REQUIRE(locals["message"].cast<std::string>() == "'missing'"); #else REQUIRE_THROWS_WITH(py::module_::import("throw_error_already_set"), Catch::Contains("ImportError: KeyError")); #endif } TEST_CASE("There can be only one interpreter") { static_assert(std::is_move_constructible<py::scoped_interpreter>::value, ""); static_assert(!std::is_move_assignable<py::scoped_interpreter>::value, ""); static_assert(!std::is_copy_constructible<py::scoped_interpreter>::value, ""); static_assert(!std::is_copy_assignable<py::scoped_interpreter>::value, ""); REQUIRE_THROWS_WITH(py::initialize_interpreter(), "The interpreter is already running"); REQUIRE_THROWS_WITH(py::scoped_interpreter(), "The interpreter is already running"); py::finalize_interpreter(); REQUIRE_NOTHROW(py::scoped_interpreter()); { auto pyi1 = py::scoped_interpreter(); auto pyi2 = std::move(pyi1); } py::initialize_interpreter(); } bool has_pybind11_internals_builtin() { auto builtins = py::handle(PyEval_GetBuiltins()); return builtins.contains(PYBIND11_INTERNALS_ID); }; bool has_pybind11_internals_static() { auto **&ipp = py::detail::get_internals_pp(); return (ipp != nullptr) && (*ipp != nullptr); } TEST_CASE("Restart the interpreter") { // Verify pre-restart state. REQUIRE(py::module_::import("widget_module").attr("add")(1, 2).cast<int>() == 3); REQUIRE(has_pybind11_internals_builtin()); REQUIRE(has_pybind11_internals_static()); REQUIRE(py::module_::import("external_module").attr("A")(123).attr("value").cast<int>() == 123); // local and foreign module internals should point to the same internals: REQUIRE(reinterpret_cast<uintptr_t>(*py::detail::get_internals_pp()) == py::module_::import("external_module").attr("internals_at")().cast<uintptr_t>()); // Restart the interpreter. py::finalize_interpreter(); REQUIRE(Py_IsInitialized() == 0); py::initialize_interpreter(); REQUIRE(Py_IsInitialized() == 1); // Internals are deleted after a restart. REQUIRE_FALSE(has_pybind11_internals_builtin()); REQUIRE_FALSE(has_pybind11_internals_static()); pybind11::detail::get_internals(); REQUIRE(has_pybind11_internals_builtin()); REQUIRE(has_pybind11_internals_static()); REQUIRE(reinterpret_cast<uintptr_t>(*py::detail::get_internals_pp()) == py::module_::import("external_module").attr("internals_at")().cast<uintptr_t>()); // Make sure that an interpreter with no get_internals() created until finalize still gets the // internals destroyed py::finalize_interpreter(); py::initialize_interpreter(); bool ran = false; py::module_::import("__main__").attr("internals_destroy_test") = py::capsule(&ran, [](void *ran) { py::detail::get_internals(); *static_cast<bool *>(ran) = true; }); REQUIRE_FALSE(has_pybind11_internals_builtin()); REQUIRE_FALSE(has_pybind11_internals_static()); REQUIRE_FALSE(ran); py::finalize_interpreter(); REQUIRE(ran); py::initialize_interpreter(); REQUIRE_FALSE(has_pybind11_internals_builtin()); REQUIRE_FALSE(has_pybind11_internals_static()); // C++ modules can be reloaded. auto cpp_module = py::module_::import("widget_module"); REQUIRE(cpp_module.attr("add")(1, 2).cast<int>() == 3); // C++ type information is reloaded and can be used in python modules. auto py_module = py::module_::import("test_interpreter"); auto py_widget = py_module.attr("DerivedWidget")("Hello after restart"); REQUIRE(py_widget.attr("the_message").cast<std::string>() == "Hello after restart"); } TEST_CASE("Subinterpreter") { // Add tags to the modules in the main interpreter and test the basics. py::module_::import("__main__").attr("main_tag") = "main interpreter"; { auto m = py::module_::import("widget_module"); m.attr("extension_module_tag") = "added to module in main interpreter"; REQUIRE(m.attr("add")(1, 2).cast<int>() == 3); } REQUIRE(has_pybind11_internals_builtin()); REQUIRE(has_pybind11_internals_static()); /// Create and switch to a subinterpreter. auto *main_tstate = PyThreadState_Get(); auto *sub_tstate = Py_NewInterpreter(); // Subinterpreters get their own copy of builtins. detail::get_internals() still // works by returning from the static variable, i.e. all interpreters share a single // global pybind11::internals; REQUIRE_FALSE(has_pybind11_internals_builtin()); REQUIRE(has_pybind11_internals_static()); // Modules tags should be gone. REQUIRE_FALSE(py::hasattr(py::module_::import("__main__"), "tag")); { auto m = py::module_::import("widget_module"); REQUIRE_FALSE(py::hasattr(m, "extension_module_tag")); // Function bindings should still work. REQUIRE(m.attr("add")(1, 2).cast<int>() == 3); } // Restore main interpreter. Py_EndInterpreter(sub_tstate); PyThreadState_Swap(main_tstate); REQUIRE(py::hasattr(py::module_::import("__main__"), "main_tag")); REQUIRE(py::hasattr(py::module_::import("widget_module"), "extension_module_tag")); } TEST_CASE("Execution frame") { // When the interpreter is embedded, there is no execution frame, but `py::exec` // should still function by using reasonable globals: `__main__.__dict__`. py::exec("var = dict(number=42)"); REQUIRE(py::globals()["var"]["number"].cast<int>() == 42); } TEST_CASE("Threads") { // Restart interpreter to ensure threads are not initialized py::finalize_interpreter(); py::initialize_interpreter(); REQUIRE_FALSE(has_pybind11_internals_static()); constexpr auto num_threads = 10; auto locals = py::dict("count"_a = 0); { py::gil_scoped_release gil_release{}; REQUIRE(has_pybind11_internals_static()); auto threads = std::vector<std::thread>(); for (auto i = 0; i < num_threads; ++i) { threads.emplace_back([&]() { py::gil_scoped_acquire gil{}; locals["count"] = locals["count"].cast<int>() + 1; }); } for (auto &thread : threads) { thread.join(); } } REQUIRE(locals["count"].cast<int>() == num_threads); } // Scope exit utility https://stackoverflow.com/a/36644501/7255855 struct scope_exit { std::function<void()> f_; explicit scope_exit(std::function<void()> f) noexcept : f_(std::move(f)) {} ~scope_exit() { if (f_) { f_(); } } }; TEST_CASE("Reload module from file") { // Disable generation of cached bytecode (.pyc files) for this test, otherwise // Python might pick up an old version from the cache instead of the new versions // of the .py files generated below auto sys = py::module_::import("sys"); bool dont_write_bytecode = sys.attr("dont_write_bytecode").cast<bool>(); sys.attr("dont_write_bytecode") = true; // Reset the value at scope exit scope_exit reset_dont_write_bytecode( [&]() { sys.attr("dont_write_bytecode") = dont_write_bytecode; }); std::string module_name = "test_module_reload"; std::string module_file = module_name + ".py"; // Create the module .py file std::ofstream test_module(module_file); test_module << "def test():\n"; test_module << " return 1\n"; test_module.close(); // Delete the file at scope exit scope_exit delete_module_file([&]() { std::remove(module_file.c_str()); }); // Import the module from file auto module_ = py::module_::import(module_name.c_str()); int result = module_.attr("test")().cast<int>(); REQUIRE(result == 1); // Update the module .py file with a small change test_module.open(module_file); test_module << "def test():\n"; test_module << " return 2\n"; test_module.close(); // Reload the module module_.reload(); result = module_.attr("test")().cast<int>(); REQUIRE(result == 2); } TEST_CASE("sys.argv gets initialized properly") { py::finalize_interpreter(); { py::scoped_interpreter default_scope; auto module = py::module::import("test_interpreter"); auto py_widget = module.attr("DerivedWidget")("The question"); const auto &cpp_widget = py_widget.cast<const Widget &>(); REQUIRE(cpp_widget.argv0().empty()); } { char *argv[] = {strdup("a.out")}; py::scoped_interpreter argv_scope(true, 1, argv); std::free(argv[0]); auto module = py::module::import("test_interpreter"); auto py_widget = module.attr("DerivedWidget")("The question"); const auto &cpp_widget = py_widget.cast<const Widget &>(); REQUIRE(cpp_widget.argv0() == "a.out"); } py::initialize_interpreter(); } TEST_CASE("make_iterator can be called before then after finalizing an interpreter") { // Reproduction of issue #2101 (https://github.com/pybind/pybind11/issues/2101) py::finalize_interpreter(); std::vector<int> container; { pybind11::scoped_interpreter g; auto iter = pybind11::make_iterator(container.begin(), container.end()); } REQUIRE_NOTHROW([&]() { pybind11::scoped_interpreter g; auto iter = pybind11::make_iterator(container.begin(), container.end()); }()); py::initialize_interpreter(); }
C++
3D
mcellteam/mcell
libs/pybind11/tests/extra_python_package/test_files.py
.py
7,578
280
# -*- coding: utf-8 -*- import contextlib import os import string import subprocess import sys import tarfile import zipfile # These tests must be run explicitly # They require CMake 3.15+ (--install) DIR = os.path.abspath(os.path.dirname(__file__)) MAIN_DIR = os.path.dirname(os.path.dirname(DIR)) main_headers = { "include/pybind11/attr.h", "include/pybind11/buffer_info.h", "include/pybind11/cast.h", "include/pybind11/chrono.h", "include/pybind11/common.h", "include/pybind11/complex.h", "include/pybind11/eigen.h", "include/pybind11/embed.h", "include/pybind11/eval.h", "include/pybind11/functional.h", "include/pybind11/gil.h", "include/pybind11/iostream.h", "include/pybind11/numpy.h", "include/pybind11/operators.h", "include/pybind11/options.h", "include/pybind11/pybind11.h", "include/pybind11/pytypes.h", "include/pybind11/stl.h", "include/pybind11/stl_bind.h", } detail_headers = { "include/pybind11/detail/class.h", "include/pybind11/detail/common.h", "include/pybind11/detail/descr.h", "include/pybind11/detail/init.h", "include/pybind11/detail/internals.h", "include/pybind11/detail/type_caster_base.h", "include/pybind11/detail/typeid.h", } stl_headers = { "include/pybind11/stl/filesystem.h", } cmake_files = { "share/cmake/pybind11/FindPythonLibsNew.cmake", "share/cmake/pybind11/pybind11Common.cmake", "share/cmake/pybind11/pybind11Config.cmake", "share/cmake/pybind11/pybind11ConfigVersion.cmake", "share/cmake/pybind11/pybind11NewTools.cmake", "share/cmake/pybind11/pybind11Targets.cmake", "share/cmake/pybind11/pybind11Tools.cmake", } py_files = { "__init__.py", "__main__.py", "_version.py", "_version.pyi", "commands.py", "py.typed", "setup_helpers.py", "setup_helpers.pyi", } headers = main_headers | detail_headers | stl_headers src_files = headers | cmake_files all_files = src_files | py_files sdist_files = { "pybind11", "pybind11/include", "pybind11/include/pybind11", "pybind11/include/pybind11/detail", "pybind11/include/pybind11/stl", "pybind11/share", "pybind11/share/cmake", "pybind11/share/cmake/pybind11", "pyproject.toml", "setup.cfg", "setup.py", "LICENSE", "MANIFEST.in", "README.rst", "PKG-INFO", } local_sdist_files = { ".egg-info", ".egg-info/PKG-INFO", ".egg-info/SOURCES.txt", ".egg-info/dependency_links.txt", ".egg-info/not-zip-safe", ".egg-info/top_level.txt", } def test_build_sdist(monkeypatch, tmpdir): monkeypatch.chdir(MAIN_DIR) out = subprocess.check_output( [ sys.executable, "setup.py", "sdist", "--formats=tar", "--dist-dir", str(tmpdir), ] ) if hasattr(out, "decode"): out = out.decode() (sdist,) = tmpdir.visit("*.tar") with tarfile.open(str(sdist)) as tar: start = tar.getnames()[0] + "/" version = start[9:-1] simpler = {n.split("/", 1)[-1] for n in tar.getnames()[1:]} with contextlib.closing( tar.extractfile(tar.getmember(start + "setup.py")) ) as f: setup_py = f.read() with contextlib.closing( tar.extractfile(tar.getmember(start + "pyproject.toml")) ) as f: pyproject_toml = f.read() with contextlib.closing( tar.extractfile( tar.getmember( start + "pybind11/share/cmake/pybind11/pybind11Config.cmake" ) ) ) as f: contents = f.read().decode("utf8") assert 'set(pybind11_INCLUDE_DIR "${PACKAGE_PREFIX_DIR}/include")' in contents files = {"pybind11/{}".format(n) for n in all_files} files |= sdist_files files |= {"pybind11{}".format(n) for n in local_sdist_files} files.add("pybind11.egg-info/entry_points.txt") files.add("pybind11.egg-info/requires.txt") assert simpler == files with open(os.path.join(MAIN_DIR, "tools", "setup_main.py.in"), "rb") as f: contents = ( string.Template(f.read().decode()) .substitute(version=version, extra_cmd="") .encode() ) assert setup_py == contents with open(os.path.join(MAIN_DIR, "tools", "pyproject.toml"), "rb") as f: contents = f.read() assert pyproject_toml == contents def test_build_global_dist(monkeypatch, tmpdir): monkeypatch.chdir(MAIN_DIR) monkeypatch.setenv("PYBIND11_GLOBAL_SDIST", "1") out = subprocess.check_output( [ sys.executable, "setup.py", "sdist", "--formats=tar", "--dist-dir", str(tmpdir), ] ) if hasattr(out, "decode"): out = out.decode() (sdist,) = tmpdir.visit("*.tar") with tarfile.open(str(sdist)) as tar: start = tar.getnames()[0] + "/" version = start[16:-1] simpler = {n.split("/", 1)[-1] for n in tar.getnames()[1:]} with contextlib.closing( tar.extractfile(tar.getmember(start + "setup.py")) ) as f: setup_py = f.read() with contextlib.closing( tar.extractfile(tar.getmember(start + "pyproject.toml")) ) as f: pyproject_toml = f.read() files = {"pybind11/{}".format(n) for n in all_files} files |= sdist_files files |= {"pybind11_global{}".format(n) for n in local_sdist_files} assert simpler == files with open(os.path.join(MAIN_DIR, "tools", "setup_global.py.in"), "rb") as f: contents = ( string.Template(f.read().decode()) .substitute(version=version, extra_cmd="") .encode() ) assert setup_py == contents with open(os.path.join(MAIN_DIR, "tools", "pyproject.toml"), "rb") as f: contents = f.read() assert pyproject_toml == contents def tests_build_wheel(monkeypatch, tmpdir): monkeypatch.chdir(MAIN_DIR) subprocess.check_output( [sys.executable, "-m", "pip", "wheel", ".", "-w", str(tmpdir)] ) (wheel,) = tmpdir.visit("*.whl") files = {"pybind11/{}".format(n) for n in all_files} files |= { "dist-info/LICENSE", "dist-info/METADATA", "dist-info/RECORD", "dist-info/WHEEL", "dist-info/entry_points.txt", "dist-info/top_level.txt", } with zipfile.ZipFile(str(wheel)) as z: names = z.namelist() trimmed = {n for n in names if "dist-info" not in n} trimmed |= { "dist-info/{}".format(n.split("/", 1)[-1]) for n in names if "dist-info" in n } assert files == trimmed def tests_build_global_wheel(monkeypatch, tmpdir): monkeypatch.chdir(MAIN_DIR) monkeypatch.setenv("PYBIND11_GLOBAL_SDIST", "1") subprocess.check_output( [sys.executable, "-m", "pip", "wheel", ".", "-w", str(tmpdir)] ) (wheel,) = tmpdir.visit("*.whl") files = {"data/data/{}".format(n) for n in src_files} files |= {"data/headers/{}".format(n[8:]) for n in headers} files |= { "dist-info/LICENSE", "dist-info/METADATA", "dist-info/WHEEL", "dist-info/top_level.txt", "dist-info/RECORD", } with zipfile.ZipFile(str(wheel)) as z: names = z.namelist() beginning = names[0].split("/", 1)[0].rsplit(".", 1)[0] trimmed = {n[len(beginning) + 1 :] for n in names} assert files == trimmed
Python
3D
mcellteam/mcell
libs/pybind11/tests/extra_setuptools/test_setuphelper.py
.py
4,221
152
# -*- coding: utf-8 -*- import os import subprocess import sys from textwrap import dedent import pytest DIR = os.path.abspath(os.path.dirname(__file__)) MAIN_DIR = os.path.dirname(os.path.dirname(DIR)) WIN = sys.platform.startswith("win32") or sys.platform.startswith("cygwin") @pytest.mark.parametrize("parallel", [False, True]) @pytest.mark.parametrize("std", [11, 0]) def test_simple_setup_py(monkeypatch, tmpdir, parallel, std): monkeypatch.chdir(tmpdir) monkeypatch.syspath_prepend(MAIN_DIR) (tmpdir / "setup.py").write_text( dedent( u"""\ import sys sys.path.append({MAIN_DIR!r}) from setuptools import setup, Extension from pybind11.setup_helpers import build_ext, Pybind11Extension std = {std} ext_modules = [ Pybind11Extension( "simple_setup", sorted(["main.cpp"]), cxx_std=std, ), ] cmdclass = dict() if std == 0: cmdclass["build_ext"] = build_ext parallel = {parallel} if parallel: from pybind11.setup_helpers import ParallelCompile ParallelCompile().install() setup( name="simple_setup_package", cmdclass=cmdclass, ext_modules=ext_modules, ) """ ).format(MAIN_DIR=MAIN_DIR, std=std, parallel=parallel), encoding="ascii", ) (tmpdir / "main.cpp").write_text( dedent( u"""\ #include <pybind11/pybind11.h> int f(int x) { return x * 3; } PYBIND11_MODULE(simple_setup, m) { m.def("f", &f); } """ ), encoding="ascii", ) out = subprocess.check_output( [sys.executable, "setup.py", "build_ext", "--inplace"], ) if not WIN: assert b"-g0" in out out = subprocess.check_output( [sys.executable, "setup.py", "build_ext", "--inplace", "--force"], env=dict(os.environ, CFLAGS="-g"), ) if not WIN: assert b"-g0" not in out # Debug helper printout, normally hidden print(out) for item in tmpdir.listdir(): print(item.basename) assert ( len([f for f in tmpdir.listdir() if f.basename.startswith("simple_setup")]) == 1 ) assert len(list(tmpdir.listdir())) == 4 # two files + output + build_dir (tmpdir / "test.py").write_text( dedent( u"""\ import simple_setup assert simple_setup.f(3) == 9 """ ), encoding="ascii", ) subprocess.check_call( [sys.executable, "test.py"], stdout=sys.stdout, stderr=sys.stderr ) def test_intree_extensions(monkeypatch, tmpdir): monkeypatch.syspath_prepend(MAIN_DIR) from pybind11.setup_helpers import intree_extensions monkeypatch.chdir(tmpdir) root = tmpdir root.ensure_dir() subdir = root / "dir" subdir.ensure_dir() src = subdir / "ext.cpp" src.ensure() (ext,) = intree_extensions([src.relto(tmpdir)]) assert ext.name == "ext" subdir.ensure("__init__.py") (ext,) = intree_extensions([src.relto(tmpdir)]) assert ext.name == "dir.ext" def test_intree_extensions_package_dir(monkeypatch, tmpdir): monkeypatch.syspath_prepend(MAIN_DIR) from pybind11.setup_helpers import intree_extensions monkeypatch.chdir(tmpdir) root = tmpdir / "src" root.ensure_dir() subdir = root / "dir" subdir.ensure_dir() src = subdir / "ext.cpp" src.ensure() (ext,) = intree_extensions([src.relto(tmpdir)], package_dir={"": "src"}) assert ext.name == "dir.ext" (ext,) = intree_extensions([src.relto(tmpdir)], package_dir={"foo": "src"}) assert ext.name == "foo.dir.ext" subdir.ensure("__init__.py") (ext,) = intree_extensions([src.relto(tmpdir)], package_dir={"": "src"}) assert ext.name == "dir.ext" (ext,) = intree_extensions([src.relto(tmpdir)], package_dir={"foo": "src"}) assert ext.name == "foo.dir.ext"
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_cmake_build/main.cpp
.cpp
152
7
#include <pybind11/pybind11.h> namespace py = pybind11; PYBIND11_MODULE(test_cmake_build, m) { m.def("add", [](int i, int j) { return i + j; }); }
C++
3D
mcellteam/mcell
libs/pybind11/tests/test_cmake_build/test.py
.py
273
11
# -*- coding: utf-8 -*- import sys import test_cmake_build if str is not bytes: # If not Python2 assert isinstance(__file__, str) # Test this is properly set assert test_cmake_build.add(1, 2) == 3 print("{} imports, runs, and adds: 1 + 2 = 3".format(sys.argv[1]))
Python
3D
mcellteam/mcell
libs/pybind11/tests/test_cmake_build/embed.cpp
.cpp
673
24
#include <pybind11/embed.h> namespace py = pybind11; PYBIND11_EMBEDDED_MODULE(test_cmake_build, m) { m.def("add", [](int i, int j) { return i + j; }); } int main(int argc, char *argv[]) { if (argc != 2) { throw std::runtime_error("Expected test.py file as the first argument"); } auto *test_py_file = argv[1]; py::scoped_interpreter guard{}; auto m = py::module_::import("test_cmake_build"); if (m.attr("add")(1, 2).cast<int>() != 3) { throw std::runtime_error("embed.cpp failed"); } py::module_::import("sys").attr("argv") = py::make_tuple("test.py", "embed.cpp"); py::eval_file(test_py_file, py::globals()); }
C++
3D
mcellteam/mcell
libs/jsoncpp/CONTRIBUTING.md
.md
5,767
145
# Contributing to JsonCpp ## Building Both CMake and Meson tools are capable of generating a variety of build environments for you preferred development environment. Using cmake or meson you can generate an XCode, Visual Studio, Unix Makefile, Ninja, or other environment that fits your needs. An example of a common Meson/Ninja environment is described next. ## Building and testing with Meson/Ninja Thanks to David Seifert (@SoapGentoo), we (the maintainers) now use [meson](http://mesonbuild.com/) and [ninja](https://ninja-build.org/) to build for debugging, as well as for continuous integration (see [`./.travis_scripts/meson_builder.sh`](./.travis_scripts/meson_builder.sh) ). Other systems may work, but minor things like version strings might break. First, install both meson (which requires Python3) and ninja. If you wish to install to a directory other than /usr/local, set an environment variable called DESTDIR with the desired path: DESTDIR=/path/to/install/dir Then, cd jsoncpp/ BUILD_TYPE=debug #BUILD_TYPE=release LIB_TYPE=shared #LIB_TYPE=static meson --buildtype ${BUILD_TYPE} --default-library ${LIB_TYPE} . build-${LIB_TYPE} ninja -v -C build-${LIB_TYPE} cd build-${LIB_TYPE} meson test --no-rebuild --print-errorlogs sudo ninja install ## Building and testing with other build systems See https://github.com/open-source-parsers/jsoncpp/wiki/Building ## Running the tests manually You need to run tests manually only if you are troubleshooting an issue. In the instructions below, replace `path/to/jsontest` with the path of the `jsontest` executable that was compiled on your platform. cd test # This will run the Reader/Writer tests python runjsontests.py path/to/jsontest # This will run the Reader/Writer tests, using JSONChecker test suite # (http://www.json.org/JSON_checker/). # Notes: not all tests pass: JsonCpp is too lenient (for example, # it allows an integer to start with '0'). The goal is to improve # strict mode parsing to get all tests to pass. python runjsontests.py --with-json-checker path/to/jsontest # This will run the unit tests (mostly Value) python rununittests.py path/to/test_lib_json # You can run the tests using valgrind: python rununittests.py --valgrind path/to/test_lib_json ## Building the documentation Run the Python script `doxybuild.py` from the top directory: python doxybuild.py --doxygen=$(which doxygen) --open --with-dot See `doxybuild.py --help` for options. ## Adding a reader/writer test To add a test, you need to create two files in test/data: * a `TESTNAME.json` file, that contains the input document in JSON format. * a `TESTNAME.expected` file, that contains a flatened representation of the input document. The `TESTNAME.expected` file format is as follows: * Each line represents a JSON element of the element tree represented by the input document. * Each line has two parts: the path to access the element separated from the element value by `=`. Array and object values are always empty (i.e. represented by either `[]` or `{}`). * Element path `.` represents the root element, and is used to separate object members. `[N]` is used to specify the value of an array element at index `N`. See the examples `test_complex_01.json` and `test_complex_01.expected` to better understand element paths. ## Understanding reader/writer test output When a test is run, output files are generated beside the input test files. Below is a short description of the content of each file: * `test_complex_01.json`: input JSON document. * `test_complex_01.expected`: flattened JSON element tree used to check if parsing was corrected. * `test_complex_01.actual`: flattened JSON element tree produced by `jsontest` from reading `test_complex_01.json`. * `test_complex_01.rewrite`: JSON document written by `jsontest` using the `Json::Value` parsed from `test_complex_01.json` and serialized using `Json::StyledWritter`. * `test_complex_01.actual-rewrite`: flattened JSON element tree produced by `jsontest` from reading `test_complex_01.rewrite`. * `test_complex_01.process-output`: `jsontest` output, typically useful for understanding parsing errors. ## Versioning rules Consumers of this library require a strict approach to incrementing versioning of the JsonCpp library. Currently, we follow the below set of rules: * Any new public symbols require a minor version bump. * Any alteration or removal of public symbols requires a major version bump, including changing the size of a class. This is necessary for consumers to do dependency injection properly. ## Preparing code for submission Generally, JsonCpp's style guide has been pretty relaxed, with the following common themes: * Variables and function names use lower camel case (E.g. parseValue or collectComments). * Class use camel case (e.g. OurReader) * Member variables have a trailing underscore * Prefer `nullptr` over `NULL`. * Passing by non-const reference is allowed. * Single statement if blocks may omit brackets. * Generally prefer less space over more space. For an example: ```c++ bool Reader::decodeNumber(Token& token) { Value decoded; if (!decodeNumber(token, decoded)) return false; currentValue().swapPayload(decoded); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); return true; } ``` Before submitting your code, ensure that you meet the versioning requirements above, follow the style guide of the file you are modifying (or the above rules for new files), and run clang format. Meson exposes clang format with the following command: ``` ninja -v -C build-${LIB_TYPE}/ clang-format ```
Markdown
3D
mcellteam/mcell
libs/jsoncpp/doxybuild.py
.py
7,416
190
"""Script to generate doxygen documentation. """ from __future__ import print_function from __future__ import unicode_literals from devtools import tarball from contextlib import contextmanager import subprocess import traceback import re import os import sys import shutil @contextmanager def cd(newdir): """ http://stackoverflow.com/questions/431684/how-do-i-cd-in-python """ prevdir = os.getcwd() os.chdir(newdir) try: yield finally: os.chdir(prevdir) def find_program(*filenames): """find a program in folders path_lst, and sets env[var] @param filenames: a list of possible names of the program to search for @return: the full path of the filename if found, or '' if filename could not be found """ paths = os.environ.get('PATH', '').split(os.pathsep) suffixes = ('win32' in sys.platform) and '.exe .com .bat .cmd' or '' for filename in filenames: for name in [filename+ext for ext in suffixes.split(' ')]: for directory in paths: full_path = os.path.join(directory, name) if os.path.isfile(full_path): return full_path return '' def do_subst_in_file(targetfile, sourcefile, dict): """Replace all instances of the keys of dict with their values. For example, if dict is {'%VERSION%': '1.2345', '%BASE%': 'MyProg'}, then all instances of %VERSION% in the file will be replaced with 1.2345 etc. """ with open(sourcefile, 'r') as f: contents = f.read() for (k,v) in list(dict.items()): v = v.replace('\\','\\\\') contents = re.sub(k, v, contents) with open(targetfile, 'w') as f: f.write(contents) def getstatusoutput(cmd): """cmd is a list. """ try: process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) output, _ = process.communicate() status = process.returncode except: status = -1 output = traceback.format_exc() return status, output def run_cmd(cmd, silent=False): """Raise exception on failure. """ info = 'Running: %r in %r' %(' '.join(cmd), os.getcwd()) print(info) sys.stdout.flush() if silent: status, output = getstatusoutput(cmd) else: status, output = subprocess.call(cmd), '' if status: msg = 'Error while %s ...\n\terror=%d, output="""%s"""' %(info, status, output) raise Exception(msg) def assert_is_exe(path): if not path: raise Exception('path is empty.') if not os.path.isfile(path): raise Exception('%r is not a file.' %path) if not os.access(path, os.X_OK): raise Exception('%r is not executable by this user.' %path) def run_doxygen(doxygen_path, config_file, working_dir, is_silent): assert_is_exe(doxygen_path) config_file = os.path.abspath(config_file) with cd(working_dir): cmd = [doxygen_path, config_file] run_cmd(cmd, is_silent) def build_doc(options, make_release=False): if make_release: options.make_tarball = True options.with_dot = True options.with_html_help = True options.with_uml_look = True options.open = False options.silent = True version = open('version', 'rt').read().strip() output_dir = 'dist/doxygen' # relative to doc/doxyfile location. if not os.path.isdir(output_dir): os.makedirs(output_dir) top_dir = os.path.abspath('.') html_output_dirname = 'jsoncpp-api-html-' + version tarball_path = os.path.join('dist', html_output_dirname + '.tar.gz') warning_log_path = os.path.join(output_dir, '../jsoncpp-doxygen-warning.log') html_output_path = os.path.join(output_dir, html_output_dirname) def yesno(bool): return bool and 'YES' or 'NO' subst_keys = { '%JSONCPP_VERSION%': version, '%DOC_TOPDIR%': '', '%TOPDIR%': top_dir, '%HTML_OUTPUT%': os.path.join('..', output_dir, html_output_dirname), '%HAVE_DOT%': yesno(options.with_dot), '%DOT_PATH%': os.path.split(options.dot_path)[0], '%HTML_HELP%': yesno(options.with_html_help), '%UML_LOOK%': yesno(options.with_uml_look), '%WARNING_LOG_PATH%': os.path.join('..', warning_log_path) } if os.path.isdir(output_dir): print('Deleting directory:', output_dir) shutil.rmtree(output_dir) if not os.path.isdir(output_dir): os.makedirs(output_dir) do_subst_in_file('doc/doxyfile', options.doxyfile_input_path, subst_keys) run_doxygen(options.doxygen_path, 'doc/doxyfile', 'doc', is_silent=options.silent) if not options.silent: print(open(warning_log_path, 'r').read()) index_path = os.path.abspath(os.path.join('doc', subst_keys['%HTML_OUTPUT%'], 'index.html')) print('Generated documentation can be found in:') print(index_path) if options.open: import webbrowser webbrowser.open('file://' + index_path) if options.make_tarball: print('Generating doc tarball to', tarball_path) tarball_sources = [ output_dir, 'README.md', 'LICENSE', 'NEWS.txt', 'version' ] tarball_basedir = os.path.join(output_dir, html_output_dirname) tarball.make_tarball(tarball_path, tarball_sources, tarball_basedir, html_output_dirname) return tarball_path, html_output_dirname def main(): usage = """%prog Generates doxygen documentation in build/doxygen. Optionally makes a tarball of the documentation to dist/. Must be started in the project top directory. """ from optparse import OptionParser parser = OptionParser(usage=usage) parser.allow_interspersed_args = False parser.add_option('--with-dot', dest="with_dot", action='store_true', default=False, help="""Enable usage of DOT to generate collaboration diagram""") parser.add_option('--dot', dest="dot_path", action='store', default=find_program('dot'), help="""Path to GraphViz dot tool. Must be full qualified path. [Default: %default]""") parser.add_option('--doxygen', dest="doxygen_path", action='store', default=find_program('doxygen'), help="""Path to Doxygen tool. [Default: %default]""") parser.add_option('--in', dest="doxyfile_input_path", action='store', default='doc/doxyfile.in', help="""Path to doxygen inputs. [Default: %default]""") parser.add_option('--with-html-help', dest="with_html_help", action='store_true', default=False, help="""Enable generation of Microsoft HTML HELP""") parser.add_option('--no-uml-look', dest="with_uml_look", action='store_false', default=True, help="""Generates DOT graph without UML look [Default: False]""") parser.add_option('--open', dest="open", action='store_true', default=False, help="""Open the HTML index in the web browser after generation""") parser.add_option('--tarball', dest="make_tarball", action='store_true', default=False, help="""Generates a tarball of the documentation in dist/ directory""") parser.add_option('-s', '--silent', dest="silent", action='store_true', default=False, help="""Hides doxygen output""") parser.enable_interspersed_args() options, args = parser.parse_args() build_doc(options) if __name__ == '__main__': main()
Python
3D
mcellteam/mcell
libs/jsoncpp/amalgamate.py
.py
7,052
160
#!/usr/bin/env python """Amalgamate json-cpp library sources into a single source and header file. Works with python2.6+ and python3.4+. Example of invocation (must be invoked from json-cpp top directory): python amalgamate.py """ import os import os.path import sys INCLUDE_PATH = "include/json" SRC_PATH = "src/lib_json" class AmalgamationFile: def __init__(self, top_dir): self.top_dir = top_dir self.blocks = [] def add_text(self, text): if not text.endswith("\n"): text += "\n" self.blocks.append(text) def add_file(self, relative_input_path, wrap_in_comment=False): def add_marker(prefix): self.add_text("") self.add_text("// " + "/"*70) self.add_text("// %s of content of file: %s" % (prefix, relative_input_path.replace("\\","/"))) self.add_text("// " + "/"*70) self.add_text("") add_marker("Beginning") f = open(os.path.join(self.top_dir, relative_input_path), "rt") content = f.read() if wrap_in_comment: content = "/*\n" + content + "\n*/" self.add_text(content) f.close() add_marker("End") self.add_text("\n\n\n\n") def get_value(self): return "".join(self.blocks).replace("\r\n","\n") def write_to(self, output_path): output_dir = os.path.dirname(output_path) if output_dir and not os.path.isdir(output_dir): os.makedirs(output_dir) f = open(output_path, "wb") f.write(str.encode(self.get_value(), 'UTF-8')) f.close() def amalgamate_source(source_top_dir=None, target_source_path=None, header_include_path=None): """Produces amalgamated source. Parameters: source_top_dir: top-directory target_source_path: output .cpp path header_include_path: generated header path relative to target_source_path. """ print("Amalgamating header...") header = AmalgamationFile(source_top_dir) header.add_text("/// Json-cpp amalgamated header (http://jsoncpp.sourceforge.net/).") header.add_text('/// It is intended to be used with #include "%s"' % header_include_path) header.add_file("LICENSE", wrap_in_comment=True) header.add_text("#ifndef JSON_AMALGAMATED_H_INCLUDED") header.add_text("# define JSON_AMALGAMATED_H_INCLUDED") header.add_text("/// If defined, indicates that the source file is amalgamated") header.add_text("/// to prevent private header inclusion.") header.add_text("#define JSON_IS_AMALGAMATION") header.add_file(os.path.join(INCLUDE_PATH, "version.h")) header.add_file(os.path.join(INCLUDE_PATH, "allocator.h")) header.add_file(os.path.join(INCLUDE_PATH, "config.h")) header.add_file(os.path.join(INCLUDE_PATH, "forwards.h")) header.add_file(os.path.join(INCLUDE_PATH, "json_features.h")) header.add_file(os.path.join(INCLUDE_PATH, "value.h")) header.add_file(os.path.join(INCLUDE_PATH, "reader.h")) header.add_file(os.path.join(INCLUDE_PATH, "writer.h")) header.add_file(os.path.join(INCLUDE_PATH, "assertions.h")) header.add_text("#endif //ifndef JSON_AMALGAMATED_H_INCLUDED") target_header_path = os.path.join(os.path.dirname(target_source_path), header_include_path) print("Writing amalgamated header to %r" % target_header_path) header.write_to(target_header_path) base, ext = os.path.splitext(header_include_path) forward_header_include_path = base + "-forwards" + ext print("Amalgamating forward header...") header = AmalgamationFile(source_top_dir) header.add_text("/// Json-cpp amalgamated forward header (http://jsoncpp.sourceforge.net/).") header.add_text('/// It is intended to be used with #include "%s"' % forward_header_include_path) header.add_text("/// This header provides forward declaration for all JsonCpp types.") header.add_file("LICENSE", wrap_in_comment=True) header.add_text("#ifndef JSON_FORWARD_AMALGAMATED_H_INCLUDED") header.add_text("# define JSON_FORWARD_AMALGAMATED_H_INCLUDED") header.add_text("/// If defined, indicates that the source file is amalgamated") header.add_text("/// to prevent private header inclusion.") header.add_text("#define JSON_IS_AMALGAMATION") header.add_file(os.path.join(INCLUDE_PATH, "config.h")) header.add_file(os.path.join(INCLUDE_PATH, "forwards.h")) header.add_text("#endif //ifndef JSON_FORWARD_AMALGAMATED_H_INCLUDED") target_forward_header_path = os.path.join(os.path.dirname(target_source_path), forward_header_include_path) print("Writing amalgamated forward header to %r" % target_forward_header_path) header.write_to(target_forward_header_path) print("Amalgamating source...") source = AmalgamationFile(source_top_dir) source.add_text("/// Json-cpp amalgamated source (http://jsoncpp.sourceforge.net/).") source.add_text('/// It is intended to be used with #include "%s"' % header_include_path) source.add_file("LICENSE", wrap_in_comment=True) source.add_text("") source.add_text('#include "%s"' % header_include_path) source.add_text(""" #ifndef JSON_IS_AMALGAMATION #error "Compile with -I PATH_TO_JSON_DIRECTORY" #endif """) source.add_text("") source.add_file(os.path.join(SRC_PATH, "json_tool.h")) source.add_file(os.path.join(SRC_PATH, "json_reader.cpp")) source.add_file(os.path.join(SRC_PATH, "json_valueiterator.inl")) source.add_file(os.path.join(SRC_PATH, "json_value.cpp")) source.add_file(os.path.join(SRC_PATH, "json_writer.cpp")) print("Writing amalgamated source to %r" % target_source_path) source.write_to(target_source_path) def main(): usage = """%prog [options] Generate a single amalgamated source and header file from the sources. """ from optparse import OptionParser parser = OptionParser(usage=usage) parser.allow_interspersed_args = False parser.add_option("-s", "--source", dest="target_source_path", action="store", default="dist/jsoncpp.cpp", help="""Output .cpp source path. [Default: %default]""") parser.add_option("-i", "--include", dest="header_include_path", action="store", default="json/json.h", help="""Header include path. Used to include the header from the amalgamated source file. [Default: %default]""") parser.add_option("-t", "--top-dir", dest="top_dir", action="store", default=os.getcwd(), help="""Source top-directory. [Default: %default]""") parser.enable_interspersed_args() options, args = parser.parse_args() msg = amalgamate_source(source_top_dir=options.top_dir, target_source_path=options.target_source_path, header_include_path=options.header_include_path) if msg: sys.stderr.write(msg + "\n") sys.exit(1) else: print("Source successfully amalgamated") if __name__ == "__main__": main()
Python
3D
mcellteam/mcell
libs/jsoncpp/include/json/allocator.h
.h
2,481
90
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #ifndef JSON_ALLOCATOR_H_INCLUDED #define JSON_ALLOCATOR_H_INCLUDED #include <cstring> #include <memory> #pragma pack(push, 8) namespace Json { template <typename T> class SecureAllocator { public: // Type definitions using value_type = T; using pointer = T*; using const_pointer = const T*; using reference = T&; using const_reference = const T&; using size_type = std::size_t; using difference_type = std::ptrdiff_t; /** * Allocate memory for N items using the standard allocator. */ pointer allocate(size_type n) { // allocate using "global operator new" return static_cast<pointer>(::operator new(n * sizeof(T))); } /** * Release memory which was allocated for N items at pointer P. * * The memory block is filled with zeroes before being released. * The pointer argument is tagged as "volatile" to prevent the * compiler optimizing out this critical step. */ void deallocate(volatile pointer p, size_type n) { std::memset(p, 0, n * sizeof(T)); // free using "global operator delete" ::operator delete(p); } /** * Construct an item in-place at pointer P. */ template <typename... Args> void construct(pointer p, Args&&... args) { // construct using "placement new" and "perfect forwarding" ::new (static_cast<void*>(p)) T(std::forward<Args>(args)...); } size_type max_size() const { return size_t(-1) / sizeof(T); } pointer address(reference x) const { return std::addressof(x); } const_pointer address(const_reference x) const { return std::addressof(x); } /** * Destroy an item in-place at pointer P. */ void destroy(pointer p) { // destroy using "explicit destructor" p->~T(); } // Boilerplate SecureAllocator() {} template <typename U> SecureAllocator(const SecureAllocator<U>&) {} template <typename U> struct rebind { using other = SecureAllocator<U>; }; }; template <typename T, typename U> bool operator==(const SecureAllocator<T>&, const SecureAllocator<U>&) { return true; } template <typename T, typename U> bool operator!=(const SecureAllocator<T>&, const SecureAllocator<U>&) { return false; } } // namespace Json #pragma pack(pop) #endif // JSON_ALLOCATOR_H_INCLUDED
Unknown
3D
mcellteam/mcell
libs/jsoncpp/include/json/value.h
.h
30,169
935
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #ifndef JSON_H_INCLUDED #define JSON_H_INCLUDED #if !defined(JSON_IS_AMALGAMATION) #include "forwards.h" #endif // if !defined(JSON_IS_AMALGAMATION) // Conditional NORETURN attribute on the throw functions would: // a) suppress false positives from static code analysis // b) possibly improve optimization opportunities. #if !defined(JSONCPP_NORETURN) #if defined(_MSC_VER) && _MSC_VER == 1800 #define JSONCPP_NORETURN __declspec(noreturn) #else #define JSONCPP_NORETURN [[noreturn]] #endif #endif // Support for '= delete' with template declarations was a late addition // to the c++11 standard and is rejected by clang 3.8 and Apple clang 8.2 // even though these declare themselves to be c++11 compilers. #if !defined(JSONCPP_TEMPLATE_DELETE) #if defined(__clang__) && defined(__apple_build_version__) #if __apple_build_version__ <= 8000042 #define JSONCPP_TEMPLATE_DELETE #endif #elif defined(__clang__) #if __clang_major__ == 3 && __clang_minor__ <= 8 #define JSONCPP_TEMPLATE_DELETE #endif #endif #if !defined(JSONCPP_TEMPLATE_DELETE) #define JSONCPP_TEMPLATE_DELETE = delete #endif #endif #include <array> #include <exception> #include <map> #include <memory> #include <string> #include <vector> // Disable warning C4251: <data member>: <type> needs to have dll-interface to // be used by... #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #pragma warning(push) #pragma warning(disable : 4251) #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #pragma pack(push, 8) /** \brief JSON (JavaScript Object Notation). */ namespace Json { #if JSON_USE_EXCEPTION /** Base class for all exceptions we throw. * * We use nothing but these internally. Of course, STL can throw others. */ class JSON_API Exception : public std::exception { public: Exception(String msg); ~Exception() JSONCPP_NOEXCEPT override; char const* what() const JSONCPP_NOEXCEPT override; protected: String msg_; }; /** Exceptions which the user cannot easily avoid. * * E.g. out-of-memory (when we use malloc), stack-overflow, malicious input * * \remark derived from Json::Exception */ class JSON_API RuntimeError : public Exception { public: RuntimeError(String const& msg); }; /** Exceptions thrown by JSON_ASSERT/JSON_FAIL macros. * * These are precondition-violations (user bugs) and internal errors (our bugs). * * \remark derived from Json::Exception */ class JSON_API LogicError : public Exception { public: LogicError(String const& msg); }; #endif /// used internally JSONCPP_NORETURN void throwRuntimeError(String const& msg); /// used internally JSONCPP_NORETURN void throwLogicError(String const& msg); /** \brief Type of the value held by a Value object. */ enum ValueType { nullValue = 0, ///< 'null' value intValue, ///< signed integer value uintValue, ///< unsigned integer value realValue, ///< double value stringValue, ///< UTF-8 string value booleanValue, ///< bool value arrayValue, ///< array value (ordered list) objectValue ///< object value (collection of name/value pairs). }; enum CommentPlacement { commentBefore = 0, ///< a comment placed on the line before a value commentAfterOnSameLine, ///< a comment just after a value on the same line commentAfter, ///< a comment on the line after a value (only make sense for /// root value) numberOfCommentPlacement }; /** \brief Type of precision for formatting of real values. */ enum PrecisionType { significantDigits = 0, ///< we set max number of significant digits in string decimalPlaces ///< we set max number of digits after "." in string }; /** \brief Lightweight wrapper to tag static string. * * Value constructor and objectValue member assignment takes advantage of the * StaticString and avoid the cost of string duplication when storing the * string or the member name. * * Example of usage: * \code * Json::Value aValue( StaticString("some text") ); * Json::Value object; * static const StaticString code("code"); * object[code] = 1234; * \endcode */ class JSON_API StaticString { public: explicit StaticString(const char* czstring) : c_str_(czstring) {} operator const char*() const { return c_str_; } const char* c_str() const { return c_str_; } private: const char* c_str_; }; /** \brief Represents a <a HREF="http://www.json.org">JSON</a> value. * * This class is a discriminated union wrapper that can represents a: * - signed integer [range: Value::minInt - Value::maxInt] * - unsigned integer (range: 0 - Value::maxUInt) * - double * - UTF-8 string * - boolean * - 'null' * - an ordered list of Value * - collection of name/value pairs (javascript object) * * The type of the held value is represented by a #ValueType and * can be obtained using type(). * * Values of an #objectValue or #arrayValue can be accessed using operator[]() * methods. * Non-const methods will automatically create the a #nullValue element * if it does not exist. * The sequence of an #arrayValue will be automatically resized and initialized * with #nullValue. resize() can be used to enlarge or truncate an #arrayValue. * * The get() methods can be used to obtain default value in the case the * required element does not exist. * * It is possible to iterate over the list of member keys of an object using * the getMemberNames() method. * * \note #Value string-length fit in size_t, but keys must be < 2^30. * (The reason is an implementation detail.) A #CharReader will raise an * exception if a bound is exceeded to avoid security holes in your app, * but the Value API does *not* check bounds. That is the responsibility * of the caller. */ class JSON_API Value { friend class ValueIteratorBase; public: using Members = std::vector<String>; using iterator = ValueIterator; using const_iterator = ValueConstIterator; using UInt = Json::UInt; using Int = Json::Int; #if defined(JSON_HAS_INT64) using UInt64 = Json::UInt64; using Int64 = Json::Int64; #endif // defined(JSON_HAS_INT64) using LargestInt = Json::LargestInt; using LargestUInt = Json::LargestUInt; using ArrayIndex = Json::ArrayIndex; // Required for boost integration, e. g. BOOST_TEST using value_type = std::string; #if JSON_USE_NULLREF // Binary compatibility kludges, do not use. static const Value& null; static const Value& nullRef; #endif // null and nullRef are deprecated, use this instead. static Value const& nullSingleton(); /// Minimum signed integer value that can be stored in a Json::Value. static constexpr LargestInt minLargestInt = LargestInt(~(LargestUInt(-1) / 2)); /// Maximum signed integer value that can be stored in a Json::Value. static constexpr LargestInt maxLargestInt = LargestInt(LargestUInt(-1) / 2); /// Maximum unsigned integer value that can be stored in a Json::Value. static constexpr LargestUInt maxLargestUInt = LargestUInt(-1); /// Minimum signed int value that can be stored in a Json::Value. static constexpr Int minInt = Int(~(UInt(-1) / 2)); /// Maximum signed int value that can be stored in a Json::Value. static constexpr Int maxInt = Int(UInt(-1) / 2); /// Maximum unsigned int value that can be stored in a Json::Value. static constexpr UInt maxUInt = UInt(-1); #if defined(JSON_HAS_INT64) /// Minimum signed 64 bits int value that can be stored in a Json::Value. static constexpr Int64 minInt64 = Int64(~(UInt64(-1) / 2)); /// Maximum signed 64 bits int value that can be stored in a Json::Value. static constexpr Int64 maxInt64 = Int64(UInt64(-1) / 2); /// Maximum unsigned 64 bits int value that can be stored in a Json::Value. static constexpr UInt64 maxUInt64 = UInt64(-1); #endif // defined(JSON_HAS_INT64) /// Default precision for real value for string representation. static constexpr UInt defaultRealPrecision = 17; // The constant is hard-coded because some compiler have trouble // converting Value::maxUInt64 to a double correctly (AIX/xlC). // Assumes that UInt64 is a 64 bits integer. static constexpr double maxUInt64AsDouble = 18446744073709551615.0; // Workaround for bug in the NVIDIAs CUDA 9.1 nvcc compiler // when using gcc and clang backend compilers. CZString // cannot be defined as private. See issue #486 #ifdef __NVCC__ public: #else private: #endif #ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION class CZString { public: enum DuplicationPolicy { noDuplication = 0, duplicate, duplicateOnCopy }; CZString(ArrayIndex index); CZString(char const* str, unsigned length, DuplicationPolicy allocate); CZString(CZString const& other); CZString(CZString&& other); ~CZString(); CZString& operator=(const CZString& other); CZString& operator=(CZString&& other); bool operator<(CZString const& other) const; bool operator==(CZString const& other) const; ArrayIndex index() const; // const char* c_str() const; ///< \deprecated char const* data() const; unsigned length() const; bool isStaticString() const; private: void swap(CZString& other); struct StringStorage { unsigned policy_ : 2; unsigned length_ : 30; // 1GB max }; char const* cstr_; // actually, a prefixed string, unless policy is noDup union { ArrayIndex index_; StringStorage storage_; }; }; public: typedef std::map<CZString, Value> ObjectValues; #endif // ifndef JSONCPP_DOC_EXCLUDE_IMPLEMENTATION public: /** * \brief Create a default Value of the given type. * * This is a very useful constructor. * To create an empty array, pass arrayValue. * To create an empty object, pass objectValue. * Another Value can then be set to this one by assignment. * This is useful since clear() and resize() will not alter types. * * Examples: * \code * Json::Value null_value; // null * Json::Value arr_value(Json::arrayValue); // [] * Json::Value obj_value(Json::objectValue); // {} * \endcode */ Value(ValueType type = nullValue); Value(Int value); Value(UInt value); #if defined(JSON_HAS_INT64) Value(Int64 value); Value(UInt64 value); #endif // if defined(JSON_HAS_INT64) Value(double value); Value(const char* value); ///< Copy til first 0. (NULL causes to seg-fault.) Value(const char* begin, const char* end); ///< Copy all, incl zeroes. /** * \brief Constructs a value from a static string. * * Like other value string constructor but do not duplicate the string for * internal storage. The given string must remain alive after the call to * this constructor. * * \note This works only for null-terminated strings. (We cannot change the * size of this class, so we have nowhere to store the length, which might be * computed later for various operations.) * * Example of usage: * \code * static StaticString foo("some text"); * Json::Value aValue(foo); * \endcode */ Value(const StaticString& value); Value(const String& value); Value(bool value); Value(const Value& other); Value(Value&& other); ~Value(); /// \note Overwrite existing comments. To preserve comments, use /// #swapPayload(). Value& operator=(const Value& other); Value& operator=(Value&& other); /// Swap everything. void swap(Value& other); /// Swap values but leave comments and source offsets in place. void swapPayload(Value& other); /// copy everything. void copy(const Value& other); /// copy values but leave comments and source offsets in place. void copyPayload(const Value& other); ValueType type() const; /// Compare payload only, not comments etc. bool operator<(const Value& other) const; bool operator<=(const Value& other) const; bool operator>=(const Value& other) const; bool operator>(const Value& other) const; bool operator==(const Value& other) const; bool operator!=(const Value& other) const; int compare(const Value& other) const; const char* asCString() const; ///< Embedded zeroes could cause you trouble! #if JSONCPP_USING_SECURE_MEMORY unsigned getCStringLength() const; // Allows you to understand the length of // the CString #endif String asString() const; ///< Embedded zeroes are possible. /** Get raw char* of string-value. * \return false if !string. (Seg-fault if str or end are NULL.) */ bool getString(char const** begin, char const** end) const; Int asInt() const; UInt asUInt() const; #if defined(JSON_HAS_INT64) Int64 asInt64() const; UInt64 asUInt64() const; #endif // if defined(JSON_HAS_INT64) LargestInt asLargestInt() const; LargestUInt asLargestUInt() const; float asFloat() const; double asDouble() const; bool asBool() const; bool isNull() const; bool isBool() const; bool isInt() const; bool isInt64() const; bool isUInt() const; bool isUInt64() const; bool isIntegral() const; bool isDouble() const; bool isNumeric() const; bool isString() const; bool isArray() const; bool isObject() const; /// The `as<T>` and `is<T>` member function templates and specializations. template <typename T> T as() const JSONCPP_TEMPLATE_DELETE; template <typename T> bool is() const JSONCPP_TEMPLATE_DELETE; bool isConvertibleTo(ValueType other) const; /// Number of values in array or object ArrayIndex size() const; /// \brief Return true if empty array, empty object, or null; /// otherwise, false. bool empty() const; /// Return !isNull() JSONCPP_OP_EXPLICIT operator bool() const; /// Remove all object members and array elements. /// \pre type() is arrayValue, objectValue, or nullValue /// \post type() is unchanged void clear(); /// Resize the array to newSize elements. /// New elements are initialized to null. /// May only be called on nullValue or arrayValue. /// \pre type() is arrayValue or nullValue /// \post type() is arrayValue void resize(ArrayIndex newSize); //@{ /// Access an array element (zero based index). If the array contains less /// than index element, then null value are inserted in the array so that /// its size is index+1. /// (You may need to say 'value[0u]' to get your compiler to distinguish /// this from the operator[] which takes a string.) Value& operator[](ArrayIndex index); Value& operator[](int index); //@} //@{ /// Access an array element (zero based index). /// (You may need to say 'value[0u]' to get your compiler to distinguish /// this from the operator[] which takes a string.) const Value& operator[](ArrayIndex index) const; const Value& operator[](int index) const; //@} /// If the array contains at least index+1 elements, returns the element /// value, otherwise returns defaultValue. Value get(ArrayIndex index, const Value& defaultValue) const; /// Return true if index < size(). bool isValidIndex(ArrayIndex index) const; /// \brief Append value to array at the end. /// /// Equivalent to jsonvalue[jsonvalue.size()] = value; Value& append(const Value& value); Value& append(Value&& value); /// \brief Insert value in array at specific index bool insert(ArrayIndex index, const Value& newValue); bool insert(ArrayIndex index, Value&& newValue); /// Access an object value by name, create a null member if it does not exist. /// \note Because of our implementation, keys are limited to 2^30 -1 chars. /// Exceeding that will cause an exception. Value& operator[](const char* key); /// Access an object value by name, returns null if there is no member with /// that name. const Value& operator[](const char* key) const; /// Access an object value by name, create a null member if it does not exist. /// \param key may contain embedded nulls. Value& operator[](const String& key); /// Access an object value by name, returns null if there is no member with /// that name. /// \param key may contain embedded nulls. const Value& operator[](const String& key) const; /** \brief Access an object value by name, create a null member if it does not * exist. * * If the object has no entry for that name, then the member name used to * store the new entry is not duplicated. * Example of use: * \code * Json::Value object; * static const StaticString code("code"); * object[code] = 1234; * \endcode */ Value& operator[](const StaticString& key); /// Return the member named key if it exist, defaultValue otherwise. /// \note deep copy Value get(const char* key, const Value& defaultValue) const; /// Return the member named key if it exist, defaultValue otherwise. /// \note deep copy /// \note key may contain embedded nulls. Value get(const char* begin, const char* end, const Value& defaultValue) const; /// Return the member named key if it exist, defaultValue otherwise. /// \note deep copy /// \param key may contain embedded nulls. Value get(const String& key, const Value& defaultValue) const; /// Most general and efficient version of isMember()const, get()const, /// and operator[]const /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30 Value const* find(char const* begin, char const* end) const; /// Most general and efficient version of object-mutators. /// \note As stated elsewhere, behavior is undefined if (end-begin) >= 2^30 /// \return non-zero, but JSON_ASSERT if this is neither object nor nullValue. Value* demand(char const* begin, char const* end); /// \brief Remove and return the named member. /// /// Do nothing if it did not exist. /// \pre type() is objectValue or nullValue /// \post type() is unchanged void removeMember(const char* key); /// Same as removeMember(const char*) /// \param key may contain embedded nulls. void removeMember(const String& key); /// Same as removeMember(const char* begin, const char* end, Value* removed), /// but 'key' is null-terminated. bool removeMember(const char* key, Value* removed); /** \brief Remove the named map member. * * Update 'removed' iff removed. * \param key may contain embedded nulls. * \return true iff removed (no exceptions) */ bool removeMember(String const& key, Value* removed); /// Same as removeMember(String const& key, Value* removed) bool removeMember(const char* begin, const char* end, Value* removed); /** \brief Remove the indexed array element. * * O(n) expensive operations. * Update 'removed' iff removed. * \return true if removed (no exceptions) */ bool removeIndex(ArrayIndex index, Value* removed); /// Return true if the object has a member named key. /// \note 'key' must be null-terminated. bool isMember(const char* key) const; /// Return true if the object has a member named key. /// \param key may contain embedded nulls. bool isMember(const String& key) const; /// Same as isMember(String const& key)const bool isMember(const char* begin, const char* end) const; /// \brief Return a list of the member names. /// /// If null, return an empty list. /// \pre type() is objectValue or nullValue /// \post if type() was nullValue, it remains nullValue Members getMemberNames() const; /// \deprecated Always pass len. JSONCPP_DEPRECATED("Use setComment(String const&) instead.") void setComment(const char* comment, CommentPlacement placement) { setComment(String(comment, strlen(comment)), placement); } /// Comments must be //... or /* ... */ void setComment(const char* comment, size_t len, CommentPlacement placement) { setComment(String(comment, len), placement); } /// Comments must be //... or /* ... */ void setComment(String comment, CommentPlacement placement); bool hasComment(CommentPlacement placement) const; /// Include delimiters and embedded newlines. String getComment(CommentPlacement placement) const; String toStyledString() const; const_iterator begin() const; const_iterator end() const; iterator begin(); iterator end(); // Accessors for the [start, limit) range of bytes within the JSON text from // which this value was parsed, if any. void setOffsetStart(ptrdiff_t start); void setOffsetLimit(ptrdiff_t limit); ptrdiff_t getOffsetStart() const; ptrdiff_t getOffsetLimit() const; private: void setType(ValueType v) { bits_.value_type_ = static_cast<unsigned char>(v); } bool isAllocated() const { return bits_.allocated_; } void setIsAllocated(bool v) { bits_.allocated_ = v; } void initBasic(ValueType type, bool allocated = false); void dupPayload(const Value& other); void releasePayload(); void dupMeta(const Value& other); Value& resolveReference(const char* key); Value& resolveReference(const char* key, const char* end); // struct MemberNamesTransform //{ // typedef const char *result_type; // const char *operator()( const CZString &name ) const // { // return name.c_str(); // } //}; union ValueHolder { LargestInt int_; LargestUInt uint_; double real_; bool bool_; char* string_; // if allocated_, ptr to { unsigned, char[] }. ObjectValues* map_; } value_; struct { // Really a ValueType, but types should agree for bitfield packing. unsigned int value_type_ : 8; // Unless allocated_, string_ must be null-terminated. unsigned int allocated_ : 1; } bits_; class Comments { public: Comments() = default; Comments(const Comments& that); Comments(Comments&& that); Comments& operator=(const Comments& that); Comments& operator=(Comments&& that); bool has(CommentPlacement slot) const; String get(CommentPlacement slot) const; void set(CommentPlacement slot, String comment); private: using Array = std::array<String, numberOfCommentPlacement>; std::unique_ptr<Array> ptr_; }; Comments comments_; // [start, limit) byte offsets in the source JSON text from which this Value // was extracted. ptrdiff_t start_; ptrdiff_t limit_; }; template <> inline bool Value::as<bool>() const { return asBool(); } template <> inline bool Value::is<bool>() const { return isBool(); } template <> inline Int Value::as<Int>() const { return asInt(); } template <> inline bool Value::is<Int>() const { return isInt(); } template <> inline UInt Value::as<UInt>() const { return asUInt(); } template <> inline bool Value::is<UInt>() const { return isUInt(); } #if defined(JSON_HAS_INT64) template <> inline Int64 Value::as<Int64>() const { return asInt64(); } template <> inline bool Value::is<Int64>() const { return isInt64(); } template <> inline UInt64 Value::as<UInt64>() const { return asUInt64(); } template <> inline bool Value::is<UInt64>() const { return isUInt64(); } #endif template <> inline double Value::as<double>() const { return asDouble(); } template <> inline bool Value::is<double>() const { return isDouble(); } template <> inline String Value::as<String>() const { return asString(); } template <> inline bool Value::is<String>() const { return isString(); } /// These `as` specializations are type conversions, and do not have a /// corresponding `is`. template <> inline float Value::as<float>() const { return asFloat(); } template <> inline const char* Value::as<const char*>() const { return asCString(); } /** \brief Experimental and untested: represents an element of the "path" to * access a node. */ class JSON_API PathArgument { public: friend class Path; PathArgument(); PathArgument(ArrayIndex index); PathArgument(const char* key); PathArgument(String key); private: enum Kind { kindNone = 0, kindIndex, kindKey }; String key_; ArrayIndex index_{}; Kind kind_{kindNone}; }; /** \brief Experimental and untested: represents a "path" to access a node. * * Syntax: * - "." => root node * - ".[n]" => elements at index 'n' of root node (an array value) * - ".name" => member named 'name' of root node (an object value) * - ".name1.name2.name3" * - ".[0][1][2].name1[3]" * - ".%" => member name is provided as parameter * - ".[%]" => index is provided as parameter */ class JSON_API Path { public: Path(const String& path, const PathArgument& a1 = PathArgument(), const PathArgument& a2 = PathArgument(), const PathArgument& a3 = PathArgument(), const PathArgument& a4 = PathArgument(), const PathArgument& a5 = PathArgument()); const Value& resolve(const Value& root) const; Value resolve(const Value& root, const Value& defaultValue) const; /// Creates the "path" to access the specified node and returns a reference on /// the node. Value& make(Value& root) const; private: using InArgs = std::vector<const PathArgument*>; using Args = std::vector<PathArgument>; void makePath(const String& path, const InArgs& in); void addPathInArg(const String& path, const InArgs& in, InArgs::const_iterator& itInArg, PathArgument::Kind kind); static void invalidPath(const String& path, int location); Args args_; }; /** \brief base class for Value iterators. * */ class JSON_API ValueIteratorBase { public: using iterator_category = std::bidirectional_iterator_tag; using size_t = unsigned int; using difference_type = int; using SelfType = ValueIteratorBase; bool operator==(const SelfType& other) const { return isEqual(other); } bool operator!=(const SelfType& other) const { return !isEqual(other); } difference_type operator-(const SelfType& other) const { return other.computeDistance(*this); } /// Return either the index or the member name of the referenced value as a /// Value. Value key() const; /// Return the index of the referenced Value, or -1 if it is not an /// arrayValue. UInt index() const; /// Return the member name of the referenced Value, or "" if it is not an /// objectValue. /// \note Avoid `c_str()` on result, as embedded zeroes are possible. String name() const; /// Return the member name of the referenced Value. "" if it is not an /// objectValue. /// \deprecated This cannot be used for UTF-8 strings, since there can be /// embedded nulls. JSONCPP_DEPRECATED("Use `key = name();` instead.") char const* memberName() const; /// Return the member name of the referenced Value, or NULL if it is not an /// objectValue. /// \note Better version than memberName(). Allows embedded nulls. char const* memberName(char const** end) const; protected: /*! Internal utility functions to assist with implementing * other iterator functions. The const and non-const versions * of the "deref" protected methods expose the protected * current_ member variable in a way that can often be * optimized away by the compiler. */ const Value& deref() const; Value& deref(); void increment(); void decrement(); difference_type computeDistance(const SelfType& other) const; bool isEqual(const SelfType& other) const; void copy(const SelfType& other); private: Value::ObjectValues::iterator current_; // Indicates that iterator is for a null value. bool isNull_{true}; public: // For some reason, BORLAND needs these at the end, rather // than earlier. No idea why. ValueIteratorBase(); explicit ValueIteratorBase(const Value::ObjectValues::iterator& current); }; /** \brief const iterator for object and array value. * */ class JSON_API ValueConstIterator : public ValueIteratorBase { friend class Value; public: using value_type = const Value; // typedef unsigned int size_t; // typedef int difference_type; using reference = const Value&; using pointer = const Value*; using SelfType = ValueConstIterator; ValueConstIterator(); ValueConstIterator(ValueIterator const& other); private: /*! \internal Use by Value to create an iterator. */ explicit ValueConstIterator(const Value::ObjectValues::iterator& current); public: SelfType& operator=(const ValueIteratorBase& other); SelfType operator++(int) { SelfType temp(*this); ++*this; return temp; } SelfType operator--(int) { SelfType temp(*this); --*this; return temp; } SelfType& operator--() { decrement(); return *this; } SelfType& operator++() { increment(); return *this; } reference operator*() const { return deref(); } pointer operator->() const { return &deref(); } }; /** \brief Iterator for object and array value. */ class JSON_API ValueIterator : public ValueIteratorBase { friend class Value; public: using value_type = Value; using size_t = unsigned int; using difference_type = int; using reference = Value&; using pointer = Value*; using SelfType = ValueIterator; ValueIterator(); explicit ValueIterator(const ValueConstIterator& other); ValueIterator(const ValueIterator& other); private: /*! \internal Use by Value to create an iterator. */ explicit ValueIterator(const Value::ObjectValues::iterator& current); public: SelfType& operator=(const SelfType& other); SelfType operator++(int) { SelfType temp(*this); ++*this; return temp; } SelfType operator--(int) { SelfType temp(*this); --*this; return temp; } SelfType& operator--() { decrement(); return *this; } SelfType& operator++() { increment(); return *this; } /*! The return value of non-const iterators can be * changed, so the these functions are not const * because the returned references/pointers can be used * to change state of the base class. */ reference operator*() { return deref(); } pointer operator->() { return &deref(); } }; inline void swap(Value& a, Value& b) { a.swap(b); } } // namespace Json #pragma pack(pop) #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #pragma warning(pop) #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #endif // JSON_H_INCLUDED
Unknown
3D
mcellteam/mcell
libs/jsoncpp/include/json/writer.h
.h
12,202
368
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #ifndef JSON_WRITER_H_INCLUDED #define JSON_WRITER_H_INCLUDED #if !defined(JSON_IS_AMALGAMATION) #include "value.h" #endif // if !defined(JSON_IS_AMALGAMATION) #include <ostream> #include <string> #include <vector> // Disable warning C4251: <data member>: <type> needs to have dll-interface to // be used by... #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) && defined(_MSC_VER) #pragma warning(push) #pragma warning(disable : 4251) #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #pragma pack(push, 8) namespace Json { class Value; /** * * Usage: * \code * using namespace Json; * void writeToStdout(StreamWriter::Factory const& factory, Value const& value) * { std::unique_ptr<StreamWriter> const writer( factory.newStreamWriter()); * writer->write(value, &std::cout); * std::cout << std::endl; // add lf and flush * } * \endcode */ class JSON_API StreamWriter { protected: OStream* sout_; // not owned; will not delete public: StreamWriter(); virtual ~StreamWriter(); /** Write Value into document as configured in sub-class. * Do not take ownership of sout, but maintain a reference during function. * \pre sout != NULL * \return zero on success (For now, we always return zero, so check the * stream instead.) \throw std::exception possibly, depending on * configuration */ virtual int write(Value const& root, OStream* sout) = 0; /** \brief A simple abstract factory. */ class JSON_API Factory { public: virtual ~Factory(); /** \brief Allocate a CharReader via operator new(). * \throw std::exception if something goes wrong (e.g. invalid settings) */ virtual StreamWriter* newStreamWriter() const = 0; }; // Factory }; // StreamWriter /** \brief Write into stringstream, then return string, for convenience. * A StreamWriter will be created from the factory, used, and then deleted. */ String JSON_API writeString(StreamWriter::Factory const& factory, Value const& root); /** \brief Build a StreamWriter implementation. * Usage: * \code * using namespace Json; * Value value = ...; * StreamWriterBuilder builder; * builder["commentStyle"] = "None"; * builder["indentation"] = " "; // or whatever you like * std::unique_ptr<Json::StreamWriter> writer( * builder.newStreamWriter()); * writer->write(value, &std::cout); * std::cout << std::endl; // add lf and flush * \endcode */ class JSON_API StreamWriterBuilder : public StreamWriter::Factory { public: // Note: We use a Json::Value so that we can add data-members to this class // without a major version bump. /** Configuration of this builder. * Available settings (case-sensitive): * - "commentStyle": "None" or "All" * - "indentation": "<anything>". * - Setting this to an empty string also omits newline characters. * - "enableYAMLCompatibility": false or true * - slightly change the whitespace around colons * - "dropNullPlaceholders": false or true * - Drop the "null" string from the writer's output for nullValues. * Strictly speaking, this is not valid JSON. But when the output is being * fed to a browser's JavaScript, it makes for smaller output and the * browser can handle the output just fine. * - "useSpecialFloats": false or true * - If true, outputs non-finite floating point values in the following way: * NaN values as "NaN", positive infinity as "Infinity", and negative * infinity as "-Infinity". * - "precision": int * - Number of precision digits for formatting of real values. * - "precisionType": "significant"(default) or "decimal" * - Type of precision for formatting of real values. * You can examine 'settings_` yourself * to see the defaults. You can also write and read them just like any * JSON Value. * \sa setDefaults() */ Json::Value settings_; StreamWriterBuilder(); ~StreamWriterBuilder() override; /** * \throw std::exception if something goes wrong (e.g. invalid settings) */ StreamWriter* newStreamWriter() const override; /** \return true if 'settings' are legal and consistent; * otherwise, indicate bad settings via 'invalid'. */ bool validate(Json::Value* invalid) const; /** A simple way to update a specific setting. */ Value& operator[](const String& key); /** Called by ctor, but you can use this to reset settings_. * \pre 'settings' != NULL (but Json::null is fine) * \remark Defaults: * \snippet src/lib_json/json_writer.cpp StreamWriterBuilderDefaults */ static void setDefaults(Json::Value* settings); }; /** \brief Abstract class for writers. * \deprecated Use StreamWriter. (And really, this is an implementation detail.) */ class JSONCPP_DEPRECATED("Use StreamWriter instead") JSON_API Writer { public: virtual ~Writer(); virtual String write(const Value& root) = 0; }; /** \brief Outputs a Value in <a HREF="http://www.json.org">JSON</a> format *without formatting (not human friendly). * * The JSON document is written in a single line. It is not intended for 'human' *consumption, * but may be useful to support feature such as RPC where bandwidth is limited. * \sa Reader, Value * \deprecated Use StreamWriterBuilder. */ #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable : 4996) // Deriving from deprecated class #endif class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API FastWriter : public Writer { public: FastWriter(); ~FastWriter() override = default; void enableYAMLCompatibility(); /** \brief Drop the "null" string from the writer's output for nullValues. * Strictly speaking, this is not valid JSON. But when the output is being * fed to a browser's JavaScript, it makes for smaller output and the * browser can handle the output just fine. */ void dropNullPlaceholders(); void omitEndingLineFeed(); public: // overridden from Writer String write(const Value& root) override; private: void writeValue(const Value& value); String document_; bool yamlCompatibilityEnabled_{false}; bool dropNullPlaceholders_{false}; bool omitEndingLineFeed_{false}; }; #if defined(_MSC_VER) #pragma warning(pop) #endif /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a *human friendly way. * * The rules for line break and indent are as follow: * - Object value: * - if empty then print {} without indent and line break * - if not empty the print '{', line break & indent, print one value per *line * and then unindent and line break and print '}'. * - Array value: * - if empty then print [] without indent and line break * - if the array contains no object value, empty array or some other value *types, * and all the values fit on one lines, then print the array on a single *line. * - otherwise, it the values do not fit on one line, or the array contains * object or non empty array, then print one value per line. * * If the Value have comments then they are outputed according to their *#CommentPlacement. * * \sa Reader, Value, Value::setComment() * \deprecated Use StreamWriterBuilder. */ #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable : 4996) // Deriving from deprecated class #endif class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API StyledWriter : public Writer { public: StyledWriter(); ~StyledWriter() override = default; public: // overridden from Writer /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format. * \param root Value to serialize. * \return String containing the JSON document that represents the root value. */ String write(const Value& root) override; private: void writeValue(const Value& value); void writeArrayValue(const Value& value); bool isMultilineArray(const Value& value); void pushValue(const String& value); void writeIndent(); void writeWithIndent(const String& value); void indent(); void unindent(); void writeCommentBeforeValue(const Value& root); void writeCommentAfterValueOnSameLine(const Value& root); static bool hasCommentForValue(const Value& value); static String normalizeEOL(const String& text); using ChildValues = std::vector<String>; ChildValues childValues_; String document_; String indentString_; unsigned int rightMargin_{74}; unsigned int indentSize_{3}; bool addChildValues_{false}; }; #if defined(_MSC_VER) #pragma warning(pop) #endif /** \brief Writes a Value in <a HREF="http://www.json.org">JSON</a> format in a human friendly way, to a stream rather than to a string. * * The rules for line break and indent are as follow: * - Object value: * - if empty then print {} without indent and line break * - if not empty the print '{', line break & indent, print one value per line * and then unindent and line break and print '}'. * - Array value: * - if empty then print [] without indent and line break * - if the array contains no object value, empty array or some other value types, * and all the values fit on one lines, then print the array on a single line. * - otherwise, it the values do not fit on one line, or the array contains * object or non empty array, then print one value per line. * * If the Value have comments then they are outputed according to their #CommentPlacement. * * \sa Reader, Value, Value::setComment() * \deprecated Use StreamWriterBuilder. */ #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable : 4996) // Deriving from deprecated class #endif class JSONCPP_DEPRECATED("Use StreamWriterBuilder instead") JSON_API StyledStreamWriter { public: /** * \param indentation Each level will be indented by this amount extra. */ StyledStreamWriter(String indentation = "\t"); ~StyledStreamWriter() = default; public: /** \brief Serialize a Value in <a HREF="http://www.json.org">JSON</a> format. * \param out Stream to write to. (Can be ostringstream, e.g.) * \param root Value to serialize. * \note There is no point in deriving from Writer, since write() should not * return a value. */ void write(OStream& out, const Value& root); private: void writeValue(const Value& value); void writeArrayValue(const Value& value); bool isMultilineArray(const Value& value); void pushValue(const String& value); void writeIndent(); void writeWithIndent(const String& value); void indent(); void unindent(); void writeCommentBeforeValue(const Value& root); void writeCommentAfterValueOnSameLine(const Value& root); static bool hasCommentForValue(const Value& value); static String normalizeEOL(const String& text); using ChildValues = std::vector<String>; ChildValues childValues_; OStream* document_; String indentString_; unsigned int rightMargin_{74}; String indentation_; bool addChildValues_ : 1; bool indented_ : 1; }; #if defined(_MSC_VER) #pragma warning(pop) #endif #if defined(JSON_HAS_INT64) String JSON_API valueToString(Int value); String JSON_API valueToString(UInt value); #endif // if defined(JSON_HAS_INT64) String JSON_API valueToString(LargestInt value); String JSON_API valueToString(LargestUInt value); String JSON_API valueToString( double value, unsigned int precision = Value::defaultRealPrecision, PrecisionType precisionType = PrecisionType::significantDigits); String JSON_API valueToString(bool value); String JSON_API valueToQuotedString(const char* value); /// \brief Output using the StyledStreamWriter. /// \see Json::operator>>() JSON_API OStream& operator<<(OStream&, const Value& root); } // namespace Json #pragma pack(pop) #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #pragma warning(pop) #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #endif // JSON_WRITER_H_INCLUDED
Unknown
3D
mcellteam/mcell
libs/jsoncpp/include/json/json.h
.h
447
16
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #ifndef JSON_JSON_H_INCLUDED #define JSON_JSON_H_INCLUDED #include "config.h" #include "json_features.h" #include "reader.h" #include "value.h" #include "writer.h" #endif // JSON_JSON_H_INCLUDED
Unknown
3D
mcellteam/mcell
libs/jsoncpp/include/json/forwards.h
.h
917
44
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #ifndef JSON_FORWARDS_H_INCLUDED #define JSON_FORWARDS_H_INCLUDED #if !defined(JSON_IS_AMALGAMATION) #include "config.h" #endif // if !defined(JSON_IS_AMALGAMATION) namespace Json { // writer.h class StreamWriter; class StreamWriterBuilder; class Writer; class FastWriter; class StyledWriter; class StyledStreamWriter; // reader.h class Reader; class CharReader; class CharReaderBuilder; // json_features.h class Features; // value.h using ArrayIndex = unsigned int; class StaticString; class Path; class PathArgument; class Value; class ValueIteratorBase; class ValueIterator; class ValueConstIterator; } // namespace Json #endif // JSON_FORWARDS_H_INCLUDED
Unknown
3D
mcellteam/mcell
libs/jsoncpp/include/json/config.h
.h
5,673
165
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #ifndef JSON_CONFIG_H_INCLUDED #define JSON_CONFIG_H_INCLUDED #include <cstddef> #include <cstdint> #include <istream> #include <memory> #include <ostream> #include <sstream> #include <string> #include <type_traits> // If non-zero, the library uses exceptions to report bad input instead of C // assertion macros. The default is to use exceptions. #ifndef JSON_USE_EXCEPTION #define JSON_USE_EXCEPTION 1 #endif // Temporary, tracked for removal with issue #982. #ifndef JSON_USE_NULLREF #define JSON_USE_NULLREF 1 #endif /// If defined, indicates that the source file is amalgamated /// to prevent private header inclusion. /// Remarks: it is automatically defined in the generated amalgamated header. // #define JSON_IS_AMALGAMATION // Export macros for DLL visibility #if defined(JSON_DLL_BUILD) #if defined(_MSC_VER) || defined(__MINGW32__) #define JSON_API __declspec(dllexport) #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING #elif defined(__GNUC__) || defined(__clang__) #define JSON_API __attribute__((visibility("default"))) #endif // if defined(_MSC_VER) #elif defined(JSON_DLL) #if defined(_MSC_VER) || defined(__MINGW32__) #define JSON_API __declspec(dllimport) #define JSONCPP_DISABLE_DLL_INTERFACE_WARNING #endif // if defined(_MSC_VER) #endif // ifdef JSON_DLL_BUILD #if !defined(JSON_API) #define JSON_API #endif #if defined(_MSC_VER) && _MSC_VER < 1800 #error \ "ERROR: Visual Studio 12 (2013) with _MSC_VER=1800 is the oldest supported compiler with sufficient C++11 capabilities" #endif #if defined(_MSC_VER) && _MSC_VER < 1900 // As recommended at // https://stackoverflow.com/questions/2915672/snprintf-and-visual-studio-2010 extern JSON_API int msvc_pre1900_c99_snprintf(char* outBuf, size_t size, const char* format, ...); #define jsoncpp_snprintf msvc_pre1900_c99_snprintf #else #define jsoncpp_snprintf std::snprintf #endif // If JSON_NO_INT64 is defined, then Json only support C++ "int" type for // integer // Storages, and 64 bits integer support is disabled. // #define JSON_NO_INT64 1 // JSONCPP_OVERRIDE is maintained for backwards compatibility of external tools. // C++11 should be used directly in JSONCPP. #define JSONCPP_OVERRIDE override #if __cplusplus >= 201103L #define JSONCPP_NOEXCEPT noexcept #define JSONCPP_OP_EXPLICIT explicit #elif defined(_MSC_VER) && _MSC_VER < 1900 #define JSONCPP_NOEXCEPT throw() #define JSONCPP_OP_EXPLICIT explicit #elif defined(_MSC_VER) && _MSC_VER >= 1900 #define JSONCPP_NOEXCEPT noexcept #define JSONCPP_OP_EXPLICIT explicit #else #define JSONCPP_NOEXCEPT throw() #define JSONCPP_OP_EXPLICIT #endif #ifdef __clang__ #if __has_extension(attribute_deprecated_with_message) #define JSONCPP_DEPRECATED(message) __attribute__((deprecated(message))) #endif #elif defined(__GNUC__) // not clang (gcc comes later since clang emulates gcc) #if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)) #define JSONCPP_DEPRECATED(message) __attribute__((deprecated(message))) #elif (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) #define JSONCPP_DEPRECATED(message) __attribute__((__deprecated__)) #endif // GNUC version #elif defined(_MSC_VER) // MSVC (after clang because clang on Windows emulates // MSVC) #define JSONCPP_DEPRECATED(message) __declspec(deprecated(message)) #endif // __clang__ || __GNUC__ || _MSC_VER #if !defined(JSONCPP_DEPRECATED) #define JSONCPP_DEPRECATED(message) #endif // if !defined(JSONCPP_DEPRECATED) #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 6)) #define JSON_USE_INT64_DOUBLE_CONVERSION 1 #endif #if !defined(JSON_IS_AMALGAMATION) #include "allocator.h" #include "version.h" #endif // if !defined(JSON_IS_AMALGAMATION) namespace Json { using Int = int; using UInt = unsigned int; #if defined(JSON_NO_INT64) using LargestInt = int; using LargestUInt = unsigned int; #undef JSON_HAS_INT64 #else // if defined(JSON_NO_INT64) // For Microsoft Visual use specific types as long long is not supported #if defined(_MSC_VER) // Microsoft Visual Studio using Int64 = __int64; using UInt64 = unsigned __int64; #else // if defined(_MSC_VER) // Other platforms, use long long using Int64 = int64_t; using UInt64 = uint64_t; #endif // if defined(_MSC_VER) using LargestInt = Int64; using LargestUInt = UInt64; #define JSON_HAS_INT64 #endif // if defined(JSON_NO_INT64) template <typename T> using Allocator = typename std::conditional<JSONCPP_USING_SECURE_MEMORY, SecureAllocator<T>, std::allocator<T>>::type; using String = std::basic_string<char, std::char_traits<char>, Allocator<char>>; using IStringStream = std::basic_istringstream<String::value_type, String::traits_type, String::allocator_type>; using OStringStream = std::basic_ostringstream<String::value_type, String::traits_type, String::allocator_type>; using IStream = std::istream; using OStream = std::ostream; } // namespace Json // Legacy names (formerly macros). using JSONCPP_STRING = Json::String; using JSONCPP_ISTRINGSTREAM = Json::IStringStream; using JSONCPP_OSTRINGSTREAM = Json::OStringStream; using JSONCPP_ISTREAM = Json::IStream; using JSONCPP_OSTREAM = Json::OStream; #endif // JSON_CONFIG_H_INCLUDED
Unknown
3D
mcellteam/mcell
libs/jsoncpp/include/json/version.h
.h
966
29
#ifndef JSON_VERSION_H_INCLUDED #define JSON_VERSION_H_INCLUDED // Note: version must be updated in three places when doing a release. This // annoying process ensures that amalgamate, CMake, and meson all report the // correct version. // 1. /meson.build // 2. /include/json/version.h // 3. /CMakeLists.txt // IMPORTANT: also update the SOVERSION!! #define JSONCPP_VERSION_STRING "1.9.3" #define JSONCPP_VERSION_MAJOR 1 #define JSONCPP_VERSION_MINOR 9 #define JSONCPP_VERSION_PATCH 3 #define JSONCPP_VERSION_QUALIFIER #define JSONCPP_VERSION_HEXA \ ((JSONCPP_VERSION_MAJOR << 24) | (JSONCPP_VERSION_MINOR << 16) | \ (JSONCPP_VERSION_PATCH << 8)) #ifdef JSONCPP_USING_SECURE_MEMORY #undef JSONCPP_USING_SECURE_MEMORY #endif #define JSONCPP_USING_SECURE_MEMORY 0 // If non-zero, the library zeroes any memory that it has allocated before // it frees its memory. #endif // JSON_VERSION_H_INCLUDED
Unknown
3D
mcellteam/mcell
libs/jsoncpp/include/json/reader.h
.h
14,114
404
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #ifndef JSON_READER_H_INCLUDED #define JSON_READER_H_INCLUDED #if !defined(JSON_IS_AMALGAMATION) #include "json_features.h" #include "value.h" #endif // if !defined(JSON_IS_AMALGAMATION) #include <deque> #include <iosfwd> #include <istream> #include <stack> #include <string> // Disable warning C4251: <data member>: <type> needs to have dll-interface to // be used by... #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #pragma warning(push) #pragma warning(disable : 4251) #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #pragma pack(push, 8) namespace Json { /** \brief Unserialize a <a HREF="http://www.json.org">JSON</a> document into a * Value. * * \deprecated Use CharReader and CharReaderBuilder. */ class /*JSONCPP_DEPRECATED( "Use CharReader and CharReaderBuilder instead.")*/ JSON_API Reader { public: using Char = char; using Location = const Char*; /** \brief An error tagged with where in the JSON text it was encountered. * * The offsets give the [start, limit) range of bytes within the text. Note * that this is bytes, not codepoints. */ struct StructuredError { ptrdiff_t offset_start; ptrdiff_t offset_limit; String message; }; /** \brief Constructs a Reader allowing all features for parsing. */ JSONCPP_DEPRECATED("Use CharReader and CharReaderBuilder instead") Reader(); /** \brief Constructs a Reader allowing the specified feature set for parsing. */ JSONCPP_DEPRECATED("Use CharReader and CharReaderBuilder instead") Reader(const Features& features); /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a> * document. * * \param document UTF-8 encoded string containing the document * to read. * \param[out] root Contains the root value of the document if it * was successfully parsed. * \param collectComments \c true to collect comment and allow writing * them back during serialization, \c false to * discard comments. This parameter is ignored * if Features::allowComments_ is \c false. * \return \c true if the document was successfully parsed, \c false if an * error occurred. */ bool parse(const std::string& document, Value& root, bool collectComments = true); /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a> * document. * * \param beginDoc Pointer on the beginning of the UTF-8 encoded * string of the document to read. * \param endDoc Pointer on the end of the UTF-8 encoded string * of the document to read. Must be >= beginDoc. * \param[out] root Contains the root value of the document if it * was successfully parsed. * \param collectComments \c true to collect comment and allow writing * them back during serialization, \c false to * discard comments. This parameter is ignored * if Features::allowComments_ is \c false. * \return \c true if the document was successfully parsed, \c false if an * error occurred. */ bool parse(const char* beginDoc, const char* endDoc, Value& root, bool collectComments = true); /// \brief Parse from input stream. /// \see Json::operator>>(std::istream&, Json::Value&). bool parse(IStream& is, Value& root, bool collectComments = true); /** \brief Returns a user friendly string that list errors in the parsed * document. * * \return Formatted error message with the list of errors with their * location in the parsed document. An empty string is returned if no error * occurred during parsing. * \deprecated Use getFormattedErrorMessages() instead (typo fix). */ JSONCPP_DEPRECATED("Use getFormattedErrorMessages() instead.") String getFormatedErrorMessages() const; /** \brief Returns a user friendly string that list errors in the parsed * document. * * \return Formatted error message with the list of errors with their * location in the parsed document. An empty string is returned if no error * occurred during parsing. */ String getFormattedErrorMessages() const; /** \brief Returns a vector of structured errors encountered while parsing. * * \return A (possibly empty) vector of StructuredError objects. Currently * only one error can be returned, but the caller should tolerate multiple * errors. This can occur if the parser recovers from a non-fatal parse * error and then encounters additional errors. */ std::vector<StructuredError> getStructuredErrors() const; /** \brief Add a semantic error message. * * \param value JSON Value location associated with the error * \param message The error message. * \return \c true if the error was successfully added, \c false if the Value * offset exceeds the document size. */ bool pushError(const Value& value, const String& message); /** \brief Add a semantic error message with extra context. * * \param value JSON Value location associated with the error * \param message The error message. * \param extra Additional JSON Value location to contextualize the error * \return \c true if the error was successfully added, \c false if either * Value offset exceeds the document size. */ bool pushError(const Value& value, const String& message, const Value& extra); /** \brief Return whether there are any errors. * * \return \c true if there are no errors to report \c false if errors have * occurred. */ bool good() const; private: enum TokenType { tokenEndOfStream = 0, tokenObjectBegin, tokenObjectEnd, tokenArrayBegin, tokenArrayEnd, tokenString, tokenNumber, tokenTrue, tokenFalse, tokenNull, tokenArraySeparator, tokenMemberSeparator, tokenComment, tokenError }; class Token { public: TokenType type_; Location start_; Location end_; }; class ErrorInfo { public: Token token_; String message_; Location extra_; }; using Errors = std::deque<ErrorInfo>; bool readToken(Token& token); void skipSpaces(); bool match(const Char* pattern, int patternLength); bool readComment(); bool readCStyleComment(); bool readCppStyleComment(); bool readString(); void readNumber(); bool readValue(); bool readObject(Token& token); bool readArray(Token& token); bool decodeNumber(Token& token); bool decodeNumber(Token& token, Value& decoded); bool decodeString(Token& token); bool decodeString(Token& token, String& decoded); bool decodeDouble(Token& token); bool decodeDouble(Token& token, Value& decoded); bool decodeUnicodeCodePoint(Token& token, Location& current, Location end, unsigned int& unicode); bool decodeUnicodeEscapeSequence(Token& token, Location& current, Location end, unsigned int& unicode); bool addError(const String& message, Token& token, Location extra = nullptr); bool recoverFromError(TokenType skipUntilToken); bool addErrorAndRecover(const String& message, Token& token, TokenType skipUntilToken); void skipUntilSpace(); Value& currentValue(); Char getNextChar(); void getLocationLineAndColumn(Location location, int& line, int& column) const; String getLocationLineAndColumn(Location location) const; void addComment(Location begin, Location end, CommentPlacement placement); void skipCommentTokens(Token& token); static bool containsNewLine(Location begin, Location end); static String normalizeEOL(Location begin, Location end); using Nodes = std::stack<Value*>; Nodes nodes_; Errors errors_; String document_; Location begin_{}; Location end_{}; Location current_{}; Location lastValueEnd_{}; Value* lastValue_{}; String commentsBefore_; Features features_; bool collectComments_{}; }; // Reader /** Interface for reading JSON from a char array. */ class JSON_API CharReader { public: virtual ~CharReader() = default; /** \brief Read a Value from a <a HREF="http://www.json.org">JSON</a> * document. The document must be a UTF-8 encoded string containing the * document to read. * * \param beginDoc Pointer on the beginning of the UTF-8 encoded string * of the document to read. * \param endDoc Pointer on the end of the UTF-8 encoded string of the * document to read. Must be >= beginDoc. * \param[out] root Contains the root value of the document if it was * successfully parsed. * \param[out] errs Formatted error messages (if not NULL) a user * friendly string that lists errors in the parsed * document. * \return \c true if the document was successfully parsed, \c false if an * error occurred. */ virtual bool parse(char const* beginDoc, char const* endDoc, Value* root, String* errs) = 0; class JSON_API Factory { public: virtual ~Factory() = default; /** \brief Allocate a CharReader via operator new(). * \throw std::exception if something goes wrong (e.g. invalid settings) */ virtual CharReader* newCharReader() const = 0; }; // Factory }; // CharReader /** \brief Build a CharReader implementation. * * Usage: * \code * using namespace Json; * CharReaderBuilder builder; * builder["collectComments"] = false; * Value value; * String errs; * bool ok = parseFromStream(builder, std::cin, &value, &errs); * \endcode */ class JSON_API CharReaderBuilder : public CharReader::Factory { public: // Note: We use a Json::Value so that we can add data-members to this class // without a major version bump. /** Configuration of this builder. * These are case-sensitive. * Available settings (case-sensitive): * - `"collectComments": false or true` * - true to collect comment and allow writing them back during * serialization, false to discard comments. This parameter is ignored * if allowComments is false. * - `"allowComments": false or true` * - true if comments are allowed. * - `"allowTrailingCommas": false or true` * - true if trailing commas in objects and arrays are allowed. * - `"strictRoot": false or true` * - true if root must be either an array or an object value * - `"allowDroppedNullPlaceholders": false or true` * - true if dropped null placeholders are allowed. (See * StreamWriterBuilder.) * - `"allowNumericKeys": false or true` * - true if numeric object keys are allowed. * - `"allowSingleQuotes": false or true` * - true if '' are allowed for strings (both keys and values) * - `"stackLimit": integer` * - Exceeding stackLimit (recursive depth of `readValue()`) will cause an * exception. * - This is a security issue (seg-faults caused by deeply nested JSON), so * the default is low. * - `"failIfExtra": false or true` * - If true, `parse()` returns false when extra non-whitespace trails the * JSON value in the input string. * - `"rejectDupKeys": false or true` * - If true, `parse()` returns false when a key is duplicated within an * object. * - `"allowSpecialFloats": false or true` * - If true, special float values (NaNs and infinities) are allowed and * their values are lossfree restorable. * * You can examine 'settings_` yourself to see the defaults. You can also * write and read them just like any JSON Value. * \sa setDefaults() */ Json::Value settings_; CharReaderBuilder(); ~CharReaderBuilder() override; CharReader* newCharReader() const override; /** \return true if 'settings' are legal and consistent; * otherwise, indicate bad settings via 'invalid'. */ bool validate(Json::Value* invalid) const; /** A simple way to update a specific setting. */ Value& operator[](const String& key); /** Called by ctor, but you can use this to reset settings_. * \pre 'settings' != NULL (but Json::null is fine) * \remark Defaults: * \snippet src/lib_json/json_reader.cpp CharReaderBuilderDefaults */ static void setDefaults(Json::Value* settings); /** Same as old Features::strictMode(). * \pre 'settings' != NULL (but Json::null is fine) * \remark Defaults: * \snippet src/lib_json/json_reader.cpp CharReaderBuilderStrictMode */ static void strictMode(Json::Value* settings); }; /** Consume entire stream and use its begin/end. * Someday we might have a real StreamReader, but for now this * is convenient. */ bool JSON_API parseFromStream(CharReader::Factory const&, IStream&, Value* root, String* errs); /** \brief Read from 'sin' into 'root'. * * Always keep comments from the input JSON. * * This can be used to read a file into a particular sub-object. * For example: * \code * Json::Value root; * cin >> root["dir"]["file"]; * cout << root; * \endcode * Result: * \verbatim * { * "dir": { * "file": { * // The input stream JSON would be nested here. * } * } * } * \endverbatim * \throw std::exception on parse error. * \see Json::operator<<() */ JSON_API IStream& operator>>(IStream&, Value&); } // namespace Json #pragma pack(pop) #if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #pragma warning(pop) #endif // if defined(JSONCPP_DISABLE_DLL_INTERFACE_WARNING) #endif // JSON_READER_H_INCLUDED
Unknown
3D
mcellteam/mcell
libs/jsoncpp/include/json/assertions.h
.h
2,625
60
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #ifndef JSON_ASSERTIONS_H_INCLUDED #define JSON_ASSERTIONS_H_INCLUDED #include <cstdlib> #include <sstream> #if !defined(JSON_IS_AMALGAMATION) #include "config.h" #endif // if !defined(JSON_IS_AMALGAMATION) /** It should not be possible for a maliciously designed file to * cause an abort() or seg-fault, so these macros are used only * for pre-condition violations and internal logic errors. */ #if JSON_USE_EXCEPTION // @todo <= add detail about condition in exception #define JSON_ASSERT(condition) \ { \ if (!(condition)) { \ Json::throwLogicError("assert json failed"); \ } \ } #define JSON_FAIL_MESSAGE(message) \ { \ OStringStream oss; \ oss << message; \ Json::throwLogicError(oss.str()); \ abort(); \ } #else // JSON_USE_EXCEPTION #define JSON_ASSERT(condition) assert(condition) // The call to assert() will show the failure message in debug builds. In // release builds we abort, for a core-dump or debugger. #define JSON_FAIL_MESSAGE(message) \ { \ OStringStream oss; \ oss << message; \ assert(false && oss.str().c_str()); \ abort(); \ } #endif #define JSON_ASSERT_MESSAGE(condition, message) \ if (!(condition)) { \ JSON_FAIL_MESSAGE(message); \ } #endif // JSON_ASSERTIONS_H_INCLUDED
Unknown
3D
mcellteam/mcell
libs/jsoncpp/include/json/json_features.h
.h
1,793
62
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #ifndef JSON_FEATURES_H_INCLUDED #define JSON_FEATURES_H_INCLUDED #if !defined(JSON_IS_AMALGAMATION) #include "forwards.h" #endif // if !defined(JSON_IS_AMALGAMATION) #pragma pack(push, 8) namespace Json { /** \brief Configuration passed to reader and writer. * This configuration object can be used to force the Reader or Writer * to behave in a standard conforming way. */ class JSON_API Features { public: /** \brief A configuration that allows all features and assumes all strings * are UTF-8. * - C & C++ comments are allowed * - Root object can be any JSON value * - Assumes Value strings are encoded in UTF-8 */ static Features all(); /** \brief A configuration that is strictly compatible with the JSON * specification. * - Comments are forbidden. * - Root object must be either an array or an object value. * - Assumes Value strings are encoded in UTF-8 */ static Features strictMode(); /** \brief Initialize the configuration like JsonConfig::allFeatures; */ Features(); /// \c true if comments are allowed. Default: \c true. bool allowComments_{true}; /// \c true if root must be either an array or an object value. Default: \c /// false. bool strictRoot_{false}; /// \c true if dropped null placeholders are allowed. Default: \c false. bool allowDroppedNullPlaceholders_{false}; /// \c true if numeric object key are allowed. Default: \c false. bool allowNumericKeys_{false}; }; } // namespace Json #pragma pack(pop) #endif // JSON_FEATURES_H_INCLUDED
Unknown
3D
mcellteam/mcell
libs/jsoncpp/devtools/licenseupdater.py
.py
3,964
95
"""Updates the license text in source file. """ from __future__ import print_function # An existing license is found if the file starts with the string below, # and ends with the first blank line. LICENSE_BEGIN = "// Copyright " BRIEF_LICENSE = LICENSE_BEGIN + """2007-2010 Baptiste Lepilleur and The JsonCpp Authors // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE """.replace('\r\n','\n') def update_license(path, dry_run, show_diff): """Update the license statement in the specified file. Parameters: path: path of the C++ source file to update. dry_run: if True, just print the path of the file that would be updated, but don't change it. show_diff: if True, print the path of the file that would be modified, as well as the change made to the file. """ with open(path, 'rt') as fin: original_text = fin.read().replace('\r\n','\n') newline = fin.newlines and fin.newlines[0] or '\n' if not original_text.startswith(LICENSE_BEGIN): # No existing license found => prepend it new_text = BRIEF_LICENSE + original_text else: license_end_index = original_text.index('\n\n') # search first blank line new_text = BRIEF_LICENSE + original_text[license_end_index+2:] if original_text != new_text: if not dry_run: with open(path, 'wb') as fout: fout.write(new_text.replace('\n', newline)) print('Updated', path) if show_diff: import difflib print('\n'.join(difflib.unified_diff(original_text.split('\n'), new_text.split('\n')))) return True return False def update_license_in_source_directories(source_dirs, dry_run, show_diff): """Updates license text in C++ source files found in directory source_dirs. Parameters: source_dirs: list of directory to scan for C++ sources. Directories are scanned recursively. dry_run: if True, just print the path of the file that would be updated, but don't change it. show_diff: if True, print the path of the file that would be modified, as well as the change made to the file. """ from devtools import antglob prune_dirs = antglob.prune_dirs + 'scons-local* ./build* ./libs ./dist' for source_dir in source_dirs: cpp_sources = antglob.glob(source_dir, includes = '''**/*.h **/*.cpp **/*.inl''', prune_dirs = prune_dirs) for source in cpp_sources: update_license(source, dry_run, show_diff) def main(): usage = """%prog DIR [DIR2...] Updates license text in sources of the project in source files found in the directory specified on the command-line. Example of call: python devtools\licenseupdater.py include src -n --diff => Show change that would be made to the sources. python devtools\licenseupdater.py include src => Update license statement on all sources in directories include/ and src/. """ from optparse import OptionParser parser = OptionParser(usage=usage) parser.allow_interspersed_args = False parser.add_option('-n', '--dry-run', dest="dry_run", action='store_true', default=False, help="""Only show what files are updated, do not update the files""") parser.add_option('--diff', dest="show_diff", action='store_true', default=False, help="""On update, show change made to the file.""") parser.enable_interspersed_args() options, args = parser.parse_args() update_license_in_source_directories(args, options.dry_run, options.show_diff) print('Done') if __name__ == '__main__': import sys import os.path sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) main()
Python
3D
mcellteam/mcell
libs/jsoncpp/devtools/tarball.py
.py
2,234
53
# Copyright 2010 Baptiste Lepilleur and The JsonCpp Authors # Distributed under MIT license, or public domain if desired and # recognized in your jurisdiction. # See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE from contextlib import closing import os import tarfile TARGZ_DEFAULT_COMPRESSION_LEVEL = 9 def make_tarball(tarball_path, sources, base_dir, prefix_dir=''): """Parameters: tarball_path: output path of the .tar.gz file sources: list of sources to include in the tarball, relative to the current directory base_dir: if a source file is in a sub-directory of base_dir, then base_dir is stripped from path in the tarball. prefix_dir: all files stored in the tarball be sub-directory of prefix_dir. Set to '' to make them child of root. """ base_dir = os.path.normpath(os.path.abspath(base_dir)) def archive_name(path): """Makes path relative to base_dir.""" path = os.path.normpath(os.path.abspath(path)) common_path = os.path.commonprefix((base_dir, path)) archive_name = path[len(common_path):] if os.path.isabs(archive_name): archive_name = archive_name[1:] return os.path.join(prefix_dir, archive_name) def visit(tar, dirname, names): for name in names: path = os.path.join(dirname, name) if os.path.isfile(path): path_in_tar = archive_name(path) tar.add(path, path_in_tar) compression = TARGZ_DEFAULT_COMPRESSION_LEVEL with closing(tarfile.TarFile.open(tarball_path, 'w:gz', compresslevel=compression)) as tar: for source in sources: source_path = source if os.path.isdir(source): for dirpath, dirnames, filenames in os.walk(source_path): visit(tar, dirpath, filenames) else: path_in_tar = archive_name(source_path) tar.add(source_path, path_in_tar) # filename, arcname def decompress(tarball_path, base_dir): """Decompress the gzipped tarball into directory base_dir. """ with closing(tarfile.TarFile.open(tarball_path)) as tar: tar.extractall(base_dir)
Python
3D
mcellteam/mcell
libs/jsoncpp/devtools/batchbuild.py
.py
11,483
279
from __future__ import print_function import collections import itertools import json import os import os.path import re import shutil import string import subprocess import sys import cgi class BuildDesc: def __init__(self, prepend_envs=None, variables=None, build_type=None, generator=None): self.prepend_envs = prepend_envs or [] # [ { "var": "value" } ] self.variables = variables or [] self.build_type = build_type self.generator = generator def merged_with(self, build_desc): """Returns a new BuildDesc by merging field content. Prefer build_desc fields to self fields for single valued field. """ return BuildDesc(self.prepend_envs + build_desc.prepend_envs, self.variables + build_desc.variables, build_desc.build_type or self.build_type, build_desc.generator or self.generator) def env(self): environ = os.environ.copy() for values_by_name in self.prepend_envs: for var, value in list(values_by_name.items()): var = var.upper() if type(value) is unicode: value = value.encode(sys.getdefaultencoding()) if var in environ: environ[var] = value + os.pathsep + environ[var] else: environ[var] = value return environ def cmake_args(self): args = ["-D%s" % var for var in self.variables] # skip build type for Visual Studio solution as it cause warning if self.build_type and 'Visual' not in self.generator: args.append("-DCMAKE_BUILD_TYPE=%s" % self.build_type) if self.generator: args.extend(['-G', self.generator]) return args def __repr__(self): return "BuildDesc(%s, build_type=%s)" % (" ".join(self.cmake_args()), self.build_type) class BuildData: def __init__(self, desc, work_dir, source_dir): self.desc = desc self.work_dir = work_dir self.source_dir = source_dir self.cmake_log_path = os.path.join(work_dir, 'batchbuild_cmake.log') self.build_log_path = os.path.join(work_dir, 'batchbuild_build.log') self.cmake_succeeded = False self.build_succeeded = False def execute_build(self): print('Build %s' % self.desc) self._make_new_work_dir() self.cmake_succeeded = self._generate_makefiles() if self.cmake_succeeded: self.build_succeeded = self._build_using_makefiles() return self.build_succeeded def _generate_makefiles(self): print(' Generating makefiles: ', end=' ') cmd = ['cmake'] + self.desc.cmake_args() + [os.path.abspath(self.source_dir)] succeeded = self._execute_build_subprocess(cmd, self.desc.env(), self.cmake_log_path) print('done' if succeeded else 'FAILED') return succeeded def _build_using_makefiles(self): print(' Building:', end=' ') cmd = ['cmake', '--build', self.work_dir] if self.desc.build_type: cmd += ['--config', self.desc.build_type] succeeded = self._execute_build_subprocess(cmd, self.desc.env(), self.build_log_path) print('done' if succeeded else 'FAILED') return succeeded def _execute_build_subprocess(self, cmd, env, log_path): process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=self.work_dir, env=env) stdout, _ = process.communicate() succeeded = (process.returncode == 0) with open(log_path, 'wb') as flog: log = ' '.join(cmd) + '\n' + stdout + '\nExit code: %r\n' % process.returncode flog.write(fix_eol(log)) return succeeded def _make_new_work_dir(self): if os.path.isdir(self.work_dir): print(' Removing work directory', self.work_dir) shutil.rmtree(self.work_dir, ignore_errors=True) if not os.path.isdir(self.work_dir): os.makedirs(self.work_dir) def fix_eol(stdout): """Fixes wrong EOL produced by cmake --build on Windows (\r\r\n instead of \r\n). """ return re.sub('\r*\n', os.linesep, stdout) def load_build_variants_from_config(config_path): with open(config_path, 'rb') as fconfig: data = json.load(fconfig) variants = data[ 'cmake_variants' ] build_descs_by_axis = collections.defaultdict(list) for axis in variants: axis_name = axis["name"] build_descs = [] if "generators" in axis: for generator_data in axis["generators"]: for generator in generator_data["generator"]: build_desc = BuildDesc(generator=generator, prepend_envs=generator_data.get("env_prepend")) build_descs.append(build_desc) elif "variables" in axis: for variables in axis["variables"]: build_desc = BuildDesc(variables=variables) build_descs.append(build_desc) elif "build_types" in axis: for build_type in axis["build_types"]: build_desc = BuildDesc(build_type=build_type) build_descs.append(build_desc) build_descs_by_axis[axis_name].extend(build_descs) return build_descs_by_axis def generate_build_variants(build_descs_by_axis): """Returns a list of BuildDesc generated for the partial BuildDesc for each axis.""" axis_names = list(build_descs_by_axis.keys()) build_descs = [] for axis_name, axis_build_descs in list(build_descs_by_axis.items()): if len(build_descs): # for each existing build_desc and each axis build desc, create a new build_desc new_build_descs = [] for prototype_build_desc, axis_build_desc in itertools.product(build_descs, axis_build_descs): new_build_descs.append(prototype_build_desc.merged_with(axis_build_desc)) build_descs = new_build_descs else: build_descs = axis_build_descs return build_descs HTML_TEMPLATE = string.Template('''<html> <head> <title>$title</title> <style type="text/css"> td.failed {background-color:#f08080;} td.ok {background-color:#c0eec0;} </style> </head> <body> <table border="1"> <thead> <tr> <th>Variables</th> $th_vars </tr> <tr> <th>Build type</th> $th_build_types </tr> </thead> <tbody> $tr_builds </tbody> </table> </body></html>''') def generate_html_report(html_report_path, builds): report_dir = os.path.dirname(html_report_path) # Vertical axis: generator # Horizontal: variables, then build_type builds_by_generator = collections.defaultdict(list) variables = set() build_types_by_variable = collections.defaultdict(set) build_by_pos_key = {} # { (generator, var_key, build_type): build } for build in builds: builds_by_generator[build.desc.generator].append(build) var_key = tuple(sorted(build.desc.variables)) variables.add(var_key) build_types_by_variable[var_key].add(build.desc.build_type) pos_key = (build.desc.generator, var_key, build.desc.build_type) build_by_pos_key[pos_key] = build variables = sorted(variables) th_vars = [] th_build_types = [] for variable in variables: build_types = sorted(build_types_by_variable[variable]) nb_build_type = len(build_types_by_variable[variable]) th_vars.append('<th colspan="%d">%s</th>' % (nb_build_type, cgi.escape(' '.join(variable)))) for build_type in build_types: th_build_types.append('<th>%s</th>' % cgi.escape(build_type)) tr_builds = [] for generator in sorted(builds_by_generator): tds = [ '<td>%s</td>\n' % cgi.escape(generator) ] for variable in variables: build_types = sorted(build_types_by_variable[variable]) for build_type in build_types: pos_key = (generator, variable, build_type) build = build_by_pos_key.get(pos_key) if build: cmake_status = 'ok' if build.cmake_succeeded else 'FAILED' build_status = 'ok' if build.build_succeeded else 'FAILED' cmake_log_url = os.path.relpath(build.cmake_log_path, report_dir) build_log_url = os.path.relpath(build.build_log_path, report_dir) td = '<td class="%s"><a href="%s" class="%s">CMake: %s</a>' % ( build_status.lower(), cmake_log_url, cmake_status.lower(), cmake_status) if build.cmake_succeeded: td += '<br><a href="%s" class="%s">Build: %s</a>' % ( build_log_url, build_status.lower(), build_status) td += '</td>' else: td = '<td></td>' tds.append(td) tr_builds.append('<tr>%s</tr>' % '\n'.join(tds)) html = HTML_TEMPLATE.substitute( title='Batch build report', th_vars=' '.join(th_vars), th_build_types=' '.join(th_build_types), tr_builds='\n'.join(tr_builds)) with open(html_report_path, 'wt') as fhtml: fhtml.write(html) print('HTML report generated in:', html_report_path) def main(): usage = r"""%prog WORK_DIR SOURCE_DIR CONFIG_JSON_PATH [CONFIG2_JSON_PATH...] Build a given CMake based project located in SOURCE_DIR with multiple generators/options.dry_run as described in CONFIG_JSON_PATH building in WORK_DIR. Example of call: python devtools\batchbuild.py e:\buildbots\jsoncpp\build . devtools\agent_vmw7.json """ from optparse import OptionParser parser = OptionParser(usage=usage) parser.allow_interspersed_args = True # parser.add_option('-v', '--verbose', dest="verbose", action='store_true', # help="""Be verbose.""") parser.enable_interspersed_args() options, args = parser.parse_args() if len(args) < 3: parser.error("Missing one of WORK_DIR SOURCE_DIR CONFIG_JSON_PATH.") work_dir = args[0] source_dir = args[1].rstrip('/\\') config_paths = args[2:] for config_path in config_paths: if not os.path.isfile(config_path): parser.error("Can not read: %r" % config_path) # generate build variants build_descs = [] for config_path in config_paths: build_descs_by_axis = load_build_variants_from_config(config_path) build_descs.extend(generate_build_variants(build_descs_by_axis)) print('Build variants (%d):' % len(build_descs)) # assign build directory for each variant if not os.path.isdir(work_dir): os.makedirs(work_dir) builds = [] with open(os.path.join(work_dir, 'matrix-dir-map.txt'), 'wt') as fmatrixmap: for index, build_desc in enumerate(build_descs): build_desc_work_dir = os.path.join(work_dir, '%03d' % (index+1)) builds.append(BuildData(build_desc, build_desc_work_dir, source_dir)) fmatrixmap.write('%s: %s\n' % (build_desc_work_dir, build_desc)) for build in builds: build.execute_build() html_report_path = os.path.join(work_dir, 'batchbuild-report.html') generate_html_report(html_report_path, builds) print('Done') if __name__ == '__main__': main()
Python
3D
mcellteam/mcell
libs/jsoncpp/devtools/fixeol.py
.py
2,226
71
# Copyright 2010 Baptiste Lepilleur and The JsonCpp Authors # Distributed under MIT license, or public domain if desired and # recognized in your jurisdiction. # See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE from __future__ import print_function import os.path import sys def fix_source_eol(path, is_dry_run = True, verbose = True, eol = '\n'): """Makes sure that all sources have the specified eol sequence (default: unix).""" if not os.path.isfile(path): raise ValueError('Path "%s" is not a file' % path) try: f = open(path, 'rb') except IOError as msg: print("%s: I/O Error: %s" % (file, str(msg)), file=sys.stderr) return False try: raw_lines = f.readlines() finally: f.close() fixed_lines = [line.rstrip('\r\n') + eol for line in raw_lines] if raw_lines != fixed_lines: print('%s =>' % path, end=' ') if not is_dry_run: f = open(path, "wb") try: f.writelines(fixed_lines) finally: f.close() if verbose: print(is_dry_run and ' NEED FIX' or ' FIXED') return True ## ## ## ##def _do_fix(is_dry_run = True): ## from waftools import antglob ## python_sources = antglob.glob('.', ## includes = '**/*.py **/wscript **/wscript_build', ## excludes = antglob.default_excludes + './waf.py', ## prune_dirs = antglob.prune_dirs + 'waf-* ./build') ## for path in python_sources: ## _fix_python_source(path, is_dry_run) ## ## cpp_sources = antglob.glob('.', ## includes = '**/*.cpp **/*.h **/*.inl', ## prune_dirs = antglob.prune_dirs + 'waf-* ./build') ## for path in cpp_sources: ## _fix_source_eol(path, is_dry_run) ## ## ##def dry_fix(context): ## _do_fix(is_dry_run = True) ## ##def fix(context): ## _do_fix(is_dry_run = False) ## ##def shutdown(): ## pass ## ##def check(context): ## # Unit tests are run when "check" target is used ## ut = UnitTest.unit_test() ## ut.change_to_testfile_dir = True ## ut.want_to_see_test_output = True ## ut.want_to_see_test_error = True ## ut.run() ## ut.print_results()
Python
3D
mcellteam/mcell
libs/jsoncpp/devtools/__init__.py
.py
250
7
# Copyright 2010 Baptiste Lepilleur and The JsonCpp Authors # Distributed under MIT license, or public domain if desired and # recognized in your jurisdiction. # See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE # module
Python
3D
mcellteam/mcell
libs/jsoncpp/devtools/antglob.py
.py
7,908
206
#!/usr/bin/env python # encoding: utf-8 # Copyright 2009 Baptiste Lepilleur and The JsonCpp Authors # Distributed under MIT license, or public domain if desired and # recognized in your jurisdiction. # See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE from __future__ import print_function from dircache import listdir import re import fnmatch import os.path # These fnmatch expressions are used by default to prune the directory tree # while doing the recursive traversal in the glob_impl method of glob function. prune_dirs = '.git .bzr .hg .svn _MTN _darcs CVS SCCS ' # These fnmatch expressions are used by default to exclude files and dirs # while doing the recursive traversal in the glob_impl method of glob function. ##exclude_pats = prune_pats + '*~ #*# .#* %*% ._* .gitignore .cvsignore vssver.scc .DS_Store'.split() # These ant_glob expressions are used by default to exclude files and dirs and also prune the directory tree # while doing the recursive traversal in the glob_impl method of glob function. default_excludes = ''' **/*~ **/#*# **/.#* **/%*% **/._* **/CVS **/CVS/** **/.cvsignore **/SCCS **/SCCS/** **/vssver.scc **/.svn **/.svn/** **/.git **/.git/** **/.gitignore **/.bzr **/.bzr/** **/.hg **/.hg/** **/_MTN **/_MTN/** **/_darcs **/_darcs/** **/.DS_Store ''' DIR = 1 FILE = 2 DIR_LINK = 4 FILE_LINK = 8 LINKS = DIR_LINK | FILE_LINK ALL_NO_LINK = DIR | FILE ALL = DIR | FILE | LINKS _ANT_RE = re.compile(r'(/\*\*/)|(\*\*/)|(/\*\*)|(\*)|(/)|([^\*/]*)') def ant_pattern_to_re(ant_pattern): """Generates a regular expression from the ant pattern. Matching convention: **/a: match 'a', 'dir/a', 'dir1/dir2/a' a/**/b: match 'a/b', 'a/c/b', 'a/d/c/b' *.py: match 'script.py' but not 'a/script.py' """ rex = ['^'] next_pos = 0 sep_rex = r'(?:/|%s)' % re.escape(os.path.sep) ## print 'Converting', ant_pattern for match in _ANT_RE.finditer(ant_pattern): ## print 'Matched', match.group() ## print match.start(0), next_pos if match.start(0) != next_pos: raise ValueError("Invalid ant pattern") if match.group(1): # /**/ rex.append(sep_rex + '(?:.*%s)?' % sep_rex) elif match.group(2): # **/ rex.append('(?:.*%s)?' % sep_rex) elif match.group(3): # /** rex.append(sep_rex + '.*') elif match.group(4): # * rex.append('[^/%s]*' % re.escape(os.path.sep)) elif match.group(5): # / rex.append(sep_rex) else: # somepath rex.append(re.escape(match.group(6))) next_pos = match.end() rex.append('$') return re.compile(''.join(rex)) def _as_list(l): if isinstance(l, basestring): return l.split() return l def glob(dir_path, includes = '**/*', excludes = default_excludes, entry_type = FILE, prune_dirs = prune_dirs, max_depth = 25): include_filter = [ant_pattern_to_re(p) for p in _as_list(includes)] exclude_filter = [ant_pattern_to_re(p) for p in _as_list(excludes)] prune_dirs = [p.replace('/',os.path.sep) for p in _as_list(prune_dirs)] dir_path = dir_path.replace('/',os.path.sep) entry_type_filter = entry_type def is_pruned_dir(dir_name): for pattern in prune_dirs: if fnmatch.fnmatch(dir_name, pattern): return True return False def apply_filter(full_path, filter_rexs): """Return True if at least one of the filter regular expression match full_path.""" for rex in filter_rexs: if rex.match(full_path): return True return False def glob_impl(root_dir_path): child_dirs = [root_dir_path] while child_dirs: dir_path = child_dirs.pop() for entry in listdir(dir_path): full_path = os.path.join(dir_path, entry) ## print 'Testing:', full_path, is_dir = os.path.isdir(full_path) if is_dir and not is_pruned_dir(entry): # explore child directory ? ## print '===> marked for recursion', child_dirs.append(full_path) included = apply_filter(full_path, include_filter) rejected = apply_filter(full_path, exclude_filter) if not included or rejected: # do not include entry ? ## print '=> not included or rejected' continue link = os.path.islink(full_path) is_file = os.path.isfile(full_path) if not is_file and not is_dir: ## print '=> unknown entry type' continue if link: entry_type = is_file and FILE_LINK or DIR_LINK else: entry_type = is_file and FILE or DIR ## print '=> type: %d' % entry_type, if (entry_type & entry_type_filter) != 0: ## print ' => KEEP' yield os.path.join(dir_path, entry) ## else: ## print ' => TYPE REJECTED' return list(glob_impl(dir_path)) if __name__ == "__main__": import unittest class AntPatternToRETest(unittest.TestCase): ## def test_conversion(self): ## self.assertEqual('^somepath$', ant_pattern_to_re('somepath').pattern) def test_matching(self): test_cases = [ ('path', ['path'], ['somepath', 'pathsuffix', '/path', '/path']), ('*.py', ['source.py', 'source.ext.py', '.py'], ['path/source.py', '/.py', 'dir.py/z', 'z.pyc', 'z.c']), ('**/path', ['path', '/path', '/a/path', 'c:/a/path', '/a/b/path', '//a/path', '/a/path/b/path'], ['path/', 'a/path/b', 'dir.py/z', 'somepath', 'pathsuffix', 'a/somepath']), ('path/**', ['path/a', 'path/path/a', 'path//'], ['path', 'somepath/a', 'a/path', 'a/path/a', 'pathsuffix/a']), ('/**/path', ['/path', '/a/path', '/a/b/path/path', '/path/path'], ['path', 'path/', 'a/path', '/pathsuffix', '/somepath']), ('a/b', ['a/b'], ['somea/b', 'a/bsuffix', 'a/b/c']), ('**/*.py', ['script.py', 'src/script.py', 'a/b/script.py', '/a/b/script.py'], ['script.pyc', 'script.pyo', 'a.py/b']), ('src/**/*.py', ['src/a.py', 'src/dir/a.py'], ['a/src/a.py', '/src/a.py']), ] for ant_pattern, accepted_matches, rejected_matches in list(test_cases): def local_path(paths): return [ p.replace('/',os.path.sep) for p in paths ] test_cases.append((ant_pattern, local_path(accepted_matches), local_path(rejected_matches))) for ant_pattern, accepted_matches, rejected_matches in test_cases: rex = ant_pattern_to_re(ant_pattern) print('ant_pattern:', ant_pattern, ' => ', rex.pattern) for accepted_match in accepted_matches: print('Accepted?:', accepted_match) self.assertTrue(rex.match(accepted_match) is not None) for rejected_match in rejected_matches: print('Rejected?:', rejected_match) self.assertTrue(rex.match(rejected_match) is None) unittest.main()
Python
3D
mcellteam/mcell
libs/jsoncpp/src/test_lib_json/fuzz.h
.h
423
15
// Copyright 2007-2010 The JsonCpp Authors // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #ifndef FUZZ_H_INCLUDED #define FUZZ_H_INCLUDED #include <cstddef> #include <stdint.h> extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size); #endif // ifndef FUZZ_H_INCLUDED
Unknown
3D
mcellteam/mcell
libs/jsoncpp/src/test_lib_json/fuzz.cpp
.cpp
1,971
55
// Copyright 2007-2019 The JsonCpp Authors // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #include "fuzz.h" #include <cstdint> #include <json/config.h> #include <json/json.h> #include <memory> #include <string> namespace Json { class Exception; } extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { Json::CharReaderBuilder builder; if (size < sizeof(uint32_t)) { return 0; } const uint32_t hash_settings = static_cast<uint32_t>(data[0]) | (static_cast<uint32_t>(data[1]) << 8) | (static_cast<uint32_t>(data[2]) << 16) | (static_cast<uint32_t>(data[3]) << 24); data += sizeof(uint32_t); size -= sizeof(uint32_t); builder.settings_["failIfExtra"] = hash_settings & (1 << 0); builder.settings_["allowComments_"] = hash_settings & (1 << 1); builder.settings_["strictRoot_"] = hash_settings & (1 << 2); builder.settings_["allowDroppedNullPlaceholders_"] = hash_settings & (1 << 3); builder.settings_["allowNumericKeys_"] = hash_settings & (1 << 4); builder.settings_["allowSingleQuotes_"] = hash_settings & (1 << 5); builder.settings_["failIfExtra_"] = hash_settings & (1 << 6); builder.settings_["rejectDupKeys_"] = hash_settings & (1 << 7); builder.settings_["allowSpecialFloats_"] = hash_settings & (1 << 8); builder.settings_["collectComments"] = hash_settings & (1 << 9); builder.settings_["allowTrailingCommas_"] = hash_settings & (1 << 10); std::unique_ptr<Json::CharReader> reader(builder.newCharReader()); Json::Value root; const auto data_str = reinterpret_cast<const char*>(data); try { reader->parse(data_str, data_str + size, &root, nullptr); } catch (Json::Exception const&) { } // Whether it succeeded or not doesn't matter. return 0; }
C++
3D
mcellteam/mcell
libs/jsoncpp/src/test_lib_json/jsontest.h
.h
11,985
289
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #ifndef JSONTEST_H_INCLUDED #define JSONTEST_H_INCLUDED #include <cstdio> #include <deque> #include <iomanip> #include <json/config.h> #include <json/value.h> #include <json/writer.h> #include <sstream> #include <string> // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // Mini Unit Testing framework // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// /** \brief Unit testing framework. * \warning: all assertions are non-aborting, test case execution will continue * even if an assertion namespace. * This constraint is for portability: the framework needs to compile * on Visual Studio 6 and must not require exception usage. */ namespace JsonTest { class Failure { public: const char* file_; unsigned int line_; Json::String expr_; Json::String message_; unsigned int nestingLevel_; }; /// Context used to create the assertion callstack on failure. /// Must be a POD to allow inline initialisation without stepping /// into the debugger. struct PredicateContext { using Id = unsigned int; Id id_; const char* file_; unsigned int line_; const char* expr_; PredicateContext* next_; /// Related Failure, set when the PredicateContext is converted /// into a Failure. Failure* failure_; }; class TestResult { public: TestResult(); /// \internal Implementation detail for assertion macros /// Not encapsulated to prevent step into when debugging failed assertions /// Incremented by one on assertion predicate entry, decreased by one /// by addPredicateContext(). PredicateContext::Id predicateId_{1}; /// \internal Implementation detail for predicate macros PredicateContext* predicateStackTail_; void setTestName(const Json::String& name); /// Adds an assertion failure. TestResult& addFailure(const char* file, unsigned int line, const char* expr = nullptr); /// Removes the last PredicateContext added to the predicate stack /// chained list. /// Next messages will be targed at the PredicateContext that was removed. TestResult& popPredicateContext(); bool failed() const; void printFailure(bool printTestName) const; // Generic operator that will work with anything ostream can deal with. template <typename T> TestResult& operator<<(const T& value) { Json::OStringStream oss; oss << std::setprecision(16) << std::hexfloat << value; return addToLastFailure(oss.str()); } // Specialized versions. TestResult& operator<<(bool value); // std:ostream does not support 64bits integers on all STL implementation TestResult& operator<<(Json::Int64 value); TestResult& operator<<(Json::UInt64 value); private: TestResult& addToLastFailure(const Json::String& message); /// Adds a failure or a predicate context void addFailureInfo(const char* file, unsigned int line, const char* expr, unsigned int nestingLevel); static Json::String indentText(const Json::String& text, const Json::String& indent); using Failures = std::deque<Failure>; Failures failures_; Json::String name_; PredicateContext rootPredicateNode_; PredicateContext::Id lastUsedPredicateId_{0}; /// Failure which is the target of the messages added using operator << Failure* messageTarget_{nullptr}; }; class TestCase { public: TestCase(); virtual ~TestCase(); void run(TestResult& result); virtual const char* testName() const = 0; protected: TestResult* result_{nullptr}; private: virtual void runTestCase() = 0; }; /// Function pointer type for TestCase factory using TestCaseFactory = TestCase* (*)(); class Runner { public: Runner(); /// Adds a test to the suite Runner& add(TestCaseFactory factory); /// Runs test as specified on the command-line /// If no command-line arguments are provided, run all tests. /// If --list-tests is provided, then print the list of all test cases /// If --test <testname> is provided, then run test testname. int runCommandLine(int argc, const char* argv[]) const; /// Runs all the test cases bool runAllTest(bool printSummary) const; /// Returns the number of test case in the suite size_t testCount() const; /// Returns the name of the test case at the specified index Json::String testNameAt(size_t index) const; /// Runs the test case at the specified index using the specified TestResult void runTestAt(size_t index, TestResult& result) const; static void printUsage(const char* appName); private: // prevents copy construction and assignment Runner(const Runner& other) = delete; Runner& operator=(const Runner& other) = delete; private: void listTests() const; bool testIndex(const Json::String& testName, size_t& indexOut) const; static void preventDialogOnCrash(); private: using Factories = std::deque<TestCaseFactory>; Factories tests_; }; template <typename T, typename U> TestResult& checkEqual(TestResult& result, T expected, U actual, const char* file, unsigned int line, const char* expr) { if (static_cast<U>(expected) != actual) { result.addFailure(file, line, expr); result << "Expected: " << static_cast<U>(expected) << "\n"; result << "Actual : " << actual; } return result; } Json::String ToJsonString(const char* toConvert); Json::String ToJsonString(Json::String in); #if JSONCPP_USING_SECURE_MEMORY Json::String ToJsonString(std::string in); #endif TestResult& checkStringEqual(TestResult& result, const Json::String& expected, const Json::String& actual, const char* file, unsigned int line, const char* expr); } // namespace JsonTest /// \brief Asserts that the given expression is true. /// JSONTEST_ASSERT( x == y ) << "x=" << x << ", y=" << y; /// JSONTEST_ASSERT( x == y ); #define JSONTEST_ASSERT(expr) \ if (expr) { \ } else \ result_->addFailure(__FILE__, __LINE__, #expr) /// \brief Asserts that the given predicate is true. /// The predicate may do other assertions and be a member function of the /// fixture. #define JSONTEST_ASSERT_PRED(expr) \ { \ JsonTest::PredicateContext _minitest_Context = { \ result_->predicateId_, __FILE__, __LINE__, #expr, NULL, NULL}; \ result_->predicateStackTail_->next_ = &_minitest_Context; \ result_->predicateId_ += 1; \ result_->predicateStackTail_ = &_minitest_Context; \ (expr); \ result_->popPredicateContext(); \ } /// \brief Asserts that two values are equals. #define JSONTEST_ASSERT_EQUAL(expected, actual) \ JsonTest::checkEqual(*result_, expected, actual, __FILE__, __LINE__, \ #expected " == " #actual) /// \brief Asserts that two values are equals. #define JSONTEST_ASSERT_STRING_EQUAL(expected, actual) \ JsonTest::checkStringEqual(*result_, JsonTest::ToJsonString(expected), \ JsonTest::ToJsonString(actual), __FILE__, \ __LINE__, #expected " == " #actual) /// \brief Asserts that a given expression throws an exception #define JSONTEST_ASSERT_THROWS(expr) \ { \ bool _threw = false; \ try { \ expr; \ } catch (...) { \ _threw = true; \ } \ if (!_threw) \ result_->addFailure(__FILE__, __LINE__, \ "expected exception thrown: " #expr); \ } /// \brief Begin a fixture test case. #define JSONTEST_FIXTURE(FixtureType, name) \ class Test##FixtureType##name : public FixtureType { \ public: \ static JsonTest::TestCase* factory() { \ return new Test##FixtureType##name(); \ } \ \ public: /* overridden from TestCase */ \ const char* testName() const override { return #FixtureType "/" #name; } \ void runTestCase() override; \ }; \ \ void Test##FixtureType##name::runTestCase() #define JSONTEST_FIXTURE_FACTORY(FixtureType, name) \ &Test##FixtureType##name::factory #define JSONTEST_REGISTER_FIXTURE(runner, FixtureType, name) \ (runner).add(JSONTEST_FIXTURE_FACTORY(FixtureType, name)) /// \brief Begin a fixture test case. #define JSONTEST_FIXTURE_V2(FixtureType, name, collections) \ class Test##FixtureType##name : public FixtureType { \ public: \ static JsonTest::TestCase* factory() { \ return new Test##FixtureType##name(); \ } \ static bool collect() { \ (collections).push_back(JSONTEST_FIXTURE_FACTORY(FixtureType, name)); \ return true; \ } \ \ public: /* overridden from TestCase */ \ const char* testName() const override { return #FixtureType "/" #name; } \ void runTestCase() override; \ }; \ \ static bool test##FixtureType##name##collect = \ Test##FixtureType##name::collect(); \ \ void Test##FixtureType##name::runTestCase() #endif // ifndef JSONTEST_H_INCLUDED
Unknown
3D
mcellteam/mcell
libs/jsoncpp/src/test_lib_json/jsontest.cpp
.cpp
12,268
431
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #define _CRT_SECURE_NO_WARNINGS 1 // Prevents deprecation warning with MSVC #include "jsontest.h" #include <cstdio> #include <string> #if defined(_MSC_VER) // Used to install a report hook that prevent dialog on assertion and error. #include <crtdbg.h> #endif // if defined(_MSC_VER) #if defined(_WIN32) // Used to prevent dialog on memory fault. // Limits headers included by Windows.h #define WIN32_LEAN_AND_MEAN #define NOSERVICE #define NOMCX #define NOIME #define NOSOUND #define NOCOMM #define NORPC #define NOGDI #define NOUSER #define NODRIVERS #define NOLOGERROR #define NOPROFILER #define NOMEMMGR #define NOLFILEIO #define NOOPENFILE #define NORESOURCE #define NOATOM #define NOLANGUAGE #define NOLSTRING #define NODBCS #define NOKEYBOARDINFO #define NOGDICAPMASKS #define NOCOLOR #define NOGDIOBJ #define NODRAWTEXT #define NOTEXTMETRIC #define NOSCALABLEFONT #define NOBITMAP #define NORASTEROPS #define NOMETAFILE #define NOSYSMETRICS #define NOSYSTEMPARAMSINFO #define NOMSG #define NOWINSTYLES #define NOWINOFFSETS #define NOSHOWWINDOW #define NODEFERWINDOWPOS #define NOVIRTUALKEYCODES #define NOKEYSTATES #define NOWH #define NOMENUS #define NOSCROLL #define NOCLIPBOARD #define NOICONS #define NOMB #define NOSYSCOMMANDS #define NOMDI #define NOCTLMGR #define NOWINMESSAGES #include <windows.h> #endif // if defined(_WIN32) namespace JsonTest { // class TestResult // ////////////////////////////////////////////////////////////////// TestResult::TestResult() { // The root predicate has id 0 rootPredicateNode_.id_ = 0; rootPredicateNode_.next_ = nullptr; predicateStackTail_ = &rootPredicateNode_; } void TestResult::setTestName(const Json::String& name) { name_ = name; } TestResult& TestResult::addFailure(const char* file, unsigned int line, const char* expr) { /// Walks the PredicateContext stack adding them to failures_ if not already /// added. unsigned int nestingLevel = 0; PredicateContext* lastNode = rootPredicateNode_.next_; for (; lastNode != nullptr; lastNode = lastNode->next_) { if (lastNode->id_ > lastUsedPredicateId_) // new PredicateContext { lastUsedPredicateId_ = lastNode->id_; addFailureInfo(lastNode->file_, lastNode->line_, lastNode->expr_, nestingLevel); // Link the PredicateContext to the failure for message target when // popping the PredicateContext. lastNode->failure_ = &(failures_.back()); } ++nestingLevel; } // Adds the failed assertion addFailureInfo(file, line, expr, nestingLevel); messageTarget_ = &(failures_.back()); return *this; } void TestResult::addFailureInfo(const char* file, unsigned int line, const char* expr, unsigned int nestingLevel) { Failure failure; failure.file_ = file; failure.line_ = line; if (expr) { failure.expr_ = expr; } failure.nestingLevel_ = nestingLevel; failures_.push_back(failure); } TestResult& TestResult::popPredicateContext() { PredicateContext* lastNode = &rootPredicateNode_; while (lastNode->next_ != nullptr && lastNode->next_->next_ != nullptr) { lastNode = lastNode->next_; } // Set message target to popped failure PredicateContext* tail = lastNode->next_; if (tail != nullptr && tail->failure_ != nullptr) { messageTarget_ = tail->failure_; } // Remove tail from list predicateStackTail_ = lastNode; lastNode->next_ = nullptr; return *this; } bool TestResult::failed() const { return !failures_.empty(); } void TestResult::printFailure(bool printTestName) const { if (failures_.empty()) { return; } if (printTestName) { printf("* Detail of %s test failure:\n", name_.c_str()); } // Print in reverse to display the callstack in the right order for (const auto& failure : failures_) { Json::String indent(failure.nestingLevel_ * 2, ' '); if (failure.file_) { printf("%s%s(%u): ", indent.c_str(), failure.file_, failure.line_); } if (!failure.expr_.empty()) { printf("%s\n", failure.expr_.c_str()); } else if (failure.file_) { printf("\n"); } if (!failure.message_.empty()) { Json::String reindented = indentText(failure.message_, indent + " "); printf("%s\n", reindented.c_str()); } } } Json::String TestResult::indentText(const Json::String& text, const Json::String& indent) { Json::String reindented; Json::String::size_type lastIndex = 0; while (lastIndex < text.size()) { Json::String::size_type nextIndex = text.find('\n', lastIndex); if (nextIndex == Json::String::npos) { nextIndex = text.size() - 1; } reindented += indent; reindented += text.substr(lastIndex, nextIndex - lastIndex + 1); lastIndex = nextIndex + 1; } return reindented; } TestResult& TestResult::addToLastFailure(const Json::String& message) { if (messageTarget_ != nullptr) { messageTarget_->message_ += message; } return *this; } TestResult& TestResult::operator<<(Json::Int64 value) { return addToLastFailure(Json::valueToString(value)); } TestResult& TestResult::operator<<(Json::UInt64 value) { return addToLastFailure(Json::valueToString(value)); } TestResult& TestResult::operator<<(bool value) { return addToLastFailure(value ? "true" : "false"); } // class TestCase // ////////////////////////////////////////////////////////////////// TestCase::TestCase() = default; TestCase::~TestCase() = default; void TestCase::run(TestResult& result) { result_ = &result; runTestCase(); } // class Runner // ////////////////////////////////////////////////////////////////// Runner::Runner() = default; Runner& Runner::add(TestCaseFactory factory) { tests_.push_back(factory); return *this; } size_t Runner::testCount() const { return tests_.size(); } Json::String Runner::testNameAt(size_t index) const { TestCase* test = tests_[index](); Json::String name = test->testName(); delete test; return name; } void Runner::runTestAt(size_t index, TestResult& result) const { TestCase* test = tests_[index](); result.setTestName(test->testName()); printf("Testing %s: ", test->testName()); fflush(stdout); #if JSON_USE_EXCEPTION try { #endif // if JSON_USE_EXCEPTION test->run(result); #if JSON_USE_EXCEPTION } catch (const std::exception& e) { result.addFailure(__FILE__, __LINE__, "Unexpected exception caught:") << e.what(); } #endif // if JSON_USE_EXCEPTION delete test; const char* status = result.failed() ? "FAILED" : "OK"; printf("%s\n", status); fflush(stdout); } bool Runner::runAllTest(bool printSummary) const { size_t const count = testCount(); std::deque<TestResult> failures; for (size_t index = 0; index < count; ++index) { TestResult result; runTestAt(index, result); if (result.failed()) { failures.push_back(result); } } if (failures.empty()) { if (printSummary) { printf("All %zu tests passed\n", count); } return true; } for (auto& result : failures) { result.printFailure(count > 1); } if (printSummary) { size_t const failedCount = failures.size(); size_t const passedCount = count - failedCount; printf("%zu/%zu tests passed (%zu failure(s))\n", passedCount, count, failedCount); } return false; } bool Runner::testIndex(const Json::String& testName, size_t& indexOut) const { const size_t count = testCount(); for (size_t index = 0; index < count; ++index) { if (testNameAt(index) == testName) { indexOut = index; return true; } } return false; } void Runner::listTests() const { const size_t count = testCount(); for (size_t index = 0; index < count; ++index) { printf("%s\n", testNameAt(index).c_str()); } } int Runner::runCommandLine(int argc, const char* argv[]) const { // typedef std::deque<String> TestNames; Runner subrunner; for (int index = 1; index < argc; ++index) { Json::String opt = argv[index]; if (opt == "--list-tests") { listTests(); return 0; } if (opt == "--test-auto") { preventDialogOnCrash(); } else if (opt == "--test") { ++index; if (index < argc) { size_t testNameIndex; if (testIndex(argv[index], testNameIndex)) { subrunner.add(tests_[testNameIndex]); } else { fprintf(stderr, "Test '%s' does not exist!\n", argv[index]); return 2; } } else { printUsage(argv[0]); return 2; } } else { printUsage(argv[0]); return 2; } } bool succeeded; if (subrunner.testCount() > 0) { succeeded = subrunner.runAllTest(subrunner.testCount() > 1); } else { succeeded = runAllTest(true); } return succeeded ? 0 : 1; } #if defined(_MSC_VER) && defined(_DEBUG) // Hook MSVCRT assertions to prevent dialog from appearing static int msvcrtSilentReportHook(int reportType, char* message, int* /*returnValue*/) { // The default CRT handling of error and assertion is to display // an error dialog to the user. // Instead, when an error or an assertion occurs, we force the // application to terminate using abort() after display // the message on stderr. if (reportType == _CRT_ERROR || reportType == _CRT_ASSERT) { // calling abort() cause the ReportHook to be called // The following is used to detect this case and let's the // error handler fallback on its default behaviour ( // display a warning message) static volatile bool isAborting = false; if (isAborting) { return TRUE; } isAborting = true; fprintf(stderr, "CRT Error/Assert:\n%s\n", message); fflush(stderr); abort(); } // Let's other reportType (_CRT_WARNING) be handled as they would by default return FALSE; } #endif // if defined(_MSC_VER) void Runner::preventDialogOnCrash() { #if defined(_MSC_VER) && defined(_DEBUG) // Install a hook to prevent MSVCRT error and assertion from // popping a dialog // This function a NO-OP in release configuration // (which cause warning since msvcrtSilentReportHook is not referenced) _CrtSetReportHook(&msvcrtSilentReportHook); #endif // if defined(_MSC_VER) // @todo investigate this handler (for buffer overflow) // _set_security_error_handler #if defined(_WIN32) // Prevents the system from popping a dialog for debugging if the // application fails due to invalid memory access. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX); #endif // if defined(_WIN32) } void Runner::printUsage(const char* appName) { printf("Usage: %s [options]\n" "\n" "If --test is not specified, then all the test cases be run.\n" "\n" "Valid options:\n" "--list-tests: print the name of all test cases on the standard\n" " output and exit.\n" "--test TESTNAME: executes the test case with the specified name.\n" " May be repeated.\n" "--test-auto: prevent dialog prompting for debugging on crash.\n", appName); } // Assertion functions // ////////////////////////////////////////////////////////////////// Json::String ToJsonString(const char* toConvert) { return Json::String(toConvert); } Json::String ToJsonString(Json::String in) { return in; } #if JSONCPP_USING_SECURE_MEMORY Json::String ToJsonString(std::string in) { return Json::String(in.data(), in.data() + in.length()); } #endif TestResult& checkStringEqual(TestResult& result, const Json::String& expected, const Json::String& actual, const char* file, unsigned int line, const char* expr) { if (expected != actual) { result.addFailure(file, line, expr); result << "Expected: '" << expected << "'\n"; result << "Actual : '" << actual << "'"; } return result; } } // namespace JsonTest
C++
3D
mcellteam/mcell
libs/jsoncpp/src/test_lib_json/main.cpp
.cpp
135,565
3,807
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #if defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #elif defined(_MSC_VER) #pragma warning(disable : 4996) #endif #include "fuzz.h" #include "jsontest.h" #include <cmath> #include <cstring> #include <functional> #include <iomanip> #include <iostream> #include <iterator> #include <json/config.h> #include <json/json.h> #include <limits> #include <memory> #include <sstream> #include <string> using CharReaderPtr = std::unique_ptr<Json::CharReader>; // Make numeric limits more convenient to talk about. // Assumes int type in 32 bits. #define kint32max Json::Value::maxInt #define kint32min Json::Value::minInt #define kuint32max Json::Value::maxUInt #define kint64max Json::Value::maxInt64 #define kint64min Json::Value::minInt64 #define kuint64max Json::Value::maxUInt64 // static const double kdint64max = double(kint64max); // static const float kfint64max = float(kint64max); static const float kfint32max = float(kint32max); static const float kfuint32max = float(kuint32max); // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // Json Library test cases // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// #if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) static inline double uint64ToDouble(Json::UInt64 value) { return static_cast<double>(value); } #else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) static inline double uint64ToDouble(Json::UInt64 value) { return static_cast<double>(Json::Int64(value / 2)) * 2.0 + static_cast<double>(Json::Int64(value & 1)); } #endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) // local_ is the collection for the testcases in this code file. static std::deque<JsonTest::TestCaseFactory> local_; #define JSONTEST_FIXTURE_LOCAL(FixtureType, name) \ JSONTEST_FIXTURE_V2(FixtureType, name, local_) struct ValueTest : JsonTest::TestCase { Json::Value null_; Json::Value emptyArray_{Json::arrayValue}; Json::Value emptyObject_{Json::objectValue}; Json::Value integer_{123456789}; Json::Value unsignedInteger_{34567890}; Json::Value smallUnsignedInteger_{Json::Value::UInt(Json::Value::maxInt)}; Json::Value real_{1234.56789}; Json::Value float_{0.00390625f}; Json::Value array1_; Json::Value object1_; Json::Value emptyString_{""}; Json::Value string1_{"a"}; Json::Value string_{"sometext with space"}; Json::Value true_{true}; Json::Value false_{false}; ValueTest() { array1_.append(1234); object1_["id"] = 1234; } struct IsCheck { /// Initialize all checks to \c false by default. IsCheck(); bool isObject_{false}; bool isArray_{false}; bool isBool_{false}; bool isString_{false}; bool isNull_{false}; bool isInt_{false}; bool isInt64_{false}; bool isUInt_{false}; bool isUInt64_{false}; bool isIntegral_{false}; bool isDouble_{false}; bool isNumeric_{false}; }; void checkConstMemberCount(const Json::Value& value, unsigned int expectedCount); void checkMemberCount(Json::Value& value, unsigned int expectedCount); void checkIs(const Json::Value& value, const IsCheck& check); void checkIsLess(const Json::Value& x, const Json::Value& y); void checkIsEqual(const Json::Value& x, const Json::Value& y); /// Normalize the representation of floating-point number by stripped leading /// 0 in exponent. static Json::String normalizeFloatingPointStr(const Json::String& s); }; Json::String ValueTest::normalizeFloatingPointStr(const Json::String& s) { auto index = s.find_last_of("eE"); if (index == s.npos) return s; std::size_t signWidth = (s[index + 1] == '+' || s[index + 1] == '-') ? 1 : 0; auto exponentStartIndex = index + 1 + signWidth; Json::String normalized = s.substr(0, exponentStartIndex); auto indexDigit = s.find_first_not_of('0', exponentStartIndex); Json::String exponent = "0"; if (indexDigit != s.npos) { // nonzero exponent exponent = s.substr(indexDigit); } return normalized + exponent; } JSONTEST_FIXTURE_LOCAL(ValueTest, checkNormalizeFloatingPointStr) { struct TestData { std::string in; std::string out; } const testData[] = { {"0.0", "0.0"}, {"0e0", "0e0"}, {"1234.0", "1234.0"}, {"1234.0e0", "1234.0e0"}, {"1234.0e-1", "1234.0e-1"}, {"1234.0e+0", "1234.0e+0"}, {"1234.0e+001", "1234.0e+1"}, {"1234e-1", "1234e-1"}, {"1234e+000", "1234e+0"}, {"1234e+001", "1234e+1"}, {"1234e10", "1234e10"}, {"1234e010", "1234e10"}, {"1234e+010", "1234e+10"}, {"1234e-010", "1234e-10"}, {"1234e+100", "1234e+100"}, {"1234e-100", "1234e-100"}, }; for (const auto& td : testData) { JSONTEST_ASSERT_STRING_EQUAL(normalizeFloatingPointStr(td.in), td.out); } } JSONTEST_FIXTURE_LOCAL(ValueTest, memberCount) { JSONTEST_ASSERT_PRED(checkMemberCount(emptyArray_, 0)); JSONTEST_ASSERT_PRED(checkMemberCount(emptyObject_, 0)); JSONTEST_ASSERT_PRED(checkMemberCount(array1_, 1)); JSONTEST_ASSERT_PRED(checkMemberCount(object1_, 1)); JSONTEST_ASSERT_PRED(checkMemberCount(null_, 0)); JSONTEST_ASSERT_PRED(checkMemberCount(integer_, 0)); JSONTEST_ASSERT_PRED(checkMemberCount(unsignedInteger_, 0)); JSONTEST_ASSERT_PRED(checkMemberCount(smallUnsignedInteger_, 0)); JSONTEST_ASSERT_PRED(checkMemberCount(real_, 0)); JSONTEST_ASSERT_PRED(checkMemberCount(emptyString_, 0)); JSONTEST_ASSERT_PRED(checkMemberCount(string_, 0)); JSONTEST_ASSERT_PRED(checkMemberCount(true_, 0)); JSONTEST_ASSERT_PRED(checkMemberCount(false_, 0)); JSONTEST_ASSERT_PRED(checkMemberCount(string1_, 0)); JSONTEST_ASSERT_PRED(checkMemberCount(float_, 0)); } JSONTEST_FIXTURE_LOCAL(ValueTest, objects) { // Types IsCheck checks; checks.isObject_ = true; JSONTEST_ASSERT_PRED(checkIs(emptyObject_, checks)); JSONTEST_ASSERT_PRED(checkIs(object1_, checks)); JSONTEST_ASSERT_EQUAL(Json::objectValue, emptyObject_.type()); // Empty object okay JSONTEST_ASSERT(emptyObject_.isConvertibleTo(Json::nullValue)); // Non-empty object not okay JSONTEST_ASSERT(!object1_.isConvertibleTo(Json::nullValue)); // Always okay JSONTEST_ASSERT(emptyObject_.isConvertibleTo(Json::objectValue)); // Never okay JSONTEST_ASSERT(!emptyObject_.isConvertibleTo(Json::arrayValue)); JSONTEST_ASSERT(!emptyObject_.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(!emptyObject_.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT(!emptyObject_.isConvertibleTo(Json::realValue)); JSONTEST_ASSERT(!emptyObject_.isConvertibleTo(Json::booleanValue)); JSONTEST_ASSERT(!emptyObject_.isConvertibleTo(Json::stringValue)); // Access through const reference const Json::Value& constObject = object1_; JSONTEST_ASSERT_EQUAL(Json::Value(1234), constObject["id"]); JSONTEST_ASSERT_EQUAL(Json::Value(), constObject["unknown id"]); // Access through find() const char idKey[] = "id"; const Json::Value* foundId = object1_.find(idKey, idKey + strlen(idKey)); JSONTEST_ASSERT(foundId != nullptr); JSONTEST_ASSERT_EQUAL(Json::Value(1234), *foundId); const char unknownIdKey[] = "unknown id"; const Json::Value* foundUnknownId = object1_.find(unknownIdKey, unknownIdKey + strlen(unknownIdKey)); JSONTEST_ASSERT_EQUAL(nullptr, foundUnknownId); // Access through demand() const char yetAnotherIdKey[] = "yet another id"; const Json::Value* foundYetAnotherId = object1_.find(yetAnotherIdKey, yetAnotherIdKey + strlen(yetAnotherIdKey)); JSONTEST_ASSERT_EQUAL(nullptr, foundYetAnotherId); Json::Value* demandedYetAnotherId = object1_.demand( yetAnotherIdKey, yetAnotherIdKey + strlen(yetAnotherIdKey)); JSONTEST_ASSERT(demandedYetAnotherId != nullptr); *demandedYetAnotherId = "baz"; JSONTEST_ASSERT_EQUAL(Json::Value("baz"), object1_["yet another id"]); // Access through non-const reference JSONTEST_ASSERT_EQUAL(Json::Value(1234), object1_["id"]); JSONTEST_ASSERT_EQUAL(Json::Value(), object1_["unknown id"]); object1_["some other id"] = "foo"; JSONTEST_ASSERT_EQUAL(Json::Value("foo"), object1_["some other id"]); JSONTEST_ASSERT_EQUAL(Json::Value("foo"), object1_["some other id"]); // Remove. Json::Value got; bool did; did = object1_.removeMember("some other id", &got); JSONTEST_ASSERT_EQUAL(Json::Value("foo"), got); JSONTEST_ASSERT_EQUAL(true, did); got = Json::Value("bar"); did = object1_.removeMember("some other id", &got); JSONTEST_ASSERT_EQUAL(Json::Value("bar"), got); JSONTEST_ASSERT_EQUAL(false, did); object1_["some other id"] = "foo"; Json::Value* gotPtr = nullptr; did = object1_.removeMember("some other id", gotPtr); JSONTEST_ASSERT_EQUAL(nullptr, gotPtr); JSONTEST_ASSERT_EQUAL(true, did); // Using other removeMember interfaces, the test idea is the same as above. object1_["some other id"] = "foo"; const Json::String key("some other id"); did = object1_.removeMember(key, &got); JSONTEST_ASSERT_EQUAL(Json::Value("foo"), got); JSONTEST_ASSERT_EQUAL(true, did); got = Json::Value("bar"); did = object1_.removeMember(key, &got); JSONTEST_ASSERT_EQUAL(Json::Value("bar"), got); JSONTEST_ASSERT_EQUAL(false, did); object1_["some other id"] = "foo"; object1_.removeMember(key); JSONTEST_ASSERT_EQUAL(Json::nullValue, object1_[key]); } JSONTEST_FIXTURE_LOCAL(ValueTest, arrays) { const unsigned int index0 = 0; // Types IsCheck checks; checks.isArray_ = true; JSONTEST_ASSERT_PRED(checkIs(emptyArray_, checks)); JSONTEST_ASSERT_PRED(checkIs(array1_, checks)); JSONTEST_ASSERT_EQUAL(Json::arrayValue, array1_.type()); // Empty array okay JSONTEST_ASSERT(emptyArray_.isConvertibleTo(Json::nullValue)); // Non-empty array not okay JSONTEST_ASSERT(!array1_.isConvertibleTo(Json::nullValue)); // Always okay JSONTEST_ASSERT(emptyArray_.isConvertibleTo(Json::arrayValue)); // Never okay JSONTEST_ASSERT(!emptyArray_.isConvertibleTo(Json::objectValue)); JSONTEST_ASSERT(!emptyArray_.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(!emptyArray_.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT(!emptyArray_.isConvertibleTo(Json::realValue)); JSONTEST_ASSERT(!emptyArray_.isConvertibleTo(Json::booleanValue)); JSONTEST_ASSERT(!emptyArray_.isConvertibleTo(Json::stringValue)); // Access through const reference const Json::Value& constArray = array1_; JSONTEST_ASSERT_EQUAL(Json::Value(1234), constArray[index0]); JSONTEST_ASSERT_EQUAL(Json::Value(1234), constArray[0]); // Access through non-const reference JSONTEST_ASSERT_EQUAL(Json::Value(1234), array1_[index0]); JSONTEST_ASSERT_EQUAL(Json::Value(1234), array1_[0]); array1_[2] = Json::Value(17); JSONTEST_ASSERT_EQUAL(Json::Value(), array1_[1]); JSONTEST_ASSERT_EQUAL(Json::Value(17), array1_[2]); Json::Value got; JSONTEST_ASSERT_EQUAL(true, array1_.removeIndex(2, &got)); JSONTEST_ASSERT_EQUAL(Json::Value(17), got); JSONTEST_ASSERT_EQUAL(false, array1_.removeIndex(2, &got)); // gone now } JSONTEST_FIXTURE_LOCAL(ValueTest, resizeArray) { Json::Value array; { for (Json::ArrayIndex i = 0; i < 10; i++) array[i] = i; JSONTEST_ASSERT_EQUAL(array.size(), 10); // The length set is greater than the length of the array. array.resize(15); JSONTEST_ASSERT_EQUAL(array.size(), 15); // The length set is less than the length of the array. array.resize(5); JSONTEST_ASSERT_EQUAL(array.size(), 5); // The length of the array is set to 0. array.resize(0); JSONTEST_ASSERT_EQUAL(array.size(), 0); } { for (Json::ArrayIndex i = 0; i < 10; i++) array[i] = i; JSONTEST_ASSERT_EQUAL(array.size(), 10); array.clear(); JSONTEST_ASSERT_EQUAL(array.size(), 0); } } JSONTEST_FIXTURE_LOCAL(ValueTest, getArrayValue) { Json::Value array; for (Json::ArrayIndex i = 0; i < 5; i++) array[i] = i; JSONTEST_ASSERT_EQUAL(array.size(), 5); const Json::Value defaultValue(10); Json::ArrayIndex index = 0; for (; index <= 4; index++) JSONTEST_ASSERT_EQUAL(index, array.get(index, defaultValue).asInt()); index = 4; JSONTEST_ASSERT_EQUAL(array.isValidIndex(index), true); index = 5; JSONTEST_ASSERT_EQUAL(array.isValidIndex(index), false); JSONTEST_ASSERT_EQUAL(defaultValue, array.get(index, defaultValue)); JSONTEST_ASSERT_EQUAL(array.isValidIndex(index), false); } JSONTEST_FIXTURE_LOCAL(ValueTest, arrayIssue252) { int count = 5; Json::Value root; Json::Value item; root["array"] = Json::Value::nullSingleton(); for (int i = 0; i < count; i++) { item["a"] = i; item["b"] = i; root["array"][i] = item; } // JSONTEST_ASSERT_EQUAL(5, root["array"].size()); } JSONTEST_FIXTURE_LOCAL(ValueTest, arrayInsertAtRandomIndex) { Json::Value array; const Json::Value str0("index2"); const Json::Value str1("index3"); array.append("index0"); // append rvalue array.append("index1"); array.append(str0); // append lvalue std::vector<Json::Value*> vec; // storage value address for checking for (Json::ArrayIndex i = 0; i < 3; i++) { vec.push_back(&array[i]); } JSONTEST_ASSERT_EQUAL(Json::Value("index0"), array[0]); // check append JSONTEST_ASSERT_EQUAL(Json::Value("index1"), array[1]); JSONTEST_ASSERT_EQUAL(Json::Value("index2"), array[2]); // insert lvalue at the head JSONTEST_ASSERT(array.insert(0, str1)); JSONTEST_ASSERT_EQUAL(Json::Value("index3"), array[0]); JSONTEST_ASSERT_EQUAL(Json::Value("index0"), array[1]); JSONTEST_ASSERT_EQUAL(Json::Value("index1"), array[2]); JSONTEST_ASSERT_EQUAL(Json::Value("index2"), array[3]); // checking address for (Json::ArrayIndex i = 0; i < 3; i++) { JSONTEST_ASSERT_EQUAL(vec[i], &array[i]); } vec.push_back(&array[3]); // insert rvalue at middle JSONTEST_ASSERT(array.insert(2, "index4")); JSONTEST_ASSERT_EQUAL(Json::Value("index3"), array[0]); JSONTEST_ASSERT_EQUAL(Json::Value("index0"), array[1]); JSONTEST_ASSERT_EQUAL(Json::Value("index4"), array[2]); JSONTEST_ASSERT_EQUAL(Json::Value("index1"), array[3]); JSONTEST_ASSERT_EQUAL(Json::Value("index2"), array[4]); // checking address for (Json::ArrayIndex i = 0; i < 4; i++) { JSONTEST_ASSERT_EQUAL(vec[i], &array[i]); } vec.push_back(&array[4]); // insert rvalue at the tail JSONTEST_ASSERT(array.insert(5, "index5")); JSONTEST_ASSERT_EQUAL(Json::Value("index3"), array[0]); JSONTEST_ASSERT_EQUAL(Json::Value("index0"), array[1]); JSONTEST_ASSERT_EQUAL(Json::Value("index4"), array[2]); JSONTEST_ASSERT_EQUAL(Json::Value("index1"), array[3]); JSONTEST_ASSERT_EQUAL(Json::Value("index2"), array[4]); JSONTEST_ASSERT_EQUAL(Json::Value("index5"), array[5]); // checking address for (Json::ArrayIndex i = 0; i < 5; i++) { JSONTEST_ASSERT_EQUAL(vec[i], &array[i]); } vec.push_back(&array[5]); // beyond max array size, it should not be allowed to insert into its tail JSONTEST_ASSERT(!array.insert(10, "index10")); } JSONTEST_FIXTURE_LOCAL(ValueTest, null) { JSONTEST_ASSERT_EQUAL(Json::nullValue, null_.type()); IsCheck checks; checks.isNull_ = true; JSONTEST_ASSERT_PRED(checkIs(null_, checks)); JSONTEST_ASSERT(null_.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(null_.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(null_.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT(null_.isConvertibleTo(Json::realValue)); JSONTEST_ASSERT(null_.isConvertibleTo(Json::booleanValue)); JSONTEST_ASSERT(null_.isConvertibleTo(Json::stringValue)); JSONTEST_ASSERT(null_.isConvertibleTo(Json::arrayValue)); JSONTEST_ASSERT(null_.isConvertibleTo(Json::objectValue)); JSONTEST_ASSERT_EQUAL(Json::Int(0), null_.asInt()); JSONTEST_ASSERT_EQUAL(Json::LargestInt(0), null_.asLargestInt()); JSONTEST_ASSERT_EQUAL(Json::UInt(0), null_.asUInt()); JSONTEST_ASSERT_EQUAL(Json::LargestUInt(0), null_.asLargestUInt()); JSONTEST_ASSERT_EQUAL(0.0, null_.asDouble()); JSONTEST_ASSERT_EQUAL(0.0, null_.asFloat()); JSONTEST_ASSERT_STRING_EQUAL("", null_.asString()); JSONTEST_ASSERT_EQUAL(Json::Value::nullSingleton(), null_); // Test using a Value in a boolean context (false iff null) JSONTEST_ASSERT_EQUAL(null_, false); JSONTEST_ASSERT_EQUAL(object1_, true); JSONTEST_ASSERT_EQUAL(!null_, true); JSONTEST_ASSERT_EQUAL(!object1_, false); } JSONTEST_FIXTURE_LOCAL(ValueTest, strings) { JSONTEST_ASSERT_EQUAL(Json::stringValue, string1_.type()); IsCheck checks; checks.isString_ = true; JSONTEST_ASSERT_PRED(checkIs(emptyString_, checks)); JSONTEST_ASSERT_PRED(checkIs(string_, checks)); JSONTEST_ASSERT_PRED(checkIs(string1_, checks)); // Empty string okay JSONTEST_ASSERT(emptyString_.isConvertibleTo(Json::nullValue)); // Non-empty string not okay JSONTEST_ASSERT(!string1_.isConvertibleTo(Json::nullValue)); // Always okay JSONTEST_ASSERT(string1_.isConvertibleTo(Json::stringValue)); // Never okay JSONTEST_ASSERT(!string1_.isConvertibleTo(Json::objectValue)); JSONTEST_ASSERT(!string1_.isConvertibleTo(Json::arrayValue)); JSONTEST_ASSERT(!string1_.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(!string1_.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT(!string1_.isConvertibleTo(Json::realValue)); JSONTEST_ASSERT_STRING_EQUAL("a", string1_.asString()); JSONTEST_ASSERT_STRING_EQUAL("a", string1_.asCString()); } JSONTEST_FIXTURE_LOCAL(ValueTest, bools) { JSONTEST_ASSERT_EQUAL(Json::booleanValue, false_.type()); IsCheck checks; checks.isBool_ = true; JSONTEST_ASSERT_PRED(checkIs(false_, checks)); JSONTEST_ASSERT_PRED(checkIs(true_, checks)); // False okay JSONTEST_ASSERT(false_.isConvertibleTo(Json::nullValue)); // True not okay JSONTEST_ASSERT(!true_.isConvertibleTo(Json::nullValue)); // Always okay JSONTEST_ASSERT(true_.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(true_.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT(true_.isConvertibleTo(Json::realValue)); JSONTEST_ASSERT(true_.isConvertibleTo(Json::booleanValue)); JSONTEST_ASSERT(true_.isConvertibleTo(Json::stringValue)); // Never okay JSONTEST_ASSERT(!true_.isConvertibleTo(Json::arrayValue)); JSONTEST_ASSERT(!true_.isConvertibleTo(Json::objectValue)); JSONTEST_ASSERT_EQUAL(true, true_.asBool()); JSONTEST_ASSERT_EQUAL(1, true_.asInt()); JSONTEST_ASSERT_EQUAL(1, true_.asLargestInt()); JSONTEST_ASSERT_EQUAL(1, true_.asUInt()); JSONTEST_ASSERT_EQUAL(1, true_.asLargestUInt()); JSONTEST_ASSERT_EQUAL(1.0, true_.asDouble()); JSONTEST_ASSERT_EQUAL(1.0, true_.asFloat()); JSONTEST_ASSERT_EQUAL(false, false_.asBool()); JSONTEST_ASSERT_EQUAL(0, false_.asInt()); JSONTEST_ASSERT_EQUAL(0, false_.asLargestInt()); JSONTEST_ASSERT_EQUAL(0, false_.asUInt()); JSONTEST_ASSERT_EQUAL(0, false_.asLargestUInt()); JSONTEST_ASSERT_EQUAL(0.0, false_.asDouble()); JSONTEST_ASSERT_EQUAL(0.0, false_.asFloat()); } JSONTEST_FIXTURE_LOCAL(ValueTest, integers) { IsCheck checks; Json::Value val; // Conversions that don't depend on the value. JSONTEST_ASSERT(Json::Value(17).isConvertibleTo(Json::realValue)); JSONTEST_ASSERT(Json::Value(17).isConvertibleTo(Json::stringValue)); JSONTEST_ASSERT(Json::Value(17).isConvertibleTo(Json::booleanValue)); JSONTEST_ASSERT(!Json::Value(17).isConvertibleTo(Json::arrayValue)); JSONTEST_ASSERT(!Json::Value(17).isConvertibleTo(Json::objectValue)); JSONTEST_ASSERT(Json::Value(17U).isConvertibleTo(Json::realValue)); JSONTEST_ASSERT(Json::Value(17U).isConvertibleTo(Json::stringValue)); JSONTEST_ASSERT(Json::Value(17U).isConvertibleTo(Json::booleanValue)); JSONTEST_ASSERT(!Json::Value(17U).isConvertibleTo(Json::arrayValue)); JSONTEST_ASSERT(!Json::Value(17U).isConvertibleTo(Json::objectValue)); JSONTEST_ASSERT(Json::Value(17.0).isConvertibleTo(Json::realValue)); JSONTEST_ASSERT(Json::Value(17.0).isConvertibleTo(Json::stringValue)); JSONTEST_ASSERT(Json::Value(17.0).isConvertibleTo(Json::booleanValue)); JSONTEST_ASSERT(!Json::Value(17.0).isConvertibleTo(Json::arrayValue)); JSONTEST_ASSERT(!Json::Value(17.0).isConvertibleTo(Json::objectValue)); // Default int val = Json::Value(Json::intValue); JSONTEST_ASSERT_EQUAL(Json::intValue, val.type()); checks = IsCheck(); checks.isInt_ = true; checks.isInt64_ = true; checks.isUInt_ = true; checks.isUInt64_ = true; checks.isIntegral_ = true; checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL(0, val.asInt()); JSONTEST_ASSERT_EQUAL(0, val.asLargestInt()); JSONTEST_ASSERT_EQUAL(0, val.asUInt()); JSONTEST_ASSERT_EQUAL(0, val.asLargestUInt()); JSONTEST_ASSERT_EQUAL(0.0, val.asDouble()); JSONTEST_ASSERT_EQUAL(0.0, val.asFloat()); JSONTEST_ASSERT_EQUAL(false, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL("0", val.asString()); // Default uint val = Json::Value(Json::uintValue); JSONTEST_ASSERT_EQUAL(Json::uintValue, val.type()); checks = IsCheck(); checks.isInt_ = true; checks.isInt64_ = true; checks.isUInt_ = true; checks.isUInt64_ = true; checks.isIntegral_ = true; checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL(0, val.asInt()); JSONTEST_ASSERT_EQUAL(0, val.asLargestInt()); JSONTEST_ASSERT_EQUAL(0, val.asUInt()); JSONTEST_ASSERT_EQUAL(0, val.asLargestUInt()); JSONTEST_ASSERT_EQUAL(0.0, val.asDouble()); JSONTEST_ASSERT_EQUAL(0.0, val.asFloat()); JSONTEST_ASSERT_EQUAL(false, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL("0", val.asString()); // Default real val = Json::Value(Json::realValue); JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); JSONTEST_ASSERT(val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); checks = IsCheck(); checks.isInt_ = true; checks.isInt64_ = true; checks.isUInt_ = true; checks.isUInt64_ = true; checks.isIntegral_ = true; checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT_EQUAL(0, val.asInt()); JSONTEST_ASSERT_EQUAL(0, val.asLargestInt()); JSONTEST_ASSERT_EQUAL(0, val.asUInt()); JSONTEST_ASSERT_EQUAL(0, val.asLargestUInt()); JSONTEST_ASSERT_EQUAL(0.0, val.asDouble()); JSONTEST_ASSERT_EQUAL(0.0, val.asFloat()); JSONTEST_ASSERT_EQUAL(false, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL("0.0", val.asString()); // Zero (signed constructor arg) val = Json::Value(0); JSONTEST_ASSERT_EQUAL(Json::intValue, val.type()); checks = IsCheck(); checks.isInt_ = true; checks.isInt64_ = true; checks.isUInt_ = true; checks.isUInt64_ = true; checks.isIntegral_ = true; checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL(0, val.asInt()); JSONTEST_ASSERT_EQUAL(0, val.asLargestInt()); JSONTEST_ASSERT_EQUAL(0, val.asUInt()); JSONTEST_ASSERT_EQUAL(0, val.asLargestUInt()); JSONTEST_ASSERT_EQUAL(0.0, val.asDouble()); JSONTEST_ASSERT_EQUAL(0.0, val.asFloat()); JSONTEST_ASSERT_EQUAL(false, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL("0", val.asString()); // Zero (unsigned constructor arg) val = Json::Value(0u); JSONTEST_ASSERT_EQUAL(Json::uintValue, val.type()); checks = IsCheck(); checks.isInt_ = true; checks.isInt64_ = true; checks.isUInt_ = true; checks.isUInt64_ = true; checks.isIntegral_ = true; checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL(0, val.asInt()); JSONTEST_ASSERT_EQUAL(0, val.asLargestInt()); JSONTEST_ASSERT_EQUAL(0, val.asUInt()); JSONTEST_ASSERT_EQUAL(0, val.asLargestUInt()); JSONTEST_ASSERT_EQUAL(0.0, val.asDouble()); JSONTEST_ASSERT_EQUAL(0.0, val.asFloat()); JSONTEST_ASSERT_EQUAL(false, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL("0", val.asString()); // Zero (floating-point constructor arg) val = Json::Value(0.0); JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); checks = IsCheck(); checks.isInt_ = true; checks.isInt64_ = true; checks.isUInt_ = true; checks.isUInt64_ = true; checks.isIntegral_ = true; checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL(0, val.asInt()); JSONTEST_ASSERT_EQUAL(0, val.asLargestInt()); JSONTEST_ASSERT_EQUAL(0, val.asUInt()); JSONTEST_ASSERT_EQUAL(0, val.asLargestUInt()); JSONTEST_ASSERT_EQUAL(0.0, val.asDouble()); JSONTEST_ASSERT_EQUAL(0.0, val.asFloat()); JSONTEST_ASSERT_EQUAL(false, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL("0.0", val.asString()); // 2^20 (signed constructor arg) val = Json::Value(1 << 20); JSONTEST_ASSERT_EQUAL(Json::intValue, val.type()); checks = IsCheck(); checks.isInt_ = true; checks.isInt64_ = true; checks.isUInt_ = true; checks.isUInt64_ = true; checks.isIntegral_ = true; checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL((1 << 20), val.asInt()); JSONTEST_ASSERT_EQUAL((1 << 20), val.asLargestInt()); JSONTEST_ASSERT_EQUAL((1 << 20), val.asUInt()); JSONTEST_ASSERT_EQUAL((1 << 20), val.asLargestUInt()); JSONTEST_ASSERT_EQUAL((1 << 20), val.asDouble()); JSONTEST_ASSERT_EQUAL((1 << 20), val.asFloat()); JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL("1048576", val.asString()); // 2^20 (unsigned constructor arg) val = Json::Value(Json::UInt(1 << 20)); JSONTEST_ASSERT_EQUAL(Json::uintValue, val.type()); checks = IsCheck(); checks.isInt_ = true; checks.isInt64_ = true; checks.isUInt_ = true; checks.isUInt64_ = true; checks.isIntegral_ = true; checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL((1 << 20), val.asInt()); JSONTEST_ASSERT_EQUAL((1 << 20), val.asLargestInt()); JSONTEST_ASSERT_EQUAL((1 << 20), val.asUInt()); JSONTEST_ASSERT_EQUAL((1 << 20), val.asLargestUInt()); JSONTEST_ASSERT_EQUAL((1 << 20), val.asDouble()); JSONTEST_ASSERT_EQUAL((1 << 20), val.asFloat()); JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL("1048576", val.asString()); // 2^20 (floating-point constructor arg) val = Json::Value((1 << 20) / 1.0); JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); checks = IsCheck(); checks.isInt_ = true; checks.isInt64_ = true; checks.isUInt_ = true; checks.isUInt64_ = true; checks.isIntegral_ = true; checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL((1 << 20), val.asInt()); JSONTEST_ASSERT_EQUAL((1 << 20), val.asLargestInt()); JSONTEST_ASSERT_EQUAL((1 << 20), val.asUInt()); JSONTEST_ASSERT_EQUAL((1 << 20), val.asLargestUInt()); JSONTEST_ASSERT_EQUAL((1 << 20), val.asDouble()); JSONTEST_ASSERT_EQUAL((1 << 20), val.asFloat()); JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL( "1048576.0", normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); // -2^20 val = Json::Value(-(1 << 20)); JSONTEST_ASSERT_EQUAL(Json::intValue, val.type()); checks = IsCheck(); checks.isInt_ = true; checks.isInt64_ = true; checks.isIntegral_ = true; checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL(-(1 << 20), val.asInt()); JSONTEST_ASSERT_EQUAL(-(1 << 20), val.asLargestInt()); JSONTEST_ASSERT_EQUAL(-(1 << 20), val.asDouble()); JSONTEST_ASSERT_EQUAL(-(1 << 20), val.asFloat()); JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL("-1048576", val.asString()); // int32 max val = Json::Value(kint32max); JSONTEST_ASSERT_EQUAL(Json::intValue, val.type()); checks = IsCheck(); checks.isInt_ = true; checks.isInt64_ = true; checks.isUInt_ = true; checks.isUInt64_ = true; checks.isIntegral_ = true; checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL(kint32max, val.asInt()); JSONTEST_ASSERT_EQUAL(kint32max, val.asLargestInt()); JSONTEST_ASSERT_EQUAL(kint32max, val.asUInt()); JSONTEST_ASSERT_EQUAL(kint32max, val.asLargestUInt()); JSONTEST_ASSERT_EQUAL(kint32max, val.asDouble()); JSONTEST_ASSERT_EQUAL(kfint32max, val.asFloat()); JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL("2147483647", val.asString()); // int32 min val = Json::Value(kint32min); JSONTEST_ASSERT_EQUAL(Json::intValue, val.type()); checks = IsCheck(); checks.isInt_ = true; checks.isInt64_ = true; checks.isIntegral_ = true; checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL(kint32min, val.asInt()); JSONTEST_ASSERT_EQUAL(kint32min, val.asLargestInt()); JSONTEST_ASSERT_EQUAL(kint32min, val.asDouble()); JSONTEST_ASSERT_EQUAL(kint32min, val.asFloat()); JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL("-2147483648", val.asString()); // uint32 max val = Json::Value(kuint32max); JSONTEST_ASSERT_EQUAL(Json::uintValue, val.type()); checks = IsCheck(); checks.isInt64_ = true; checks.isUInt_ = true; checks.isUInt64_ = true; checks.isIntegral_ = true; checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); #ifndef JSON_NO_INT64 JSONTEST_ASSERT_EQUAL(kuint32max, val.asLargestInt()); #endif JSONTEST_ASSERT_EQUAL(kuint32max, val.asUInt()); JSONTEST_ASSERT_EQUAL(kuint32max, val.asLargestUInt()); JSONTEST_ASSERT_EQUAL(kuint32max, val.asDouble()); JSONTEST_ASSERT_EQUAL(kfuint32max, val.asFloat()); JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL("4294967295", val.asString()); #ifdef JSON_NO_INT64 // int64 max val = Json::Value(double(kint64max)); JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); checks = IsCheck(); checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL(double(kint64max), val.asDouble()); JSONTEST_ASSERT_EQUAL(float(kint64max), val.asFloat()); JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL("9.22337e+18", val.asString()); // int64 min val = Json::Value(double(kint64min)); JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); checks = IsCheck(); checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL(double(kint64min), val.asDouble()); JSONTEST_ASSERT_EQUAL(float(kint64min), val.asFloat()); JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL("-9.22337e+18", val.asString()); // uint64 max val = Json::Value(double(kuint64max)); JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); checks = IsCheck(); checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL(double(kuint64max), val.asDouble()); JSONTEST_ASSERT_EQUAL(float(kuint64max), val.asFloat()); JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL("1.84467e+19", val.asString()); #else // ifdef JSON_NO_INT64 // 2^40 (signed constructor arg) val = Json::Value(Json::Int64(1) << 40); JSONTEST_ASSERT_EQUAL(Json::intValue, val.type()); checks = IsCheck(); checks.isInt64_ = true; checks.isUInt64_ = true; checks.isIntegral_ = true; checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asInt64()); JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asLargestInt()); JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asUInt64()); JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asLargestUInt()); JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asDouble()); JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asFloat()); JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL("1099511627776", val.asString()); // 2^40 (unsigned constructor arg) val = Json::Value(Json::UInt64(1) << 40); JSONTEST_ASSERT_EQUAL(Json::uintValue, val.type()); checks = IsCheck(); checks.isInt64_ = true; checks.isUInt64_ = true; checks.isIntegral_ = true; checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asInt64()); JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asLargestInt()); JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asUInt64()); JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asLargestUInt()); JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asDouble()); JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asFloat()); JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL("1099511627776", val.asString()); // 2^40 (floating-point constructor arg) val = Json::Value((Json::Int64(1) << 40) / 1.0); JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); checks = IsCheck(); checks.isInt64_ = true; checks.isUInt64_ = true; checks.isIntegral_ = true; checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asInt64()); JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asLargestInt()); JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asUInt64()); JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asLargestUInt()); JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asDouble()); JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 40), val.asFloat()); JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL( "1099511627776.0", normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); // -2^40 val = Json::Value(-(Json::Int64(1) << 40)); JSONTEST_ASSERT_EQUAL(Json::intValue, val.type()); checks = IsCheck(); checks.isInt64_ = true; checks.isIntegral_ = true; checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL(-(Json::Int64(1) << 40), val.asInt64()); JSONTEST_ASSERT_EQUAL(-(Json::Int64(1) << 40), val.asLargestInt()); JSONTEST_ASSERT_EQUAL(-(Json::Int64(1) << 40), val.asDouble()); JSONTEST_ASSERT_EQUAL(-(Json::Int64(1) << 40), val.asFloat()); JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL("-1099511627776", val.asString()); // int64 max val = Json::Value(Json::Int64(kint64max)); JSONTEST_ASSERT_EQUAL(Json::intValue, val.type()); checks = IsCheck(); checks.isInt64_ = true; checks.isUInt64_ = true; checks.isIntegral_ = true; checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL(kint64max, val.asInt64()); JSONTEST_ASSERT_EQUAL(kint64max, val.asLargestInt()); JSONTEST_ASSERT_EQUAL(kint64max, val.asUInt64()); JSONTEST_ASSERT_EQUAL(kint64max, val.asLargestUInt()); JSONTEST_ASSERT_EQUAL(double(kint64max), val.asDouble()); JSONTEST_ASSERT_EQUAL(float(kint64max), val.asFloat()); JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL("9223372036854775807", val.asString()); // int64 max (floating point constructor). Note that kint64max is not exactly // representable as a double, and will be rounded up to be higher. val = Json::Value(double(kint64max)); JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); checks = IsCheck(); checks.isUInt64_ = true; checks.isIntegral_ = true; checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL(Json::UInt64(1) << 63, val.asUInt64()); JSONTEST_ASSERT_EQUAL(Json::UInt64(1) << 63, val.asLargestUInt()); JSONTEST_ASSERT_EQUAL(uint64ToDouble(Json::UInt64(1) << 63), val.asDouble()); JSONTEST_ASSERT_EQUAL(float(Json::UInt64(1) << 63), val.asFloat()); JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL( "9.2233720368547758e+18", normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); // int64 min val = Json::Value(Json::Int64(kint64min)); JSONTEST_ASSERT_EQUAL(Json::intValue, val.type()); checks = IsCheck(); checks.isInt64_ = true; checks.isIntegral_ = true; checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL(kint64min, val.asInt64()); JSONTEST_ASSERT_EQUAL(kint64min, val.asLargestInt()); JSONTEST_ASSERT_EQUAL(double(kint64min), val.asDouble()); JSONTEST_ASSERT_EQUAL(float(kint64min), val.asFloat()); JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL("-9223372036854775808", val.asString()); // int64 min (floating point constructor). Note that kint64min *is* exactly // representable as a double. val = Json::Value(double(kint64min)); JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); checks = IsCheck(); checks.isInt64_ = true; checks.isIntegral_ = true; checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL(kint64min, val.asInt64()); JSONTEST_ASSERT_EQUAL(kint64min, val.asLargestInt()); JSONTEST_ASSERT_EQUAL(-9223372036854775808.0, val.asDouble()); JSONTEST_ASSERT_EQUAL(-9223372036854775808.0, val.asFloat()); JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL( "-9.2233720368547758e+18", normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); // 10^19 const auto ten_to_19 = static_cast<Json::UInt64>(1e19); val = Json::Value(Json::UInt64(ten_to_19)); JSONTEST_ASSERT_EQUAL(Json::uintValue, val.type()); checks = IsCheck(); checks.isUInt64_ = true; checks.isIntegral_ = true; checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL(ten_to_19, val.asUInt64()); JSONTEST_ASSERT_EQUAL(ten_to_19, val.asLargestUInt()); JSONTEST_ASSERT_EQUAL(uint64ToDouble(ten_to_19), val.asDouble()); JSONTEST_ASSERT_EQUAL(float(uint64ToDouble(ten_to_19)), val.asFloat()); JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL("10000000000000000000", val.asString()); // 10^19 (double constructor). Note that 10^19 is not exactly representable // as a double. val = Json::Value(uint64ToDouble(ten_to_19)); JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); checks = IsCheck(); checks.isUInt64_ = true; checks.isIntegral_ = true; checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL(1e19, val.asDouble()); JSONTEST_ASSERT_EQUAL(1e19, val.asFloat()); JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL( "1e+19", normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); // uint64 max val = Json::Value(Json::UInt64(kuint64max)); JSONTEST_ASSERT_EQUAL(Json::uintValue, val.type()); checks = IsCheck(); checks.isUInt64_ = true; checks.isIntegral_ = true; checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL(kuint64max, val.asUInt64()); JSONTEST_ASSERT_EQUAL(kuint64max, val.asLargestUInt()); JSONTEST_ASSERT_EQUAL(uint64ToDouble(kuint64max), val.asDouble()); JSONTEST_ASSERT_EQUAL(float(uint64ToDouble(kuint64max)), val.asFloat()); JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL("18446744073709551615", val.asString()); // uint64 max (floating point constructor). Note that kuint64max is not // exactly representable as a double, and will be rounded up to be higher. val = Json::Value(uint64ToDouble(kuint64max)); JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); checks = IsCheck(); checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT_EQUAL(18446744073709551616.0, val.asDouble()); JSONTEST_ASSERT_EQUAL(18446744073709551616.0, val.asFloat()); JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_STRING_EQUAL( "1.8446744073709552e+19", normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); #endif } JSONTEST_FIXTURE_LOCAL(ValueTest, nonIntegers) { IsCheck checks; Json::Value val; // Small positive number val = Json::Value(1.5); JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); checks = IsCheck(); checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::realValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::booleanValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::stringValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::arrayValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::objectValue)); JSONTEST_ASSERT_EQUAL(1.5, val.asDouble()); JSONTEST_ASSERT_EQUAL(1.5, val.asFloat()); JSONTEST_ASSERT_EQUAL(1, val.asInt()); JSONTEST_ASSERT_EQUAL(1, val.asLargestInt()); JSONTEST_ASSERT_EQUAL(1, val.asUInt()); JSONTEST_ASSERT_EQUAL(1, val.asLargestUInt()); JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_EQUAL("1.5", val.asString()); // Small negative number val = Json::Value(-1.5); JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); checks = IsCheck(); checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::realValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::booleanValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::stringValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::arrayValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::objectValue)); JSONTEST_ASSERT_EQUAL(-1.5, val.asDouble()); JSONTEST_ASSERT_EQUAL(-1.5, val.asFloat()); JSONTEST_ASSERT_EQUAL(-1, val.asInt()); JSONTEST_ASSERT_EQUAL(-1, val.asLargestInt()); JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_EQUAL("-1.5", val.asString()); // A bit over int32 max val = Json::Value(kint32max + 0.5); JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); checks = IsCheck(); checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::realValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::booleanValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::stringValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::arrayValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::objectValue)); JSONTEST_ASSERT_EQUAL(2147483647.5, val.asDouble()); JSONTEST_ASSERT_EQUAL(float(2147483647.5), val.asFloat()); JSONTEST_ASSERT_EQUAL(2147483647U, val.asUInt()); #ifdef JSON_HAS_INT64 JSONTEST_ASSERT_EQUAL(2147483647L, val.asLargestInt()); JSONTEST_ASSERT_EQUAL(2147483647U, val.asLargestUInt()); #endif JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_EQUAL( "2147483647.5", normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); // A bit under int32 min val = Json::Value(kint32min - 0.5); JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); checks = IsCheck(); checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(val.isConvertibleTo(Json::realValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::booleanValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::stringValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::arrayValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::objectValue)); JSONTEST_ASSERT_EQUAL(-2147483648.5, val.asDouble()); JSONTEST_ASSERT_EQUAL(float(-2147483648.5), val.asFloat()); #ifdef JSON_HAS_INT64 JSONTEST_ASSERT_EQUAL(-(Json::Int64(1) << 31), val.asLargestInt()); #endif JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_EQUAL( "-2147483648.5", normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); // A bit over uint32 max val = Json::Value(kuint32max + 0.5); JSONTEST_ASSERT_EQUAL(Json::realValue, val.type()); checks = IsCheck(); checks.isDouble_ = true; checks.isNumeric_ = true; JSONTEST_ASSERT_PRED(checkIs(val, checks)); JSONTEST_ASSERT(val.isConvertibleTo(Json::realValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::booleanValue)); JSONTEST_ASSERT(val.isConvertibleTo(Json::stringValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::nullValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::intValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::uintValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::arrayValue)); JSONTEST_ASSERT(!val.isConvertibleTo(Json::objectValue)); JSONTEST_ASSERT_EQUAL(4294967295.5, val.asDouble()); JSONTEST_ASSERT_EQUAL(float(4294967295.5), val.asFloat()); #ifdef JSON_HAS_INT64 JSONTEST_ASSERT_EQUAL((Json::Int64(1) << 32) - 1, val.asLargestInt()); JSONTEST_ASSERT_EQUAL((Json::UInt64(1) << 32) - Json::UInt64(1), val.asLargestUInt()); #endif JSONTEST_ASSERT_EQUAL(true, val.asBool()); JSONTEST_ASSERT_EQUAL( "4294967295.5", normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); val = Json::Value(1.2345678901234); JSONTEST_ASSERT_STRING_EQUAL( "1.2345678901234001", normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); // A 16-digit floating point number. val = Json::Value(2199023255552000.0f); JSONTEST_ASSERT_EQUAL(float(2199023255552000.0f), val.asFloat()); JSONTEST_ASSERT_STRING_EQUAL( "2199023255552000.0", normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); // A very large floating point number. val = Json::Value(3.402823466385289e38); JSONTEST_ASSERT_EQUAL(float(3.402823466385289e38), val.asFloat()); JSONTEST_ASSERT_STRING_EQUAL( "3.402823466385289e+38", normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); // An even larger floating point number. val = Json::Value(1.2345678e300); JSONTEST_ASSERT_EQUAL(double(1.2345678e300), val.asDouble()); JSONTEST_ASSERT_STRING_EQUAL( "1.2345678e+300", normalizeFloatingPointStr(JsonTest::ToJsonString(val.asString()))); } void ValueTest::checkConstMemberCount(const Json::Value& value, unsigned int expectedCount) { unsigned int count = 0; Json::Value::const_iterator itEnd = value.end(); for (Json::Value::const_iterator it = value.begin(); it != itEnd; ++it) { ++count; } JSONTEST_ASSERT_EQUAL(expectedCount, count) << "Json::Value::const_iterator"; } void ValueTest::checkMemberCount(Json::Value& value, unsigned int expectedCount) { JSONTEST_ASSERT_EQUAL(expectedCount, value.size()); unsigned int count = 0; Json::Value::iterator itEnd = value.end(); for (Json::Value::iterator it = value.begin(); it != itEnd; ++it) { ++count; } JSONTEST_ASSERT_EQUAL(expectedCount, count) << "Json::Value::iterator"; JSONTEST_ASSERT_PRED(checkConstMemberCount(value, expectedCount)); } ValueTest::IsCheck::IsCheck() = default; void ValueTest::checkIs(const Json::Value& value, const IsCheck& check) { JSONTEST_ASSERT_EQUAL(check.isObject_, value.isObject()); JSONTEST_ASSERT_EQUAL(check.isArray_, value.isArray()); JSONTEST_ASSERT_EQUAL(check.isBool_, value.isBool()); JSONTEST_ASSERT_EQUAL(check.isDouble_, value.isDouble()); JSONTEST_ASSERT_EQUAL(check.isInt_, value.isInt()); JSONTEST_ASSERT_EQUAL(check.isUInt_, value.isUInt()); JSONTEST_ASSERT_EQUAL(check.isIntegral_, value.isIntegral()); JSONTEST_ASSERT_EQUAL(check.isNumeric_, value.isNumeric()); JSONTEST_ASSERT_EQUAL(check.isString_, value.isString()); JSONTEST_ASSERT_EQUAL(check.isNull_, value.isNull()); #ifdef JSON_HAS_INT64 JSONTEST_ASSERT_EQUAL(check.isInt64_, value.isInt64()); JSONTEST_ASSERT_EQUAL(check.isUInt64_, value.isUInt64()); #else JSONTEST_ASSERT_EQUAL(false, value.isInt64()); JSONTEST_ASSERT_EQUAL(false, value.isUInt64()); #endif } JSONTEST_FIXTURE_LOCAL(ValueTest, compareNull) { JSONTEST_ASSERT_PRED(checkIsEqual(Json::Value(), Json::Value())); JSONTEST_ASSERT_PRED( checkIsEqual(Json::Value::nullSingleton(), Json::Value())); JSONTEST_ASSERT_PRED( checkIsEqual(Json::Value::nullSingleton(), Json::Value::nullSingleton())); } JSONTEST_FIXTURE_LOCAL(ValueTest, compareInt) { JSONTEST_ASSERT_PRED(checkIsLess(0, 10)); JSONTEST_ASSERT_PRED(checkIsEqual(10, 10)); JSONTEST_ASSERT_PRED(checkIsEqual(-10, -10)); JSONTEST_ASSERT_PRED(checkIsLess(-10, 0)); } JSONTEST_FIXTURE_LOCAL(ValueTest, compareUInt) { JSONTEST_ASSERT_PRED(checkIsLess(0u, 10u)); JSONTEST_ASSERT_PRED(checkIsLess(0u, Json::Value::maxUInt)); JSONTEST_ASSERT_PRED(checkIsEqual(10u, 10u)); } JSONTEST_FIXTURE_LOCAL(ValueTest, compareDouble) { JSONTEST_ASSERT_PRED(checkIsLess(0.0, 10.0)); JSONTEST_ASSERT_PRED(checkIsEqual(10.0, 10.0)); JSONTEST_ASSERT_PRED(checkIsEqual(-10.0, -10.0)); JSONTEST_ASSERT_PRED(checkIsLess(-10.0, 0.0)); } JSONTEST_FIXTURE_LOCAL(ValueTest, compareString) { JSONTEST_ASSERT_PRED(checkIsLess("", " ")); JSONTEST_ASSERT_PRED(checkIsLess("", "a")); JSONTEST_ASSERT_PRED(checkIsLess("abcd", "zyui")); JSONTEST_ASSERT_PRED(checkIsLess("abc", "abcd")); JSONTEST_ASSERT_PRED(checkIsEqual("abcd", "abcd")); JSONTEST_ASSERT_PRED(checkIsEqual(" ", " ")); JSONTEST_ASSERT_PRED(checkIsLess("ABCD", "abcd")); JSONTEST_ASSERT_PRED(checkIsEqual("ABCD", "ABCD")); } JSONTEST_FIXTURE_LOCAL(ValueTest, compareBoolean) { JSONTEST_ASSERT_PRED(checkIsLess(false, true)); JSONTEST_ASSERT_PRED(checkIsEqual(false, false)); JSONTEST_ASSERT_PRED(checkIsEqual(true, true)); } JSONTEST_FIXTURE_LOCAL(ValueTest, compareArray) { // array compare size then content Json::Value emptyArray(Json::arrayValue); Json::Value l1aArray; l1aArray.append(0); Json::Value l1bArray; l1bArray.append(10); Json::Value l2aArray; l2aArray.append(0); l2aArray.append(0); Json::Value l2bArray; l2bArray.append(0); l2bArray.append(10); JSONTEST_ASSERT_PRED(checkIsLess(emptyArray, l1aArray)); JSONTEST_ASSERT_PRED(checkIsLess(emptyArray, l2aArray)); JSONTEST_ASSERT_PRED(checkIsLess(l1aArray, l1bArray)); JSONTEST_ASSERT_PRED(checkIsLess(l1bArray, l2aArray)); JSONTEST_ASSERT_PRED(checkIsLess(l2aArray, l2bArray)); JSONTEST_ASSERT_PRED(checkIsEqual(emptyArray, Json::Value(emptyArray))); JSONTEST_ASSERT_PRED(checkIsEqual(l1aArray, Json::Value(l1aArray))); JSONTEST_ASSERT_PRED(checkIsEqual(l1bArray, Json::Value(l1bArray))); JSONTEST_ASSERT_PRED(checkIsEqual(l2aArray, Json::Value(l2aArray))); JSONTEST_ASSERT_PRED(checkIsEqual(l2bArray, Json::Value(l2bArray))); } JSONTEST_FIXTURE_LOCAL(ValueTest, compareObject) { // object compare size then content Json::Value emptyObject(Json::objectValue); Json::Value l1aObject; l1aObject["key1"] = 0; Json::Value l1bObject; l1bObject["key1"] = 10; Json::Value l2aObject; l2aObject["key1"] = 0; l2aObject["key2"] = 0; Json::Value l2bObject; l2bObject["key1"] = 10; l2bObject["key2"] = 0; JSONTEST_ASSERT_PRED(checkIsLess(emptyObject, l1aObject)); JSONTEST_ASSERT_PRED(checkIsLess(l1aObject, l1bObject)); JSONTEST_ASSERT_PRED(checkIsLess(l1bObject, l2aObject)); JSONTEST_ASSERT_PRED(checkIsLess(l2aObject, l2bObject)); JSONTEST_ASSERT_PRED(checkIsEqual(emptyObject, Json::Value(emptyObject))); JSONTEST_ASSERT_PRED(checkIsEqual(l1aObject, Json::Value(l1aObject))); JSONTEST_ASSERT_PRED(checkIsEqual(l1bObject, Json::Value(l1bObject))); JSONTEST_ASSERT_PRED(checkIsEqual(l2aObject, Json::Value(l2aObject))); JSONTEST_ASSERT_PRED(checkIsEqual(l2bObject, Json::Value(l2bObject))); { Json::Value aObject; aObject["a"] = 10; Json::Value bObject; bObject["b"] = 0; Json::Value cObject; cObject["c"] = 20; cObject["f"] = 15; Json::Value dObject; dObject["d"] = -2; dObject["e"] = 10; JSONTEST_ASSERT_PRED(checkIsLess(aObject, bObject)); JSONTEST_ASSERT_PRED(checkIsLess(bObject, cObject)); JSONTEST_ASSERT_PRED(checkIsLess(cObject, dObject)); JSONTEST_ASSERT_PRED(checkIsEqual(aObject, Json::Value(aObject))); JSONTEST_ASSERT_PRED(checkIsEqual(bObject, Json::Value(bObject))); JSONTEST_ASSERT_PRED(checkIsEqual(cObject, Json::Value(cObject))); JSONTEST_ASSERT_PRED(checkIsEqual(dObject, Json::Value(dObject))); } } JSONTEST_FIXTURE_LOCAL(ValueTest, compareType) { // object of different type are ordered according to their type JSONTEST_ASSERT_PRED(checkIsLess(Json::Value(), Json::Value(1))); JSONTEST_ASSERT_PRED(checkIsLess(Json::Value(1), Json::Value(1u))); JSONTEST_ASSERT_PRED(checkIsLess(Json::Value(1u), Json::Value(1.0))); JSONTEST_ASSERT_PRED(checkIsLess(Json::Value(1.0), Json::Value("a"))); JSONTEST_ASSERT_PRED(checkIsLess(Json::Value("a"), Json::Value(true))); JSONTEST_ASSERT_PRED( checkIsLess(Json::Value(true), Json::Value(Json::arrayValue))); JSONTEST_ASSERT_PRED(checkIsLess(Json::Value(Json::arrayValue), Json::Value(Json::objectValue))); } JSONTEST_FIXTURE_LOCAL(ValueTest, CopyObject) { Json::Value arrayVal; arrayVal.append("val1"); arrayVal.append("val2"); arrayVal.append("val3"); Json::Value stringVal("string value"); Json::Value copy1, copy2; { Json::Value arrayCopy, stringCopy; arrayCopy.copy(arrayVal); stringCopy.copy(stringVal); JSONTEST_ASSERT_PRED(checkIsEqual(arrayCopy, arrayVal)); JSONTEST_ASSERT_PRED(checkIsEqual(stringCopy, stringVal)); arrayCopy.append("val4"); JSONTEST_ASSERT(arrayCopy.size() == 4); arrayVal.append("new4"); arrayVal.append("new5"); JSONTEST_ASSERT(arrayVal.size() == 5); JSONTEST_ASSERT(!(arrayCopy == arrayVal)); stringCopy = "another string"; JSONTEST_ASSERT(!(stringCopy == stringVal)); copy1.copy(arrayCopy); copy2.copy(stringCopy); } JSONTEST_ASSERT(arrayVal.size() == 5); JSONTEST_ASSERT(stringVal == "string value"); JSONTEST_ASSERT(copy1.size() == 4); JSONTEST_ASSERT(copy2 == "another string"); copy1.copy(stringVal); JSONTEST_ASSERT(copy1 == "string value"); copy2.copy(arrayVal); JSONTEST_ASSERT(copy2.size() == 5); { Json::Value srcObject, objectCopy, otherObject; srcObject["key0"] = 10; objectCopy.copy(srcObject); JSONTEST_ASSERT(srcObject["key0"] == 10); JSONTEST_ASSERT(objectCopy["key0"] == 10); JSONTEST_ASSERT(srcObject.getMemberNames().size() == 1); JSONTEST_ASSERT(objectCopy.getMemberNames().size() == 1); otherObject["key1"] = 15; otherObject["key2"] = 16; JSONTEST_ASSERT(otherObject.getMemberNames().size() == 2); objectCopy.copy(otherObject); JSONTEST_ASSERT(objectCopy["key1"] == 15); JSONTEST_ASSERT(objectCopy["key2"] == 16); JSONTEST_ASSERT(objectCopy.getMemberNames().size() == 2); otherObject["key1"] = 20; JSONTEST_ASSERT(objectCopy["key1"] == 15); } } void ValueTest::checkIsLess(const Json::Value& x, const Json::Value& y) { JSONTEST_ASSERT(x < y); JSONTEST_ASSERT(y > x); JSONTEST_ASSERT(x <= y); JSONTEST_ASSERT(y >= x); JSONTEST_ASSERT(!(x == y)); JSONTEST_ASSERT(!(y == x)); JSONTEST_ASSERT(!(x >= y)); JSONTEST_ASSERT(!(y <= x)); JSONTEST_ASSERT(!(x > y)); JSONTEST_ASSERT(!(y < x)); JSONTEST_ASSERT(x.compare(y) < 0); JSONTEST_ASSERT(y.compare(x) >= 0); } void ValueTest::checkIsEqual(const Json::Value& x, const Json::Value& y) { JSONTEST_ASSERT(x == y); JSONTEST_ASSERT(y == x); JSONTEST_ASSERT(x <= y); JSONTEST_ASSERT(y <= x); JSONTEST_ASSERT(x >= y); JSONTEST_ASSERT(y >= x); JSONTEST_ASSERT(!(x < y)); JSONTEST_ASSERT(!(y < x)); JSONTEST_ASSERT(!(x > y)); JSONTEST_ASSERT(!(y > x)); JSONTEST_ASSERT(x.compare(y) == 0); JSONTEST_ASSERT(y.compare(x) == 0); } JSONTEST_FIXTURE_LOCAL(ValueTest, typeChecksThrowExceptions) { #if JSON_USE_EXCEPTION Json::Value intVal(1); Json::Value strVal("Test"); Json::Value objVal(Json::objectValue); Json::Value arrVal(Json::arrayValue); JSONTEST_ASSERT_THROWS(intVal["test"]); JSONTEST_ASSERT_THROWS(strVal["test"]); JSONTEST_ASSERT_THROWS(arrVal["test"]); JSONTEST_ASSERT_THROWS(intVal.removeMember("test")); JSONTEST_ASSERT_THROWS(strVal.removeMember("test")); JSONTEST_ASSERT_THROWS(arrVal.removeMember("test")); JSONTEST_ASSERT_THROWS(intVal.getMemberNames()); JSONTEST_ASSERT_THROWS(strVal.getMemberNames()); JSONTEST_ASSERT_THROWS(arrVal.getMemberNames()); JSONTEST_ASSERT_THROWS(intVal[0]); JSONTEST_ASSERT_THROWS(objVal[0]); JSONTEST_ASSERT_THROWS(strVal[0]); JSONTEST_ASSERT_THROWS(intVal.clear()); JSONTEST_ASSERT_THROWS(intVal.resize(1)); JSONTEST_ASSERT_THROWS(strVal.resize(1)); JSONTEST_ASSERT_THROWS(objVal.resize(1)); JSONTEST_ASSERT_THROWS(intVal.asCString()); JSONTEST_ASSERT_THROWS(objVal.asString()); JSONTEST_ASSERT_THROWS(arrVal.asString()); JSONTEST_ASSERT_THROWS(strVal.asInt()); JSONTEST_ASSERT_THROWS(objVal.asInt()); JSONTEST_ASSERT_THROWS(arrVal.asInt()); JSONTEST_ASSERT_THROWS(strVal.asUInt()); JSONTEST_ASSERT_THROWS(objVal.asUInt()); JSONTEST_ASSERT_THROWS(arrVal.asUInt()); JSONTEST_ASSERT_THROWS(strVal.asInt64()); JSONTEST_ASSERT_THROWS(objVal.asInt64()); JSONTEST_ASSERT_THROWS(arrVal.asInt64()); JSONTEST_ASSERT_THROWS(strVal.asUInt64()); JSONTEST_ASSERT_THROWS(objVal.asUInt64()); JSONTEST_ASSERT_THROWS(arrVal.asUInt64()); JSONTEST_ASSERT_THROWS(strVal.asDouble()); JSONTEST_ASSERT_THROWS(objVal.asDouble()); JSONTEST_ASSERT_THROWS(arrVal.asDouble()); JSONTEST_ASSERT_THROWS(strVal.asFloat()); JSONTEST_ASSERT_THROWS(objVal.asFloat()); JSONTEST_ASSERT_THROWS(arrVal.asFloat()); JSONTEST_ASSERT_THROWS(strVal.asBool()); JSONTEST_ASSERT_THROWS(objVal.asBool()); JSONTEST_ASSERT_THROWS(arrVal.asBool()); #endif } JSONTEST_FIXTURE_LOCAL(ValueTest, offsetAccessors) { Json::Value x; JSONTEST_ASSERT(x.getOffsetStart() == 0); JSONTEST_ASSERT(x.getOffsetLimit() == 0); x.setOffsetStart(10); x.setOffsetLimit(20); JSONTEST_ASSERT(x.getOffsetStart() == 10); JSONTEST_ASSERT(x.getOffsetLimit() == 20); Json::Value y(x); JSONTEST_ASSERT(y.getOffsetStart() == 10); JSONTEST_ASSERT(y.getOffsetLimit() == 20); Json::Value z; z.swap(y); JSONTEST_ASSERT(z.getOffsetStart() == 10); JSONTEST_ASSERT(z.getOffsetLimit() == 20); JSONTEST_ASSERT(y.getOffsetStart() == 0); JSONTEST_ASSERT(y.getOffsetLimit() == 0); } JSONTEST_FIXTURE_LOCAL(ValueTest, StaticString) { char mutant[] = "hello"; Json::StaticString ss(mutant); Json::String regular(mutant); mutant[1] = 'a'; JSONTEST_ASSERT_STRING_EQUAL("hallo", ss.c_str()); JSONTEST_ASSERT_STRING_EQUAL("hello", regular.c_str()); { Json::Value root; root["top"] = ss; JSONTEST_ASSERT_STRING_EQUAL("hallo", root["top"].asString()); mutant[1] = 'u'; JSONTEST_ASSERT_STRING_EQUAL("hullo", root["top"].asString()); } { Json::Value root; root["top"] = regular; JSONTEST_ASSERT_STRING_EQUAL("hello", root["top"].asString()); mutant[1] = 'u'; JSONTEST_ASSERT_STRING_EQUAL("hello", root["top"].asString()); } } JSONTEST_FIXTURE_LOCAL(ValueTest, WideString) { // https://github.com/open-source-parsers/jsoncpp/issues/756 const std::string uni = u8"\u5f0f\uff0c\u8fdb"; // "式,进" std::string styled; { Json::Value v; v["abc"] = uni; styled = v.toStyledString(); } Json::Value root; { JSONCPP_STRING errs; std::istringstream iss(styled); bool ok = parseFromStream(Json::CharReaderBuilder(), iss, &root, &errs); JSONTEST_ASSERT(ok); if (!ok) { std::cerr << "errs: " << errs << std::endl; } } JSONTEST_ASSERT_STRING_EQUAL(root["abc"].asString(), uni); } JSONTEST_FIXTURE_LOCAL(ValueTest, CommentBefore) { Json::Value val; // fill val val.setComment(Json::String("// this comment should appear before"), Json::commentBefore); Json::StreamWriterBuilder wbuilder; wbuilder.settings_["commentStyle"] = "All"; { char const expected[] = "// this comment should appear before\nnull"; Json::String result = Json::writeString(wbuilder, val); JSONTEST_ASSERT_STRING_EQUAL(expected, result); Json::String res2 = val.toStyledString(); Json::String exp2 = "\n"; exp2 += expected; exp2 += "\n"; JSONTEST_ASSERT_STRING_EQUAL(exp2, res2); } Json::Value other = "hello"; val.swapPayload(other); { char const expected[] = "// this comment should appear before\n\"hello\""; Json::String result = Json::writeString(wbuilder, val); JSONTEST_ASSERT_STRING_EQUAL(expected, result); Json::String res2 = val.toStyledString(); Json::String exp2 = "\n"; exp2 += expected; exp2 += "\n"; JSONTEST_ASSERT_STRING_EQUAL(exp2, res2); JSONTEST_ASSERT_STRING_EQUAL("null\n", other.toStyledString()); } val = "hello"; // val.setComment("// this comment should appear before", // Json::CommentPlacement::commentBefore); Assignment over-writes comments. { char const expected[] = "\"hello\""; Json::String result = Json::writeString(wbuilder, val); JSONTEST_ASSERT_STRING_EQUAL(expected, result); Json::String res2 = val.toStyledString(); Json::String exp2 = ""; exp2 += expected; exp2 += "\n"; JSONTEST_ASSERT_STRING_EQUAL(exp2, res2); } } JSONTEST_FIXTURE_LOCAL(ValueTest, zeroes) { char const cstr[] = "h\0i"; Json::String binary(cstr, sizeof(cstr)); // include trailing 0 JSONTEST_ASSERT_EQUAL(4U, binary.length()); Json::StreamWriterBuilder b; { Json::Value root; root = binary; JSONTEST_ASSERT_STRING_EQUAL(binary, root.asString()); } { char const top[] = "top"; Json::Value root; root[top] = binary; JSONTEST_ASSERT_STRING_EQUAL(binary, root[top].asString()); Json::Value removed; bool did; did = root.removeMember(top, top + sizeof(top) - 1U, &removed); JSONTEST_ASSERT(did); JSONTEST_ASSERT_STRING_EQUAL(binary, removed.asString()); did = root.removeMember(top, top + sizeof(top) - 1U, &removed); JSONTEST_ASSERT(!did); JSONTEST_ASSERT_STRING_EQUAL(binary, removed.asString()); // still } } JSONTEST_FIXTURE_LOCAL(ValueTest, zeroesInKeys) { char const cstr[] = "h\0i"; Json::String binary(cstr, sizeof(cstr)); // include trailing 0 JSONTEST_ASSERT_EQUAL(4U, binary.length()); { Json::Value root; root[binary] = "there"; JSONTEST_ASSERT_STRING_EQUAL("there", root[binary].asString()); JSONTEST_ASSERT(!root.isMember("h")); JSONTEST_ASSERT(root.isMember(binary)); JSONTEST_ASSERT_STRING_EQUAL( "there", root.get(binary, Json::Value::nullSingleton()).asString()); Json::Value removed; bool did; did = root.removeMember(binary.data(), binary.data() + binary.length(), &removed); JSONTEST_ASSERT(did); JSONTEST_ASSERT_STRING_EQUAL("there", removed.asString()); did = root.removeMember(binary.data(), binary.data() + binary.length(), &removed); JSONTEST_ASSERT(!did); JSONTEST_ASSERT_STRING_EQUAL("there", removed.asString()); // still JSONTEST_ASSERT(!root.isMember(binary)); JSONTEST_ASSERT_STRING_EQUAL( "", root.get(binary, Json::Value::nullSingleton()).asString()); } } JSONTEST_FIXTURE_LOCAL(ValueTest, specialFloats) { Json::StreamWriterBuilder b; b.settings_["useSpecialFloats"] = true; Json::Value v = std::numeric_limits<double>::quiet_NaN(); Json::String expected = "NaN"; Json::String result = Json::writeString(b, v); JSONTEST_ASSERT_STRING_EQUAL(expected, result); v = std::numeric_limits<double>::infinity(); expected = "Infinity"; result = Json::writeString(b, v); JSONTEST_ASSERT_STRING_EQUAL(expected, result); v = -std::numeric_limits<double>::infinity(); expected = "-Infinity"; result = Json::writeString(b, v); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } JSONTEST_FIXTURE_LOCAL(ValueTest, precision) { Json::StreamWriterBuilder b; b.settings_["precision"] = 5; Json::Value v = 100.0 / 3; Json::String expected = "33.333"; Json::String result = Json::writeString(b, v); JSONTEST_ASSERT_STRING_EQUAL(expected, result); v = 0.25000000; expected = "0.25"; result = Json::writeString(b, v); JSONTEST_ASSERT_STRING_EQUAL(expected, result); v = 0.2563456; expected = "0.25635"; result = Json::writeString(b, v); JSONTEST_ASSERT_STRING_EQUAL(expected, result); b.settings_["precision"] = 1; expected = "0.3"; result = Json::writeString(b, v); JSONTEST_ASSERT_STRING_EQUAL(expected, result); b.settings_["precision"] = 17; v = 1234857476305.256345694873740545068; expected = "1234857476305.2563"; result = Json::writeString(b, v); JSONTEST_ASSERT_STRING_EQUAL(expected, result); b.settings_["precision"] = 24; v = 0.256345694873740545068; expected = "0.25634569487374054"; result = Json::writeString(b, v); JSONTEST_ASSERT_STRING_EQUAL(expected, result); b.settings_["precision"] = 5; b.settings_["precisionType"] = "decimal"; v = 0.256345694873740545068; expected = "0.25635"; result = Json::writeString(b, v); JSONTEST_ASSERT_STRING_EQUAL(expected, result); b.settings_["precision"] = 1; b.settings_["precisionType"] = "decimal"; v = 0.256345694873740545068; expected = "0.3"; result = Json::writeString(b, v); JSONTEST_ASSERT_STRING_EQUAL(expected, result); b.settings_["precision"] = 10; b.settings_["precisionType"] = "decimal"; v = 0.23300000; expected = "0.233"; result = Json::writeString(b, v); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } JSONTEST_FIXTURE_LOCAL(ValueTest, searchValueByPath) { Json::Value root, subroot; root["property1"][0] = 0; root["property1"][1] = 1; subroot["object"] = "object"; root["property2"] = subroot; const Json::Value defaultValue("error"); Json::FastWriter writer; { const Json::String expected("{" "\"property1\":[0,1]," "\"property2\":{\"object\":\"object\"}" "}\n"); Json::String outcome = writer.write(root); JSONTEST_ASSERT_STRING_EQUAL(expected, outcome); // Array member exists. const Json::Path path1(".property1.[%]", 1); Json::Value result = path1.resolve(root); JSONTEST_ASSERT_EQUAL(Json::Value(1), result); result = path1.resolve(root, defaultValue); JSONTEST_ASSERT_EQUAL(Json::Value(1), result); // Array member does not exist. const Json::Path path2(".property1.[2]"); result = path2.resolve(root); JSONTEST_ASSERT_EQUAL(Json::nullValue, result); result = path2.resolve(root, defaultValue); JSONTEST_ASSERT_EQUAL(defaultValue, result); // Access array path form error const Json::Path path3(".property1.0"); result = path3.resolve(root); JSONTEST_ASSERT_EQUAL(Json::nullValue, result); result = path3.resolve(root, defaultValue); JSONTEST_ASSERT_EQUAL(defaultValue, result); // Object member exists. const Json::Path path4(".property2.%", "object"); result = path4.resolve(root); JSONTEST_ASSERT_EQUAL(Json::Value("object"), result); result = path4.resolve(root, defaultValue); JSONTEST_ASSERT_EQUAL(Json::Value("object"), result); // Object member does not exist. const Json::Path path5(".property2.hello"); result = path5.resolve(root); JSONTEST_ASSERT_EQUAL(Json::nullValue, result); result = path5.resolve(root, defaultValue); JSONTEST_ASSERT_EQUAL(defaultValue, result); // Access object path form error const Json::Path path6(".property2.[0]"); result = path5.resolve(root); JSONTEST_ASSERT_EQUAL(Json::nullValue, result); result = path6.resolve(root, defaultValue); JSONTEST_ASSERT_EQUAL(defaultValue, result); // resolve will not change the value outcome = writer.write(root); JSONTEST_ASSERT_STRING_EQUAL(expected, outcome); } { const Json::String expected("{" "\"property1\":[0,1,null]," "\"property2\":{" "\"hello\":null," "\"object\":\"object\"}}\n"); Json::Path path1(".property1.[%]", 2); Json::Value& value1 = path1.make(root); JSONTEST_ASSERT_EQUAL(Json::nullValue, value1); Json::Path path2(".property2.%", "hello"); Json::Value& value2 = path2.make(root); JSONTEST_ASSERT_EQUAL(Json::nullValue, value2); // make will change the value const Json::String outcome = writer.write(root); JSONTEST_ASSERT_STRING_EQUAL(expected, outcome); } } struct FastWriterTest : JsonTest::TestCase {}; JSONTEST_FIXTURE_LOCAL(FastWriterTest, dropNullPlaceholders) { Json::FastWriter writer; Json::Value nullValue; JSONTEST_ASSERT(writer.write(nullValue) == "null\n"); writer.dropNullPlaceholders(); JSONTEST_ASSERT(writer.write(nullValue) == "\n"); } JSONTEST_FIXTURE_LOCAL(FastWriterTest, enableYAMLCompatibility) { Json::FastWriter writer; Json::Value root; root["hello"] = "world"; JSONTEST_ASSERT(writer.write(root) == "{\"hello\":\"world\"}\n"); writer.enableYAMLCompatibility(); JSONTEST_ASSERT(writer.write(root) == "{\"hello\": \"world\"}\n"); } JSONTEST_FIXTURE_LOCAL(FastWriterTest, omitEndingLineFeed) { Json::FastWriter writer; Json::Value nullValue; JSONTEST_ASSERT(writer.write(nullValue) == "null\n"); writer.omitEndingLineFeed(); JSONTEST_ASSERT(writer.write(nullValue) == "null"); } JSONTEST_FIXTURE_LOCAL(FastWriterTest, writeNumericValue) { Json::FastWriter writer; const Json::String expected("{" "\"emptyValue\":null," "\"false\":false," "\"null\":\"null\"," "\"number\":-6200000000000000.0," "\"real\":1.256," "\"uintValue\":17" "}\n"); Json::Value root; root["emptyValue"] = Json::nullValue; root["false"] = false; root["null"] = "null"; root["number"] = -6.2e+15; root["real"] = 1.256; root["uintValue"] = Json::Value(17U); const Json::String result = writer.write(root); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } JSONTEST_FIXTURE_LOCAL(FastWriterTest, writeArrays) { Json::FastWriter writer; const Json::String expected("{" "\"property1\":[\"value1\",\"value2\"]," "\"property2\":[]" "}\n"); Json::Value root; root["property1"][0] = "value1"; root["property1"][1] = "value2"; root["property2"] = Json::arrayValue; const Json::String result = writer.write(root); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } JSONTEST_FIXTURE_LOCAL(FastWriterTest, writeNestedObjects) { Json::FastWriter writer; const Json::String expected("{" "\"object1\":{" "\"bool\":true," "\"nested\":123" "}," "\"object2\":{}" "}\n"); Json::Value root, child; child["nested"] = 123; child["bool"] = true; root["object1"] = child; root["object2"] = Json::objectValue; const Json::String result = writer.write(root); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } struct StyledWriterTest : JsonTest::TestCase {}; JSONTEST_FIXTURE_LOCAL(StyledWriterTest, writeNumericValue) { Json::StyledWriter writer; const Json::String expected("{\n" " \"emptyValue\" : null,\n" " \"false\" : false,\n" " \"null\" : \"null\",\n" " \"number\" : -6200000000000000.0,\n" " \"real\" : 1.256,\n" " \"uintValue\" : 17\n" "}\n"); Json::Value root; root["emptyValue"] = Json::nullValue; root["false"] = false; root["null"] = "null"; root["number"] = -6.2e+15; root["real"] = 1.256; root["uintValue"] = Json::Value(17U); const Json::String result = writer.write(root); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } JSONTEST_FIXTURE_LOCAL(StyledWriterTest, writeArrays) { Json::StyledWriter writer; const Json::String expected("{\n" " \"property1\" : [ \"value1\", \"value2\" ],\n" " \"property2\" : []\n" "}\n"); Json::Value root; root["property1"][0] = "value1"; root["property1"][1] = "value2"; root["property2"] = Json::arrayValue; const Json::String result = writer.write(root); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } JSONTEST_FIXTURE_LOCAL(StyledWriterTest, writeNestedObjects) { Json::StyledWriter writer; const Json::String expected("{\n" " \"object1\" : {\n" " \"bool\" : true,\n" " \"nested\" : 123\n" " },\n" " \"object2\" : {}\n" "}\n"); Json::Value root, child; child["nested"] = 123; child["bool"] = true; root["object1"] = child; root["object2"] = Json::objectValue; const Json::String result = writer.write(root); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } JSONTEST_FIXTURE_LOCAL(StyledWriterTest, multiLineArray) { Json::StyledWriter writer; { // Array member has more than 20 print effect rendering lines const Json::String expected("[\n " "0,\n 1,\n 2,\n " "3,\n 4,\n 5,\n " "6,\n 7,\n 8,\n " "9,\n 10,\n 11,\n " "12,\n 13,\n 14,\n " "15,\n 16,\n 17,\n " "18,\n 19,\n 20\n]\n"); Json::Value root; for (Json::ArrayIndex i = 0; i < 21; i++) root[i] = i; const Json::String result = writer.write(root); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } { // Array members do not exceed 21 print effects to render a single line const Json::String expected("[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]\n"); Json::Value root; for (Json::ArrayIndex i = 0; i < 10; i++) root[i] = i; const Json::String result = writer.write(root); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } } JSONTEST_FIXTURE_LOCAL(StyledWriterTest, writeValueWithComment) { Json::StyledWriter writer; { const Json::String expected("\n//commentBeforeValue\n\"hello\"\n"); Json::Value root = "hello"; root.setComment(Json::String("//commentBeforeValue"), Json::commentBefore); const Json::String result = writer.write(root); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } { const Json::String expected("\"hello\" //commentAfterValueOnSameLine\n"); Json::Value root = "hello"; root.setComment(Json::String("//commentAfterValueOnSameLine"), Json::commentAfterOnSameLine); const Json::String result = writer.write(root); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } { const Json::String expected("\"hello\"\n//commentAfter\n\n"); Json::Value root = "hello"; root.setComment(Json::String("//commentAfter"), Json::commentAfter); const Json::String result = writer.write(root); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } } struct StyledStreamWriterTest : JsonTest::TestCase {}; JSONTEST_FIXTURE_LOCAL(StyledStreamWriterTest, writeNumericValue) { Json::StyledStreamWriter writer; const Json::String expected("{\n" "\t\"emptyValue\" : null,\n" "\t\"false\" : false,\n" "\t\"null\" : \"null\",\n" "\t\"number\" : -6200000000000000.0,\n" "\t\"real\" : 1.256,\n" "\t\"uintValue\" : 17\n" "}\n"); Json::Value root; root["emptyValue"] = Json::nullValue; root["false"] = false; root["null"] = "null"; root["number"] = -6.2e+15; // big float number root["real"] = 1.256; // float number root["uintValue"] = Json::Value(17U); Json::OStringStream sout; writer.write(sout, root); const Json::String result = sout.str(); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } JSONTEST_FIXTURE_LOCAL(StyledStreamWriterTest, writeArrays) { Json::StyledStreamWriter writer; const Json::String expected("{\n" "\t\"property1\" : [ \"value1\", \"value2\" ],\n" "\t\"property2\" : []\n" "}\n"); Json::Value root; root["property1"][0] = "value1"; root["property1"][1] = "value2"; root["property2"] = Json::arrayValue; Json::OStringStream sout; writer.write(sout, root); const Json::String result = sout.str(); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } JSONTEST_FIXTURE_LOCAL(StyledStreamWriterTest, writeNestedObjects) { Json::StyledStreamWriter writer; const Json::String expected("{\n" "\t\"object1\" : \n" "\t" "{\n" "\t\t\"bool\" : true,\n" "\t\t\"nested\" : 123\n" "\t},\n" "\t\"object2\" : {}\n" "}\n"); Json::Value root, child; child["nested"] = 123; child["bool"] = true; root["object1"] = child; root["object2"] = Json::objectValue; Json::OStringStream sout; writer.write(sout, root); const Json::String result = sout.str(); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } JSONTEST_FIXTURE_LOCAL(StyledStreamWriterTest, multiLineArray) { { // Array member has more than 20 print effect rendering lines const Json::String expected("[\n\t0," "\n\t1," "\n\t2," "\n\t3," "\n\t4," "\n\t5," "\n\t6," "\n\t7," "\n\t8," "\n\t9," "\n\t10," "\n\t11," "\n\t12," "\n\t13," "\n\t14," "\n\t15," "\n\t16," "\n\t17," "\n\t18," "\n\t19," "\n\t20\n]\n"); Json::StyledStreamWriter writer; Json::Value root; for (Json::ArrayIndex i = 0; i < 21; i++) root[i] = i; Json::OStringStream sout; writer.write(sout, root); const Json::String result = sout.str(); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } { Json::StyledStreamWriter writer; // Array members do not exceed 21 print effects to render a single line const Json::String expected("[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]\n"); Json::Value root; for (Json::ArrayIndex i = 0; i < 10; i++) root[i] = i; Json::OStringStream sout; writer.write(sout, root); const Json::String result = sout.str(); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } } JSONTEST_FIXTURE_LOCAL(StyledStreamWriterTest, writeValueWithComment) { Json::StyledStreamWriter writer("\t"); { const Json::String expected("//commentBeforeValue\n\"hello\"\n"); Json::Value root = "hello"; Json::OStringStream sout; root.setComment(Json::String("//commentBeforeValue"), Json::commentBefore); writer.write(sout, root); const Json::String result = sout.str(); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } { const Json::String expected("\"hello\" //commentAfterValueOnSameLine\n"); Json::Value root = "hello"; Json::OStringStream sout; root.setComment(Json::String("//commentAfterValueOnSameLine"), Json::commentAfterOnSameLine); writer.write(sout, root); const Json::String result = sout.str(); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } { const Json::String expected("\"hello\"\n//commentAfter\n"); Json::Value root = "hello"; Json::OStringStream sout; root.setComment(Json::String("//commentAfter"), Json::commentAfter); writer.write(sout, root); const Json::String result = sout.str(); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } } struct StreamWriterTest : JsonTest::TestCase {}; JSONTEST_FIXTURE_LOCAL(StreamWriterTest, writeNumericValue) { Json::StreamWriterBuilder writer; const Json::String expected("{\n" "\t\"emptyValue\" : null,\n" "\t\"false\" : false,\n" "\t\"null\" : \"null\",\n" "\t\"number\" : -6200000000000000.0,\n" "\t\"real\" : 1.256,\n" "\t\"uintValue\" : 17\n" "}"); Json::Value root; root["emptyValue"] = Json::nullValue; root["false"] = false; root["null"] = "null"; root["number"] = -6.2e+15; root["real"] = 1.256; root["uintValue"] = Json::Value(17U); const Json::String result = Json::writeString(writer, root); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } JSONTEST_FIXTURE_LOCAL(StreamWriterTest, writeArrays) { Json::StreamWriterBuilder writer; const Json::String expected("{\n" "\t\"property1\" : \n" "\t[\n" "\t\t\"value1\",\n" "\t\t\"value2\"\n" "\t],\n" "\t\"property2\" : []\n" "}"); Json::Value root; root["property1"][0] = "value1"; root["property1"][1] = "value2"; root["property2"] = Json::arrayValue; const Json::String result = Json::writeString(writer, root); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } JSONTEST_FIXTURE_LOCAL(StreamWriterTest, writeNestedObjects) { Json::StreamWriterBuilder writer; const Json::String expected("{\n" "\t\"object1\" : \n" "\t{\n" "\t\t\"bool\" : true,\n" "\t\t\"nested\" : 123\n" "\t},\n" "\t\"object2\" : {}\n" "}"); Json::Value root, child; child["nested"] = 123; child["bool"] = true; root["object1"] = child; root["object2"] = Json::objectValue; const Json::String result = Json::writeString(writer, root); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } JSONTEST_FIXTURE_LOCAL(StreamWriterTest, multiLineArray) { Json::StreamWriterBuilder wb; wb.settings_["commentStyle"] = "None"; { // When wb.settings_["commentStyle"] = "None", the effect of // printing multiple lines will be displayed when there are // more than 20 array members. const Json::String expected("[\n\t0," "\n\t1," "\n\t2," "\n\t3," "\n\t4," "\n\t5," "\n\t6," "\n\t7," "\n\t8," "\n\t9," "\n\t10," "\n\t11," "\n\t12," "\n\t13," "\n\t14," "\n\t15," "\n\t16," "\n\t17," "\n\t18," "\n\t19," "\n\t20\n]"); Json::Value root; for (Json::ArrayIndex i = 0; i < 21; i++) root[i] = i; const Json::String result = Json::writeString(wb, root); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } { // Array members do not exceed 21 print effects to render a single line const Json::String expected("[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]"); Json::Value root; for (Json::ArrayIndex i = 0; i < 10; i++) root[i] = i; const Json::String result = Json::writeString(wb, root); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } } JSONTEST_FIXTURE_LOCAL(StreamWriterTest, dropNullPlaceholders) { Json::StreamWriterBuilder b; Json::Value nullValue; b.settings_["dropNullPlaceholders"] = false; JSONTEST_ASSERT(Json::writeString(b, nullValue) == "null"); b.settings_["dropNullPlaceholders"] = true; JSONTEST_ASSERT(Json::writeString(b, nullValue).empty()); } JSONTEST_FIXTURE_LOCAL(StreamWriterTest, enableYAMLCompatibility) { Json::StreamWriterBuilder b; Json::Value root; root["hello"] = "world"; b.settings_["indentation"] = ""; JSONTEST_ASSERT(Json::writeString(b, root) == "{\"hello\":\"world\"}"); b.settings_["enableYAMLCompatibility"] = true; JSONTEST_ASSERT(Json::writeString(b, root) == "{\"hello\": \"world\"}"); b.settings_["enableYAMLCompatibility"] = false; JSONTEST_ASSERT(Json::writeString(b, root) == "{\"hello\":\"world\"}"); } JSONTEST_FIXTURE_LOCAL(StreamWriterTest, indentation) { Json::StreamWriterBuilder b; Json::Value root; root["hello"] = "world"; b.settings_["indentation"] = ""; JSONTEST_ASSERT(Json::writeString(b, root) == "{\"hello\":\"world\"}"); b.settings_["indentation"] = "\t"; JSONTEST_ASSERT(Json::writeString(b, root) == "{\n\t\"hello\" : \"world\"\n}"); } JSONTEST_FIXTURE_LOCAL(StreamWriterTest, writeZeroes) { Json::String binary("hi", 3); // include trailing 0 JSONTEST_ASSERT_EQUAL(3, binary.length()); Json::String expected("\"hi\\u0000\""); // unicoded zero Json::StreamWriterBuilder b; { Json::Value root; root = binary; JSONTEST_ASSERT_STRING_EQUAL(binary, root.asString()); Json::String out = Json::writeString(b, root); JSONTEST_ASSERT_EQUAL(expected.size(), out.size()); JSONTEST_ASSERT_STRING_EQUAL(expected, out); } { Json::Value root; root["top"] = binary; JSONTEST_ASSERT_STRING_EQUAL(binary, root["top"].asString()); Json::String out = Json::writeString(b, root["top"]); JSONTEST_ASSERT_STRING_EQUAL(expected, out); } } JSONTEST_FIXTURE_LOCAL(StreamWriterTest, unicode) { // Create a Json value containing UTF-8 string with some chars that need // escape (tab,newline). Json::Value root; root["test"] = "\t\n\xF0\x91\xA2\xA1\x3D\xC4\xB3\xF0\x9B\x84\x9B\xEF\xBD\xA7"; Json::StreamWriterBuilder b; // Default settings - should be unicode escaped. JSONTEST_ASSERT(Json::writeString(b, root) == "{\n\t\"test\" : " "\"\\t\\n\\ud806\\udca1=\\u0133\\ud82c\\udd1b\\uff67\"\n}"); b.settings_["emitUTF8"] = true; // Should not be unicode escaped. JSONTEST_ASSERT( Json::writeString(b, root) == "{\n\t\"test\" : " "\"\\t\\n\xF0\x91\xA2\xA1=\xC4\xB3\xF0\x9B\x84\x9B\xEF\xBD\xA7\"\n}"); b.settings_["emitUTF8"] = false; // Should be unicode escaped. JSONTEST_ASSERT(Json::writeString(b, root) == "{\n\t\"test\" : " "\"\\t\\n\\ud806\\udca1=\\u0133\\ud82c\\udd1b\\uff67\"\n}"); } struct ReaderTest : JsonTest::TestCase { void setStrictMode() { reader = std::unique_ptr<Json::Reader>( new Json::Reader(Json::Features{}.strictMode())); } void setFeatures(Json::Features& features) { reader = std::unique_ptr<Json::Reader>(new Json::Reader(features)); } void checkStructuredErrors( const std::vector<Json::Reader::StructuredError>& actual, const std::vector<Json::Reader::StructuredError>& expected) { JSONTEST_ASSERT_EQUAL(expected.size(), actual.size()); for (size_t i = 0; i < actual.size(); ++i) { const auto& a = actual[i]; const auto& e = expected[i]; JSONTEST_ASSERT_EQUAL(e.offset_start, a.offset_start) << i; JSONTEST_ASSERT_EQUAL(e.offset_limit, a.offset_limit) << i; JSONTEST_ASSERT_EQUAL(e.message, a.message) << i; } } template <typename Input> void checkParse(Input&& input) { JSONTEST_ASSERT(reader->parse(input, root)); } template <typename Input> void checkParse(Input&& input, const std::vector<Json::Reader::StructuredError>& structured) { JSONTEST_ASSERT(!reader->parse(input, root)); checkStructuredErrors(reader->getStructuredErrors(), structured); } template <typename Input> void checkParse(Input&& input, const std::vector<Json::Reader::StructuredError>& structured, const std::string& formatted) { checkParse(input, structured); JSONTEST_ASSERT_EQUAL(formatted, reader->getFormattedErrorMessages()); } std::unique_ptr<Json::Reader> reader{new Json::Reader()}; Json::Value root; }; JSONTEST_FIXTURE_LOCAL(ReaderTest, parseWithNoErrors) { checkParse(R"({ "property" : "value" })"); } JSONTEST_FIXTURE_LOCAL(ReaderTest, parseObject) { checkParse(R"({"property"})", {{11, 12, "Missing ':' after object member name"}}, "* Line 1, Column 12\n Missing ':' after object member name\n"); checkParse( R"({"property" : "value" )", {{22, 22, "Missing ',' or '}' in object declaration"}}, "* Line 1, Column 23\n Missing ',' or '}' in object declaration\n"); checkParse(R"({"property" : "value", )", {{23, 23, "Missing '}' or object member name"}}, "* Line 1, Column 24\n Missing '}' or object member name\n"); } JSONTEST_FIXTURE_LOCAL(ReaderTest, parseArray) { checkParse( R"([ "value" )", {{10, 10, "Missing ',' or ']' in array declaration"}}, "* Line 1, Column 11\n Missing ',' or ']' in array declaration\n"); checkParse( R"([ "value1" "value2" ] )", {{11, 19, "Missing ',' or ']' in array declaration"}}, "* Line 1, Column 12\n Missing ',' or ']' in array declaration\n"); } JSONTEST_FIXTURE_LOCAL(ReaderTest, parseString) { checkParse(R"([ "\u8a2a" ])"); checkParse( R"([ "\ud801" ])", {{2, 10, "additional six characters expected to parse unicode surrogate " "pair."}}, "* Line 1, Column 3\n" " additional six characters expected to parse unicode surrogate pair.\n" "See Line 1, Column 10 for detail.\n"); checkParse(R"([ "\ud801\d1234" ])", {{2, 16, "expecting another \\u token to begin the " "second half of a unicode surrogate pair"}}, "* Line 1, Column 3\n" " expecting another \\u token to begin the " "second half of a unicode surrogate pair\n" "See Line 1, Column 12 for detail.\n"); checkParse(R"([ "\ua3t@" ])", {{2, 10, "Bad unicode escape sequence in string: " "hexadecimal digit expected."}}, "* Line 1, Column 3\n" " Bad unicode escape sequence in string: " "hexadecimal digit expected.\n" "See Line 1, Column 9 for detail.\n"); checkParse( R"([ "\ua3t" ])", {{2, 9, "Bad unicode escape sequence in string: four digits expected."}}, "* Line 1, Column 3\n" " Bad unicode escape sequence in string: four digits expected.\n" "See Line 1, Column 6 for detail.\n"); } JSONTEST_FIXTURE_LOCAL(ReaderTest, parseComment) { checkParse( R"({ /*commentBeforeValue*/ "property" : "value" }//commentAfterValue)" "\n"); checkParse(" true //comment1\n//comment2\r//comment3\r\n"); } JSONTEST_FIXTURE_LOCAL(ReaderTest, streamParseWithNoErrors) { std::string styled = R"({ "property" : "value" })"; std::istringstream iss(styled); checkParse(iss); } JSONTEST_FIXTURE_LOCAL(ReaderTest, parseWithNoErrorsTestingOffsets) { checkParse(R"({)" R"( "property" : ["value", "value2"],)" R"( "obj" : { "nested" : -6.2e+15, "bool" : true},)" R"( "null" : null,)" R"( "false" : false)" R"( })"); auto checkOffsets = [&](const Json::Value& v, int start, int limit) { JSONTEST_ASSERT_EQUAL(start, v.getOffsetStart()); JSONTEST_ASSERT_EQUAL(limit, v.getOffsetLimit()); }; checkOffsets(root, 0, 115); checkOffsets(root["property"], 15, 34); checkOffsets(root["property"][0], 16, 23); checkOffsets(root["property"][1], 25, 33); checkOffsets(root["obj"], 44, 81); checkOffsets(root["obj"]["nested"], 57, 65); checkOffsets(root["obj"]["bool"], 76, 80); checkOffsets(root["null"], 92, 96); checkOffsets(root["false"], 108, 113); } JSONTEST_FIXTURE_LOCAL(ReaderTest, parseWithOneError) { checkParse(R"({ "property" :: "value" })", {{14, 15, "Syntax error: value, object or array expected."}}, "* Line 1, Column 15\n Syntax error: value, object or array " "expected.\n"); checkParse("s", {{0, 1, "Syntax error: value, object or array expected."}}, "* Line 1, Column 1\n Syntax error: value, object or array " "expected.\n"); } JSONTEST_FIXTURE_LOCAL(ReaderTest, parseSpecialFloat) { checkParse(R"({ "a" : Infi })", {{8, 9, "Syntax error: value, object or array expected."}}, "* Line 1, Column 9\n Syntax error: value, object or array " "expected.\n"); checkParse(R"({ "a" : Infiniaa })", {{8, 9, "Syntax error: value, object or array expected."}}, "* Line 1, Column 9\n Syntax error: value, object or array " "expected.\n"); } JSONTEST_FIXTURE_LOCAL(ReaderTest, strictModeParseNumber) { setStrictMode(); checkParse( "123", {{0, 3, "A valid JSON document must be either an array or an object value."}}, "* Line 1, Column 1\n" " A valid JSON document must be either an array or an object value.\n"); } JSONTEST_FIXTURE_LOCAL(ReaderTest, parseChineseWithOneError) { checkParse(R"({ "pr)" u8"\u4f50\u85e4" // 佐藤 R"(erty" :: "value" })", {{18, 19, "Syntax error: value, object or array expected."}}, "* Line 1, Column 19\n Syntax error: value, object or array " "expected.\n"); } JSONTEST_FIXTURE_LOCAL(ReaderTest, parseWithDetailError) { checkParse(R"({ "property" : "v\alue" })", {{15, 23, "Bad escape sequence in string"}}, "* Line 1, Column 16\n" " Bad escape sequence in string\n" "See Line 1, Column 20 for detail.\n"); } JSONTEST_FIXTURE_LOCAL(ReaderTest, pushErrorTest) { checkParse(R"({ "AUTHOR" : 123 })"); if (!root["AUTHOR"].isString()) { JSONTEST_ASSERT( reader->pushError(root["AUTHOR"], "AUTHOR must be a string")); } JSONTEST_ASSERT_STRING_EQUAL(reader->getFormattedErrorMessages(), "* Line 1, Column 14\n" " AUTHOR must be a string\n"); checkParse(R"({ "AUTHOR" : 123 })"); if (!root["AUTHOR"].isString()) { JSONTEST_ASSERT(reader->pushError(root["AUTHOR"], "AUTHOR must be a string", root["AUTHOR"])); } JSONTEST_ASSERT_STRING_EQUAL(reader->getFormattedErrorMessages(), "* Line 1, Column 14\n" " AUTHOR must be a string\n" "See Line 1, Column 14 for detail.\n"); } JSONTEST_FIXTURE_LOCAL(ReaderTest, allowNumericKeysTest) { Json::Features features; features.allowNumericKeys_ = true; setFeatures(features); checkParse(R"({ 123 : "abc" })"); } struct CharReaderTest : JsonTest::TestCase {}; JSONTEST_FIXTURE_LOCAL(CharReaderTest, parseWithNoErrors) { Json::CharReaderBuilder b; CharReaderPtr reader(b.newCharReader()); Json::String errs; Json::Value root; char const doc[] = "{ \"property\" : \"value\" }"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(ok); JSONTEST_ASSERT(errs.empty()); } JSONTEST_FIXTURE_LOCAL(CharReaderTest, parseWithNoErrorsTestingOffsets) { Json::CharReaderBuilder b; CharReaderPtr reader(b.newCharReader()); Json::String errs; Json::Value root; char const doc[] = "{ \"property\" : [\"value\", \"value2\"], \"obj\" : " "{ \"nested\" : -6.2e+15, \"num\" : +123, \"bool\" : " "true}, \"null\" : null, \"false\" : false }"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(ok); JSONTEST_ASSERT(errs.empty()); } JSONTEST_FIXTURE_LOCAL(CharReaderTest, parseNumber) { Json::CharReaderBuilder b; CharReaderPtr reader(b.newCharReader()); Json::String errs; Json::Value root; { // if intvalue > threshold, treat the number as a double. // 21 digits char const doc[] = "[111111111111111111111]"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(ok); JSONTEST_ASSERT(errs.empty()); JSONTEST_ASSERT_EQUAL(1.1111111111111111e+020, root[0]); } } JSONTEST_FIXTURE_LOCAL(CharReaderTest, parseString) { Json::CharReaderBuilder b; CharReaderPtr reader(b.newCharReader()); Json::Value root; Json::String errs; { char const doc[] = "[\"\"]"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(ok); JSONTEST_ASSERT(errs.empty()); JSONTEST_ASSERT_EQUAL("", root[0]); } { char const doc[] = "[\"\\u8A2a\"]"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(ok); JSONTEST_ASSERT(errs.empty()); JSONTEST_ASSERT_EQUAL(u8"\u8A2a", root[0].asString()); // "訪" } { char const doc[] = "[ \"\\uD801\" ]"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(!ok); JSONTEST_ASSERT(errs == "* Line 1, Column 3\n" " additional six characters expected to " "parse unicode surrogate pair.\n" "See Line 1, Column 10 for detail.\n"); } { char const doc[] = "[ \"\\uD801\\d1234\" ]"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(!ok); JSONTEST_ASSERT(errs == "* Line 1, Column 3\n" " expecting another \\u token to begin the " "second half of a unicode surrogate pair\n" "See Line 1, Column 12 for detail.\n"); } { char const doc[] = "[ \"\\ua3t@\" ]"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(!ok); JSONTEST_ASSERT(errs == "* Line 1, Column 3\n" " Bad unicode escape sequence in string: " "hexadecimal digit expected.\n" "See Line 1, Column 9 for detail.\n"); } { char const doc[] = "[ \"\\ua3t\" ]"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(!ok); JSONTEST_ASSERT( errs == "* Line 1, Column 3\n" " Bad unicode escape sequence in string: four digits expected.\n" "See Line 1, Column 6 for detail.\n"); } { b.settings_["allowSingleQuotes"] = true; CharReaderPtr charreader(b.newCharReader()); char const doc[] = "{'a': 'x\\ty', \"b\":'x\\\\y'}"; bool ok = charreader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(ok); JSONTEST_ASSERT_STRING_EQUAL("", errs); JSONTEST_ASSERT_EQUAL(2u, root.size()); JSONTEST_ASSERT_STRING_EQUAL("x\ty", root["a"].asString()); JSONTEST_ASSERT_STRING_EQUAL("x\\y", root["b"].asString()); } } JSONTEST_FIXTURE_LOCAL(CharReaderTest, parseComment) { Json::CharReaderBuilder b; CharReaderPtr reader(b.newCharReader()); Json::Value root; Json::String errs; { char const doc[] = "//comment1\n { //comment2\n \"property\" :" " \"value\" //comment3\n } //comment4\n"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(ok); JSONTEST_ASSERT(errs.empty()); JSONTEST_ASSERT_EQUAL("value", root["property"]); } { char const doc[] = "{ \"property\" //comment\n : \"value\" }"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(!ok); JSONTEST_ASSERT(errs == "* Line 1, Column 14\n" " Missing ':' after object member name\n"); } { char const doc[] = "//comment1\n [ //comment2\n \"value\" //comment3\n," " //comment4\n true //comment5\n ] //comment6\n"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(ok); JSONTEST_ASSERT(errs.empty()); JSONTEST_ASSERT_EQUAL("value", root[0]); JSONTEST_ASSERT_EQUAL(true, root[1]); } } JSONTEST_FIXTURE_LOCAL(CharReaderTest, parseObjectWithErrors) { Json::CharReaderBuilder b; CharReaderPtr reader(b.newCharReader()); Json::Value root; Json::String errs; { char const doc[] = "{ \"property\" : \"value\" "; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(!ok); JSONTEST_ASSERT(errs == "* Line 1, Column 24\n" " Missing ',' or '}' in object declaration\n"); JSONTEST_ASSERT_EQUAL("value", root["property"]); } { char const doc[] = "{ \"property\" : \"value\" ,"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(!ok); JSONTEST_ASSERT(errs == "* Line 1, Column 25\n" " Missing '}' or object member name\n"); JSONTEST_ASSERT_EQUAL("value", root["property"]); } } JSONTEST_FIXTURE_LOCAL(CharReaderTest, parseArrayWithErrors) { Json::CharReaderBuilder b; CharReaderPtr reader(b.newCharReader()); Json::Value root; Json::String errs; { char const doc[] = "[ \"value\" "; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(!ok); JSONTEST_ASSERT(errs == "* Line 1, Column 11\n" " Missing ',' or ']' in array declaration\n"); JSONTEST_ASSERT_EQUAL("value", root[0]); } { char const doc[] = "[ \"value1\" \"value2\" ]"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(!ok); JSONTEST_ASSERT(errs == "* Line 1, Column 12\n" " Missing ',' or ']' in array declaration\n"); JSONTEST_ASSERT_EQUAL("value1", root[0]); } } JSONTEST_FIXTURE_LOCAL(CharReaderTest, parseWithOneError) { Json::CharReaderBuilder b; CharReaderPtr reader(b.newCharReader()); Json::String errs; Json::Value root; char const doc[] = "{ \"property\" :: \"value\" }"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(!ok); JSONTEST_ASSERT(errs == "* Line 1, Column 15\n Syntax error: value, object or array " "expected.\n"); } JSONTEST_FIXTURE_LOCAL(CharReaderTest, parseChineseWithOneError) { Json::CharReaderBuilder b; CharReaderPtr reader(b.newCharReader()); Json::String errs; Json::Value root; char const doc[] = "{ \"pr佐藤erty\" :: \"value\" }"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(!ok); JSONTEST_ASSERT(errs == "* Line 1, Column 19\n Syntax error: value, object or array " "expected.\n"); } JSONTEST_FIXTURE_LOCAL(CharReaderTest, parseWithDetailError) { Json::CharReaderBuilder b; CharReaderPtr reader(b.newCharReader()); Json::String errs; Json::Value root; char const doc[] = "{ \"property\" : \"v\\alue\" }"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(!ok); JSONTEST_ASSERT(errs == "* Line 1, Column 16\n Bad escape sequence in string\nSee " "Line 1, Column 20 for detail.\n"); } JSONTEST_FIXTURE_LOCAL(CharReaderTest, parseWithStackLimit) { Json::CharReaderBuilder b; Json::Value root; char const doc[] = "{ \"property\" : \"value\" }"; { b.settings_["stackLimit"] = 2; CharReaderPtr reader(b.newCharReader()); Json::String errs; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(ok); JSONTEST_ASSERT(errs.empty()); JSONTEST_ASSERT_EQUAL("value", root["property"]); } { b.settings_["stackLimit"] = 1; CharReaderPtr reader(b.newCharReader()); Json::String errs; JSONTEST_ASSERT_THROWS( reader->parse(doc, doc + std::strlen(doc), &root, &errs)); } } JSONTEST_FIXTURE_LOCAL(CharReaderTest, testOperator) { const std::string styled = "{ \"property\" : \"value\" }"; std::istringstream iss(styled); Json::Value root; iss >> root; JSONTEST_ASSERT_EQUAL("value", root["property"]); } struct CharReaderStrictModeTest : JsonTest::TestCase {}; JSONTEST_FIXTURE_LOCAL(CharReaderStrictModeTest, dupKeys) { Json::CharReaderBuilder b; Json::Value root; char const doc[] = "{ \"property\" : \"value\", \"key\" : \"val1\", \"key\" : \"val2\" }"; { b.strictMode(&b.settings_); CharReaderPtr reader(b.newCharReader()); Json::String errs; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(!ok); JSONTEST_ASSERT_STRING_EQUAL("* Line 1, Column 41\n" " Duplicate key: 'key'\n", errs); JSONTEST_ASSERT_EQUAL("val1", root["key"]); // so far } } struct CharReaderFailIfExtraTest : JsonTest::TestCase {}; JSONTEST_FIXTURE_LOCAL(CharReaderFailIfExtraTest, issue164) { // This is interpreted as a string value followed by a colon. Json::CharReaderBuilder b; Json::Value root; char const doc[] = " \"property\" : \"value\" }"; { b.settings_["failIfExtra"] = false; CharReaderPtr reader(b.newCharReader()); Json::String errs; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(ok); JSONTEST_ASSERT(errs.empty()); JSONTEST_ASSERT_EQUAL("property", root); } { b.settings_["failIfExtra"] = true; CharReaderPtr reader(b.newCharReader()); Json::String errs; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(!ok); JSONTEST_ASSERT_STRING_EQUAL("* Line 1, Column 13\n" " Extra non-whitespace after JSON value.\n", errs); JSONTEST_ASSERT_EQUAL("property", root); } { b.strictMode(&b.settings_); CharReaderPtr reader(b.newCharReader()); Json::String errs; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(!ok); JSONTEST_ASSERT_STRING_EQUAL("* Line 1, Column 13\n" " Extra non-whitespace after JSON value.\n", errs); JSONTEST_ASSERT_EQUAL("property", root); } { b.strictMode(&b.settings_); b.settings_["failIfExtra"] = false; CharReaderPtr reader(b.newCharReader()); Json::String errs; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(!ok); JSONTEST_ASSERT_STRING_EQUAL( "* Line 1, Column 1\n" " A valid JSON document must be either an array or an object value.\n", errs); JSONTEST_ASSERT_EQUAL("property", root); } } JSONTEST_FIXTURE_LOCAL(CharReaderFailIfExtraTest, issue107) { // This is interpreted as an int value followed by a colon. Json::CharReaderBuilder b; Json::Value root; char const doc[] = "1:2:3"; b.settings_["failIfExtra"] = true; CharReaderPtr reader(b.newCharReader()); Json::String errs; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(!ok); JSONTEST_ASSERT_STRING_EQUAL("* Line 1, Column 2\n" " Extra non-whitespace after JSON value.\n", errs); JSONTEST_ASSERT_EQUAL(1, root.asInt()); } JSONTEST_FIXTURE_LOCAL(CharReaderFailIfExtraTest, commentAfterObject) { Json::CharReaderBuilder b; Json::Value root; { char const doc[] = "{ \"property\" : \"value\" } //trailing\n//comment\n"; b.settings_["failIfExtra"] = true; CharReaderPtr reader(b.newCharReader()); Json::String errs; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(ok); JSONTEST_ASSERT_STRING_EQUAL("", errs); JSONTEST_ASSERT_EQUAL("value", root["property"]); } } JSONTEST_FIXTURE_LOCAL(CharReaderFailIfExtraTest, commentAfterArray) { Json::CharReaderBuilder b; Json::Value root; char const doc[] = "[ \"property\" , \"value\" ] //trailing\n//comment\n"; b.settings_["failIfExtra"] = true; CharReaderPtr reader(b.newCharReader()); Json::String errs; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(ok); JSONTEST_ASSERT_STRING_EQUAL("", errs); JSONTEST_ASSERT_EQUAL("value", root[1u]); } JSONTEST_FIXTURE_LOCAL(CharReaderFailIfExtraTest, commentAfterBool) { Json::CharReaderBuilder b; Json::Value root; char const doc[] = " true /*trailing\ncomment*/"; b.settings_["failIfExtra"] = true; CharReaderPtr reader(b.newCharReader()); Json::String errs; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(ok); JSONTEST_ASSERT_STRING_EQUAL("", errs); JSONTEST_ASSERT_EQUAL(true, root.asBool()); } JSONTEST_FIXTURE_LOCAL(CharReaderFailIfExtraTest, parseComment) { Json::CharReaderBuilder b; b.settings_["failIfExtra"] = true; CharReaderPtr reader(b.newCharReader()); Json::Value root; Json::String errs; { char const doc[] = " true //comment1\n//comment2\r//comment3\r\n"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(ok); JSONTEST_ASSERT_STRING_EQUAL("", errs); JSONTEST_ASSERT_EQUAL(true, root.asBool()); } { char const doc[] = " true //com\rment"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(!ok); JSONTEST_ASSERT_STRING_EQUAL("* Line 2, Column 1\n" " Extra non-whitespace after JSON value.\n", errs); JSONTEST_ASSERT_EQUAL(true, root.asBool()); } { char const doc[] = " true //com\nment"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(!ok); JSONTEST_ASSERT_STRING_EQUAL("* Line 2, Column 1\n" " Extra non-whitespace after JSON value.\n", errs); JSONTEST_ASSERT_EQUAL(true, root.asBool()); } } struct CharReaderAllowDropNullTest : JsonTest::TestCase { using Value = Json::Value; using ValueCheck = std::function<void(const Value&)>; Value nullValue = Value{Json::nullValue}; Value emptyArray = Value{Json::arrayValue}; ValueCheck checkEq(const Value& v) { return [=](const Value& root) { JSONTEST_ASSERT_EQUAL(root, v); }; } ValueCheck objGetAnd(std::string idx, ValueCheck f) { return [=](const Value& root) { f(root.get(idx, true)); }; } ValueCheck arrGetAnd(int idx, ValueCheck f) { return [=](const Value& root) { f(root[idx]); }; } }; JSONTEST_FIXTURE_LOCAL(CharReaderAllowDropNullTest, issue178) { struct TestSpec { int line; std::string doc; size_t rootSize; ValueCheck onRoot; }; const TestSpec specs[] = { {__LINE__, R"({"a":,"b":true})", 2, objGetAnd("a", checkEq(nullValue))}, {__LINE__, R"({"a":,"b":true})", 2, objGetAnd("a", checkEq(nullValue))}, {__LINE__, R"({"a":})", 1, objGetAnd("a", checkEq(nullValue))}, {__LINE__, "[]", 0, checkEq(emptyArray)}, {__LINE__, "[null]", 1, nullptr}, {__LINE__, "[,]", 2, nullptr}, {__LINE__, "[,,,]", 4, nullptr}, {__LINE__, "[null,]", 2, nullptr}, {__LINE__, "[,null]", 2, nullptr}, {__LINE__, "[,,]", 3, nullptr}, {__LINE__, "[null,,]", 3, nullptr}, {__LINE__, "[,null,]", 3, nullptr}, {__LINE__, "[,,null]", 3, nullptr}, {__LINE__, "[[],,,]", 4, arrGetAnd(0, checkEq(emptyArray))}, {__LINE__, "[,[],,]", 4, arrGetAnd(1, checkEq(emptyArray))}, {__LINE__, "[,,,[]]", 4, arrGetAnd(3, checkEq(emptyArray))}, }; for (const auto& spec : specs) { Json::CharReaderBuilder b; b.settings_["allowDroppedNullPlaceholders"] = true; std::unique_ptr<Json::CharReader> reader(b.newCharReader()); Json::Value root; Json::String errs; bool ok = reader->parse(spec.doc.data(), spec.doc.data() + spec.doc.size(), &root, &errs); JSONTEST_ASSERT(ok); JSONTEST_ASSERT_STRING_EQUAL(errs, ""); if (spec.onRoot) { spec.onRoot(root); } } } struct CharReaderAllowNumericKeysTest : JsonTest::TestCase {}; JSONTEST_FIXTURE_LOCAL(CharReaderAllowNumericKeysTest, allowNumericKeys) { Json::CharReaderBuilder b; b.settings_["allowNumericKeys"] = true; Json::Value root; Json::String errs; CharReaderPtr reader(b.newCharReader()); char const doc[] = "{15:true,-16:true,12.01:true}"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(ok); JSONTEST_ASSERT_STRING_EQUAL("", errs); JSONTEST_ASSERT_EQUAL(3u, root.size()); JSONTEST_ASSERT_EQUAL(true, root.get("15", false)); JSONTEST_ASSERT_EQUAL(true, root.get("-16", false)); JSONTEST_ASSERT_EQUAL(true, root.get("12.01", false)); } struct CharReaderAllowSingleQuotesTest : JsonTest::TestCase {}; JSONTEST_FIXTURE_LOCAL(CharReaderAllowSingleQuotesTest, issue182) { Json::CharReaderBuilder b; b.settings_["allowSingleQuotes"] = true; Json::Value root; Json::String errs; CharReaderPtr reader(b.newCharReader()); { char const doc[] = "{'a':true,\"b\":true}"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(ok); JSONTEST_ASSERT_STRING_EQUAL("", errs); JSONTEST_ASSERT_EQUAL(2u, root.size()); JSONTEST_ASSERT_EQUAL(true, root.get("a", false)); JSONTEST_ASSERT_EQUAL(true, root.get("b", false)); } { char const doc[] = "{'a': 'x', \"b\":'y'}"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(ok); JSONTEST_ASSERT_STRING_EQUAL("", errs); JSONTEST_ASSERT_EQUAL(2u, root.size()); JSONTEST_ASSERT_STRING_EQUAL("x", root["a"].asString()); JSONTEST_ASSERT_STRING_EQUAL("y", root["b"].asString()); } } struct CharReaderAllowZeroesTest : JsonTest::TestCase {}; JSONTEST_FIXTURE_LOCAL(CharReaderAllowZeroesTest, issue176) { Json::CharReaderBuilder b; b.settings_["allowSingleQuotes"] = true; Json::Value root; Json::String errs; CharReaderPtr reader(b.newCharReader()); { char const doc[] = "{'a':true,\"b\":true}"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(ok); JSONTEST_ASSERT_STRING_EQUAL("", errs); JSONTEST_ASSERT_EQUAL(2u, root.size()); JSONTEST_ASSERT_EQUAL(true, root.get("a", false)); JSONTEST_ASSERT_EQUAL(true, root.get("b", false)); } { char const doc[] = "{'a': 'x', \"b\":'y'}"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(ok); JSONTEST_ASSERT_STRING_EQUAL("", errs); JSONTEST_ASSERT_EQUAL(2u, root.size()); JSONTEST_ASSERT_STRING_EQUAL("x", root["a"].asString()); JSONTEST_ASSERT_STRING_EQUAL("y", root["b"].asString()); } } struct CharReaderAllowSpecialFloatsTest : JsonTest::TestCase {}; JSONTEST_FIXTURE_LOCAL(CharReaderAllowSpecialFloatsTest, specialFloat) { Json::CharReaderBuilder b; CharReaderPtr reader(b.newCharReader()); Json::Value root; Json::String errs; { char const doc[] = "{\"a\": NaN}"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(!ok); JSONTEST_ASSERT_STRING_EQUAL( "* Line 1, Column 7\n" " Syntax error: value, object or array expected.\n", errs); } { char const doc[] = "{\"a\": Infinity}"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(!ok); JSONTEST_ASSERT_STRING_EQUAL( "* Line 1, Column 7\n" " Syntax error: value, object or array expected.\n", errs); } } JSONTEST_FIXTURE_LOCAL(CharReaderAllowSpecialFloatsTest, issue209) { Json::CharReaderBuilder b; b.settings_["allowSpecialFloats"] = true; Json::Value root; Json::String errs; CharReaderPtr reader(b.newCharReader()); { char const doc[] = "{\"a\":NaN,\"b\":Infinity,\"c\":-Infinity,\"d\":+Infinity}"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(ok); JSONTEST_ASSERT_STRING_EQUAL("", errs); JSONTEST_ASSERT_EQUAL(4u, root.size()); double n = root["a"].asDouble(); JSONTEST_ASSERT(std::isnan(n)); JSONTEST_ASSERT_EQUAL(std::numeric_limits<double>::infinity(), root.get("b", 0.0)); JSONTEST_ASSERT_EQUAL(-std::numeric_limits<double>::infinity(), root.get("c", 0.0)); JSONTEST_ASSERT_EQUAL(std::numeric_limits<double>::infinity(), root.get("d", 0.0)); } struct TestData { int line; bool ok; Json::String in; }; const TestData test_data[] = { {__LINE__, true, "{\"a\":9}"}, // {__LINE__, false, "{\"a\":0Infinity}"}, // {__LINE__, false, "{\"a\":1Infinity}"}, // {__LINE__, false, "{\"a\":9Infinity}"}, // {__LINE__, false, "{\"a\":0nfinity}"}, // {__LINE__, false, "{\"a\":1nfinity}"}, // {__LINE__, false, "{\"a\":9nfinity}"}, // {__LINE__, false, "{\"a\":nfinity}"}, // {__LINE__, false, "{\"a\":.nfinity}"}, // {__LINE__, false, "{\"a\":9nfinity}"}, // {__LINE__, false, "{\"a\":-nfinity}"}, // {__LINE__, true, "{\"a\":Infinity}"}, // {__LINE__, false, "{\"a\":.Infinity}"}, // {__LINE__, false, "{\"a\":_Infinity}"}, // {__LINE__, false, "{\"a\":_nfinity}"}, // {__LINE__, true, "{\"a\":-Infinity}"}, // {__LINE__, true, "{\"a\":+Infinity}"} // }; for (const auto& td : test_data) { bool ok = reader->parse(&*td.in.begin(), &*td.in.begin() + td.in.size(), &root, &errs); JSONTEST_ASSERT(td.ok == ok) << "line:" << td.line << "\n" << " expected: {" << "ok:" << td.ok << ", in:\'" << td.in << "\'" << "}\n" << " actual: {" << "ok:" << ok << "}\n"; } { char const doc[] = "{\"posInf\": +Infinity, \"NegInf\": -Infinity}"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(ok); JSONTEST_ASSERT_STRING_EQUAL("", errs); JSONTEST_ASSERT_EQUAL(2u, root.size()); JSONTEST_ASSERT_EQUAL(std::numeric_limits<double>::infinity(), root["posInf"].asDouble()); JSONTEST_ASSERT_EQUAL(-std::numeric_limits<double>::infinity(), root["NegInf"].asDouble()); } } struct EscapeSequenceTest : JsonTest::TestCase {}; JSONTEST_FIXTURE_LOCAL(EscapeSequenceTest, readerParseEscapeSequence) { Json::Reader reader; Json::Value root; bool ok = reader.parse("[\"\\\"\",\"\\/\",\"\\\\\",\"\\b\"," "\"\\f\",\"\\n\",\"\\r\",\"\\t\"," "\"\\u0278\",\"\\ud852\\udf62\"]\n", root); JSONTEST_ASSERT(ok); JSONTEST_ASSERT(reader.getFormattedErrorMessages().empty()); JSONTEST_ASSERT(reader.getStructuredErrors().empty()); } JSONTEST_FIXTURE_LOCAL(EscapeSequenceTest, charReaderParseEscapeSequence) { Json::CharReaderBuilder b; CharReaderPtr reader(b.newCharReader()); Json::Value root; Json::String errs; char const doc[] = "[\"\\\"\",\"\\/\",\"\\\\\",\"\\b\"," "\"\\f\",\"\\n\",\"\\r\",\"\\t\"," "\"\\u0278\",\"\\ud852\\udf62\"]"; bool ok = reader->parse(doc, doc + std::strlen(doc), &root, &errs); JSONTEST_ASSERT(ok); JSONTEST_ASSERT(errs.empty()); } JSONTEST_FIXTURE_LOCAL(EscapeSequenceTest, writeEscapeSequence) { Json::FastWriter writer; const Json::String expected("[\"\\\"\",\"\\\\\",\"\\b\"," "\"\\f\",\"\\n\",\"\\r\",\"\\t\"," "\"\\u0278\",\"\\ud852\\udf62\"]\n"); Json::Value root; root[0] = "\""; root[1] = "\\"; root[2] = "\b"; root[3] = "\f"; root[4] = "\n"; root[5] = "\r"; root[6] = "\t"; root[7] = "ɸ"; root[8] = "𤭢"; const Json::String result = writer.write(root); JSONTEST_ASSERT_STRING_EQUAL(expected, result); } struct BuilderTest : JsonTest::TestCase {}; JSONTEST_FIXTURE_LOCAL(BuilderTest, settings) { { Json::Value errs; Json::CharReaderBuilder rb; JSONTEST_ASSERT_EQUAL(false, rb.settings_.isMember("foo")); JSONTEST_ASSERT_EQUAL(true, rb.validate(&errs)); rb["foo"] = "bar"; JSONTEST_ASSERT_EQUAL(true, rb.settings_.isMember("foo")); JSONTEST_ASSERT_EQUAL(false, rb.validate(&errs)); } { Json::Value errs; Json::StreamWriterBuilder wb; JSONTEST_ASSERT_EQUAL(false, wb.settings_.isMember("foo")); JSONTEST_ASSERT_EQUAL(true, wb.validate(&errs)); wb["foo"] = "bar"; JSONTEST_ASSERT_EQUAL(true, wb.settings_.isMember("foo")); JSONTEST_ASSERT_EQUAL(false, wb.validate(&errs)); } } struct IteratorTest : JsonTest::TestCase {}; JSONTEST_FIXTURE_LOCAL(IteratorTest, convert) { Json::Value j; const Json::Value& cj = j; auto it = j.begin(); Json::Value::const_iterator cit; cit = it; JSONTEST_ASSERT(cit == cj.begin()); } JSONTEST_FIXTURE_LOCAL(IteratorTest, decrement) { Json::Value json; json["k1"] = "a"; json["k2"] = "b"; std::vector<std::string> values; for (auto it = json.end(); it != json.begin();) { --it; values.push_back(it->asString()); } JSONTEST_ASSERT((values == std::vector<std::string>{"b", "a"})); } JSONTEST_FIXTURE_LOCAL(IteratorTest, reverseIterator) { Json::Value json; json["k1"] = "a"; json["k2"] = "b"; std::vector<std::string> values; using Iter = decltype(json.begin()); auto re = std::reverse_iterator<Iter>(json.begin()); for (auto it = std::reverse_iterator<Iter>(json.end()); it != re; ++it) { values.push_back(it->asString()); } JSONTEST_ASSERT((values == std::vector<std::string>{"b", "a"})); } JSONTEST_FIXTURE_LOCAL(IteratorTest, distance) { { Json::Value json; json["k1"] = "a"; json["k2"] = "b"; int i = 0; auto it = json.begin(); for (;; ++it, ++i) { auto dist = it - json.begin(); JSONTEST_ASSERT_EQUAL(i, dist); if (it == json.end()) break; } } { Json::Value empty; JSONTEST_ASSERT_EQUAL(0, empty.end() - empty.end()); JSONTEST_ASSERT_EQUAL(0, empty.end() - empty.begin()); } } JSONTEST_FIXTURE_LOCAL(IteratorTest, nullValues) { { Json::Value json; auto end = json.end(); auto endCopy = end; JSONTEST_ASSERT(endCopy == end); endCopy = end; JSONTEST_ASSERT(endCopy == end); } { // Same test, now with const Value. const Json::Value json; auto end = json.end(); auto endCopy = end; JSONTEST_ASSERT(endCopy == end); endCopy = end; JSONTEST_ASSERT(endCopy == end); } } JSONTEST_FIXTURE_LOCAL(IteratorTest, staticStringKey) { Json::Value json; json[Json::StaticString("k1")] = "a"; JSONTEST_ASSERT_EQUAL(Json::Value("k1"), json.begin().key()); } JSONTEST_FIXTURE_LOCAL(IteratorTest, names) { Json::Value json; json["k1"] = "a"; json["k2"] = "b"; Json::ValueIterator it = json.begin(); JSONTEST_ASSERT(it != json.end()); JSONTEST_ASSERT_EQUAL(Json::Value("k1"), it.key()); JSONTEST_ASSERT_STRING_EQUAL("k1", it.name()); JSONTEST_ASSERT_STRING_EQUAL("k1", it.memberName()); JSONTEST_ASSERT_EQUAL(-1, it.index()); ++it; JSONTEST_ASSERT(it != json.end()); JSONTEST_ASSERT_EQUAL(Json::Value("k2"), it.key()); JSONTEST_ASSERT_STRING_EQUAL("k2", it.name()); JSONTEST_ASSERT_STRING_EQUAL("k2", it.memberName()); JSONTEST_ASSERT_EQUAL(-1, it.index()); ++it; JSONTEST_ASSERT(it == json.end()); } JSONTEST_FIXTURE_LOCAL(IteratorTest, indexes) { Json::Value json; json[0] = "a"; json[1] = "b"; Json::ValueIterator it = json.begin(); JSONTEST_ASSERT(it != json.end()); JSONTEST_ASSERT_EQUAL(Json::Value(Json::ArrayIndex(0)), it.key()); JSONTEST_ASSERT_STRING_EQUAL("", it.name()); JSONTEST_ASSERT_EQUAL(0, it.index()); ++it; JSONTEST_ASSERT(it != json.end()); JSONTEST_ASSERT_EQUAL(Json::Value(Json::ArrayIndex(1)), it.key()); JSONTEST_ASSERT_STRING_EQUAL("", it.name()); JSONTEST_ASSERT_EQUAL(1, it.index()); ++it; JSONTEST_ASSERT(it == json.end()); } JSONTEST_FIXTURE_LOCAL(IteratorTest, constness) { Json::Value const v; JSONTEST_ASSERT_THROWS( Json::Value::iterator it(v.begin())); // Compile, but throw. Json::Value value; for (int i = 9; i < 12; ++i) { Json::OStringStream out; out << std::setw(2) << i; Json::String str = out.str(); value[str] = str; } Json::OStringStream out; // in old code, this will get a compile error Json::Value::const_iterator iter = value.begin(); for (; iter != value.end(); ++iter) { out << *iter << ','; } Json::String expected = "\" 9\",\"10\",\"11\","; JSONTEST_ASSERT_STRING_EQUAL(expected, out.str()); } struct RValueTest : JsonTest::TestCase {}; JSONTEST_FIXTURE_LOCAL(RValueTest, moveConstruction) { Json::Value json; json["key"] = "value"; Json::Value moved = std::move(json); JSONTEST_ASSERT(moved != json); // Possibly not nullValue; definitely not // equal. JSONTEST_ASSERT_EQUAL(Json::objectValue, moved.type()); JSONTEST_ASSERT_EQUAL(Json::stringValue, moved["key"].type()); } struct FuzzTest : JsonTest::TestCase {}; // Build and run the fuzz test without any fuzzer, so that it's guaranteed not // go out of date, even if it's never run as an actual fuzz test. JSONTEST_FIXTURE_LOCAL(FuzzTest, fuzzDoesntCrash) { const std::string example = "{}"; JSONTEST_ASSERT_EQUAL( 0, LLVMFuzzerTestOneInput(reinterpret_cast<const uint8_t*>(example.c_str()), example.size())); } int main(int argc, const char* argv[]) { JsonTest::Runner runner; for (auto& local : local_) { runner.add(local); } return runner.runCommandLine(argc, argv); } struct MemberTemplateAs : JsonTest::TestCase { template <typename T, typename F> JsonTest::TestResult& EqEval(T v, F f) const { const Json::Value j = v; return JSONTEST_ASSERT_EQUAL(j.as<T>(), f(j)); } }; JSONTEST_FIXTURE_LOCAL(MemberTemplateAs, BehavesSameAsNamedAs) { const Json::Value jstr = "hello world"; JSONTEST_ASSERT_STRING_EQUAL(jstr.as<const char*>(), jstr.asCString()); JSONTEST_ASSERT_STRING_EQUAL(jstr.as<Json::String>(), jstr.asString()); EqEval(Json::Int(64), [](const Json::Value& j) { return j.asInt(); }); EqEval(Json::UInt(64), [](const Json::Value& j) { return j.asUInt(); }); #if defined(JSON_HAS_INT64) EqEval(Json::Int64(64), [](const Json::Value& j) { return j.asInt64(); }); EqEval(Json::UInt64(64), [](const Json::Value& j) { return j.asUInt64(); }); #endif // if defined(JSON_HAS_INT64) EqEval(Json::LargestInt(64), [](const Json::Value& j) { return j.asLargestInt(); }); EqEval(Json::LargestUInt(64), [](const Json::Value& j) { return j.asLargestUInt(); }); EqEval(69.69f, [](const Json::Value& j) { return j.asFloat(); }); EqEval(69.69, [](const Json::Value& j) { return j.asDouble(); }); EqEval(false, [](const Json::Value& j) { return j.asBool(); }); EqEval(true, [](const Json::Value& j) { return j.asBool(); }); } class MemberTemplateIs : public JsonTest::TestCase {}; JSONTEST_FIXTURE_LOCAL(MemberTemplateIs, BehavesSameAsNamedIs) { const Json::Value values[] = {true, 142, 40.63, "hello world"}; for (const Json::Value& j : values) { JSONTEST_ASSERT_EQUAL(j.is<bool>(), j.isBool()); JSONTEST_ASSERT_EQUAL(j.is<Json::Int>(), j.isInt()); JSONTEST_ASSERT_EQUAL(j.is<Json::Int64>(), j.isInt64()); JSONTEST_ASSERT_EQUAL(j.is<Json::UInt>(), j.isUInt()); JSONTEST_ASSERT_EQUAL(j.is<Json::UInt64>(), j.isUInt64()); JSONTEST_ASSERT_EQUAL(j.is<double>(), j.isDouble()); JSONTEST_ASSERT_EQUAL(j.is<Json::String>(), j.isString()); } } #if defined(__GNUC__) #pragma GCC diagnostic pop #endif
C++
3D
mcellteam/mcell
libs/jsoncpp/src/lib_json/json_tool.h
.h
3,812
135
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #ifndef LIB_JSONCPP_JSON_TOOL_H_INCLUDED #define LIB_JSONCPP_JSON_TOOL_H_INCLUDED #if !defined(JSON_IS_AMALGAMATION) #include <json/config.h> #endif // Also support old flag NO_LOCALE_SUPPORT #ifdef NO_LOCALE_SUPPORT #define JSONCPP_NO_LOCALE_SUPPORT #endif #ifndef JSONCPP_NO_LOCALE_SUPPORT #include <clocale> #endif /* This header provides common string manipulation support, such as UTF-8, * portable conversion from/to string... * * It is an internal header that must not be exposed. */ namespace Json { static inline char getDecimalPoint() { #ifdef JSONCPP_NO_LOCALE_SUPPORT return '\0'; #else struct lconv* lc = localeconv(); return lc ? *(lc->decimal_point) : '\0'; #endif } /// Converts a unicode code-point to UTF-8. static inline String codePointToUTF8(unsigned int cp) { String result; // based on description from http://en.wikipedia.org/wiki/UTF-8 if (cp <= 0x7f) { result.resize(1); result[0] = static_cast<char>(cp); } else if (cp <= 0x7FF) { result.resize(2); result[1] = static_cast<char>(0x80 | (0x3f & cp)); result[0] = static_cast<char>(0xC0 | (0x1f & (cp >> 6))); } else if (cp <= 0xFFFF) { result.resize(3); result[2] = static_cast<char>(0x80 | (0x3f & cp)); result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 6))); result[0] = static_cast<char>(0xE0 | (0xf & (cp >> 12))); } else if (cp <= 0x10FFFF) { result.resize(4); result[3] = static_cast<char>(0x80 | (0x3f & cp)); result[2] = static_cast<char>(0x80 | (0x3f & (cp >> 6))); result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 12))); result[0] = static_cast<char>(0xF0 | (0x7 & (cp >> 18))); } return result; } enum { /// Constant that specify the size of the buffer that must be passed to /// uintToString. uintToStringBufferSize = 3 * sizeof(LargestUInt) + 1 }; // Defines a char buffer for use with uintToString(). using UIntToStringBuffer = char[uintToStringBufferSize]; /** Converts an unsigned integer to string. * @param value Unsigned integer to convert to string * @param current Input/Output string buffer. * Must have at least uintToStringBufferSize chars free. */ static inline void uintToString(LargestUInt value, char*& current) { *--current = 0; do { *--current = static_cast<char>(value % 10U + static_cast<unsigned>('0')); value /= 10; } while (value != 0); } /** Change ',' to '.' everywhere in buffer. * * We had a sophisticated way, but it did not work in WinCE. * @see https://github.com/open-source-parsers/jsoncpp/pull/9 */ template <typename Iter> Iter fixNumericLocale(Iter begin, Iter end) { for (; begin != end; ++begin) { if (*begin == ',') { *begin = '.'; } } return begin; } template <typename Iter> void fixNumericLocaleInput(Iter begin, Iter end) { char decimalPoint = getDecimalPoint(); if (decimalPoint == '\0' || decimalPoint == '.') { return; } for (; begin != end; ++begin) { if (*begin == '.') { *begin = decimalPoint; } } } /** * Return iterator that would be the new end of the range [begin,end), if we * were to delete zeros in the end of string, but not the last zero before '.'. */ template <typename Iter> Iter fixZerosInTheEnd(Iter begin, Iter end) { for (; begin != end; --end) { if (*(end - 1) != '0') { return end; } // Don't delete the last zero before the decimal point. if (begin != (end - 1) && *(end - 2) == '.') { return end; } } return end; } } // namespace Json #endif // LIB_JSONCPP_JSON_TOOL_H_INCLUDED
Unknown
3D
mcellteam/mcell
libs/jsoncpp/src/lib_json/json_reader.cpp
.cpp
57,893
1,982
// Copyright 2007-2011 Baptiste Lepilleur and The JsonCpp Authors // Copyright (C) 2016 InfoTeCS JSC. All rights reserved. // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #if !defined(JSON_IS_AMALGAMATION) #include "json_tool.h" #include <json/assertions.h> #include <json/reader.h> #include <json/value.h> #endif // if !defined(JSON_IS_AMALGAMATION) #include <cassert> #include <cstring> #include <iostream> #include <istream> #include <limits> #include <memory> #include <set> #include <sstream> #include <utility> #include <cstdio> #if __cplusplus >= 201103L #if !defined(sscanf) #define sscanf std::sscanf #endif #endif //__cplusplus #if defined(_MSC_VER) #if !defined(_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES) #define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1 #endif //_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES #endif //_MSC_VER #if defined(_MSC_VER) // Disable warning about strdup being deprecated. #pragma warning(disable : 4996) #endif // Define JSONCPP_DEPRECATED_STACK_LIMIT as an appropriate integer at compile // time to change the stack limit #if !defined(JSONCPP_DEPRECATED_STACK_LIMIT) #define JSONCPP_DEPRECATED_STACK_LIMIT 1000 #endif static size_t const stackLimit_g = JSONCPP_DEPRECATED_STACK_LIMIT; // see readValue() namespace Json { #if __cplusplus >= 201103L || (defined(_CPPLIB_VER) && _CPPLIB_VER >= 520) using CharReaderPtr = std::unique_ptr<CharReader>; #else using CharReaderPtr = std::auto_ptr<CharReader>; #endif // Implementation of class Features // //////////////////////////////// Features::Features() = default; Features Features::all() { return {}; } Features Features::strictMode() { Features features; features.allowComments_ = false; features.strictRoot_ = true; features.allowDroppedNullPlaceholders_ = false; features.allowNumericKeys_ = false; return features; } // Implementation of class Reader // //////////////////////////////// bool Reader::containsNewLine(Reader::Location begin, Reader::Location end) { for (; begin < end; ++begin) if (*begin == '\n' || *begin == '\r') return true; return false; } // Class Reader // ////////////////////////////////////////////////////////////////// Reader::Reader() : features_(Features::all()) {} Reader::Reader(const Features& features) : features_(features) {} bool Reader::parse(const std::string& document, Value& root, bool collectComments) { document_.assign(document.begin(), document.end()); const char* begin = document_.c_str(); const char* end = begin + document_.length(); return parse(begin, end, root, collectComments); } bool Reader::parse(std::istream& is, Value& root, bool collectComments) { // std::istream_iterator<char> begin(is); // std::istream_iterator<char> end; // Those would allow streamed input from a file, if parse() were a // template function. // Since String is reference-counted, this at least does not // create an extra copy. String doc; std::getline(is, doc, static_cast<char> EOF); return parse(doc.data(), doc.data() + doc.size(), root, collectComments); } bool Reader::parse(const char* beginDoc, const char* endDoc, Value& root, bool collectComments) { if (!features_.allowComments_) { collectComments = false; } begin_ = beginDoc; end_ = endDoc; collectComments_ = collectComments; current_ = begin_; lastValueEnd_ = nullptr; lastValue_ = nullptr; commentsBefore_.clear(); errors_.clear(); while (!nodes_.empty()) nodes_.pop(); nodes_.push(&root); bool successful = readValue(); Token token; skipCommentTokens(token); if (collectComments_ && !commentsBefore_.empty()) root.setComment(commentsBefore_, commentAfter); if (features_.strictRoot_) { if (!root.isArray() && !root.isObject()) { // Set error location to start of doc, ideally should be first token found // in doc token.type_ = tokenError; token.start_ = beginDoc; token.end_ = endDoc; addError( "A valid JSON document must be either an array or an object value.", token); return false; } } return successful; } bool Reader::readValue() { // readValue() may call itself only if it calls readObject() or ReadArray(). // These methods execute nodes_.push() just before and nodes_.pop)() just // after calling readValue(). parse() executes one nodes_.push(), so > instead // of >=. if (nodes_.size() > stackLimit_g) throwRuntimeError("Exceeded stackLimit in readValue()."); Token token; skipCommentTokens(token); bool successful = true; if (collectComments_ && !commentsBefore_.empty()) { currentValue().setComment(commentsBefore_, commentBefore); commentsBefore_.clear(); } switch (token.type_) { case tokenObjectBegin: successful = readObject(token); currentValue().setOffsetLimit(current_ - begin_); break; case tokenArrayBegin: successful = readArray(token); currentValue().setOffsetLimit(current_ - begin_); break; case tokenNumber: successful = decodeNumber(token); break; case tokenString: successful = decodeString(token); break; case tokenTrue: { Value v(true); currentValue().swapPayload(v); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); } break; case tokenFalse: { Value v(false); currentValue().swapPayload(v); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); } break; case tokenNull: { Value v; currentValue().swapPayload(v); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); } break; case tokenArraySeparator: case tokenObjectEnd: case tokenArrayEnd: if (features_.allowDroppedNullPlaceholders_) { // "Un-read" the current token and mark the current value as a null // token. current_--; Value v; currentValue().swapPayload(v); currentValue().setOffsetStart(current_ - begin_ - 1); currentValue().setOffsetLimit(current_ - begin_); break; } // Else, fall through... default: currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); return addError("Syntax error: value, object or array expected.", token); } if (collectComments_) { lastValueEnd_ = current_; lastValue_ = &currentValue(); } return successful; } void Reader::skipCommentTokens(Token& token) { if (features_.allowComments_) { do { readToken(token); } while (token.type_ == tokenComment); } else { readToken(token); } } bool Reader::readToken(Token& token) { skipSpaces(); token.start_ = current_; Char c = getNextChar(); bool ok = true; switch (c) { case '{': token.type_ = tokenObjectBegin; break; case '}': token.type_ = tokenObjectEnd; break; case '[': token.type_ = tokenArrayBegin; break; case ']': token.type_ = tokenArrayEnd; break; case '"': token.type_ = tokenString; ok = readString(); break; case '/': token.type_ = tokenComment; ok = readComment(); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': token.type_ = tokenNumber; readNumber(); break; case 't': token.type_ = tokenTrue; ok = match("rue", 3); break; case 'f': token.type_ = tokenFalse; ok = match("alse", 4); break; case 'n': token.type_ = tokenNull; ok = match("ull", 3); break; case ',': token.type_ = tokenArraySeparator; break; case ':': token.type_ = tokenMemberSeparator; break; case 0: token.type_ = tokenEndOfStream; break; default: ok = false; break; } if (!ok) token.type_ = tokenError; token.end_ = current_; return ok; } void Reader::skipSpaces() { while (current_ != end_) { Char c = *current_; if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++current_; else break; } } bool Reader::match(const Char* pattern, int patternLength) { if (end_ - current_ < patternLength) return false; int index = patternLength; while (index--) if (current_[index] != pattern[index]) return false; current_ += patternLength; return true; } bool Reader::readComment() { Location commentBegin = current_ - 1; Char c = getNextChar(); bool successful = false; if (c == '*') successful = readCStyleComment(); else if (c == '/') successful = readCppStyleComment(); if (!successful) return false; if (collectComments_) { CommentPlacement placement = commentBefore; if (lastValueEnd_ && !containsNewLine(lastValueEnd_, commentBegin)) { if (c != '*' || !containsNewLine(commentBegin, current_)) placement = commentAfterOnSameLine; } addComment(commentBegin, current_, placement); } return true; } String Reader::normalizeEOL(Reader::Location begin, Reader::Location end) { String normalized; normalized.reserve(static_cast<size_t>(end - begin)); Reader::Location current = begin; while (current != end) { char c = *current++; if (c == '\r') { if (current != end && *current == '\n') // convert dos EOL ++current; // convert Mac EOL normalized += '\n'; } else { normalized += c; } } return normalized; } void Reader::addComment(Location begin, Location end, CommentPlacement placement) { assert(collectComments_); const String& normalized = normalizeEOL(begin, end); if (placement == commentAfterOnSameLine) { assert(lastValue_ != nullptr); lastValue_->setComment(normalized, placement); } else { commentsBefore_ += normalized; } } bool Reader::readCStyleComment() { while ((current_ + 1) < end_) { Char c = getNextChar(); if (c == '*' && *current_ == '/') break; } return getNextChar() == '/'; } bool Reader::readCppStyleComment() { while (current_ != end_) { Char c = getNextChar(); if (c == '\n') break; if (c == '\r') { // Consume DOS EOL. It will be normalized in addComment. if (current_ != end_ && *current_ == '\n') getNextChar(); // Break on Moc OS 9 EOL. break; } } return true; } void Reader::readNumber() { Location p = current_; char c = '0'; // stopgap for already consumed character // integral part while (c >= '0' && c <= '9') c = (current_ = p) < end_ ? *p++ : '\0'; // fractional part if (c == '.') { c = (current_ = p) < end_ ? *p++ : '\0'; while (c >= '0' && c <= '9') c = (current_ = p) < end_ ? *p++ : '\0'; } // exponential part if (c == 'e' || c == 'E') { c = (current_ = p) < end_ ? *p++ : '\0'; if (c == '+' || c == '-') c = (current_ = p) < end_ ? *p++ : '\0'; while (c >= '0' && c <= '9') c = (current_ = p) < end_ ? *p++ : '\0'; } } bool Reader::readString() { Char c = '\0'; while (current_ != end_) { c = getNextChar(); if (c == '\\') getNextChar(); else if (c == '"') break; } return c == '"'; } bool Reader::readObject(Token& token) { Token tokenName; String name; Value init(objectValue); currentValue().swapPayload(init); currentValue().setOffsetStart(token.start_ - begin_); while (readToken(tokenName)) { bool initialTokenOk = true; while (tokenName.type_ == tokenComment && initialTokenOk) initialTokenOk = readToken(tokenName); if (!initialTokenOk) break; if (tokenName.type_ == tokenObjectEnd && name.empty()) // empty object return true; name.clear(); if (tokenName.type_ == tokenString) { if (!decodeString(tokenName, name)) return recoverFromError(tokenObjectEnd); } else if (tokenName.type_ == tokenNumber && features_.allowNumericKeys_) { Value numberName; if (!decodeNumber(tokenName, numberName)) return recoverFromError(tokenObjectEnd); name = numberName.asString(); } else { break; } Token colon; if (!readToken(colon) || colon.type_ != tokenMemberSeparator) { return addErrorAndRecover("Missing ':' after object member name", colon, tokenObjectEnd); } Value& value = currentValue()[name]; nodes_.push(&value); bool ok = readValue(); nodes_.pop(); if (!ok) // error already set return recoverFromError(tokenObjectEnd); Token comma; if (!readToken(comma) || (comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator && comma.type_ != tokenComment)) { return addErrorAndRecover("Missing ',' or '}' in object declaration", comma, tokenObjectEnd); } bool finalizeTokenOk = true; while (comma.type_ == tokenComment && finalizeTokenOk) finalizeTokenOk = readToken(comma); if (comma.type_ == tokenObjectEnd) return true; } return addErrorAndRecover("Missing '}' or object member name", tokenName, tokenObjectEnd); } bool Reader::readArray(Token& token) { Value init(arrayValue); currentValue().swapPayload(init); currentValue().setOffsetStart(token.start_ - begin_); skipSpaces(); if (current_ != end_ && *current_ == ']') // empty array { Token endArray; readToken(endArray); return true; } int index = 0; for (;;) { Value& value = currentValue()[index++]; nodes_.push(&value); bool ok = readValue(); nodes_.pop(); if (!ok) // error already set return recoverFromError(tokenArrayEnd); Token currentToken; // Accept Comment after last item in the array. ok = readToken(currentToken); while (currentToken.type_ == tokenComment && ok) { ok = readToken(currentToken); } bool badTokenType = (currentToken.type_ != tokenArraySeparator && currentToken.type_ != tokenArrayEnd); if (!ok || badTokenType) { return addErrorAndRecover("Missing ',' or ']' in array declaration", currentToken, tokenArrayEnd); } if (currentToken.type_ == tokenArrayEnd) break; } return true; } bool Reader::decodeNumber(Token& token) { Value decoded; if (!decodeNumber(token, decoded)) return false; currentValue().swapPayload(decoded); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); return true; } bool Reader::decodeNumber(Token& token, Value& decoded) { // Attempts to parse the number as an integer. If the number is // larger than the maximum supported value of an integer then // we decode the number as a double. Location current = token.start_; bool isNegative = *current == '-'; if (isNegative) ++current; // TODO: Help the compiler do the div and mod at compile time or get rid of // them. Value::LargestUInt maxIntegerValue = isNegative ? Value::LargestUInt(Value::maxLargestInt) + 1 : Value::maxLargestUInt; Value::LargestUInt threshold = maxIntegerValue / 10; Value::LargestUInt value = 0; while (current < token.end_) { Char c = *current++; if (c < '0' || c > '9') return decodeDouble(token, decoded); auto digit(static_cast<Value::UInt>(c - '0')); if (value >= threshold) { // We've hit or exceeded the max value divided by 10 (rounded down). If // a) we've only just touched the limit, b) this is the last digit, and // c) it's small enough to fit in that rounding delta, we're okay. // Otherwise treat this number as a double to avoid overflow. if (value > threshold || current != token.end_ || digit > maxIntegerValue % 10) { return decodeDouble(token, decoded); } } value = value * 10 + digit; } if (isNegative && value == maxIntegerValue) decoded = Value::minLargestInt; else if (isNegative) decoded = -Value::LargestInt(value); else if (value <= Value::LargestUInt(Value::maxInt)) decoded = Value::LargestInt(value); else decoded = value; return true; } bool Reader::decodeDouble(Token& token) { Value decoded; if (!decodeDouble(token, decoded)) return false; currentValue().swapPayload(decoded); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); return true; } bool Reader::decodeDouble(Token& token, Value& decoded) { double value = 0; String buffer(token.start_, token.end_); IStringStream is(buffer); if (!(is >> value)) return addError( "'" + String(token.start_, token.end_) + "' is not a number.", token); decoded = value; return true; } bool Reader::decodeString(Token& token) { String decoded_string; if (!decodeString(token, decoded_string)) return false; Value decoded(decoded_string); currentValue().swapPayload(decoded); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); return true; } bool Reader::decodeString(Token& token, String& decoded) { decoded.reserve(static_cast<size_t>(token.end_ - token.start_ - 2)); Location current = token.start_ + 1; // skip '"' Location end = token.end_ - 1; // do not include '"' while (current != end) { Char c = *current++; if (c == '"') break; if (c == '\\') { if (current == end) return addError("Empty escape sequence in string", token, current); Char escape = *current++; switch (escape) { case '"': decoded += '"'; break; case '/': decoded += '/'; break; case '\\': decoded += '\\'; break; case 'b': decoded += '\b'; break; case 'f': decoded += '\f'; break; case 'n': decoded += '\n'; break; case 'r': decoded += '\r'; break; case 't': decoded += '\t'; break; case 'u': { unsigned int unicode; if (!decodeUnicodeCodePoint(token, current, end, unicode)) return false; decoded += codePointToUTF8(unicode); } break; default: return addError("Bad escape sequence in string", token, current); } } else { decoded += c; } } return true; } bool Reader::decodeUnicodeCodePoint(Token& token, Location& current, Location end, unsigned int& unicode) { if (!decodeUnicodeEscapeSequence(token, current, end, unicode)) return false; if (unicode >= 0xD800 && unicode <= 0xDBFF) { // surrogate pairs if (end - current < 6) return addError( "additional six characters expected to parse unicode surrogate pair.", token, current); if (*(current++) == '\\' && *(current++) == 'u') { unsigned int surrogatePair; if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) { unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF); } else return false; } else return addError("expecting another \\u token to begin the second half of " "a unicode surrogate pair", token, current); } return true; } bool Reader::decodeUnicodeEscapeSequence(Token& token, Location& current, Location end, unsigned int& ret_unicode) { if (end - current < 4) return addError( "Bad unicode escape sequence in string: four digits expected.", token, current); int unicode = 0; for (int index = 0; index < 4; ++index) { Char c = *current++; unicode *= 16; if (c >= '0' && c <= '9') unicode += c - '0'; else if (c >= 'a' && c <= 'f') unicode += c - 'a' + 10; else if (c >= 'A' && c <= 'F') unicode += c - 'A' + 10; else return addError( "Bad unicode escape sequence in string: hexadecimal digit expected.", token, current); } ret_unicode = static_cast<unsigned int>(unicode); return true; } bool Reader::addError(const String& message, Token& token, Location extra) { ErrorInfo info; info.token_ = token; info.message_ = message; info.extra_ = extra; errors_.push_back(info); return false; } bool Reader::recoverFromError(TokenType skipUntilToken) { size_t const errorCount = errors_.size(); Token skip; for (;;) { if (!readToken(skip)) errors_.resize(errorCount); // discard errors caused by recovery if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream) break; } errors_.resize(errorCount); return false; } bool Reader::addErrorAndRecover(const String& message, Token& token, TokenType skipUntilToken) { addError(message, token); return recoverFromError(skipUntilToken); } Value& Reader::currentValue() { return *(nodes_.top()); } Reader::Char Reader::getNextChar() { if (current_ == end_) return 0; return *current_++; } void Reader::getLocationLineAndColumn(Location location, int& line, int& column) const { Location current = begin_; Location lastLineStart = current; line = 0; while (current < location && current != end_) { Char c = *current++; if (c == '\r') { if (*current == '\n') ++current; lastLineStart = current; ++line; } else if (c == '\n') { lastLineStart = current; ++line; } } // column & line start at 1 column = int(location - lastLineStart) + 1; ++line; } String Reader::getLocationLineAndColumn(Location location) const { int line, column; getLocationLineAndColumn(location, line, column); char buffer[18 + 16 + 16 + 1]; jsoncpp_snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column); return buffer; } // Deprecated. Preserved for backward compatibility String Reader::getFormatedErrorMessages() const { return getFormattedErrorMessages(); } String Reader::getFormattedErrorMessages() const { String formattedMessage; for (const auto& error : errors_) { formattedMessage += "* " + getLocationLineAndColumn(error.token_.start_) + "\n"; formattedMessage += " " + error.message_ + "\n"; if (error.extra_) formattedMessage += "See " + getLocationLineAndColumn(error.extra_) + " for detail.\n"; } return formattedMessage; } std::vector<Reader::StructuredError> Reader::getStructuredErrors() const { std::vector<Reader::StructuredError> allErrors; for (const auto& error : errors_) { Reader::StructuredError structured; structured.offset_start = error.token_.start_ - begin_; structured.offset_limit = error.token_.end_ - begin_; structured.message = error.message_; allErrors.push_back(structured); } return allErrors; } bool Reader::pushError(const Value& value, const String& message) { ptrdiff_t const length = end_ - begin_; if (value.getOffsetStart() > length || value.getOffsetLimit() > length) return false; Token token; token.type_ = tokenError; token.start_ = begin_ + value.getOffsetStart(); token.end_ = begin_ + value.getOffsetLimit(); ErrorInfo info; info.token_ = token; info.message_ = message; info.extra_ = nullptr; errors_.push_back(info); return true; } bool Reader::pushError(const Value& value, const String& message, const Value& extra) { ptrdiff_t const length = end_ - begin_; if (value.getOffsetStart() > length || value.getOffsetLimit() > length || extra.getOffsetLimit() > length) return false; Token token; token.type_ = tokenError; token.start_ = begin_ + value.getOffsetStart(); token.end_ = begin_ + value.getOffsetLimit(); ErrorInfo info; info.token_ = token; info.message_ = message; info.extra_ = begin_ + extra.getOffsetStart(); errors_.push_back(info); return true; } bool Reader::good() const { return errors_.empty(); } // Originally copied from the Features class (now deprecated), used internally // for features implementation. class OurFeatures { public: static OurFeatures all(); bool allowComments_; bool allowTrailingCommas_; bool strictRoot_; bool allowDroppedNullPlaceholders_; bool allowNumericKeys_; bool allowSingleQuotes_; bool failIfExtra_; bool rejectDupKeys_; bool allowSpecialFloats_; size_t stackLimit_; }; // OurFeatures OurFeatures OurFeatures::all() { return {}; } // Implementation of class Reader // //////////////////////////////// // Originally copied from the Reader class (now deprecated), used internally // for implementing JSON reading. class OurReader { public: using Char = char; using Location = const Char*; struct StructuredError { ptrdiff_t offset_start; ptrdiff_t offset_limit; String message; }; explicit OurReader(OurFeatures const& features); bool parse(const char* beginDoc, const char* endDoc, Value& root, bool collectComments = true); String getFormattedErrorMessages() const; std::vector<StructuredError> getStructuredErrors() const; private: OurReader(OurReader const&); // no impl void operator=(OurReader const&); // no impl enum TokenType { tokenEndOfStream = 0, tokenObjectBegin, tokenObjectEnd, tokenArrayBegin, tokenArrayEnd, tokenString, tokenNumber, tokenTrue, tokenFalse, tokenNull, tokenNaN, tokenPosInf, tokenNegInf, tokenArraySeparator, tokenMemberSeparator, tokenComment, tokenError }; class Token { public: TokenType type_; Location start_; Location end_; }; class ErrorInfo { public: Token token_; String message_; Location extra_; }; using Errors = std::deque<ErrorInfo>; bool readToken(Token& token); void skipSpaces(); bool match(const Char* pattern, int patternLength); bool readComment(); bool readCStyleComment(bool* containsNewLineResult); bool readCppStyleComment(); bool readString(); bool readStringSingleQuote(); bool readNumber(bool checkInf); bool readValue(); bool readObject(Token& token); bool readArray(Token& token); bool decodeNumber(Token& token); bool decodeNumber(Token& token, Value& decoded); bool decodeString(Token& token); bool decodeString(Token& token, String& decoded); bool decodeDouble(Token& token); bool decodeDouble(Token& token, Value& decoded); bool decodeUnicodeCodePoint(Token& token, Location& current, Location end, unsigned int& unicode); bool decodeUnicodeEscapeSequence(Token& token, Location& current, Location end, unsigned int& unicode); bool addError(const String& message, Token& token, Location extra = nullptr); bool recoverFromError(TokenType skipUntilToken); bool addErrorAndRecover(const String& message, Token& token, TokenType skipUntilToken); void skipUntilSpace(); Value& currentValue(); Char getNextChar(); void getLocationLineAndColumn(Location location, int& line, int& column) const; String getLocationLineAndColumn(Location location) const; void addComment(Location begin, Location end, CommentPlacement placement); void skipCommentTokens(Token& token); static String normalizeEOL(Location begin, Location end); static bool containsNewLine(Location begin, Location end); using Nodes = std::stack<Value*>; Nodes nodes_{}; Errors errors_{}; String document_{}; Location begin_ = nullptr; Location end_ = nullptr; Location current_ = nullptr; Location lastValueEnd_ = nullptr; Value* lastValue_ = nullptr; bool lastValueHasAComment_ = false; String commentsBefore_{}; OurFeatures const features_; bool collectComments_ = false; }; // OurReader // complete copy of Read impl, for OurReader bool OurReader::containsNewLine(OurReader::Location begin, OurReader::Location end) { for (; begin < end; ++begin) if (*begin == '\n' || *begin == '\r') return true; return false; } OurReader::OurReader(OurFeatures const& features) : features_(features) {} bool OurReader::parse(const char* beginDoc, const char* endDoc, Value& root, bool collectComments) { if (!features_.allowComments_) { collectComments = false; } begin_ = beginDoc; end_ = endDoc; collectComments_ = collectComments; current_ = begin_; lastValueEnd_ = nullptr; lastValue_ = nullptr; commentsBefore_.clear(); errors_.clear(); while (!nodes_.empty()) nodes_.pop(); nodes_.push(&root); bool successful = readValue(); nodes_.pop(); Token token; skipCommentTokens(token); if (features_.failIfExtra_ && (token.type_ != tokenEndOfStream)) { addError("Extra non-whitespace after JSON value.", token); return false; } if (collectComments_ && !commentsBefore_.empty()) root.setComment(commentsBefore_, commentAfter); if (features_.strictRoot_) { if (!root.isArray() && !root.isObject()) { // Set error location to start of doc, ideally should be first token found // in doc token.type_ = tokenError; token.start_ = beginDoc; token.end_ = endDoc; addError( "A valid JSON document must be either an array or an object value.", token); return false; } } return successful; } bool OurReader::readValue() { // To preserve the old behaviour we cast size_t to int. if (nodes_.size() > features_.stackLimit_) throwRuntimeError("Exceeded stackLimit in readValue()."); Token token; skipCommentTokens(token); bool successful = true; if (collectComments_ && !commentsBefore_.empty()) { currentValue().setComment(commentsBefore_, commentBefore); commentsBefore_.clear(); } switch (token.type_) { case tokenObjectBegin: successful = readObject(token); currentValue().setOffsetLimit(current_ - begin_); break; case tokenArrayBegin: successful = readArray(token); currentValue().setOffsetLimit(current_ - begin_); break; case tokenNumber: successful = decodeNumber(token); break; case tokenString: successful = decodeString(token); break; case tokenTrue: { Value v(true); currentValue().swapPayload(v); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); } break; case tokenFalse: { Value v(false); currentValue().swapPayload(v); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); } break; case tokenNull: { Value v; currentValue().swapPayload(v); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); } break; case tokenNaN: { Value v(std::numeric_limits<double>::quiet_NaN()); currentValue().swapPayload(v); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); } break; case tokenPosInf: { Value v(std::numeric_limits<double>::infinity()); currentValue().swapPayload(v); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); } break; case tokenNegInf: { Value v(-std::numeric_limits<double>::infinity()); currentValue().swapPayload(v); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); } break; case tokenArraySeparator: case tokenObjectEnd: case tokenArrayEnd: if (features_.allowDroppedNullPlaceholders_) { // "Un-read" the current token and mark the current value as a null // token. current_--; Value v; currentValue().swapPayload(v); currentValue().setOffsetStart(current_ - begin_ - 1); currentValue().setOffsetLimit(current_ - begin_); break; } // else, fall through ... default: currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); return addError("Syntax error: value, object or array expected.", token); } if (collectComments_) { lastValueEnd_ = current_; lastValueHasAComment_ = false; lastValue_ = &currentValue(); } return successful; } void OurReader::skipCommentTokens(Token& token) { if (features_.allowComments_) { do { readToken(token); } while (token.type_ == tokenComment); } else { readToken(token); } } bool OurReader::readToken(Token& token) { skipSpaces(); token.start_ = current_; Char c = getNextChar(); bool ok = true; switch (c) { case '{': token.type_ = tokenObjectBegin; break; case '}': token.type_ = tokenObjectEnd; break; case '[': token.type_ = tokenArrayBegin; break; case ']': token.type_ = tokenArrayEnd; break; case '"': token.type_ = tokenString; ok = readString(); break; case '\'': if (features_.allowSingleQuotes_) { token.type_ = tokenString; ok = readStringSingleQuote(); break; } // else fall through case '/': token.type_ = tokenComment; ok = readComment(); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': token.type_ = tokenNumber; readNumber(false); break; case '-': if (readNumber(true)) { token.type_ = tokenNumber; } else { token.type_ = tokenNegInf; ok = features_.allowSpecialFloats_ && match("nfinity", 7); } break; case '+': if (readNumber(true)) { token.type_ = tokenNumber; } else { token.type_ = tokenPosInf; ok = features_.allowSpecialFloats_ && match("nfinity", 7); } break; case 't': token.type_ = tokenTrue; ok = match("rue", 3); break; case 'f': token.type_ = tokenFalse; ok = match("alse", 4); break; case 'n': token.type_ = tokenNull; ok = match("ull", 3); break; case 'N': if (features_.allowSpecialFloats_) { token.type_ = tokenNaN; ok = match("aN", 2); } else { ok = false; } break; case 'I': if (features_.allowSpecialFloats_) { token.type_ = tokenPosInf; ok = match("nfinity", 7); } else { ok = false; } break; case ',': token.type_ = tokenArraySeparator; break; case ':': token.type_ = tokenMemberSeparator; break; case 0: token.type_ = tokenEndOfStream; break; default: ok = false; break; } if (!ok) token.type_ = tokenError; token.end_ = current_; return ok; } void OurReader::skipSpaces() { while (current_ != end_) { Char c = *current_; if (c == ' ' || c == '\t' || c == '\r' || c == '\n') ++current_; else break; } } bool OurReader::match(const Char* pattern, int patternLength) { if (end_ - current_ < patternLength) return false; int index = patternLength; while (index--) if (current_[index] != pattern[index]) return false; current_ += patternLength; return true; } bool OurReader::readComment() { const Location commentBegin = current_ - 1; const Char c = getNextChar(); bool successful = false; bool cStyleWithEmbeddedNewline = false; const bool isCStyleComment = (c == '*'); const bool isCppStyleComment = (c == '/'); if (isCStyleComment) { successful = readCStyleComment(&cStyleWithEmbeddedNewline); } else if (isCppStyleComment) { successful = readCppStyleComment(); } if (!successful) return false; if (collectComments_) { CommentPlacement placement = commentBefore; if (!lastValueHasAComment_) { if (lastValueEnd_ && !containsNewLine(lastValueEnd_, commentBegin)) { if (isCppStyleComment || !cStyleWithEmbeddedNewline) { placement = commentAfterOnSameLine; lastValueHasAComment_ = true; } } } addComment(commentBegin, current_, placement); } return true; } String OurReader::normalizeEOL(OurReader::Location begin, OurReader::Location end) { String normalized; normalized.reserve(static_cast<size_t>(end - begin)); OurReader::Location current = begin; while (current != end) { char c = *current++; if (c == '\r') { if (current != end && *current == '\n') // convert dos EOL ++current; // convert Mac EOL normalized += '\n'; } else { normalized += c; } } return normalized; } void OurReader::addComment(Location begin, Location end, CommentPlacement placement) { assert(collectComments_); const String& normalized = normalizeEOL(begin, end); if (placement == commentAfterOnSameLine) { assert(lastValue_ != nullptr); lastValue_->setComment(normalized, placement); } else { commentsBefore_ += normalized; } } bool OurReader::readCStyleComment(bool* containsNewLineResult) { *containsNewLineResult = false; while ((current_ + 1) < end_) { Char c = getNextChar(); if (c == '*' && *current_ == '/') break; if (c == '\n') *containsNewLineResult = true; } return getNextChar() == '/'; } bool OurReader::readCppStyleComment() { while (current_ != end_) { Char c = getNextChar(); if (c == '\n') break; if (c == '\r') { // Consume DOS EOL. It will be normalized in addComment. if (current_ != end_ && *current_ == '\n') getNextChar(); // Break on Moc OS 9 EOL. break; } } return true; } bool OurReader::readNumber(bool checkInf) { Location p = current_; if (checkInf && p != end_ && *p == 'I') { current_ = ++p; return false; } char c = '0'; // stopgap for already consumed character // integral part while (c >= '0' && c <= '9') c = (current_ = p) < end_ ? *p++ : '\0'; // fractional part if (c == '.') { c = (current_ = p) < end_ ? *p++ : '\0'; while (c >= '0' && c <= '9') c = (current_ = p) < end_ ? *p++ : '\0'; } // exponential part if (c == 'e' || c == 'E') { c = (current_ = p) < end_ ? *p++ : '\0'; if (c == '+' || c == '-') c = (current_ = p) < end_ ? *p++ : '\0'; while (c >= '0' && c <= '9') c = (current_ = p) < end_ ? *p++ : '\0'; } return true; } bool OurReader::readString() { Char c = 0; while (current_ != end_) { c = getNextChar(); if (c == '\\') getNextChar(); else if (c == '"') break; } return c == '"'; } bool OurReader::readStringSingleQuote() { Char c = 0; while (current_ != end_) { c = getNextChar(); if (c == '\\') getNextChar(); else if (c == '\'') break; } return c == '\''; } bool OurReader::readObject(Token& token) { Token tokenName; String name; Value init(objectValue); currentValue().swapPayload(init); currentValue().setOffsetStart(token.start_ - begin_); while (readToken(tokenName)) { bool initialTokenOk = true; while (tokenName.type_ == tokenComment && initialTokenOk) initialTokenOk = readToken(tokenName); if (!initialTokenOk) break; if (tokenName.type_ == tokenObjectEnd && (name.empty() || features_.allowTrailingCommas_)) // empty object or trailing comma return true; name.clear(); if (tokenName.type_ == tokenString) { if (!decodeString(tokenName, name)) return recoverFromError(tokenObjectEnd); } else if (tokenName.type_ == tokenNumber && features_.allowNumericKeys_) { Value numberName; if (!decodeNumber(tokenName, numberName)) return recoverFromError(tokenObjectEnd); name = numberName.asString(); } else { break; } if (name.length() >= (1U << 30)) throwRuntimeError("keylength >= 2^30"); if (features_.rejectDupKeys_ && currentValue().isMember(name)) { String msg = "Duplicate key: '" + name + "'"; return addErrorAndRecover(msg, tokenName, tokenObjectEnd); } Token colon; if (!readToken(colon) || colon.type_ != tokenMemberSeparator) { return addErrorAndRecover("Missing ':' after object member name", colon, tokenObjectEnd); } Value& value = currentValue()[name]; nodes_.push(&value); bool ok = readValue(); nodes_.pop(); if (!ok) // error already set return recoverFromError(tokenObjectEnd); Token comma; if (!readToken(comma) || (comma.type_ != tokenObjectEnd && comma.type_ != tokenArraySeparator && comma.type_ != tokenComment)) { return addErrorAndRecover("Missing ',' or '}' in object declaration", comma, tokenObjectEnd); } bool finalizeTokenOk = true; while (comma.type_ == tokenComment && finalizeTokenOk) finalizeTokenOk = readToken(comma); if (comma.type_ == tokenObjectEnd) return true; } return addErrorAndRecover("Missing '}' or object member name", tokenName, tokenObjectEnd); } bool OurReader::readArray(Token& token) { Value init(arrayValue); currentValue().swapPayload(init); currentValue().setOffsetStart(token.start_ - begin_); int index = 0; for (;;) { skipSpaces(); if (current_ != end_ && *current_ == ']' && (index == 0 || (features_.allowTrailingCommas_ && !features_.allowDroppedNullPlaceholders_))) // empty array or trailing // comma { Token endArray; readToken(endArray); return true; } Value& value = currentValue()[index++]; nodes_.push(&value); bool ok = readValue(); nodes_.pop(); if (!ok) // error already set return recoverFromError(tokenArrayEnd); Token currentToken; // Accept Comment after last item in the array. ok = readToken(currentToken); while (currentToken.type_ == tokenComment && ok) { ok = readToken(currentToken); } bool badTokenType = (currentToken.type_ != tokenArraySeparator && currentToken.type_ != tokenArrayEnd); if (!ok || badTokenType) { return addErrorAndRecover("Missing ',' or ']' in array declaration", currentToken, tokenArrayEnd); } if (currentToken.type_ == tokenArrayEnd) break; } return true; } bool OurReader::decodeNumber(Token& token) { Value decoded; if (!decodeNumber(token, decoded)) return false; currentValue().swapPayload(decoded); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); return true; } bool OurReader::decodeNumber(Token& token, Value& decoded) { // Attempts to parse the number as an integer. If the number is // larger than the maximum supported value of an integer then // we decode the number as a double. Location current = token.start_; const bool isNegative = *current == '-'; if (isNegative) { ++current; } // We assume we can represent the largest and smallest integer types as // unsigned integers with separate sign. This is only true if they can fit // into an unsigned integer. static_assert(Value::maxLargestInt <= Value::maxLargestUInt, "Int must be smaller than UInt"); // We need to convert minLargestInt into a positive number. The easiest way // to do this conversion is to assume our "threshold" value of minLargestInt // divided by 10 can fit in maxLargestInt when absolute valued. This should // be a safe assumption. static_assert(Value::minLargestInt <= -Value::maxLargestInt, "The absolute value of minLargestInt must be greater than or " "equal to maxLargestInt"); static_assert(Value::minLargestInt / 10 >= -Value::maxLargestInt, "The absolute value of minLargestInt must be only 1 magnitude " "larger than maxLargest Int"); static constexpr Value::LargestUInt positive_threshold = Value::maxLargestUInt / 10; static constexpr Value::UInt positive_last_digit = Value::maxLargestUInt % 10; // For the negative values, we have to be more careful. Since typically // -Value::minLargestInt will cause an overflow, we first divide by 10 and // then take the inverse. This assumes that minLargestInt is only a single // power of 10 different in magnitude, which we check above. For the last // digit, we take the modulus before negating for the same reason. static constexpr auto negative_threshold = Value::LargestUInt(-(Value::minLargestInt / 10)); static constexpr auto negative_last_digit = Value::UInt(-(Value::minLargestInt % 10)); const Value::LargestUInt threshold = isNegative ? negative_threshold : positive_threshold; const Value::UInt max_last_digit = isNegative ? negative_last_digit : positive_last_digit; Value::LargestUInt value = 0; while (current < token.end_) { Char c = *current++; if (c < '0' || c > '9') return decodeDouble(token, decoded); const auto digit(static_cast<Value::UInt>(c - '0')); if (value >= threshold) { // We've hit or exceeded the max value divided by 10 (rounded down). If // a) we've only just touched the limit, meaing value == threshold, // b) this is the last digit, or // c) it's small enough to fit in that rounding delta, we're okay. // Otherwise treat this number as a double to avoid overflow. if (value > threshold || current != token.end_ || digit > max_last_digit) { return decodeDouble(token, decoded); } } value = value * 10 + digit; } if (isNegative) { // We use the same magnitude assumption here, just in case. const auto last_digit = static_cast<Value::UInt>(value % 10); decoded = -Value::LargestInt(value / 10) * 10 - last_digit; } else if (value <= Value::LargestUInt(Value::maxLargestInt)) { decoded = Value::LargestInt(value); } else { decoded = value; } return true; } bool OurReader::decodeDouble(Token& token) { Value decoded; if (!decodeDouble(token, decoded)) return false; currentValue().swapPayload(decoded); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); return true; } bool OurReader::decodeDouble(Token& token, Value& decoded) { double value = 0; const String buffer(token.start_, token.end_); IStringStream is(buffer); if (!(is >> value)) { return addError( "'" + String(token.start_, token.end_) + "' is not a number.", token); } decoded = value; return true; } bool OurReader::decodeString(Token& token) { String decoded_string; if (!decodeString(token, decoded_string)) return false; Value decoded(decoded_string); currentValue().swapPayload(decoded); currentValue().setOffsetStart(token.start_ - begin_); currentValue().setOffsetLimit(token.end_ - begin_); return true; } bool OurReader::decodeString(Token& token, String& decoded) { decoded.reserve(static_cast<size_t>(token.end_ - token.start_ - 2)); Location current = token.start_ + 1; // skip '"' Location end = token.end_ - 1; // do not include '"' while (current != end) { Char c = *current++; if (c == '"') break; if (c == '\\') { if (current == end) return addError("Empty escape sequence in string", token, current); Char escape = *current++; switch (escape) { case '"': decoded += '"'; break; case '/': decoded += '/'; break; case '\\': decoded += '\\'; break; case 'b': decoded += '\b'; break; case 'f': decoded += '\f'; break; case 'n': decoded += '\n'; break; case 'r': decoded += '\r'; break; case 't': decoded += '\t'; break; case 'u': { unsigned int unicode; if (!decodeUnicodeCodePoint(token, current, end, unicode)) return false; decoded += codePointToUTF8(unicode); } break; default: return addError("Bad escape sequence in string", token, current); } } else { decoded += c; } } return true; } bool OurReader::decodeUnicodeCodePoint(Token& token, Location& current, Location end, unsigned int& unicode) { if (!decodeUnicodeEscapeSequence(token, current, end, unicode)) return false; if (unicode >= 0xD800 && unicode <= 0xDBFF) { // surrogate pairs if (end - current < 6) return addError( "additional six characters expected to parse unicode surrogate pair.", token, current); if (*(current++) == '\\' && *(current++) == 'u') { unsigned int surrogatePair; if (decodeUnicodeEscapeSequence(token, current, end, surrogatePair)) { unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF); } else return false; } else return addError("expecting another \\u token to begin the second half of " "a unicode surrogate pair", token, current); } return true; } bool OurReader::decodeUnicodeEscapeSequence(Token& token, Location& current, Location end, unsigned int& ret_unicode) { if (end - current < 4) return addError( "Bad unicode escape sequence in string: four digits expected.", token, current); int unicode = 0; for (int index = 0; index < 4; ++index) { Char c = *current++; unicode *= 16; if (c >= '0' && c <= '9') unicode += c - '0'; else if (c >= 'a' && c <= 'f') unicode += c - 'a' + 10; else if (c >= 'A' && c <= 'F') unicode += c - 'A' + 10; else return addError( "Bad unicode escape sequence in string: hexadecimal digit expected.", token, current); } ret_unicode = static_cast<unsigned int>(unicode); return true; } bool OurReader::addError(const String& message, Token& token, Location extra) { ErrorInfo info; info.token_ = token; info.message_ = message; info.extra_ = extra; errors_.push_back(info); return false; } bool OurReader::recoverFromError(TokenType skipUntilToken) { size_t errorCount = errors_.size(); Token skip; for (;;) { if (!readToken(skip)) errors_.resize(errorCount); // discard errors caused by recovery if (skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream) break; } errors_.resize(errorCount); return false; } bool OurReader::addErrorAndRecover(const String& message, Token& token, TokenType skipUntilToken) { addError(message, token); return recoverFromError(skipUntilToken); } Value& OurReader::currentValue() { return *(nodes_.top()); } OurReader::Char OurReader::getNextChar() { if (current_ == end_) return 0; return *current_++; } void OurReader::getLocationLineAndColumn(Location location, int& line, int& column) const { Location current = begin_; Location lastLineStart = current; line = 0; while (current < location && current != end_) { Char c = *current++; if (c == '\r') { if (*current == '\n') ++current; lastLineStart = current; ++line; } else if (c == '\n') { lastLineStart = current; ++line; } } // column & line start at 1 column = int(location - lastLineStart) + 1; ++line; } String OurReader::getLocationLineAndColumn(Location location) const { int line, column; getLocationLineAndColumn(location, line, column); char buffer[18 + 16 + 16 + 1]; jsoncpp_snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column); return buffer; } String OurReader::getFormattedErrorMessages() const { String formattedMessage; for (const auto& error : errors_) { formattedMessage += "* " + getLocationLineAndColumn(error.token_.start_) + "\n"; formattedMessage += " " + error.message_ + "\n"; if (error.extra_) formattedMessage += "See " + getLocationLineAndColumn(error.extra_) + " for detail.\n"; } return formattedMessage; } std::vector<OurReader::StructuredError> OurReader::getStructuredErrors() const { std::vector<OurReader::StructuredError> allErrors; for (const auto& error : errors_) { OurReader::StructuredError structured; structured.offset_start = error.token_.start_ - begin_; structured.offset_limit = error.token_.end_ - begin_; structured.message = error.message_; allErrors.push_back(structured); } return allErrors; } class OurCharReader : public CharReader { bool const collectComments_; OurReader reader_; public: OurCharReader(bool collectComments, OurFeatures const& features) : collectComments_(collectComments), reader_(features) {} bool parse(char const* beginDoc, char const* endDoc, Value* root, String* errs) override { bool ok = reader_.parse(beginDoc, endDoc, *root, collectComments_); if (errs) { *errs = reader_.getFormattedErrorMessages(); } return ok; } }; CharReaderBuilder::CharReaderBuilder() { setDefaults(&settings_); } CharReaderBuilder::~CharReaderBuilder() = default; CharReader* CharReaderBuilder::newCharReader() const { bool collectComments = settings_["collectComments"].asBool(); OurFeatures features = OurFeatures::all(); features.allowComments_ = settings_["allowComments"].asBool(); features.allowTrailingCommas_ = settings_["allowTrailingCommas"].asBool(); features.strictRoot_ = settings_["strictRoot"].asBool(); features.allowDroppedNullPlaceholders_ = settings_["allowDroppedNullPlaceholders"].asBool(); features.allowNumericKeys_ = settings_["allowNumericKeys"].asBool(); features.allowSingleQuotes_ = settings_["allowSingleQuotes"].asBool(); // Stack limit is always a size_t, so we get this as an unsigned int // regardless of it we have 64-bit integer support enabled. features.stackLimit_ = static_cast<size_t>(settings_["stackLimit"].asUInt()); features.failIfExtra_ = settings_["failIfExtra"].asBool(); features.rejectDupKeys_ = settings_["rejectDupKeys"].asBool(); features.allowSpecialFloats_ = settings_["allowSpecialFloats"].asBool(); return new OurCharReader(collectComments, features); } static void getValidReaderKeys(std::set<String>* valid_keys) { valid_keys->clear(); valid_keys->insert("collectComments"); valid_keys->insert("allowComments"); valid_keys->insert("allowTrailingCommas"); valid_keys->insert("strictRoot"); valid_keys->insert("allowDroppedNullPlaceholders"); valid_keys->insert("allowNumericKeys"); valid_keys->insert("allowSingleQuotes"); valid_keys->insert("stackLimit"); valid_keys->insert("failIfExtra"); valid_keys->insert("rejectDupKeys"); valid_keys->insert("allowSpecialFloats"); } bool CharReaderBuilder::validate(Json::Value* invalid) const { Json::Value my_invalid; if (!invalid) invalid = &my_invalid; // so we do not need to test for NULL Json::Value& inv = *invalid; std::set<String> valid_keys; getValidReaderKeys(&valid_keys); Value::Members keys = settings_.getMemberNames(); size_t n = keys.size(); for (size_t i = 0; i < n; ++i) { String const& key = keys[i]; if (valid_keys.find(key) == valid_keys.end()) { inv[key] = settings_[key]; } } return inv.empty(); } Value& CharReaderBuilder::operator[](const String& key) { return settings_[key]; } // static void CharReaderBuilder::strictMode(Json::Value* settings) { //! [CharReaderBuilderStrictMode] (*settings)["allowComments"] = false; (*settings)["allowTrailingCommas"] = false; (*settings)["strictRoot"] = true; (*settings)["allowDroppedNullPlaceholders"] = false; (*settings)["allowNumericKeys"] = false; (*settings)["allowSingleQuotes"] = false; (*settings)["stackLimit"] = 1000; (*settings)["failIfExtra"] = true; (*settings)["rejectDupKeys"] = true; (*settings)["allowSpecialFloats"] = false; //! [CharReaderBuilderStrictMode] } // static void CharReaderBuilder::setDefaults(Json::Value* settings) { //! [CharReaderBuilderDefaults] (*settings)["collectComments"] = true; (*settings)["allowComments"] = true; (*settings)["allowTrailingCommas"] = true; (*settings)["strictRoot"] = false; (*settings)["allowDroppedNullPlaceholders"] = false; (*settings)["allowNumericKeys"] = false; (*settings)["allowSingleQuotes"] = false; (*settings)["stackLimit"] = 1000; (*settings)["failIfExtra"] = false; (*settings)["rejectDupKeys"] = false; (*settings)["allowSpecialFloats"] = false; //! [CharReaderBuilderDefaults] } ////////////////////////////////// // global functions bool parseFromStream(CharReader::Factory const& fact, IStream& sin, Value* root, String* errs) { OStringStream ssin; ssin << sin.rdbuf(); String doc = ssin.str(); char const* begin = doc.data(); char const* end = begin + doc.size(); // Note that we do not actually need a null-terminator. CharReaderPtr const reader(fact.newCharReader()); return reader->parse(begin, end, root, errs); } IStream& operator>>(IStream& sin, Value& root) { CharReaderBuilder b; String errs; bool ok = parseFromStream(b, sin, &root, &errs); if (!ok) { throwRuntimeError(errs); } return sin; } } // namespace Json
C++
3D
mcellteam/mcell
libs/jsoncpp/src/lib_json/json_writer.cpp
.cpp
37,920
1,261
// Copyright 2011 Baptiste Lepilleur and The JsonCpp Authors // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #if !defined(JSON_IS_AMALGAMATION) #include "json_tool.h" #include <json/writer.h> #endif // if !defined(JSON_IS_AMALGAMATION) #include <cassert> #include <cstring> #include <iomanip> #include <memory> #include <set> #include <sstream> #include <utility> #if __cplusplus >= 201103L #include <cmath> #include <cstdio> #if !defined(isnan) #define isnan std::isnan #endif #if !defined(isfinite) #define isfinite std::isfinite #endif #else #include <cmath> #include <cstdio> #if defined(_MSC_VER) #if !defined(isnan) #include <float.h> #define isnan _isnan #endif #if !defined(isfinite) #include <float.h> #define isfinite _finite #endif #if !defined(_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES) #define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1 #endif //_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES #endif //_MSC_VER #if defined(__sun) && defined(__SVR4) // Solaris #if !defined(isfinite) #include <ieeefp.h> #define isfinite finite #endif #endif #if defined(__hpux) #if !defined(isfinite) #if defined(__ia64) && !defined(finite) #define isfinite(x) \ ((sizeof(x) == sizeof(float) ? _Isfinitef(x) : _IsFinite(x))) #endif #endif #endif #if !defined(isnan) // IEEE standard states that NaN values will not compare to themselves #define isnan(x) (x != x) #endif #if !defined(__APPLE__) #if !defined(isfinite) #define isfinite finite #endif #endif #endif #if defined(_MSC_VER) // Disable warning about strdup being deprecated. #pragma warning(disable : 4996) #endif namespace Json { #if __cplusplus >= 201103L || (defined(_CPPLIB_VER) && _CPPLIB_VER >= 520) using StreamWriterPtr = std::unique_ptr<StreamWriter>; #else using StreamWriterPtr = std::auto_ptr<StreamWriter>; #endif String valueToString(LargestInt value) { UIntToStringBuffer buffer; char* current = buffer + sizeof(buffer); if (value == Value::minLargestInt) { uintToString(LargestUInt(Value::maxLargestInt) + 1, current); *--current = '-'; } else if (value < 0) { uintToString(LargestUInt(-value), current); *--current = '-'; } else { uintToString(LargestUInt(value), current); } assert(current >= buffer); return current; } String valueToString(LargestUInt value) { UIntToStringBuffer buffer; char* current = buffer + sizeof(buffer); uintToString(value, current); assert(current >= buffer); return current; } #if defined(JSON_HAS_INT64) String valueToString(Int value) { return valueToString(LargestInt(value)); } String valueToString(UInt value) { return valueToString(LargestUInt(value)); } #endif // # if defined(JSON_HAS_INT64) namespace { String valueToString(double value, bool useSpecialFloats, unsigned int precision, PrecisionType precisionType) { // Print into the buffer. We need not request the alternative representation // that always has a decimal point because JSON doesn't distinguish the // concepts of reals and integers. if (!isfinite(value)) { static const char* const reps[2][3] = {{"NaN", "-Infinity", "Infinity"}, {"null", "-1e+9999", "1e+9999"}}; return reps[useSpecialFloats ? 0 : 1] [isnan(value) ? 0 : (value < 0) ? 1 : 2]; } String buffer(size_t(36), '\0'); while (true) { int len = jsoncpp_snprintf( &*buffer.begin(), buffer.size(), (precisionType == PrecisionType::significantDigits) ? "%.*g" : "%.*f", precision, value); assert(len >= 0); auto wouldPrint = static_cast<size_t>(len); if (wouldPrint >= buffer.size()) { buffer.resize(wouldPrint + 1); continue; } buffer.resize(wouldPrint); break; } buffer.erase(fixNumericLocale(buffer.begin(), buffer.end()), buffer.end()); // strip the zero padding from the right if (precisionType == PrecisionType::decimalPlaces) { buffer.erase(fixZerosInTheEnd(buffer.begin(), buffer.end()), buffer.end()); } // try to ensure we preserve the fact that this was given to us as a double on // input if (buffer.find('.') == buffer.npos && buffer.find('e') == buffer.npos) { buffer += ".0"; } return buffer; } } // namespace String valueToString(double value, unsigned int precision, PrecisionType precisionType) { return valueToString(value, false, precision, precisionType); } String valueToString(bool value) { return value ? "true" : "false"; } static bool isAnyCharRequiredQuoting(char const* s, size_t n) { assert(s || !n); char const* const end = s + n; for (char const* cur = s; cur < end; ++cur) { if (*cur == '\\' || *cur == '\"' || static_cast<unsigned char>(*cur) < ' ' || static_cast<unsigned char>(*cur) >= 0x80) return true; } return false; } static unsigned int utf8ToCodepoint(const char*& s, const char* e) { const unsigned int REPLACEMENT_CHARACTER = 0xFFFD; unsigned int firstByte = static_cast<unsigned char>(*s); if (firstByte < 0x80) return firstByte; if (firstByte < 0xE0) { if (e - s < 2) return REPLACEMENT_CHARACTER; unsigned int calculated = ((firstByte & 0x1F) << 6) | (static_cast<unsigned int>(s[1]) & 0x3F); s += 1; // oversized encoded characters are invalid return calculated < 0x80 ? REPLACEMENT_CHARACTER : calculated; } if (firstByte < 0xF0) { if (e - s < 3) return REPLACEMENT_CHARACTER; unsigned int calculated = ((firstByte & 0x0F) << 12) | ((static_cast<unsigned int>(s[1]) & 0x3F) << 6) | (static_cast<unsigned int>(s[2]) & 0x3F); s += 2; // surrogates aren't valid codepoints itself // shouldn't be UTF-8 encoded if (calculated >= 0xD800 && calculated <= 0xDFFF) return REPLACEMENT_CHARACTER; // oversized encoded characters are invalid return calculated < 0x800 ? REPLACEMENT_CHARACTER : calculated; } if (firstByte < 0xF8) { if (e - s < 4) return REPLACEMENT_CHARACTER; unsigned int calculated = ((firstByte & 0x07) << 18) | ((static_cast<unsigned int>(s[1]) & 0x3F) << 12) | ((static_cast<unsigned int>(s[2]) & 0x3F) << 6) | (static_cast<unsigned int>(s[3]) & 0x3F); s += 3; // oversized encoded characters are invalid return calculated < 0x10000 ? REPLACEMENT_CHARACTER : calculated; } return REPLACEMENT_CHARACTER; } static const char hex2[] = "000102030405060708090a0b0c0d0e0f" "101112131415161718191a1b1c1d1e1f" "202122232425262728292a2b2c2d2e2f" "303132333435363738393a3b3c3d3e3f" "404142434445464748494a4b4c4d4e4f" "505152535455565758595a5b5c5d5e5f" "606162636465666768696a6b6c6d6e6f" "707172737475767778797a7b7c7d7e7f" "808182838485868788898a8b8c8d8e8f" "909192939495969798999a9b9c9d9e9f" "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf" "b0b1b2b3b4b5b6b7b8b9babbbcbdbebf" "c0c1c2c3c4c5c6c7c8c9cacbcccdcecf" "d0d1d2d3d4d5d6d7d8d9dadbdcdddedf" "e0e1e2e3e4e5e6e7e8e9eaebecedeeef" "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"; static String toHex16Bit(unsigned int x) { const unsigned int hi = (x >> 8) & 0xff; const unsigned int lo = x & 0xff; String result(4, ' '); result[0] = hex2[2 * hi]; result[1] = hex2[2 * hi + 1]; result[2] = hex2[2 * lo]; result[3] = hex2[2 * lo + 1]; return result; } static String valueToQuotedStringN(const char* value, unsigned length, bool emitUTF8 = false) { if (value == nullptr) return ""; if (!isAnyCharRequiredQuoting(value, length)) return String("\"") + value + "\""; // We have to walk value and escape any special characters. // Appending to String is not efficient, but this should be rare. // (Note: forward slashes are *not* rare, but I am not escaping them.) String::size_type maxsize = length * 2 + 3; // allescaped+quotes+NULL String result; result.reserve(maxsize); // to avoid lots of mallocs result += "\""; char const* end = value + length; for (const char* c = value; c != end; ++c) { switch (*c) { case '\"': result += "\\\""; break; case '\\': result += "\\\\"; break; case '\b': result += "\\b"; break; case '\f': result += "\\f"; break; case '\n': result += "\\n"; break; case '\r': result += "\\r"; break; case '\t': result += "\\t"; break; // case '/': // Even though \/ is considered a legal escape in JSON, a bare // slash is also legal, so I see no reason to escape it. // (I hope I am not misunderstanding something.) // blep notes: actually escaping \/ may be useful in javascript to avoid </ // sequence. // Should add a flag to allow this compatibility mode and prevent this // sequence from occurring. default: { if (emitUTF8) { result += *c; } else { unsigned int codepoint = utf8ToCodepoint(c, end); const unsigned int FIRST_NON_CONTROL_CODEPOINT = 0x20; const unsigned int LAST_NON_CONTROL_CODEPOINT = 0x7F; const unsigned int FIRST_SURROGATE_PAIR_CODEPOINT = 0x10000; // don't escape non-control characters // (short escape sequence are applied above) if (FIRST_NON_CONTROL_CODEPOINT <= codepoint && codepoint <= LAST_NON_CONTROL_CODEPOINT) { result += static_cast<char>(codepoint); } else if (codepoint < FIRST_SURROGATE_PAIR_CODEPOINT) { // codepoint is in Basic // Multilingual Plane result += "\\u"; result += toHex16Bit(codepoint); } else { // codepoint is not in Basic Multilingual Plane // convert to surrogate pair first codepoint -= FIRST_SURROGATE_PAIR_CODEPOINT; result += "\\u"; result += toHex16Bit((codepoint >> 10) + 0xD800); result += "\\u"; result += toHex16Bit((codepoint & 0x3FF) + 0xDC00); } } } break; } } result += "\""; return result; } String valueToQuotedString(const char* value) { return valueToQuotedStringN(value, static_cast<unsigned int>(strlen(value))); } // Class Writer // ////////////////////////////////////////////////////////////////// Writer::~Writer() = default; // Class FastWriter // ////////////////////////////////////////////////////////////////// FastWriter::FastWriter() = default; void FastWriter::enableYAMLCompatibility() { yamlCompatibilityEnabled_ = true; } void FastWriter::dropNullPlaceholders() { dropNullPlaceholders_ = true; } void FastWriter::omitEndingLineFeed() { omitEndingLineFeed_ = true; } String FastWriter::write(const Value& root) { document_.clear(); writeValue(root); if (!omitEndingLineFeed_) document_ += '\n'; return document_; } void FastWriter::writeValue(const Value& value) { switch (value.type()) { case nullValue: if (!dropNullPlaceholders_) document_ += "null"; break; case intValue: document_ += valueToString(value.asLargestInt()); break; case uintValue: document_ += valueToString(value.asLargestUInt()); break; case realValue: document_ += valueToString(value.asDouble()); break; case stringValue: { // Is NULL possible for value.string_? No. char const* str; char const* end; bool ok = value.getString(&str, &end); if (ok) document_ += valueToQuotedStringN(str, static_cast<unsigned>(end - str)); break; } case booleanValue: document_ += valueToString(value.asBool()); break; case arrayValue: { document_ += '['; ArrayIndex size = value.size(); for (ArrayIndex index = 0; index < size; ++index) { if (index > 0) document_ += ','; writeValue(value[index]); } document_ += ']'; } break; case objectValue: { Value::Members members(value.getMemberNames()); document_ += '{'; for (auto it = members.begin(); it != members.end(); ++it) { const String& name = *it; if (it != members.begin()) document_ += ','; document_ += valueToQuotedStringN(name.data(), static_cast<unsigned>(name.length())); document_ += yamlCompatibilityEnabled_ ? ": " : ":"; writeValue(value[name]); } document_ += '}'; } break; } } // Class StyledWriter // ////////////////////////////////////////////////////////////////// StyledWriter::StyledWriter() = default; String StyledWriter::write(const Value& root) { document_.clear(); addChildValues_ = false; indentString_.clear(); writeCommentBeforeValue(root); writeValue(root); writeCommentAfterValueOnSameLine(root); document_ += '\n'; return document_; } void StyledWriter::writeValue(const Value& value) { switch (value.type()) { case nullValue: pushValue("null"); break; case intValue: pushValue(valueToString(value.asLargestInt())); break; case uintValue: pushValue(valueToString(value.asLargestUInt())); break; case realValue: pushValue(valueToString(value.asDouble())); break; case stringValue: { // Is NULL possible for value.string_? No. char const* str; char const* end; bool ok = value.getString(&str, &end); if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end - str))); else pushValue(""); break; } case booleanValue: pushValue(valueToString(value.asBool())); break; case arrayValue: writeArrayValue(value); break; case objectValue: { Value::Members members(value.getMemberNames()); if (members.empty()) pushValue("{}"); else { writeWithIndent("{"); indent(); auto it = members.begin(); for (;;) { const String& name = *it; const Value& childValue = value[name]; writeCommentBeforeValue(childValue); writeWithIndent(valueToQuotedString(name.c_str())); document_ += " : "; writeValue(childValue); if (++it == members.end()) { writeCommentAfterValueOnSameLine(childValue); break; } document_ += ','; writeCommentAfterValueOnSameLine(childValue); } unindent(); writeWithIndent("}"); } } break; } } void StyledWriter::writeArrayValue(const Value& value) { unsigned size = value.size(); if (size == 0) pushValue("[]"); else { bool isArrayMultiLine = isMultilineArray(value); if (isArrayMultiLine) { writeWithIndent("["); indent(); bool hasChildValue = !childValues_.empty(); unsigned index = 0; for (;;) { const Value& childValue = value[index]; writeCommentBeforeValue(childValue); if (hasChildValue) writeWithIndent(childValues_[index]); else { writeIndent(); writeValue(childValue); } if (++index == size) { writeCommentAfterValueOnSameLine(childValue); break; } document_ += ','; writeCommentAfterValueOnSameLine(childValue); } unindent(); writeWithIndent("]"); } else // output on a single line { assert(childValues_.size() == size); document_ += "[ "; for (unsigned index = 0; index < size; ++index) { if (index > 0) document_ += ", "; document_ += childValues_[index]; } document_ += " ]"; } } } bool StyledWriter::isMultilineArray(const Value& value) { ArrayIndex const size = value.size(); bool isMultiLine = size * 3 >= rightMargin_; childValues_.clear(); for (ArrayIndex index = 0; index < size && !isMultiLine; ++index) { const Value& childValue = value[index]; isMultiLine = ((childValue.isArray() || childValue.isObject()) && !childValue.empty()); } if (!isMultiLine) // check if line length > max line length { childValues_.reserve(size); addChildValues_ = true; ArrayIndex lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]' for (ArrayIndex index = 0; index < size; ++index) { if (hasCommentForValue(value[index])) { isMultiLine = true; } writeValue(value[index]); lineLength += static_cast<ArrayIndex>(childValues_[index].length()); } addChildValues_ = false; isMultiLine = isMultiLine || lineLength >= rightMargin_; } return isMultiLine; } void StyledWriter::pushValue(const String& value) { if (addChildValues_) childValues_.push_back(value); else document_ += value; } void StyledWriter::writeIndent() { if (!document_.empty()) { char last = document_[document_.length() - 1]; if (last == ' ') // already indented return; if (last != '\n') // Comments may add new-line document_ += '\n'; } document_ += indentString_; } void StyledWriter::writeWithIndent(const String& value) { writeIndent(); document_ += value; } void StyledWriter::indent() { indentString_ += String(indentSize_, ' '); } void StyledWriter::unindent() { assert(indentString_.size() >= indentSize_); indentString_.resize(indentString_.size() - indentSize_); } void StyledWriter::writeCommentBeforeValue(const Value& root) { if (!root.hasComment(commentBefore)) return; document_ += '\n'; writeIndent(); const String& comment = root.getComment(commentBefore); String::const_iterator iter = comment.begin(); while (iter != comment.end()) { document_ += *iter; if (*iter == '\n' && ((iter + 1) != comment.end() && *(iter + 1) == '/')) writeIndent(); ++iter; } // Comments are stripped of trailing newlines, so add one here document_ += '\n'; } void StyledWriter::writeCommentAfterValueOnSameLine(const Value& root) { if (root.hasComment(commentAfterOnSameLine)) document_ += " " + root.getComment(commentAfterOnSameLine); if (root.hasComment(commentAfter)) { document_ += '\n'; document_ += root.getComment(commentAfter); document_ += '\n'; } } bool StyledWriter::hasCommentForValue(const Value& value) { return value.hasComment(commentBefore) || value.hasComment(commentAfterOnSameLine) || value.hasComment(commentAfter); } // Class StyledStreamWriter // ////////////////////////////////////////////////////////////////// StyledStreamWriter::StyledStreamWriter(String indentation) : document_(nullptr), indentation_(std::move(indentation)), addChildValues_(), indented_(false) {} void StyledStreamWriter::write(OStream& out, const Value& root) { document_ = &out; addChildValues_ = false; indentString_.clear(); indented_ = true; writeCommentBeforeValue(root); if (!indented_) writeIndent(); indented_ = true; writeValue(root); writeCommentAfterValueOnSameLine(root); *document_ << "\n"; document_ = nullptr; // Forget the stream, for safety. } void StyledStreamWriter::writeValue(const Value& value) { switch (value.type()) { case nullValue: pushValue("null"); break; case intValue: pushValue(valueToString(value.asLargestInt())); break; case uintValue: pushValue(valueToString(value.asLargestUInt())); break; case realValue: pushValue(valueToString(value.asDouble())); break; case stringValue: { // Is NULL possible for value.string_? No. char const* str; char const* end; bool ok = value.getString(&str, &end); if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end - str))); else pushValue(""); break; } case booleanValue: pushValue(valueToString(value.asBool())); break; case arrayValue: writeArrayValue(value); break; case objectValue: { Value::Members members(value.getMemberNames()); if (members.empty()) pushValue("{}"); else { writeWithIndent("{"); indent(); auto it = members.begin(); for (;;) { const String& name = *it; const Value& childValue = value[name]; writeCommentBeforeValue(childValue); writeWithIndent(valueToQuotedString(name.c_str())); *document_ << " : "; writeValue(childValue); if (++it == members.end()) { writeCommentAfterValueOnSameLine(childValue); break; } *document_ << ","; writeCommentAfterValueOnSameLine(childValue); } unindent(); writeWithIndent("}"); } } break; } } void StyledStreamWriter::writeArrayValue(const Value& value) { unsigned size = value.size(); if (size == 0) pushValue("[]"); else { bool isArrayMultiLine = isMultilineArray(value); if (isArrayMultiLine) { writeWithIndent("["); indent(); bool hasChildValue = !childValues_.empty(); unsigned index = 0; for (;;) { const Value& childValue = value[index]; writeCommentBeforeValue(childValue); if (hasChildValue) writeWithIndent(childValues_[index]); else { if (!indented_) writeIndent(); indented_ = true; writeValue(childValue); indented_ = false; } if (++index == size) { writeCommentAfterValueOnSameLine(childValue); break; } *document_ << ","; writeCommentAfterValueOnSameLine(childValue); } unindent(); writeWithIndent("]"); } else // output on a single line { assert(childValues_.size() == size); *document_ << "[ "; for (unsigned index = 0; index < size; ++index) { if (index > 0) *document_ << ", "; *document_ << childValues_[index]; } *document_ << " ]"; } } } bool StyledStreamWriter::isMultilineArray(const Value& value) { ArrayIndex const size = value.size(); bool isMultiLine = size * 3 >= rightMargin_; childValues_.clear(); for (ArrayIndex index = 0; index < size && !isMultiLine; ++index) { const Value& childValue = value[index]; isMultiLine = ((childValue.isArray() || childValue.isObject()) && !childValue.empty()); } if (!isMultiLine) // check if line length > max line length { childValues_.reserve(size); addChildValues_ = true; ArrayIndex lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]' for (ArrayIndex index = 0; index < size; ++index) { if (hasCommentForValue(value[index])) { isMultiLine = true; } writeValue(value[index]); lineLength += static_cast<ArrayIndex>(childValues_[index].length()); } addChildValues_ = false; isMultiLine = isMultiLine || lineLength >= rightMargin_; } return isMultiLine; } void StyledStreamWriter::pushValue(const String& value) { if (addChildValues_) childValues_.push_back(value); else *document_ << value; } void StyledStreamWriter::writeIndent() { // blep intended this to look at the so-far-written string // to determine whether we are already indented, but // with a stream we cannot do that. So we rely on some saved state. // The caller checks indented_. *document_ << '\n' << indentString_; } void StyledStreamWriter::writeWithIndent(const String& value) { if (!indented_) writeIndent(); *document_ << value; indented_ = false; } void StyledStreamWriter::indent() { indentString_ += indentation_; } void StyledStreamWriter::unindent() { assert(indentString_.size() >= indentation_.size()); indentString_.resize(indentString_.size() - indentation_.size()); } void StyledStreamWriter::writeCommentBeforeValue(const Value& root) { if (!root.hasComment(commentBefore)) return; if (!indented_) writeIndent(); const String& comment = root.getComment(commentBefore); String::const_iterator iter = comment.begin(); while (iter != comment.end()) { *document_ << *iter; if (*iter == '\n' && ((iter + 1) != comment.end() && *(iter + 1) == '/')) // writeIndent(); // would include newline *document_ << indentString_; ++iter; } indented_ = false; } void StyledStreamWriter::writeCommentAfterValueOnSameLine(const Value& root) { if (root.hasComment(commentAfterOnSameLine)) *document_ << ' ' << root.getComment(commentAfterOnSameLine); if (root.hasComment(commentAfter)) { writeIndent(); *document_ << root.getComment(commentAfter); } indented_ = false; } bool StyledStreamWriter::hasCommentForValue(const Value& value) { return value.hasComment(commentBefore) || value.hasComment(commentAfterOnSameLine) || value.hasComment(commentAfter); } ////////////////////////// // BuiltStyledStreamWriter /// Scoped enums are not available until C++11. struct CommentStyle { /// Decide whether to write comments. enum Enum { None, ///< Drop all comments. Most, ///< Recover odd behavior of previous versions (not implemented yet). All ///< Keep all comments. }; }; struct BuiltStyledStreamWriter : public StreamWriter { BuiltStyledStreamWriter(String indentation, CommentStyle::Enum cs, String colonSymbol, String nullSymbol, String endingLineFeedSymbol, bool useSpecialFloats, bool emitUTF8, unsigned int precision, PrecisionType precisionType); int write(Value const& root, OStream* sout) override; private: void writeValue(Value const& value); void writeArrayValue(Value const& value); bool isMultilineArray(Value const& value); void pushValue(String const& value); void writeIndent(); void writeWithIndent(String const& value); void indent(); void unindent(); void writeCommentBeforeValue(Value const& root); void writeCommentAfterValueOnSameLine(Value const& root); static bool hasCommentForValue(const Value& value); using ChildValues = std::vector<String>; ChildValues childValues_; String indentString_; unsigned int rightMargin_; String indentation_; CommentStyle::Enum cs_; String colonSymbol_; String nullSymbol_; String endingLineFeedSymbol_; bool addChildValues_ : 1; bool indented_ : 1; bool useSpecialFloats_ : 1; bool emitUTF8_ : 1; unsigned int precision_; PrecisionType precisionType_; }; BuiltStyledStreamWriter::BuiltStyledStreamWriter( String indentation, CommentStyle::Enum cs, String colonSymbol, String nullSymbol, String endingLineFeedSymbol, bool useSpecialFloats, bool emitUTF8, unsigned int precision, PrecisionType precisionType) : rightMargin_(74), indentation_(std::move(indentation)), cs_(cs), colonSymbol_(std::move(colonSymbol)), nullSymbol_(std::move(nullSymbol)), endingLineFeedSymbol_(std::move(endingLineFeedSymbol)), addChildValues_(false), indented_(false), useSpecialFloats_(useSpecialFloats), emitUTF8_(emitUTF8), precision_(precision), precisionType_(precisionType) {} int BuiltStyledStreamWriter::write(Value const& root, OStream* sout) { sout_ = sout; addChildValues_ = false; indented_ = true; indentString_.clear(); writeCommentBeforeValue(root); if (!indented_) writeIndent(); indented_ = true; writeValue(root); writeCommentAfterValueOnSameLine(root); *sout_ << endingLineFeedSymbol_; sout_ = nullptr; return 0; } void BuiltStyledStreamWriter::writeValue(Value const& value) { switch (value.type()) { case nullValue: pushValue(nullSymbol_); break; case intValue: pushValue(valueToString(value.asLargestInt())); break; case uintValue: pushValue(valueToString(value.asLargestUInt())); break; case realValue: pushValue(valueToString(value.asDouble(), useSpecialFloats_, precision_, precisionType_)); break; case stringValue: { // Is NULL is possible for value.string_? No. char const* str; char const* end; bool ok = value.getString(&str, &end); if (ok) pushValue(valueToQuotedStringN(str, static_cast<unsigned>(end - str), emitUTF8_)); else pushValue(""); break; } case booleanValue: pushValue(valueToString(value.asBool())); break; case arrayValue: writeArrayValue(value); break; case objectValue: { Value::Members members(value.getMemberNames()); if (members.empty()) pushValue("{}"); else { writeWithIndent("{"); indent(); auto it = members.begin(); for (;;) { String const& name = *it; Value const& childValue = value[name]; writeCommentBeforeValue(childValue); writeWithIndent(valueToQuotedStringN( name.data(), static_cast<unsigned>(name.length()), emitUTF8_)); *sout_ << colonSymbol_; writeValue(childValue); if (++it == members.end()) { writeCommentAfterValueOnSameLine(childValue); break; } *sout_ << ","; writeCommentAfterValueOnSameLine(childValue); } unindent(); writeWithIndent("}"); } } break; } } void BuiltStyledStreamWriter::writeArrayValue(Value const& value) { unsigned size = value.size(); if (size == 0) pushValue("[]"); else { bool isMultiLine = (cs_ == CommentStyle::All) || isMultilineArray(value); if (isMultiLine) { writeWithIndent("["); indent(); bool hasChildValue = !childValues_.empty(); unsigned index = 0; for (;;) { Value const& childValue = value[index]; writeCommentBeforeValue(childValue); if (hasChildValue) writeWithIndent(childValues_[index]); else { if (!indented_) writeIndent(); indented_ = true; writeValue(childValue); indented_ = false; } if (++index == size) { writeCommentAfterValueOnSameLine(childValue); break; } *sout_ << ","; writeCommentAfterValueOnSameLine(childValue); } unindent(); writeWithIndent("]"); } else // output on a single line { assert(childValues_.size() == size); *sout_ << "["; if (!indentation_.empty()) *sout_ << " "; for (unsigned index = 0; index < size; ++index) { if (index > 0) *sout_ << ((!indentation_.empty()) ? ", " : ","); *sout_ << childValues_[index]; } if (!indentation_.empty()) *sout_ << " "; *sout_ << "]"; } } } bool BuiltStyledStreamWriter::isMultilineArray(Value const& value) { ArrayIndex const size = value.size(); bool isMultiLine = size * 3 >= rightMargin_; childValues_.clear(); for (ArrayIndex index = 0; index < size && !isMultiLine; ++index) { Value const& childValue = value[index]; isMultiLine = ((childValue.isArray() || childValue.isObject()) && !childValue.empty()); } if (!isMultiLine) // check if line length > max line length { childValues_.reserve(size); addChildValues_ = true; ArrayIndex lineLength = 4 + (size - 1) * 2; // '[ ' + ', '*n + ' ]' for (ArrayIndex index = 0; index < size; ++index) { if (hasCommentForValue(value[index])) { isMultiLine = true; } writeValue(value[index]); lineLength += static_cast<ArrayIndex>(childValues_[index].length()); } addChildValues_ = false; isMultiLine = isMultiLine || lineLength >= rightMargin_; } return isMultiLine; } void BuiltStyledStreamWriter::pushValue(String const& value) { if (addChildValues_) childValues_.push_back(value); else *sout_ << value; } void BuiltStyledStreamWriter::writeIndent() { // blep intended this to look at the so-far-written string // to determine whether we are already indented, but // with a stream we cannot do that. So we rely on some saved state. // The caller checks indented_. if (!indentation_.empty()) { // In this case, drop newlines too. *sout_ << '\n' << indentString_; } } void BuiltStyledStreamWriter::writeWithIndent(String const& value) { if (!indented_) writeIndent(); *sout_ << value; indented_ = false; } void BuiltStyledStreamWriter::indent() { indentString_ += indentation_; } void BuiltStyledStreamWriter::unindent() { assert(indentString_.size() >= indentation_.size()); indentString_.resize(indentString_.size() - indentation_.size()); } void BuiltStyledStreamWriter::writeCommentBeforeValue(Value const& root) { if (cs_ == CommentStyle::None) return; if (!root.hasComment(commentBefore)) return; if (!indented_) writeIndent(); const String& comment = root.getComment(commentBefore); String::const_iterator iter = comment.begin(); while (iter != comment.end()) { *sout_ << *iter; if (*iter == '\n' && ((iter + 1) != comment.end() && *(iter + 1) == '/')) // writeIndent(); // would write extra newline *sout_ << indentString_; ++iter; } indented_ = false; } void BuiltStyledStreamWriter::writeCommentAfterValueOnSameLine( Value const& root) { if (cs_ == CommentStyle::None) return; if (root.hasComment(commentAfterOnSameLine)) *sout_ << " " + root.getComment(commentAfterOnSameLine); if (root.hasComment(commentAfter)) { writeIndent(); *sout_ << root.getComment(commentAfter); } } // static bool BuiltStyledStreamWriter::hasCommentForValue(const Value& value) { return value.hasComment(commentBefore) || value.hasComment(commentAfterOnSameLine) || value.hasComment(commentAfter); } /////////////// // StreamWriter StreamWriter::StreamWriter() : sout_(nullptr) {} StreamWriter::~StreamWriter() = default; StreamWriter::Factory::~Factory() = default; StreamWriterBuilder::StreamWriterBuilder() { setDefaults(&settings_); } StreamWriterBuilder::~StreamWriterBuilder() = default; StreamWriter* StreamWriterBuilder::newStreamWriter() const { const String indentation = settings_["indentation"].asString(); const String cs_str = settings_["commentStyle"].asString(); const String pt_str = settings_["precisionType"].asString(); const bool eyc = settings_["enableYAMLCompatibility"].asBool(); const bool dnp = settings_["dropNullPlaceholders"].asBool(); const bool usf = settings_["useSpecialFloats"].asBool(); const bool emitUTF8 = settings_["emitUTF8"].asBool(); unsigned int pre = settings_["precision"].asUInt(); CommentStyle::Enum cs = CommentStyle::All; if (cs_str == "All") { cs = CommentStyle::All; } else if (cs_str == "None") { cs = CommentStyle::None; } else { throwRuntimeError("commentStyle must be 'All' or 'None'"); } PrecisionType precisionType(significantDigits); if (pt_str == "significant") { precisionType = PrecisionType::significantDigits; } else if (pt_str == "decimal") { precisionType = PrecisionType::decimalPlaces; } else { throwRuntimeError("precisionType must be 'significant' or 'decimal'"); } String colonSymbol = " : "; if (eyc) { colonSymbol = ": "; } else if (indentation.empty()) { colonSymbol = ":"; } String nullSymbol = "null"; if (dnp) { nullSymbol.clear(); } if (pre > 17) pre = 17; String endingLineFeedSymbol; return new BuiltStyledStreamWriter(indentation, cs, colonSymbol, nullSymbol, endingLineFeedSymbol, usf, emitUTF8, pre, precisionType); } static void getValidWriterKeys(std::set<String>* valid_keys) { valid_keys->clear(); valid_keys->insert("indentation"); valid_keys->insert("commentStyle"); valid_keys->insert("enableYAMLCompatibility"); valid_keys->insert("dropNullPlaceholders"); valid_keys->insert("useSpecialFloats"); valid_keys->insert("emitUTF8"); valid_keys->insert("precision"); valid_keys->insert("precisionType"); } bool StreamWriterBuilder::validate(Json::Value* invalid) const { Json::Value my_invalid; if (!invalid) invalid = &my_invalid; // so we do not need to test for NULL Json::Value& inv = *invalid; std::set<String> valid_keys; getValidWriterKeys(&valid_keys); Value::Members keys = settings_.getMemberNames(); size_t n = keys.size(); for (size_t i = 0; i < n; ++i) { String const& key = keys[i]; if (valid_keys.find(key) == valid_keys.end()) { inv[key] = settings_[key]; } } return inv.empty(); } Value& StreamWriterBuilder::operator[](const String& key) { return settings_[key]; } // static void StreamWriterBuilder::setDefaults(Json::Value* settings) { //! [StreamWriterBuilderDefaults] (*settings)["commentStyle"] = "All"; (*settings)["indentation"] = "\t"; (*settings)["enableYAMLCompatibility"] = false; (*settings)["dropNullPlaceholders"] = false; (*settings)["useSpecialFloats"] = false; (*settings)["emitUTF8"] = false; (*settings)["precision"] = 17; (*settings)["precisionType"] = "significant"; //! [StreamWriterBuilderDefaults] } String writeString(StreamWriter::Factory const& factory, Value const& root) { OStringStream sout; StreamWriterPtr const writer(factory.newStreamWriter()); writer->write(root, &sout); return sout.str(); } OStream& operator<<(OStream& sout, Value const& root) { StreamWriterBuilder builder; StreamWriterPtr const writer(builder.newStreamWriter()); writer->write(root, &sout); return sout; } } // namespace Json
C++
3D
mcellteam/mcell
libs/jsoncpp/src/lib_json/json_value.cpp
.cpp
48,043
1,628
// Copyright 2011 Baptiste Lepilleur and The JsonCpp Authors // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #if !defined(JSON_IS_AMALGAMATION) #include <json/assertions.h> #include <json/value.h> #include <json/writer.h> #endif // if !defined(JSON_IS_AMALGAMATION) #include <algorithm> #include <cassert> #include <cmath> #include <cstddef> #include <cstring> #include <sstream> #include <utility> // Provide implementation equivalent of std::snprintf for older _MSC compilers #if defined(_MSC_VER) && _MSC_VER < 1900 #include <stdarg.h> static int msvc_pre1900_c99_vsnprintf(char* outBuf, size_t size, const char* format, va_list ap) { int count = -1; if (size != 0) count = _vsnprintf_s(outBuf, size, _TRUNCATE, format, ap); if (count == -1) count = _vscprintf(format, ap); return count; } int JSON_API msvc_pre1900_c99_snprintf(char* outBuf, size_t size, const char* format, ...) { va_list ap; va_start(ap, format); const int count = msvc_pre1900_c99_vsnprintf(outBuf, size, format, ap); va_end(ap); return count; } #endif // Disable warning C4702 : unreachable code #if defined(_MSC_VER) #pragma warning(disable : 4702) #endif #define JSON_ASSERT_UNREACHABLE assert(false) namespace Json { template <typename T> static std::unique_ptr<T> cloneUnique(const std::unique_ptr<T>& p) { std::unique_ptr<T> r; if (p) { r = std::unique_ptr<T>(new T(*p)); } return r; } // This is a walkaround to avoid the static initialization of Value::null. // kNull must be word-aligned to avoid crashing on ARM. We use an alignment of // 8 (instead of 4) as a bit of future-proofing. #if defined(__ARMEL__) #define ALIGNAS(byte_alignment) __attribute__((aligned(byte_alignment))) #else #define ALIGNAS(byte_alignment) #endif // static Value const& Value::nullSingleton() { static Value const nullStatic; return nullStatic; } #if JSON_USE_NULLREF // for backwards compatibility, we'll leave these global references around, but // DO NOT use them in JSONCPP library code any more! // static Value const& Value::null = Value::nullSingleton(); // static Value const& Value::nullRef = Value::nullSingleton(); #endif #if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) template <typename T, typename U> static inline bool InRange(double d, T min, U max) { // The casts can lose precision, but we are looking only for // an approximate range. Might fail on edge cases though. ~cdunn return d >= static_cast<double>(min) && d <= static_cast<double>(max); } #else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) static inline double integerToDouble(Json::UInt64 value) { return static_cast<double>(Int64(value / 2)) * 2.0 + static_cast<double>(Int64(value & 1)); } template <typename T> static inline double integerToDouble(T value) { return static_cast<double>(value); } template <typename T, typename U> static inline bool InRange(double d, T min, U max) { return d >= integerToDouble(min) && d <= integerToDouble(max); } #endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) /** Duplicates the specified string value. * @param value Pointer to the string to duplicate. Must be zero-terminated if * length is "unknown". * @param length Length of the value. if equals to unknown, then it will be * computed using strlen(value). * @return Pointer on the duplicate instance of string. */ static inline char* duplicateStringValue(const char* value, size_t length) { // Avoid an integer overflow in the call to malloc below by limiting length // to a sane value. if (length >= static_cast<size_t>(Value::maxInt)) length = Value::maxInt - 1; auto newString = static_cast<char*>(malloc(length + 1)); if (newString == nullptr) { throwRuntimeError("in Json::Value::duplicateStringValue(): " "Failed to allocate string value buffer"); } memcpy(newString, value, length); newString[length] = 0; return newString; } /* Record the length as a prefix. */ static inline char* duplicateAndPrefixStringValue(const char* value, unsigned int length) { // Avoid an integer overflow in the call to malloc below by limiting length // to a sane value. JSON_ASSERT_MESSAGE(length <= static_cast<unsigned>(Value::maxInt) - sizeof(unsigned) - 1U, "in Json::Value::duplicateAndPrefixStringValue(): " "length too big for prefixing"); size_t actualLength = sizeof(length) + length + 1; auto newString = static_cast<char*>(malloc(actualLength)); if (newString == nullptr) { throwRuntimeError("in Json::Value::duplicateAndPrefixStringValue(): " "Failed to allocate string value buffer"); } *reinterpret_cast<unsigned*>(newString) = length; memcpy(newString + sizeof(unsigned), value, length); newString[actualLength - 1U] = 0; // to avoid buffer over-run accidents by users later return newString; } inline static void decodePrefixedString(bool isPrefixed, char const* prefixed, unsigned* length, char const** value) { if (!isPrefixed) { *length = static_cast<unsigned>(strlen(prefixed)); *value = prefixed; } else { *length = *reinterpret_cast<unsigned const*>(prefixed); *value = prefixed + sizeof(unsigned); } } /** Free the string duplicated by * duplicateStringValue()/duplicateAndPrefixStringValue(). */ #if JSONCPP_USING_SECURE_MEMORY static inline void releasePrefixedStringValue(char* value) { unsigned length = 0; char const* valueDecoded; decodePrefixedString(true, value, &length, &valueDecoded); size_t const size = sizeof(unsigned) + length + 1U; memset(value, 0, size); free(value); } static inline void releaseStringValue(char* value, unsigned length) { // length==0 => we allocated the strings memory size_t size = (length == 0) ? strlen(value) : length; memset(value, 0, size); free(value); } #else // !JSONCPP_USING_SECURE_MEMORY static inline void releasePrefixedStringValue(char* value) { free(value); } static inline void releaseStringValue(char* value, unsigned) { free(value); } #endif // JSONCPP_USING_SECURE_MEMORY } // namespace Json // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ValueInternals... // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// #if !defined(JSON_IS_AMALGAMATION) #include "json_valueiterator.inl" #endif // if !defined(JSON_IS_AMALGAMATION) namespace Json { #if JSON_USE_EXCEPTION Exception::Exception(String msg) : msg_(std::move(msg)) {} Exception::~Exception() JSONCPP_NOEXCEPT = default; char const* Exception::what() const JSONCPP_NOEXCEPT { return msg_.c_str(); } RuntimeError::RuntimeError(String const& msg) : Exception(msg) {} LogicError::LogicError(String const& msg) : Exception(msg) {} JSONCPP_NORETURN void throwRuntimeError(String const& msg) { throw RuntimeError(msg); } JSONCPP_NORETURN void throwLogicError(String const& msg) { throw LogicError(msg); } #else // !JSON_USE_EXCEPTION JSONCPP_NORETURN void throwRuntimeError(String const& msg) { abort(); } JSONCPP_NORETURN void throwLogicError(String const& msg) { abort(); } #endif // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // class Value::CZString // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // Notes: policy_ indicates if the string was allocated when // a string is stored. Value::CZString::CZString(ArrayIndex index) : cstr_(nullptr), index_(index) {} Value::CZString::CZString(char const* str, unsigned length, DuplicationPolicy allocate) : cstr_(str) { // allocate != duplicate storage_.policy_ = allocate & 0x3; storage_.length_ = length & 0x3FFFFFFF; } Value::CZString::CZString(const CZString& other) { cstr_ = (other.storage_.policy_ != noDuplication && other.cstr_ != nullptr ? duplicateStringValue(other.cstr_, other.storage_.length_) : other.cstr_); storage_.policy_ = static_cast<unsigned>( other.cstr_ ? (static_cast<DuplicationPolicy>(other.storage_.policy_) == noDuplication ? noDuplication : duplicate) : static_cast<DuplicationPolicy>(other.storage_.policy_)) & 3U; storage_.length_ = other.storage_.length_; } Value::CZString::CZString(CZString&& other) : cstr_(other.cstr_), index_(other.index_) { other.cstr_ = nullptr; } Value::CZString::~CZString() { if (cstr_ && storage_.policy_ == duplicate) { releaseStringValue(const_cast<char*>(cstr_), storage_.length_ + 1U); // +1 for null terminating // character for sake of // completeness but not actually // necessary } } void Value::CZString::swap(CZString& other) { std::swap(cstr_, other.cstr_); std::swap(index_, other.index_); } Value::CZString& Value::CZString::operator=(const CZString& other) { cstr_ = other.cstr_; index_ = other.index_; return *this; } Value::CZString& Value::CZString::operator=(CZString&& other) { cstr_ = other.cstr_; index_ = other.index_; other.cstr_ = nullptr; return *this; } bool Value::CZString::operator<(const CZString& other) const { if (!cstr_) return index_ < other.index_; // return strcmp(cstr_, other.cstr_) < 0; // Assume both are strings. unsigned this_len = this->storage_.length_; unsigned other_len = other.storage_.length_; unsigned min_len = std::min<unsigned>(this_len, other_len); JSON_ASSERT(this->cstr_ && other.cstr_); int comp = memcmp(this->cstr_, other.cstr_, min_len); if (comp < 0) return true; if (comp > 0) return false; return (this_len < other_len); } bool Value::CZString::operator==(const CZString& other) const { if (!cstr_) return index_ == other.index_; // return strcmp(cstr_, other.cstr_) == 0; // Assume both are strings. unsigned this_len = this->storage_.length_; unsigned other_len = other.storage_.length_; if (this_len != other_len) return false; JSON_ASSERT(this->cstr_ && other.cstr_); int comp = memcmp(this->cstr_, other.cstr_, this_len); return comp == 0; } ArrayIndex Value::CZString::index() const { return index_; } // const char* Value::CZString::c_str() const { return cstr_; } const char* Value::CZString::data() const { return cstr_; } unsigned Value::CZString::length() const { return storage_.length_; } bool Value::CZString::isStaticString() const { return storage_.policy_ == noDuplication; } // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // class Value::Value // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////// /*! \internal Default constructor initialization must be equivalent to: * memset( this, 0, sizeof(Value) ) * This optimization is used in ValueInternalMap fast allocator. */ Value::Value(ValueType type) { static char const emptyString[] = ""; initBasic(type); switch (type) { case nullValue: break; case intValue: case uintValue: value_.int_ = 0; break; case realValue: value_.real_ = 0.0; break; case stringValue: // allocated_ == false, so this is safe. value_.string_ = const_cast<char*>(static_cast<char const*>(emptyString)); break; case arrayValue: case objectValue: value_.map_ = new ObjectValues(); break; case booleanValue: value_.bool_ = false; break; default: JSON_ASSERT_UNREACHABLE; } } Value::Value(Int value) { initBasic(intValue); value_.int_ = value; } Value::Value(UInt value) { initBasic(uintValue); value_.uint_ = value; } #if defined(JSON_HAS_INT64) Value::Value(Int64 value) { initBasic(intValue); value_.int_ = value; } Value::Value(UInt64 value) { initBasic(uintValue); value_.uint_ = value; } #endif // defined(JSON_HAS_INT64) Value::Value(double value) { initBasic(realValue); value_.real_ = value; } Value::Value(const char* value) { initBasic(stringValue, true); JSON_ASSERT_MESSAGE(value != nullptr, "Null Value Passed to Value Constructor"); value_.string_ = duplicateAndPrefixStringValue( value, static_cast<unsigned>(strlen(value))); } Value::Value(const char* begin, const char* end) { initBasic(stringValue, true); value_.string_ = duplicateAndPrefixStringValue(begin, static_cast<unsigned>(end - begin)); } Value::Value(const String& value) { initBasic(stringValue, true); value_.string_ = duplicateAndPrefixStringValue( value.data(), static_cast<unsigned>(value.length())); } Value::Value(const StaticString& value) { initBasic(stringValue); value_.string_ = const_cast<char*>(value.c_str()); } Value::Value(bool value) { initBasic(booleanValue); value_.bool_ = value; } Value::Value(const Value& other) { dupPayload(other); dupMeta(other); } Value::Value(Value&& other) { initBasic(nullValue); swap(other); } Value::~Value() { releasePayload(); value_.uint_ = 0; } Value& Value::operator=(const Value& other) { Value(other).swap(*this); return *this; } Value& Value::operator=(Value&& other) { other.swap(*this); return *this; } void Value::swapPayload(Value& other) { std::swap(bits_, other.bits_); std::swap(value_, other.value_); } void Value::copyPayload(const Value& other) { releasePayload(); dupPayload(other); } void Value::swap(Value& other) { swapPayload(other); std::swap(comments_, other.comments_); std::swap(start_, other.start_); std::swap(limit_, other.limit_); } void Value::copy(const Value& other) { copyPayload(other); dupMeta(other); } ValueType Value::type() const { return static_cast<ValueType>(bits_.value_type_); } int Value::compare(const Value& other) const { if (*this < other) return -1; if (*this > other) return 1; return 0; } bool Value::operator<(const Value& other) const { int typeDelta = type() - other.type(); if (typeDelta) return typeDelta < 0; switch (type()) { case nullValue: return false; case intValue: return value_.int_ < other.value_.int_; case uintValue: return value_.uint_ < other.value_.uint_; case realValue: return value_.real_ < other.value_.real_; case booleanValue: return value_.bool_ < other.value_.bool_; case stringValue: { if ((value_.string_ == nullptr) || (other.value_.string_ == nullptr)) { return other.value_.string_ != nullptr; } unsigned this_len; unsigned other_len; char const* this_str; char const* other_str; decodePrefixedString(this->isAllocated(), this->value_.string_, &this_len, &this_str); decodePrefixedString(other.isAllocated(), other.value_.string_, &other_len, &other_str); unsigned min_len = std::min<unsigned>(this_len, other_len); JSON_ASSERT(this_str && other_str); int comp = memcmp(this_str, other_str, min_len); if (comp < 0) return true; if (comp > 0) return false; return (this_len < other_len); } case arrayValue: case objectValue: { auto thisSize = value_.map_->size(); auto otherSize = other.value_.map_->size(); if (thisSize != otherSize) return thisSize < otherSize; return (*value_.map_) < (*other.value_.map_); } default: JSON_ASSERT_UNREACHABLE; } return false; // unreachable } bool Value::operator<=(const Value& other) const { return !(other < *this); } bool Value::operator>=(const Value& other) const { return !(*this < other); } bool Value::operator>(const Value& other) const { return other < *this; } bool Value::operator==(const Value& other) const { if (type() != other.type()) return false; switch (type()) { case nullValue: return true; case intValue: return value_.int_ == other.value_.int_; case uintValue: return value_.uint_ == other.value_.uint_; case realValue: return value_.real_ == other.value_.real_; case booleanValue: return value_.bool_ == other.value_.bool_; case stringValue: { if ((value_.string_ == nullptr) || (other.value_.string_ == nullptr)) { return (value_.string_ == other.value_.string_); } unsigned this_len; unsigned other_len; char const* this_str; char const* other_str; decodePrefixedString(this->isAllocated(), this->value_.string_, &this_len, &this_str); decodePrefixedString(other.isAllocated(), other.value_.string_, &other_len, &other_str); if (this_len != other_len) return false; JSON_ASSERT(this_str && other_str); int comp = memcmp(this_str, other_str, this_len); return comp == 0; } case arrayValue: case objectValue: return value_.map_->size() == other.value_.map_->size() && (*value_.map_) == (*other.value_.map_); default: JSON_ASSERT_UNREACHABLE; } return false; // unreachable } bool Value::operator!=(const Value& other) const { return !(*this == other); } const char* Value::asCString() const { JSON_ASSERT_MESSAGE(type() == stringValue, "in Json::Value::asCString(): requires stringValue"); if (value_.string_ == nullptr) return nullptr; unsigned this_len; char const* this_str; decodePrefixedString(this->isAllocated(), this->value_.string_, &this_len, &this_str); return this_str; } #if JSONCPP_USING_SECURE_MEMORY unsigned Value::getCStringLength() const { JSON_ASSERT_MESSAGE(type() == stringValue, "in Json::Value::asCString(): requires stringValue"); if (value_.string_ == 0) return 0; unsigned this_len; char const* this_str; decodePrefixedString(this->isAllocated(), this->value_.string_, &this_len, &this_str); return this_len; } #endif bool Value::getString(char const** begin, char const** end) const { if (type() != stringValue) return false; if (value_.string_ == nullptr) return false; unsigned length; decodePrefixedString(this->isAllocated(), this->value_.string_, &length, begin); *end = *begin + length; return true; } String Value::asString() const { switch (type()) { case nullValue: return ""; case stringValue: { if (value_.string_ == nullptr) return ""; unsigned this_len; char const* this_str; decodePrefixedString(this->isAllocated(), this->value_.string_, &this_len, &this_str); return String(this_str, this_len); } case booleanValue: return value_.bool_ ? "true" : "false"; case intValue: return valueToString(value_.int_); case uintValue: return valueToString(value_.uint_); case realValue: return valueToString(value_.real_); default: JSON_FAIL_MESSAGE("Type is not convertible to string"); } } Value::Int Value::asInt() const { switch (type()) { case intValue: JSON_ASSERT_MESSAGE(isInt(), "LargestInt out of Int range"); return Int(value_.int_); case uintValue: JSON_ASSERT_MESSAGE(isInt(), "LargestUInt out of Int range"); return Int(value_.uint_); case realValue: JSON_ASSERT_MESSAGE(InRange(value_.real_, minInt, maxInt), "double out of Int range"); return Int(value_.real_); case nullValue: return 0; case booleanValue: return value_.bool_ ? 1 : 0; default: break; } JSON_FAIL_MESSAGE("Value is not convertible to Int."); } Value::UInt Value::asUInt() const { switch (type()) { case intValue: JSON_ASSERT_MESSAGE(isUInt(), "LargestInt out of UInt range"); return UInt(value_.int_); case uintValue: JSON_ASSERT_MESSAGE(isUInt(), "LargestUInt out of UInt range"); return UInt(value_.uint_); case realValue: JSON_ASSERT_MESSAGE(InRange(value_.real_, 0, maxUInt), "double out of UInt range"); return UInt(value_.real_); case nullValue: return 0; case booleanValue: return value_.bool_ ? 1 : 0; default: break; } JSON_FAIL_MESSAGE("Value is not convertible to UInt."); } #if defined(JSON_HAS_INT64) Value::Int64 Value::asInt64() const { switch (type()) { case intValue: return Int64(value_.int_); case uintValue: JSON_ASSERT_MESSAGE(isInt64(), "LargestUInt out of Int64 range"); return Int64(value_.uint_); case realValue: JSON_ASSERT_MESSAGE(InRange(value_.real_, minInt64, maxInt64), "double out of Int64 range"); return Int64(value_.real_); case nullValue: return 0; case booleanValue: return value_.bool_ ? 1 : 0; default: break; } JSON_FAIL_MESSAGE("Value is not convertible to Int64."); } Value::UInt64 Value::asUInt64() const { switch (type()) { case intValue: JSON_ASSERT_MESSAGE(isUInt64(), "LargestInt out of UInt64 range"); return UInt64(value_.int_); case uintValue: return UInt64(value_.uint_); case realValue: JSON_ASSERT_MESSAGE(InRange(value_.real_, 0, maxUInt64), "double out of UInt64 range"); return UInt64(value_.real_); case nullValue: return 0; case booleanValue: return value_.bool_ ? 1 : 0; default: break; } JSON_FAIL_MESSAGE("Value is not convertible to UInt64."); } #endif // if defined(JSON_HAS_INT64) LargestInt Value::asLargestInt() const { #if defined(JSON_NO_INT64) return asInt(); #else return asInt64(); #endif } LargestUInt Value::asLargestUInt() const { #if defined(JSON_NO_INT64) return asUInt(); #else return asUInt64(); #endif } double Value::asDouble() const { switch (type()) { case intValue: return static_cast<double>(value_.int_); case uintValue: #if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) return static_cast<double>(value_.uint_); #else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) return integerToDouble(value_.uint_); #endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) case realValue: return value_.real_; case nullValue: return 0.0; case booleanValue: return value_.bool_ ? 1.0 : 0.0; default: break; } JSON_FAIL_MESSAGE("Value is not convertible to double."); } float Value::asFloat() const { switch (type()) { case intValue: return static_cast<float>(value_.int_); case uintValue: #if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) return static_cast<float>(value_.uint_); #else // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) // This can fail (silently?) if the value is bigger than MAX_FLOAT. return static_cast<float>(integerToDouble(value_.uint_)); #endif // if !defined(JSON_USE_INT64_DOUBLE_CONVERSION) case realValue: return static_cast<float>(value_.real_); case nullValue: return 0.0; case booleanValue: return value_.bool_ ? 1.0F : 0.0F; default: break; } JSON_FAIL_MESSAGE("Value is not convertible to float."); } bool Value::asBool() const { switch (type()) { case booleanValue: return value_.bool_; case nullValue: return false; case intValue: return value_.int_ != 0; case uintValue: return value_.uint_ != 0; case realValue: { // According to JavaScript language zero or NaN is regarded as false const auto value_classification = std::fpclassify(value_.real_); return value_classification != FP_ZERO && value_classification != FP_NAN; } default: break; } JSON_FAIL_MESSAGE("Value is not convertible to bool."); } bool Value::isConvertibleTo(ValueType other) const { switch (other) { case nullValue: return (isNumeric() && asDouble() == 0.0) || (type() == booleanValue && !value_.bool_) || (type() == stringValue && asString().empty()) || (type() == arrayValue && value_.map_->empty()) || (type() == objectValue && value_.map_->empty()) || type() == nullValue; case intValue: return isInt() || (type() == realValue && InRange(value_.real_, minInt, maxInt)) || type() == booleanValue || type() == nullValue; case uintValue: return isUInt() || (type() == realValue && InRange(value_.real_, 0, maxUInt)) || type() == booleanValue || type() == nullValue; case realValue: return isNumeric() || type() == booleanValue || type() == nullValue; case booleanValue: return isNumeric() || type() == booleanValue || type() == nullValue; case stringValue: return isNumeric() || type() == booleanValue || type() == stringValue || type() == nullValue; case arrayValue: return type() == arrayValue || type() == nullValue; case objectValue: return type() == objectValue || type() == nullValue; } JSON_ASSERT_UNREACHABLE; return false; } /// Number of values in array or object ArrayIndex Value::size() const { switch (type()) { case nullValue: case intValue: case uintValue: case realValue: case booleanValue: case stringValue: return 0; case arrayValue: // size of the array is highest index + 1 if (!value_.map_->empty()) { ObjectValues::const_iterator itLast = value_.map_->end(); --itLast; return (*itLast).first.index() + 1; } return 0; case objectValue: return ArrayIndex(value_.map_->size()); } JSON_ASSERT_UNREACHABLE; return 0; // unreachable; } bool Value::empty() const { if (isNull() || isArray() || isObject()) return size() == 0U; return false; } Value::operator bool() const { return !isNull(); } void Value::clear() { JSON_ASSERT_MESSAGE(type() == nullValue || type() == arrayValue || type() == objectValue, "in Json::Value::clear(): requires complex value"); start_ = 0; limit_ = 0; switch (type()) { case arrayValue: case objectValue: value_.map_->clear(); break; default: break; } } void Value::resize(ArrayIndex newSize) { JSON_ASSERT_MESSAGE(type() == nullValue || type() == arrayValue, "in Json::Value::resize(): requires arrayValue"); if (type() == nullValue) *this = Value(arrayValue); ArrayIndex oldSize = size(); if (newSize == 0) clear(); else if (newSize > oldSize) this->operator[](newSize - 1); else { for (ArrayIndex index = newSize; index < oldSize; ++index) { value_.map_->erase(index); } JSON_ASSERT(size() == newSize); } } Value& Value::operator[](ArrayIndex index) { JSON_ASSERT_MESSAGE( type() == nullValue || type() == arrayValue, "in Json::Value::operator[](ArrayIndex): requires arrayValue"); if (type() == nullValue) *this = Value(arrayValue); CZString key(index); auto it = value_.map_->lower_bound(key); if (it != value_.map_->end() && (*it).first == key) return (*it).second; ObjectValues::value_type defaultValue(key, nullSingleton()); it = value_.map_->insert(it, defaultValue); return (*it).second; } Value& Value::operator[](int index) { JSON_ASSERT_MESSAGE( index >= 0, "in Json::Value::operator[](int index): index cannot be negative"); return (*this)[ArrayIndex(index)]; } const Value& Value::operator[](ArrayIndex index) const { JSON_ASSERT_MESSAGE( type() == nullValue || type() == arrayValue, "in Json::Value::operator[](ArrayIndex)const: requires arrayValue"); if (type() == nullValue) return nullSingleton(); CZString key(index); ObjectValues::const_iterator it = value_.map_->find(key); if (it == value_.map_->end()) return nullSingleton(); return (*it).second; } const Value& Value::operator[](int index) const { JSON_ASSERT_MESSAGE( index >= 0, "in Json::Value::operator[](int index) const: index cannot be negative"); return (*this)[ArrayIndex(index)]; } void Value::initBasic(ValueType type, bool allocated) { setType(type); setIsAllocated(allocated); comments_ = Comments{}; start_ = 0; limit_ = 0; } void Value::dupPayload(const Value& other) { setType(other.type()); setIsAllocated(false); switch (type()) { case nullValue: case intValue: case uintValue: case realValue: case booleanValue: value_ = other.value_; break; case stringValue: if (other.value_.string_ && other.isAllocated()) { unsigned len; char const* str; decodePrefixedString(other.isAllocated(), other.value_.string_, &len, &str); value_.string_ = duplicateAndPrefixStringValue(str, len); setIsAllocated(true); } else { value_.string_ = other.value_.string_; } break; case arrayValue: case objectValue: value_.map_ = new ObjectValues(*other.value_.map_); break; default: JSON_ASSERT_UNREACHABLE; } } void Value::releasePayload() { switch (type()) { case nullValue: case intValue: case uintValue: case realValue: case booleanValue: break; case stringValue: if (isAllocated()) releasePrefixedStringValue(value_.string_); break; case arrayValue: case objectValue: delete value_.map_; break; default: JSON_ASSERT_UNREACHABLE; } } void Value::dupMeta(const Value& other) { comments_ = other.comments_; start_ = other.start_; limit_ = other.limit_; } // Access an object value by name, create a null member if it does not exist. // @pre Type of '*this' is object or null. // @param key is null-terminated. Value& Value::resolveReference(const char* key) { JSON_ASSERT_MESSAGE( type() == nullValue || type() == objectValue, "in Json::Value::resolveReference(): requires objectValue"); if (type() == nullValue) *this = Value(objectValue); CZString actualKey(key, static_cast<unsigned>(strlen(key)), CZString::noDuplication); // NOTE! auto it = value_.map_->lower_bound(actualKey); if (it != value_.map_->end() && (*it).first == actualKey) return (*it).second; ObjectValues::value_type defaultValue(actualKey, nullSingleton()); it = value_.map_->insert(it, defaultValue); Value& value = (*it).second; return value; } // @param key is not null-terminated. Value& Value::resolveReference(char const* key, char const* end) { JSON_ASSERT_MESSAGE( type() == nullValue || type() == objectValue, "in Json::Value::resolveReference(key, end): requires objectValue"); if (type() == nullValue) *this = Value(objectValue); CZString actualKey(key, static_cast<unsigned>(end - key), CZString::duplicateOnCopy); auto it = value_.map_->lower_bound(actualKey); if (it != value_.map_->end() && (*it).first == actualKey) return (*it).second; ObjectValues::value_type defaultValue(actualKey, nullSingleton()); it = value_.map_->insert(it, defaultValue); Value& value = (*it).second; return value; } Value Value::get(ArrayIndex index, const Value& defaultValue) const { const Value* value = &((*this)[index]); return value == &nullSingleton() ? defaultValue : *value; } bool Value::isValidIndex(ArrayIndex index) const { return index < size(); } Value const* Value::find(char const* begin, char const* end) const { JSON_ASSERT_MESSAGE(type() == nullValue || type() == objectValue, "in Json::Value::find(begin, end): requires " "objectValue or nullValue"); if (type() == nullValue) return nullptr; CZString actualKey(begin, static_cast<unsigned>(end - begin), CZString::noDuplication); ObjectValues::const_iterator it = value_.map_->find(actualKey); if (it == value_.map_->end()) return nullptr; return &(*it).second; } Value* Value::demand(char const* begin, char const* end) { JSON_ASSERT_MESSAGE(type() == nullValue || type() == objectValue, "in Json::Value::demand(begin, end): requires " "objectValue or nullValue"); return &resolveReference(begin, end); } const Value& Value::operator[](const char* key) const { Value const* found = find(key, key + strlen(key)); if (!found) return nullSingleton(); return *found; } Value const& Value::operator[](const String& key) const { Value const* found = find(key.data(), key.data() + key.length()); if (!found) return nullSingleton(); return *found; } Value& Value::operator[](const char* key) { return resolveReference(key, key + strlen(key)); } Value& Value::operator[](const String& key) { return resolveReference(key.data(), key.data() + key.length()); } Value& Value::operator[](const StaticString& key) { return resolveReference(key.c_str()); } Value& Value::append(const Value& value) { return append(Value(value)); } Value& Value::append(Value&& value) { JSON_ASSERT_MESSAGE(type() == nullValue || type() == arrayValue, "in Json::Value::append: requires arrayValue"); if (type() == nullValue) { *this = Value(arrayValue); } return this->value_.map_->emplace(size(), std::move(value)).first->second; } bool Value::insert(ArrayIndex index, const Value& newValue) { return insert(index, Value(newValue)); } bool Value::insert(ArrayIndex index, Value&& newValue) { JSON_ASSERT_MESSAGE(type() == nullValue || type() == arrayValue, "in Json::Value::insert: requires arrayValue"); ArrayIndex length = size(); if (index > length) { return false; } for (ArrayIndex i = length; i > index; i--) { (*this)[i] = std::move((*this)[i - 1]); } (*this)[index] = std::move(newValue); return true; } Value Value::get(char const* begin, char const* end, Value const& defaultValue) const { Value const* found = find(begin, end); return !found ? defaultValue : *found; } Value Value::get(char const* key, Value const& defaultValue) const { return get(key, key + strlen(key), defaultValue); } Value Value::get(String const& key, Value const& defaultValue) const { return get(key.data(), key.data() + key.length(), defaultValue); } bool Value::removeMember(const char* begin, const char* end, Value* removed) { if (type() != objectValue) { return false; } CZString actualKey(begin, static_cast<unsigned>(end - begin), CZString::noDuplication); auto it = value_.map_->find(actualKey); if (it == value_.map_->end()) return false; if (removed) *removed = std::move(it->second); value_.map_->erase(it); return true; } bool Value::removeMember(const char* key, Value* removed) { return removeMember(key, key + strlen(key), removed); } bool Value::removeMember(String const& key, Value* removed) { return removeMember(key.data(), key.data() + key.length(), removed); } void Value::removeMember(const char* key) { JSON_ASSERT_MESSAGE(type() == nullValue || type() == objectValue, "in Json::Value::removeMember(): requires objectValue"); if (type() == nullValue) return; CZString actualKey(key, unsigned(strlen(key)), CZString::noDuplication); value_.map_->erase(actualKey); } void Value::removeMember(const String& key) { removeMember(key.c_str()); } bool Value::removeIndex(ArrayIndex index, Value* removed) { if (type() != arrayValue) { return false; } CZString key(index); auto it = value_.map_->find(key); if (it == value_.map_->end()) { return false; } if (removed) *removed = it->second; ArrayIndex oldSize = size(); // shift left all items left, into the place of the "removed" for (ArrayIndex i = index; i < (oldSize - 1); ++i) { CZString keey(i); (*value_.map_)[keey] = (*this)[i + 1]; } // erase the last one ("leftover") CZString keyLast(oldSize - 1); auto itLast = value_.map_->find(keyLast); value_.map_->erase(itLast); return true; } bool Value::isMember(char const* begin, char const* end) const { Value const* value = find(begin, end); return nullptr != value; } bool Value::isMember(char const* key) const { return isMember(key, key + strlen(key)); } bool Value::isMember(String const& key) const { return isMember(key.data(), key.data() + key.length()); } Value::Members Value::getMemberNames() const { JSON_ASSERT_MESSAGE( type() == nullValue || type() == objectValue, "in Json::Value::getMemberNames(), value must be objectValue"); if (type() == nullValue) return Value::Members(); Members members; members.reserve(value_.map_->size()); ObjectValues::const_iterator it = value_.map_->begin(); ObjectValues::const_iterator itEnd = value_.map_->end(); for (; it != itEnd; ++it) { members.push_back(String((*it).first.data(), (*it).first.length())); } return members; } static bool IsIntegral(double d) { double integral_part; return modf(d, &integral_part) == 0.0; } bool Value::isNull() const { return type() == nullValue; } bool Value::isBool() const { return type() == booleanValue; } bool Value::isInt() const { switch (type()) { case intValue: #if defined(JSON_HAS_INT64) return value_.int_ >= minInt && value_.int_ <= maxInt; #else return true; #endif case uintValue: return value_.uint_ <= UInt(maxInt); case realValue: return value_.real_ >= minInt && value_.real_ <= maxInt && IsIntegral(value_.real_); default: break; } return false; } bool Value::isUInt() const { switch (type()) { case intValue: #if defined(JSON_HAS_INT64) return value_.int_ >= 0 && LargestUInt(value_.int_) <= LargestUInt(maxUInt); #else return value_.int_ >= 0; #endif case uintValue: #if defined(JSON_HAS_INT64) return value_.uint_ <= maxUInt; #else return true; #endif case realValue: return value_.real_ >= 0 && value_.real_ <= maxUInt && IsIntegral(value_.real_); default: break; } return false; } bool Value::isInt64() const { #if defined(JSON_HAS_INT64) switch (type()) { case intValue: return true; case uintValue: return value_.uint_ <= UInt64(maxInt64); case realValue: // Note that maxInt64 (= 2^63 - 1) is not exactly representable as a // double, so double(maxInt64) will be rounded up to 2^63. Therefore we // require the value to be strictly less than the limit. return value_.real_ >= double(minInt64) && value_.real_ < double(maxInt64) && IsIntegral(value_.real_); default: break; } #endif // JSON_HAS_INT64 return false; } bool Value::isUInt64() const { #if defined(JSON_HAS_INT64) switch (type()) { case intValue: return value_.int_ >= 0; case uintValue: return true; case realValue: // Note that maxUInt64 (= 2^64 - 1) is not exactly representable as a // double, so double(maxUInt64) will be rounded up to 2^64. Therefore we // require the value to be strictly less than the limit. return value_.real_ >= 0 && value_.real_ < maxUInt64AsDouble && IsIntegral(value_.real_); default: break; } #endif // JSON_HAS_INT64 return false; } bool Value::isIntegral() const { switch (type()) { case intValue: case uintValue: return true; case realValue: #if defined(JSON_HAS_INT64) // Note that maxUInt64 (= 2^64 - 1) is not exactly representable as a // double, so double(maxUInt64) will be rounded up to 2^64. Therefore we // require the value to be strictly less than the limit. return value_.real_ >= double(minInt64) && value_.real_ < maxUInt64AsDouble && IsIntegral(value_.real_); #else return value_.real_ >= minInt && value_.real_ <= maxUInt && IsIntegral(value_.real_); #endif // JSON_HAS_INT64 default: break; } return false; } bool Value::isDouble() const { return type() == intValue || type() == uintValue || type() == realValue; } bool Value::isNumeric() const { return isDouble(); } bool Value::isString() const { return type() == stringValue; } bool Value::isArray() const { return type() == arrayValue; } bool Value::isObject() const { return type() == objectValue; } Value::Comments::Comments(const Comments& that) : ptr_{cloneUnique(that.ptr_)} {} Value::Comments::Comments(Comments&& that) : ptr_{std::move(that.ptr_)} {} Value::Comments& Value::Comments::operator=(const Comments& that) { ptr_ = cloneUnique(that.ptr_); return *this; } Value::Comments& Value::Comments::operator=(Comments&& that) { ptr_ = std::move(that.ptr_); return *this; } bool Value::Comments::has(CommentPlacement slot) const { return ptr_ && !(*ptr_)[slot].empty(); } String Value::Comments::get(CommentPlacement slot) const { if (!ptr_) return {}; return (*ptr_)[slot]; } void Value::Comments::set(CommentPlacement slot, String comment) { if (!ptr_) { ptr_ = std::unique_ptr<Array>(new Array()); } // check comments array boundry. if (slot < CommentPlacement::numberOfCommentPlacement) { (*ptr_)[slot] = std::move(comment); } } void Value::setComment(String comment, CommentPlacement placement) { if (!comment.empty() && (comment.back() == '\n')) { // Always discard trailing newline, to aid indentation. comment.pop_back(); } JSON_ASSERT(!comment.empty()); JSON_ASSERT_MESSAGE( comment[0] == '\0' || comment[0] == '/', "in Json::Value::setComment(): Comments must start with /"); comments_.set(placement, std::move(comment)); } bool Value::hasComment(CommentPlacement placement) const { return comments_.has(placement); } String Value::getComment(CommentPlacement placement) const { return comments_.get(placement); } void Value::setOffsetStart(ptrdiff_t start) { start_ = start; } void Value::setOffsetLimit(ptrdiff_t limit) { limit_ = limit; } ptrdiff_t Value::getOffsetStart() const { return start_; } ptrdiff_t Value::getOffsetLimit() const { return limit_; } String Value::toStyledString() const { StreamWriterBuilder builder; String out = this->hasComment(commentBefore) ? "\n" : ""; out += Json::writeString(builder, *this); out += '\n'; return out; } Value::const_iterator Value::begin() const { switch (type()) { case arrayValue: case objectValue: if (value_.map_) return const_iterator(value_.map_->begin()); break; default: break; } return {}; } Value::const_iterator Value::end() const { switch (type()) { case arrayValue: case objectValue: if (value_.map_) return const_iterator(value_.map_->end()); break; default: break; } return {}; } Value::iterator Value::begin() { switch (type()) { case arrayValue: case objectValue: if (value_.map_) return iterator(value_.map_->begin()); break; default: break; } return iterator(); } Value::iterator Value::end() { switch (type()) { case arrayValue: case objectValue: if (value_.map_) return iterator(value_.map_->end()); break; default: break; } return iterator(); } // class PathArgument // ////////////////////////////////////////////////////////////////// PathArgument::PathArgument() = default; PathArgument::PathArgument(ArrayIndex index) : index_(index), kind_(kindIndex) {} PathArgument::PathArgument(const char* key) : key_(key), kind_(kindKey) {} PathArgument::PathArgument(String key) : key_(std::move(key)), kind_(kindKey) {} // class Path // ////////////////////////////////////////////////////////////////// Path::Path(const String& path, const PathArgument& a1, const PathArgument& a2, const PathArgument& a3, const PathArgument& a4, const PathArgument& a5) { InArgs in; in.reserve(5); in.push_back(&a1); in.push_back(&a2); in.push_back(&a3); in.push_back(&a4); in.push_back(&a5); makePath(path, in); } void Path::makePath(const String& path, const InArgs& in) { const char* current = path.c_str(); const char* end = current + path.length(); auto itInArg = in.begin(); while (current != end) { if (*current == '[') { ++current; if (*current == '%') addPathInArg(path, in, itInArg, PathArgument::kindIndex); else { ArrayIndex index = 0; for (; current != end && *current >= '0' && *current <= '9'; ++current) index = index * 10 + ArrayIndex(*current - '0'); args_.push_back(index); } if (current == end || *++current != ']') invalidPath(path, int(current - path.c_str())); } else if (*current == '%') { addPathInArg(path, in, itInArg, PathArgument::kindKey); ++current; } else if (*current == '.' || *current == ']') { ++current; } else { const char* beginName = current; while (current != end && !strchr("[.", *current)) ++current; args_.push_back(String(beginName, current)); } } } void Path::addPathInArg(const String& /*path*/, const InArgs& in, InArgs::const_iterator& itInArg, PathArgument::Kind kind) { if (itInArg == in.end()) { // Error: missing argument %d } else if ((*itInArg)->kind_ != kind) { // Error: bad argument type } else { args_.push_back(**itInArg++); } } void Path::invalidPath(const String& /*path*/, int /*location*/) { // Error: invalid path. } const Value& Path::resolve(const Value& root) const { const Value* node = &root; for (const auto& arg : args_) { if (arg.kind_ == PathArgument::kindIndex) { if (!node->isArray() || !node->isValidIndex(arg.index_)) { // Error: unable to resolve path (array value expected at position... ) return Value::nullSingleton(); } node = &((*node)[arg.index_]); } else if (arg.kind_ == PathArgument::kindKey) { if (!node->isObject()) { // Error: unable to resolve path (object value expected at position...) return Value::nullSingleton(); } node = &((*node)[arg.key_]); if (node == &Value::nullSingleton()) { // Error: unable to resolve path (object has no member named '' at // position...) return Value::nullSingleton(); } } } return *node; } Value Path::resolve(const Value& root, const Value& defaultValue) const { const Value* node = &root; for (const auto& arg : args_) { if (arg.kind_ == PathArgument::kindIndex) { if (!node->isArray() || !node->isValidIndex(arg.index_)) return defaultValue; node = &((*node)[arg.index_]); } else if (arg.kind_ == PathArgument::kindKey) { if (!node->isObject()) return defaultValue; node = &((*node)[arg.key_]); if (node == &Value::nullSingleton()) return defaultValue; } } return *node; } Value& Path::make(Value& root) const { Value* node = &root; for (const auto& arg : args_) { if (arg.kind_ == PathArgument::kindIndex) { if (!node->isArray()) { // Error: node is not an array at position ... } node = &((*node)[arg.index_]); } else if (arg.kind_ == PathArgument::kindKey) { if (!node->isObject()) { // Error: node is not an object at position... } node = &((*node)[arg.key_]); } } return *node; } } // namespace Json
C++
3D
mcellteam/mcell
libs/jsoncpp/src/jsontestrunner/main.cpp
.cpp
10,855
343
// Copyright 2007-2010 Baptiste Lepilleur and The JsonCpp Authors // Distributed under MIT license, or public domain if desired and // recognized in your jurisdiction. // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE #if defined(__GNUC__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #elif defined(_MSC_VER) #pragma warning(disable : 4996) #endif /* This executable is used for testing parser/writer using real JSON files. */ #include <algorithm> // sort #include <cstdio> #include <iostream> #include <json/json.h> #include <memory> #include <sstream> struct Options { Json::String path; Json::Features features; bool parseOnly; using writeFuncType = Json::String (*)(Json::Value const&); writeFuncType write; }; static Json::String normalizeFloatingPointStr(double value) { char buffer[32]; jsoncpp_snprintf(buffer, sizeof(buffer), "%.16g", value); buffer[sizeof(buffer) - 1] = 0; Json::String s(buffer); Json::String::size_type index = s.find_last_of("eE"); if (index != Json::String::npos) { Json::String::size_type hasSign = (s[index + 1] == '+' || s[index + 1] == '-') ? 1 : 0; Json::String::size_type exponentStartIndex = index + 1 + hasSign; Json::String normalized = s.substr(0, exponentStartIndex); Json::String::size_type indexDigit = s.find_first_not_of('0', exponentStartIndex); Json::String exponent = "0"; if (indexDigit != Json::String::npos) // There is an exponent different // from 0 { exponent = s.substr(indexDigit); } return normalized + exponent; } return s; } static Json::String readInputTestFile(const char* path) { FILE* file = fopen(path, "rb"); if (!file) return ""; fseek(file, 0, SEEK_END); auto const size = ftell(file); auto const usize = static_cast<size_t>(size); fseek(file, 0, SEEK_SET); auto buffer = new char[size + 1]; buffer[size] = 0; Json::String text; if (fread(buffer, 1, usize, file) == usize) text = buffer; fclose(file); delete[] buffer; return text; } static void printValueTree(FILE* fout, Json::Value& value, const Json::String& path = ".") { if (value.hasComment(Json::commentBefore)) { fprintf(fout, "%s\n", value.getComment(Json::commentBefore).c_str()); } switch (value.type()) { case Json::nullValue: fprintf(fout, "%s=null\n", path.c_str()); break; case Json::intValue: fprintf(fout, "%s=%s\n", path.c_str(), Json::valueToString(value.asLargestInt()).c_str()); break; case Json::uintValue: fprintf(fout, "%s=%s\n", path.c_str(), Json::valueToString(value.asLargestUInt()).c_str()); break; case Json::realValue: fprintf(fout, "%s=%s\n", path.c_str(), normalizeFloatingPointStr(value.asDouble()).c_str()); break; case Json::stringValue: fprintf(fout, "%s=\"%s\"\n", path.c_str(), value.asString().c_str()); break; case Json::booleanValue: fprintf(fout, "%s=%s\n", path.c_str(), value.asBool() ? "true" : "false"); break; case Json::arrayValue: { fprintf(fout, "%s=[]\n", path.c_str()); Json::ArrayIndex size = value.size(); for (Json::ArrayIndex index = 0; index < size; ++index) { static char buffer[16]; jsoncpp_snprintf(buffer, sizeof(buffer), "[%u]", index); printValueTree(fout, value[index], path + buffer); } } break; case Json::objectValue: { fprintf(fout, "%s={}\n", path.c_str()); Json::Value::Members members(value.getMemberNames()); std::sort(members.begin(), members.end()); Json::String suffix = *(path.end() - 1) == '.' ? "" : "."; for (auto name : members) { printValueTree(fout, value[name], path + suffix + name); } } break; default: break; } if (value.hasComment(Json::commentAfter)) { fprintf(fout, "%s\n", value.getComment(Json::commentAfter).c_str()); } } static int parseAndSaveValueTree(const Json::String& input, const Json::String& actual, const Json::String& kind, const Json::Features& features, bool parseOnly, Json::Value* root, bool use_legacy) { if (!use_legacy) { Json::CharReaderBuilder builder; builder.settings_["allowComments"] = features.allowComments_; builder.settings_["strictRoot"] = features.strictRoot_; builder.settings_["allowDroppedNullPlaceholders"] = features.allowDroppedNullPlaceholders_; builder.settings_["allowNumericKeys"] = features.allowNumericKeys_; std::unique_ptr<Json::CharReader> reader(builder.newCharReader()); Json::String errors; const bool parsingSuccessful = reader->parse(input.data(), input.data() + input.size(), root, &errors); if (!parsingSuccessful) { std::cerr << "Failed to parse " << kind << " file: " << std::endl << errors << std::endl; return 1; } // We may instead check the legacy implementation (to ensure it doesn't // randomly get broken). } else { Json::Reader reader(features); const bool parsingSuccessful = reader.parse(input.data(), input.data() + input.size(), *root); if (!parsingSuccessful) { std::cerr << "Failed to parse " << kind << " file: " << std::endl << reader.getFormatedErrorMessages() << std::endl; return 1; } } if (!parseOnly) { FILE* factual = fopen(actual.c_str(), "wt"); if (!factual) { std::cerr << "Failed to create '" << kind << "' actual file." << std::endl; return 2; } printValueTree(factual, *root); fclose(factual); } return 0; } // static Json::String useFastWriter(Json::Value const& root) { // Json::FastWriter writer; // writer.enableYAMLCompatibility(); // return writer.write(root); // } static Json::String useStyledWriter(Json::Value const& root) { Json::StyledWriter writer; return writer.write(root); } static Json::String useStyledStreamWriter(Json::Value const& root) { Json::StyledStreamWriter writer; Json::OStringStream sout; writer.write(sout, root); return sout.str(); } static Json::String useBuiltStyledStreamWriter(Json::Value const& root) { Json::StreamWriterBuilder builder; return Json::writeString(builder, root); } static int rewriteValueTree(const Json::String& rewritePath, const Json::Value& root, Options::writeFuncType write, Json::String* rewrite) { *rewrite = write(root); FILE* fout = fopen(rewritePath.c_str(), "wt"); if (!fout) { std::cerr << "Failed to create rewrite file: " << rewritePath << std::endl; return 2; } fprintf(fout, "%s\n", rewrite->c_str()); fclose(fout); return 0; } static Json::String removeSuffix(const Json::String& path, const Json::String& extension) { if (extension.length() >= path.length()) return Json::String(""); Json::String suffix = path.substr(path.length() - extension.length()); if (suffix != extension) return Json::String(""); return path.substr(0, path.length() - extension.length()); } static void printConfig() { // Print the configuration used to compile JsonCpp #if defined(JSON_NO_INT64) std::cout << "JSON_NO_INT64=1" << std::endl; #else std::cout << "JSON_NO_INT64=0" << std::endl; #endif } static int printUsage(const char* argv[]) { std::cout << "Usage: " << argv[0] << " [--strict] input-json-file" << std::endl; return 3; } static int parseCommandLine(int argc, const char* argv[], Options* opts) { opts->parseOnly = false; opts->write = &useStyledWriter; if (argc < 2) { return printUsage(argv); } int index = 1; if (Json::String(argv[index]) == "--json-checker") { opts->features = Json::Features::strictMode(); opts->parseOnly = true; ++index; } if (Json::String(argv[index]) == "--json-config") { printConfig(); return 3; } if (Json::String(argv[index]) == "--json-writer") { ++index; Json::String const writerName(argv[index++]); if (writerName == "StyledWriter") { opts->write = &useStyledWriter; } else if (writerName == "StyledStreamWriter") { opts->write = &useStyledStreamWriter; } else if (writerName == "BuiltStyledStreamWriter") { opts->write = &useBuiltStyledStreamWriter; } else { std::cerr << "Unknown '--json-writer' " << writerName << std::endl; return 4; } } if (index == argc || index + 1 < argc) { return printUsage(argv); } opts->path = argv[index]; return 0; } static int runTest(Options const& opts, bool use_legacy) { int exitCode = 0; Json::String input = readInputTestFile(opts.path.c_str()); if (input.empty()) { std::cerr << "Invalid input file: " << opts.path << std::endl; return 3; } Json::String basePath = removeSuffix(opts.path, ".json"); if (!opts.parseOnly && basePath.empty()) { std::cerr << "Bad input path '" << opts.path << "'. Must end with '.expected'" << std::endl; return 3; } Json::String const actualPath = basePath + ".actual"; Json::String const rewritePath = basePath + ".rewrite"; Json::String const rewriteActualPath = basePath + ".actual-rewrite"; Json::Value root; exitCode = parseAndSaveValueTree(input, actualPath, "input", opts.features, opts.parseOnly, &root, use_legacy); if (exitCode || opts.parseOnly) { return exitCode; } Json::String rewrite; exitCode = rewriteValueTree(rewritePath, root, opts.write, &rewrite); if (exitCode) { return exitCode; } Json::Value rewriteRoot; exitCode = parseAndSaveValueTree(rewrite, rewriteActualPath, "rewrite", opts.features, opts.parseOnly, &rewriteRoot, use_legacy); return exitCode; } int main(int argc, const char* argv[]) { Options opts; try { int exitCode = parseCommandLine(argc, argv, &opts); if (exitCode != 0) { std::cerr << "Failed to parse command-line." << std::endl; return exitCode; } const int modern_return_code = runTest(opts, false); if (modern_return_code) { return modern_return_code; } const std::string filename = opts.path.substr(opts.path.find_last_of("\\/") + 1); const bool should_run_legacy = (filename.rfind("legacy_", 0) == 0); if (should_run_legacy) { return runTest(opts, true); } } catch (const std::exception& e) { std::cerr << "Unhandled exception:" << std::endl << e.what() << std::endl; return 1; } } #if defined(__GNUC__) #pragma GCC diagnostic pop #endif
C++
3D
mcellteam/mcell
libs/jsoncpp/test/generate_expected.py
.py
576
18
# Copyright 2007 Baptiste Lepilleur and The JsonCpp Authors # Distributed under MIT license, or public domain if desired and # recognized in your jurisdiction. # See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE from __future__ import print_function import glob import os.path for path in glob.glob('*.json'): text = file(path,'rt').read() target = os.path.splitext(path)[0] + '.expected' if os.path.exists(target): print('skipping:', target) else: print('creating:', target) file(target,'wt').write(text)
Python
3D
mcellteam/mcell
libs/jsoncpp/test/cleantests.py
.py
490
17
# Copyright 2007 Baptiste Lepilleur and The JsonCpp Authors # Distributed under MIT license, or public domain if desired and # recognized in your jurisdiction. # See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE """Removes all files created during testing.""" import glob import os paths = [] for pattern in [ '*.actual', '*.actual-rewrite', '*.rewrite', '*.process-output' ]: paths += glob.glob('data/' + pattern) for path in paths: os.unlink(path)
Python
3D
mcellteam/mcell
libs/jsoncpp/test/pyjsontestrunner.py
.py
2,370
72
# Copyright 2007 Baptiste Lepilleur and The JsonCpp Authors # Distributed under MIT license, or public domain if desired and # recognized in your jurisdiction. # See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE """Simple implementation of a json test runner to run the test against json-py.""" from __future__ import print_function import sys import os.path import json import types if len(sys.argv) != 2: print("Usage: %s input-json-file", sys.argv[0]) sys.exit(3) input_path = sys.argv[1] base_path = os.path.splitext(input_path)[0] actual_path = base_path + '.actual' rewrite_path = base_path + '.rewrite' rewrite_actual_path = base_path + '.actual-rewrite' def valueTreeToString(fout, value, path = '.'): ty = type(value) if ty is types.DictType: fout.write('%s={}\n' % path) suffix = path[-1] != '.' and '.' or '' names = value.keys() names.sort() for name in names: valueTreeToString(fout, value[name], path + suffix + name) elif ty is types.ListType: fout.write('%s=[]\n' % path) for index, childValue in zip(xrange(0,len(value)), value): valueTreeToString(fout, childValue, path + '[%d]' % index) elif ty is types.StringType: fout.write('%s="%s"\n' % (path,value)) elif ty is types.IntType: fout.write('%s=%d\n' % (path,value)) elif ty is types.FloatType: fout.write('%s=%.16g\n' % (path,value)) elif value is True: fout.write('%s=true\n' % path) elif value is False: fout.write('%s=false\n' % path) elif value is None: fout.write('%s=null\n' % path) else: assert False and "Unexpected value type" def parseAndSaveValueTree(input, actual_path): root = json.loads(input) fout = file(actual_path, 'wt') valueTreeToString(fout, root) fout.close() return root def rewriteValueTree(value, rewrite_path): rewrite = json.dumps(value) #rewrite = rewrite[1:-1] # Somehow the string is quoted ! jsonpy bug ? file(rewrite_path, 'wt').write(rewrite + '\n') return rewrite input = file(input_path, 'rt').read() root = parseAndSaveValueTree(input, actual_path) rewrite = rewriteValueTree(json.write(root), rewrite_path) rewrite_root = parseAndSaveValueTree(rewrite, rewrite_actual_path) sys.exit(0)
Python
3D
mcellteam/mcell
libs/jsoncpp/test/runjsontests.py
.py
8,490
211
# Copyright 2007 Baptiste Lepilleur and The JsonCpp Authors # Distributed under MIT license, or public domain if desired and # recognized in your jurisdiction. # See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE from __future__ import print_function from __future__ import unicode_literals from io import open from glob import glob import sys import os import os.path import optparse VALGRIND_CMD = 'valgrind --tool=memcheck --leak-check=yes --undef-value-errors=yes ' def getStatusOutput(cmd): """ Return int, unicode (for both Python 2 and 3). Note: os.popen().close() would return None for 0. """ print(cmd, file=sys.stderr) pipe = os.popen(cmd) process_output = pipe.read() try: # We have been using os.popen(). When we read() the result # we get 'str' (bytes) in py2, and 'str' (unicode) in py3. # Ugh! There must be a better way to handle this. process_output = process_output.decode('utf-8') except AttributeError: pass # python3 status = pipe.close() return status, process_output def compareOutputs(expected, actual, message): expected = expected.strip().replace('\r','').split('\n') actual = actual.strip().replace('\r','').split('\n') diff_line = 0 max_line_to_compare = min(len(expected), len(actual)) for index in range(0,max_line_to_compare): if expected[index].strip() != actual[index].strip(): diff_line = index + 1 break if diff_line == 0 and len(expected) != len(actual): diff_line = max_line_to_compare+1 if diff_line == 0: return None def safeGetLine(lines, index): index += -1 if index >= len(lines): return '' return lines[index].strip() return """ Difference in %s at line %d: Expected: '%s' Actual: '%s' """ % (message, diff_line, safeGetLine(expected,diff_line), safeGetLine(actual,diff_line)) def safeReadFile(path): try: return open(path, 'rt', encoding = 'utf-8').read() except IOError as e: return '<File "%s" is missing: %s>' % (path,e) def runAllTests(jsontest_executable_path, input_dir = None, use_valgrind=False, with_json_checker=False, writerClass='StyledWriter'): if not input_dir: input_dir = os.path.join(os.getcwd(), 'data') tests = glob(os.path.join(input_dir, '*.json')) if with_json_checker: all_test_jsonchecker = glob(os.path.join(input_dir, '../jsonchecker', '*.json')) # These tests fail with strict json support, but pass with jsoncpp extra lieniency """ Failure details: * Test ../jsonchecker/fail25.json Parsing should have failed: [" tab character in string "] * Test ../jsonchecker/fail13.json Parsing should have failed: {"Numbers cannot have leading zeroes": 013} * Test ../jsonchecker/fail18.json Parsing should have failed: [[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]] * Test ../jsonchecker/fail8.json Parsing should have failed: ["Extra close"]] * Test ../jsonchecker/fail7.json Parsing should have failed: ["Comma after the close"], * Test ../jsonchecker/fail10.json Parsing should have failed: {"Extra value after close": true} "misplaced quoted value" * Test ../jsonchecker/fail27.json Parsing should have failed: ["line break"] """ known_differences_withjsonchecker = [ "fail25.json", "fail13.json", "fail18.json", "fail8.json", "fail7.json", "fail10.json", "fail27.json" ] test_jsonchecker = [ test for test in all_test_jsonchecker if os.path.basename(test) not in known_differences_withjsonchecker ] else: test_jsonchecker = [] failed_tests = [] valgrind_path = use_valgrind and VALGRIND_CMD or '' for input_path in tests + test_jsonchecker: expect_failure = os.path.basename(input_path).startswith('fail') is_json_checker_test = (input_path in test_jsonchecker) or expect_failure print('TESTING:', input_path, end=' ') options = is_json_checker_test and '--json-checker' or '' options += ' --json-writer %s'%writerClass cmd = '%s%s %s "%s"' % ( valgrind_path, jsontest_executable_path, options, input_path) status, process_output = getStatusOutput(cmd) if is_json_checker_test: if expect_failure: if not status: print('FAILED') failed_tests.append((input_path, 'Parsing should have failed:\n%s' % safeReadFile(input_path))) else: print('OK') else: if status: print('FAILED') failed_tests.append((input_path, 'Parsing failed:\n' + process_output)) else: print('OK') else: base_path = os.path.splitext(input_path)[0] actual_output = safeReadFile(base_path + '.actual') actual_rewrite_output = safeReadFile(base_path + '.actual-rewrite') open(base_path + '.process-output', 'wt', encoding = 'utf-8').write(process_output) if status: print('parsing failed') failed_tests.append((input_path, 'Parsing failed:\n' + process_output)) else: expected_output_path = os.path.splitext(input_path)[0] + '.expected' expected_output = open(expected_output_path, 'rt', encoding = 'utf-8').read() detail = (compareOutputs(expected_output, actual_output, 'input') or compareOutputs(expected_output, actual_rewrite_output, 'rewrite')) if detail: print('FAILED') failed_tests.append((input_path, detail)) else: print('OK') if failed_tests: print() print('Failure details:') for failed_test in failed_tests: print('* Test', failed_test[0]) print(failed_test[1]) print() print('Test results: %d passed, %d failed.' % (len(tests)-len(failed_tests), len(failed_tests))) return 1 else: print('All %d tests passed.' % len(tests)) return 0 def main(): from optparse import OptionParser parser = OptionParser(usage="%prog [options] <path to jsontestrunner.exe> [test case directory]") parser.add_option("--valgrind", action="store_true", dest="valgrind", default=False, help="run all the tests using valgrind to detect memory leaks") parser.add_option("-c", "--with-json-checker", action="store_true", dest="with_json_checker", default=False, help="run all the tests from the official JSONChecker test suite of json.org") parser.enable_interspersed_args() options, args = parser.parse_args() if len(args) < 1 or len(args) > 2: parser.error('Must provides at least path to jsontestrunner executable.') sys.exit(1) jsontest_executable_path = os.path.normpath(os.path.abspath(args[0])) if len(args) > 1: input_path = os.path.normpath(os.path.abspath(args[1])) else: input_path = None status = runAllTests(jsontest_executable_path, input_path, use_valgrind=options.valgrind, with_json_checker=options.with_json_checker, writerClass='StyledWriter') if status: sys.exit(status) status = runAllTests(jsontest_executable_path, input_path, use_valgrind=options.valgrind, with_json_checker=options.with_json_checker, writerClass='StyledStreamWriter') if status: sys.exit(status) status = runAllTests(jsontest_executable_path, input_path, use_valgrind=options.valgrind, with_json_checker=options.with_json_checker, writerClass='BuiltStyledStreamWriter') if status: sys.exit(status) if __name__ == '__main__': main()
Python
3D
mcellteam/mcell
libs/jsoncpp/test/rununittests.py
.py
2,922
85
# Copyright 2009 Baptiste Lepilleur and The JsonCpp Authors # Distributed under MIT license, or public domain if desired and # recognized in your jurisdiction. # See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE from __future__ import print_function from __future__ import unicode_literals from io import open from glob import glob import sys import os import os.path import subprocess import optparse VALGRIND_CMD = 'valgrind --tool=memcheck --leak-check=yes --undef-value-errors=yes' class TestProxy(object): def __init__(self, test_exe_path, use_valgrind=False): self.test_exe_path = os.path.normpath(os.path.abspath(test_exe_path)) self.use_valgrind = use_valgrind def run(self, options): if self.use_valgrind: cmd = VALGRIND_CMD.split() else: cmd = [] cmd.extend([self.test_exe_path, '--test-auto'] + options) try: process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) except: print(cmd) raise stdout = process.communicate()[0] if process.returncode: return False, stdout return True, stdout def runAllTests(exe_path, use_valgrind=False): test_proxy = TestProxy(exe_path, use_valgrind=use_valgrind) status, test_names = test_proxy.run(['--list-tests']) if not status: print("Failed to obtain unit tests list:\n" + test_names, file=sys.stderr) return 1 test_names = [name.strip() for name in test_names.decode('utf-8').strip().split('\n')] failures = [] for name in test_names: print('TESTING %s:' % name, end=' ') succeed, result = test_proxy.run(['--test', name]) if succeed: print('OK') else: failures.append((name, result)) print('FAILED') failed_count = len(failures) pass_count = len(test_names) - failed_count if failed_count: print() for name, result in failures: print(result) print('%d/%d tests passed (%d failure(s))' % ( pass_count, len(test_names), failed_count)) return 1 else: print('All %d tests passed' % len(test_names)) return 0 def main(): from optparse import OptionParser parser = OptionParser(usage="%prog [options] <path to test_lib_json.exe>") parser.add_option("--valgrind", action="store_true", dest="valgrind", default=False, help="run all the tests using valgrind to detect memory leaks") parser.enable_interspersed_args() options, args = parser.parse_args() if len(args) != 1: parser.error('Must provides at least path to test_lib_json executable.') sys.exit(1) exit_code = runAllTests(args[0], use_valgrind=options.valgrind) sys.exit(exit_code) if __name__ == '__main__': main()
Python