(get_module)
| 133 | @pytest.mark.skipif(sys.version_info >= (3, 12), reason="no numpy.distutils") |
| 134 | @pytest.mark.slow |
| 135 | def test_cstruct(get_module): |
| 136 | |
| 137 | class data_source: |
| 138 | """ |
| 139 | This class is for testing the timing of the PyCapsule destructor |
| 140 | invoked when numpy release its reference to the shared data as part of |
| 141 | the numpy array interface protocol. If the PyCapsule destructor is |
| 142 | called early the shared data is freed and invalid memory accesses will |
| 143 | occur. |
| 144 | """ |
| 145 | |
| 146 | def __init__(self, size, value): |
| 147 | self.size = size |
| 148 | self.value = value |
| 149 | |
| 150 | @property |
| 151 | def __array_struct__(self): |
| 152 | return get_module.new_array_struct(self.size, self.value) |
| 153 | |
| 154 | # write to the same stream as the C code |
| 155 | stderr = sys.__stderr__ |
| 156 | |
| 157 | # used to validate the shared data. |
| 158 | expected_value = -3.1415 |
| 159 | multiplier = -10000.0 |
| 160 | |
| 161 | # create some data to share with numpy via the array interface |
| 162 | # assign the data an expected value. |
| 163 | stderr.write(' ---- create an object to share data ---- \n') |
| 164 | buf = data_source(256, expected_value) |
| 165 | stderr.write(' ---- OK!\n\n') |
| 166 | |
| 167 | # share the data |
| 168 | stderr.write(' ---- share data via the array interface protocol ---- \n') |
| 169 | arr = np.array(buf, copy=False) |
| 170 | stderr.write('arr.__array_interface___ = %s\n' % ( |
| 171 | str(arr.__array_interface__))) |
| 172 | stderr.write('arr.base = %s\n' % (str(arr.base))) |
| 173 | stderr.write(' ---- OK!\n\n') |
| 174 | |
| 175 | # release the source of the shared data. this will not release the data |
| 176 | # that was shared with numpy, that is done in the PyCapsule destructor. |
| 177 | stderr.write(' ---- destroy the object that shared data ---- \n') |
| 178 | buf = None |
| 179 | stderr.write(' ---- OK!\n\n') |
| 180 | |
| 181 | # check that we got the expected data. If the PyCapsule destructor we |
| 182 | # defined was prematurely called then this test will fail because our |
| 183 | # destructor sets the elements of the array to NaN before free'ing the |
| 184 | # buffer. Reading the values here may also cause a SEGV |
| 185 | assert np.allclose(arr, expected_value) |
| 186 | |
| 187 | # read the data. If the PyCapsule destructor we defined was prematurely |
| 188 | # called then reading the values here may cause a SEGV and will be reported |
| 189 | # as invalid reads by valgrind |
| 190 | stderr.write(' ---- read shared data ---- \n') |
| 191 | stderr.write('arr = %s\n' % (str(arr))) |
| 192 | stderr.write(' ---- OK!\n\n') |
nothing calls this directly
no test coverage detected