-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathPyBufferTest.java
More file actions
1783 lines (1567 loc) · 67.9 KB
/
Copy pathPyBufferTest.java
File metadata and controls
1783 lines (1567 loc) · 67.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.python.core;
import java.lang.ref.Reference;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import junit.framework.TestCase;
import org.python.core.buffer.BaseBuffer;
import org.python.core.buffer.SimpleBuffer;
import org.python.core.buffer.SimpleStringBuffer;
import org.python.core.buffer.SimpleWritableBuffer;
import org.python.util.PythonInterpreter;
/**
* Test the several implementations (and exporters) of the PyBuffer interface provided in the Jython
* core.
* <p>
* The approach is to create test material once that has the necessary variety in byte array values,
* then for each test, when the JUnit framework creates an instance of the function-specific test,
* to use this material to create instances of each read-only type and each writable type. Writable
* instance types go onto the lists buffersToRead and buffersToWrite, while read-only instances go
* onto the lists buffersToRead and buffersToFailToWrite.
* <p>
* In general, tests of methods that read data apply themselves to all the elements of the
* buffersToRead list, while tests of methods that write data apply themselves to all the elements
* of the buffersToWrite list and check that members of the buffersToFailToWrite list raise an
* exception.
* <p>
* The Jython buffer API follows the structures of the CPython buffer API so that it supports in
* principle the use of multi-dimensional, strided and indirect array structures as buffers.
* However, actual buffers in the Jython core, and therefore these tests, limit themselves to one
* dimensional (possibly non-contiguous) directly-indexed buffers. Some tests apply directly to the
* N-dimensional cases, and some need a complete re-think. Sub-classing this test would probably be
* a good way to extend it to a wider range.
*/
public class PyBufferTest extends TestCase {
/** Control amount of output. Instance variable so can be adjusted temporarily in test. */
protected int verbosity = 0;
/**
* Generated constructor
*
* @param name
*/
public PyBufferTest(String name) {
super(name);
}
/** Sometimes we need the interpreter to be initialised **/
PythonInterpreter interp;
/*
* Values for initialising the exporters.
*/
private static final ByteMaterial byteMaterial = new ByteMaterial(0, 16, 17);
private static final ByteMaterial abcMaterial = new ByteMaterial("abcdefgh");
private static final ByteMaterial stringMaterial = new ByteMaterial("Mon côté fâcheux");
private static final ByteMaterial emptyMaterial = new ByteMaterial(new byte[0]);
public static final int LONG = 1000;
private static final ByteMaterial longMaterial = new ByteMaterial(0, LONG, 5);
@Override
protected void setUp() throws Exception {
super.setUp();
// Exception raising requires the Jython interpreter
interp = new PythonInterpreter();
// Tests using local types of exporter
genWritable(new SimpleWritableExporter(abcMaterial.getBytes()), abcMaterial);
genReadonly(new SimpleExporter(byteMaterial.getBytes()), byteMaterial);
genReadonly(new StringExporter(stringMaterial.string), stringMaterial);
genWritable(new SimpleWritableExporter(emptyMaterial.getBytes()), emptyMaterial);
// Tests with PyByteArray
genWritable(new PyByteArray(abcMaterial.getBytes()), abcMaterial);
genWritable(new PyByteArray(longMaterial.getBytes()), longMaterial);
genWritable(new PyByteArray(), emptyMaterial);
// Tests with PyBytes
genReadonly(new PyBytes(abcMaterial.string), abcMaterial);
genReadonly(new PyBytes(), emptyMaterial);
// Ensure case is tested where PyByteArray has an internal offset
PyByteArray truncated = new PyByteArray(stringMaterial.getBytes());
truncated.delRange(0, 4);
ByteMaterial truncatedMaterial = new ByteMaterial(stringMaterial.string.substring(4));
assert truncated.__alloc__() > truncatedMaterial.length;
genWritable(truncated, truncatedMaterial);
}
/** Generate a series of test material for a writable object. */
private void genWritable(BufferProtocol exporter, ByteMaterial material) {
generate(exporter, material, false);
}
/** Generate a series of test material for a read-only object. */
private void genReadonly(BufferProtocol exporter, ByteMaterial material) {
generate(exporter, material, true);
}
/** Lengths we will use if we can when slicing view */
private static final int[] sliceLengths = {1, 2, 5, 0, LONG / 4};
/** Step sizes we will use if we can when slicing view */
private static final int[] sliceSteps = {1, 2, 3, 7};
/**
* Generate a series of test material for a read-only or writable object. Given one exporter,
* and its reference ByteMaterial this method first queues a BufferTestPair corresponding to the
* exporter as the test subject and its test material. This provides a "direct" PyBuffer view on
* the exporter. It then goes on to make a variety of sliced PyBuffer views of the exporter by
* calling {@link PyBuffer#getBufferSlice(int, int, int, int)} on the direct view. The slices
* are made with a variety of argument combinations, filtered down to those that make sense for
* the size of the direct view. Each sliced buffer (considered a test subject now), together
* with correspondingly sliced reference ByteMaterial is queued as BufferTestPair.
*
* @param exporter underlying object
* @param material reference material corresponding to the exporter
* @param readonly whether the exporter is of read-only type
*/
private void generate(BufferProtocol exporter, ByteMaterial material, boolean readonly) {
// Generate a test using the buffer directly exported by the exporter
PyBuffer direct = queue(exporter, material, readonly);
// Generate some slices from the material and this direct view
int N = material.length;
int M = (N + 4) / 4; // At least one and about N/4
// For a range of start positions up to one beyond the end
for (int start = 0; start <= N; start += M) {
// For a range of lengths
for (int length : sliceLengths) {
if (length == 0) {
queue(direct, material, start, 0, 1, readonly);
queue(direct, material, start, 0, 2, readonly);
} else if (length == 1 && start < N) {
queue(direct, material, start, 1, 1, readonly);
queue(direct, material, start, 1, 2, readonly);
} else if (start < N) {
// And for a range of step sizes
for (int step : sliceSteps) {
// Check this is a feasible slice
if (start + (length - 1) * step < N) {
queue(direct, material, start, length, step, readonly);
}
}
// Now use all the step sizes negatively
for (int step : sliceSteps) {
// Check this is a feasible slice
if (start - (length - 1) * step >= 0) {
queue(direct, material, start, length, -step, readonly);
}
}
}
}
}
}
/** Generate and queue one test of non-slice type (if getting a buffer succeeds). */
private PyBuffer queue(BufferProtocol exporter, ByteMaterial material, boolean readonly) {
if (verbosity > 2) {
System.out.printf("queue non-slice: length=%d, readonly=%s\n", material.length,
readonly);
}
BufferTestPair pair = new BufferTestPair(exporter, material, readonly);
queue(pair);
return pair.view;
}
/** Generate and queue one test of slice type (if getting a buffer succeeds). */
private PyBuffer queue(PyBuffer direct, ByteMaterial material, int start, int length, int step,
boolean readonly) {
int flags = readonly ? PyBUF.FULL_RO : PyBUF.FULL;
PyBuffer subject = null;
/*
* Make a slice. We ignore this case if we fail, because we are not testing slice creation
* here, but making slices to be tested as buffers. We'll test slice creation in
* testGetBufferSlice.
*/
try {
if (verbosity > 2) {
System.out.printf(" queue slice: start=%4d, length=%4d, step=%4d\n", start,
length, step);
}
subject = direct.getBufferSlice(flags, start, length, step);
ByteMaterial sliceMaterial = material.slice(start, length, step);
BufferTestPair pair = new BufferTestPair(subject, sliceMaterial, step, readonly);
queue(pair);
} catch (Exception e) {
/*
* We ignore this case if we fail, because we are not testing slice creation here, but
* making slices to be tested as buffers. We'll test slice creation elsewhere.
*/
if (verbosity > 2) {
System.out.printf("*** SKIP %s\n", e);
}
}
return subject;
}
/** Queue one instance of test material for a read-only or writable object. */
private void queue(BufferTestPair pair) {
buffersToRead.add(pair);
if (pair.readonly) {
buffersToFailToWrite.add(pair);
} else {
buffersToWrite.add(pair);
}
}
/** Read operations should succeed on all these objects. */
private List<BufferTestPair> buffersToRead = new LinkedList<BufferTestPair>();
/** Write operations should succeed on all these objects. */
private List<BufferTestPair> buffersToWrite = new LinkedList<BufferTestPair>();
/** Write operations should fail on all these objects. */
private List<BufferTestPair> buffersToFailToWrite = new LinkedList<BufferTestPair>();
/**
* A one-dimensional exporter should be able to give us a buffer for all these flag types.
*/
private static final int[] simpleFlags = {PyBUF.SIMPLE, PyBUF.ND, PyBUF.STRIDES,
PyBUF.INDIRECT, PyBUF.FULL_RO};
/** To {@link #simpleFlags} we can add any of these */
private static final int[] simpleTassles = {0, PyBUF.FORMAT, PyBUF.C_CONTIGUOUS,
PyBUF.F_CONTIGUOUS, PyBUF.ANY_CONTIGUOUS};
/**
* A one-dimensional exporter with stride!=1 is restricted to give us a buffer only for these
* flag types.
*/
private static final int[] strided1DFlags = {PyBUF.STRIDES, PyBUF.INDIRECT, PyBUF.FULL_RO};
/** To {@link #strided1DFlags} we can add any of these */
private static final int[] strided1DTassles = {0, PyBUF.FORMAT};
/**
* Test method for {@link org.python.core.PyBUF#isReadonly()}.
*/
public void testIsReadonly() {
for (BufferTestPair test : buffersToWrite) {
if (verbosity > 0) {
System.out.println("isReadonly: " + test);
}
assertFalse(test.view.isReadonly());
}
for (BufferTestPair test : buffersToFailToWrite) {
if (verbosity > 0) {
System.out.println("isReadonly: " + test);
}
assertTrue(test.view.isReadonly());
}
}
/**
* Test method for {@link org.python.core.PyBUF#getNdim()}.
*/
public void testGetNdim() {
for (BufferTestPair test : buffersToRead) {
if (verbosity > 0) {
System.out.println("getNdim: " + test);
}
assertEquals("unexpected ndim", test.shape.length, test.view.getNdim());
}
}
/**
* Test method for {@link org.python.core.PyBUF#getShape()}.
*/
public void testGetShape() {
for (BufferTestPair test : buffersToRead) {
if (verbosity > 0) {
System.out.println("getShape: " + test);
}
int[] shape = test.view.getShape();
assertNotNull("shape[] should always be provided", shape);
assertIntsEqual("unexpected shape", test.shape, shape);
}
}
/**
* Test method for {@link org.python.core.PyBUF#getLen()}.
*/
public void testGetLen() {
for (BufferTestPair test : buffersToRead) {
if (verbosity > 0) {
System.out.println("getLen: " + test);
}
assertEquals("unexpected length", test.material.length, test.view.getLen());
}
}
/**
* Test method for {@link org.python.core.PyBuffer#byteAt(int)}.
*/
public void testByteAt() {
for (BufferTestPair test : buffersToRead) {
if (verbosity > 0) {
System.out.println("byteAt: " + test);
}
int n = test.material.length;
byte[] exp = test.material.bytes;
for (int i = 0; i < n; i++) {
assertEquals(exp[i], test.view.byteAt(i));
}
}
}
/**
* Test method for {@link org.python.core.PyBuffer#byteAt(int[])}.
*/
public void testByteAtNdim() {
int[] index = new int[1];
for (BufferTestPair test : buffersToRead) {
if (verbosity > 0) {
System.out.println("byteAt(array): " + test);
}
if (test.view.getShape().length != 1) {
fail("Test not implemented if dimensions != 1");
}
byte[] exp = test.material.bytes;
int n = test.material.length;
// Run through 1D index for view
for (int i = 0; i < n; i++) {
index[0] = i;
assertEquals(exp[i], test.view.byteAt(index));
}
// Check 2D index throws
try {
test.view.byteAt(0, 0);
fail("Use of 2D index did not raise exception");
} catch (PyException pye) {
// Expect BufferError
assertEquals(Py.BufferError, pye.type);
}
}
}
/**
* Test method for {@link org.python.core.PyBuffer#intAt(int)}.
*/
public void testIntAt() {
for (BufferTestPair test : buffersToRead) {
if (verbosity > 0) {
System.out.println("intAt: " + test);
}
int n = test.material.length;
int[] exp = test.material.ints;
for (int i = 0; i < n; i++) {
assertEquals(exp[i], test.view.intAt(i));
}
}
}
/**
* Test method for {@link org.python.core.PyBuffer#intAt(int[])}.
*/
public void testIntAtNdim() {
int[] index = new int[1];
for (BufferTestPair test : buffersToRead) {
if (verbosity > 0) {
System.out.println("intAt(array): " + test);
}
if (test.view.getShape().length != 1) {
fail("Test not implemented for dimensions != 1");
}
int[] exp = test.material.ints;
int n = test.material.length;
// Run through 1D index for view
for (int i = 0; i < n; i++) {
index[0] = i;
assertEquals(exp[i], test.view.intAt(index));
}
// Check 2D index throws
try {
test.view.intAt(0, 0);
fail("Use of 2D index did not raise exception");
} catch (PyException pye) {
// Expect BufferError
assertEquals(Py.BufferError, pye.type);
}
}
}
/**
* Test method for {@link org.python.core.PyBuffer#storeAt(byte, int)}.
*/
public void testStoreAt() {
for (BufferTestPair test : buffersToWrite) {
if (verbosity > 0) {
System.out.println("storeAt: " + test);
}
int n = test.material.length;
int[] exp = test.material.ints;
// Write modified test material into each location using storeAt()
for (int i = 0; i < n; i++) {
byte v = (byte)(exp[i] ^ 3); // twiddle some bits
test.view.storeAt(v, i);
}
// Compare each location with modified test data using intAt()
for (int i = 0; i < n; i++) {
assertEquals(exp[i] ^ 3, test.view.intAt(i));
}
}
}
/**
* Test method for {@link org.python.core.PyBuffer#storeAt(byte, int[])}.
*/
public void testStoreAtNdim() {
for (BufferTestPair test : buffersToWrite) {
if (verbosity > 0) {
System.out.println("storeAt: " + test);
}
int n = test.material.length;
int[] exp = test.material.ints;
// Write modified test material into each location using storeAt()
for (int i = 0; i < n; i++) {
byte v = (byte)(exp[i] ^ 3); // twiddle some bits
test.view.storeAt(v, i);
}
// Compare each location with modified test data using intAt()
for (int i = 0; i < n; i++) {
assertEquals(exp[i] ^ 3, test.view.intAt(i));
}
// Check 2D index throws
try {
test.view.storeAt((byte)1, 0, 0);
fail("Use of 2D index did not raise exception");
} catch (PyException pye) {
// Expect BufferError
assertEquals(Py.BufferError, pye.type);
}
}
}
/**
* Test method for {@link org.python.core.PyBuffer#copyTo(byte[], int)}.
*/
public void testCopyTo() {
final int OFFSET = 5;
for (BufferTestPair test : buffersToRead) {
if (verbosity > 0) {
System.out.println("copyTo: " + test);
}
int n = test.material.length;
// Try with zero offset
byte[] actual = new byte[n];
test.view.copyTo(actual, 0);
assertBytesEqual("copyTo() incorrect", test.material.bytes, actual, 0);
// Try to middle of array
actual = new byte[n + 2 * OFFSET];
test.view.copyTo(actual, OFFSET);
assertBytesEqual("copyTo(offset) incorrect", test.material.bytes, actual, OFFSET);
assertEquals("data before destination", 0, actual[OFFSET - 1]);
assertEquals("data after destination", 0, actual[OFFSET + n]);
}
}
/**
* Test method for {@link org.python.core.PyBuffer#copyTo(int, byte[], int, int)}.
*/
public void testSliceCopyTo() {
final int OFFSET = 5;
final byte BLANK = 7;
for (BufferTestPair test : buffersToRead) {
if (verbosity > 0) {
System.out.println("copyTo(from slice): " + test);
}
PyBuffer view = test.view;
int n = test.material.length;
byte[] actual = new byte[n + 2 * OFFSET];
// Try destination positions in actual[] of 0 and OFFSET
for (int destPos = 0; destPos <= OFFSET; destPos += OFFSET) {
// Try source positions in 0 and OFFSET
for (int srcIndex = 0; srcIndex <= OFFSET; srcIndex += OFFSET) {
// A variety of lengths from zero to (n-srcIndex)-ish
for (int length = 0; srcIndex + length <= n; length = 2 * length + 1) {
if (verbosity > 1) {
System.out.printf(" copy src[%d:%d] (%d) to dst[%d:%d] (%d)\n",
srcIndex, srcIndex + length, n, destPos, destPos + length,
actual.length);
}
Arrays.fill(actual, BLANK);
// Test the method
view.copyTo(srcIndex, actual, destPos, length);
// Check changed part of destination
assertBytesEqual("copyTo(slice) incorrect", test.material.bytes, srcIndex,
length, actual, destPos);
if (destPos > 0) {
assertEquals("data before destination", BLANK, actual[destPos - 1]);
}
assertEquals("data after destination", BLANK, actual[destPos + length]);
}
// And from exactly n-srcIndex down to zero-ish
for (int trim = 0; srcIndex + trim <= n; trim = 2 * trim + 1) {
int length = n - srcIndex - trim;
if (verbosity > 1) {
System.out.printf(" copy src[%d:%d] (%d) to dst[%d:%d] (%d)\n",
srcIndex, srcIndex + length, n, destPos, destPos + length,
actual.length);
}
Arrays.fill(actual, BLANK);
// Test the method
view.copyTo(srcIndex, actual, destPos, length);
// Check changed part of destination
assertBytesEqual("copyTo(slice) incorrect", test.material.bytes, srcIndex,
length, actual, destPos);
if (destPos > 0) {
assertEquals("data before destination", BLANK, actual[destPos - 1]);
}
assertEquals("data after destination", BLANK, actual[destPos + length]);
}
}
}
}
}
/**
* Test method for {@link org.python.core.PyBuffer#copyFrom(byte[], int, int, int)}.
*/
public void testCopyFrom() {
final int OFFSET = 5;
final byte BLANK = 7;
for (BufferTestPair test : buffersToWrite) {
if (verbosity > 0) {
System.out.println("copyFrom(): " + test);
}
PyBuffer view = test.view;
int n = test.material.length;
byte[] actual = new byte[n];
byte[] expected = new byte[n];
// Make some source material for copies (need to test at OFFSET too).
byte[] src = new byte[n + OFFSET];
for (int i = 0; i < src.length; i++) {
src[i] = (byte)i;
}
// Try destination positions in test object of 0 and OFFSET
for (int destIndex = 0; destIndex <= OFFSET; destIndex += OFFSET) {
// Try source positions in 0 and OFFSET
for (int srcPos = 0; srcPos <= OFFSET; srcPos += OFFSET) {
// A variety of lengths from zero to (n-destIndex)-ish
for (int length = 0; destIndex + length <= n; length = 2 * length + 1) {
if (verbosity > 1) {
System.out.printf(" copy src[%d:%d] (%d) to dst[%d:%d] (%d)\n",
srcPos, srcPos + length, n, destIndex, destIndex + length,
actual.length);
}
// Initialise the object (have to do each time) and expected value
for (int i = 0; i < n; i++) {
expected[i] = BLANK;
view.storeAt(BLANK, i);
}
// Test the method and extract the result to actual[]
view.copyFrom(src, srcPos, destIndex, length);
view.copyTo(actual, 0);
// Complete what is should be in expected[]
for (int i = 0; i < length; i++) {
expected[destIndex + i] = src[srcPos + i];
}
assertBytesEqual("copyFrom() incorrect", expected, actual, 0);
}
// And from exactly n-destIndex down to zero-ish
for (int trim = 0; destIndex + trim <= n; trim = 2 * trim + 1) {
int length = n - destIndex - trim;
if (verbosity > 1) {
System.out.printf(" copy src[%d:%d] (%d) to dst[%d:%d] (%d)\n",
srcPos, srcPos + length, n, destIndex, destIndex + length,
actual.length);
}
// Initialise the object (have to do each time) and expected value
for (int i = 0; i < n; i++) {
expected[i] = BLANK;
view.storeAt(BLANK, i);
}
// Test the method and extract the result to actual[]
view.copyFrom(src, srcPos, destIndex, length);
view.copyTo(actual, 0);
// Complete what is should be in expected[]
for (int i = 0; i < length; i++) {
expected[destIndex + i] = src[srcPos + i];
}
assertBytesEqual("copyFrom() incorrect", expected, actual, 0);
}
}
}
}
}
/**
* Test method for {@link org.python.core.BufferProtocol#getBuffer()} and
* {@link org.python.core.PyBuffer#getBuffer()}.
*/
public void testGetBuffer() {
for (BufferTestPair test : buffersToRead) {
if (verbosity > 0) {
System.out.println("getBuffer(): " + test);
}
for (int flags : test.validFlags) {
for (int tassle : test.validTassles) {
PyBuffer view = test.subject.getBuffer(flags | tassle);
assertNotNull(view);
}
}
}
for (BufferTestPair test : buffersToWrite) {
if (verbosity > 0) {
System.out.println("getBuffer(WRITABLE): " + test);
}
for (int flags : test.validFlags) {
for (int tassle : test.validTassles) {
PyBuffer view = test.subject.getBuffer(flags | tassle | PyBUF.WRITABLE);
assertNotNull(view);
}
}
}
for (BufferTestPair test : buffersToFailToWrite) {
if (verbosity > 0) {
System.out.println("getBuffer(WRITABLE): " + test);
}
for (int flags : test.validFlags) {
try {
test.subject.getBuffer(flags | PyBUF.WRITABLE);
fail("Write access not prevented: " + test);
} catch (PyException pye) {
// Expect BufferError
assertEquals(Py.BufferError, pye.type);
}
}
}
}
/**
* Test method for {@link org.python.core.PyBUF#release()}, exercising the release semantics of
* PyBuffer.
*/
public void testRelease() {
/*
* Testing the semantics of release() is tricky when it comes to 'final' release behaviour.
* We'd like to test that buffers can be acquired and released, that "over release" is
* detected as an error, and that after final release of the buffer (where the export count
* becomes zero) an exporter remains capable of exporting again. Each test is constructed
* with a subject and a view on the subject (if the subject is an exporter), so you might
* think the export count would be one in every case. Two problems: in many tests, the
* subject is a PyBuffer, which has the option (if it would work) to return itself; and a
* PyBuffer is not expected to provide a new buffer view once finally released.
*/
Set<PyBuffer> uniqueBuffers = new HashSet<PyBuffer>();
// Test a balanced sequence of acquire and release using try-with-resources
for (BufferTestPair test : buffersToRead) {
doTestTryWithResources(test);
}
// Now test a pattern of acquire and release with one more release than acquire
for (BufferTestPair test : buffersToRead) {
doTestRelease(test);
uniqueBuffers.add(test.view);
}
// All buffers are released: test that any further release is detected as an error.
for (PyBuffer view : uniqueBuffers) {
doTestOverRelease(view);
}
// All exporters are currently not exporting buffers
for (BufferTestPair test : buffersToRead) {
if (!(test.subject instanceof PyBuffer)) {
doTestGetAfterRelease(test);
}
}
}
/**
* Exercise try-with-resources on one BufferTestPair.
*/
private void doTestTryWithResources(BufferTestPair test) {
if (verbosity > 0) {
System.out.println("try with resources: " + test);
}
int flags = PyBUF.STRIDES | PyBUF.FORMAT;
BufferProtocol sub = test.subject;
// The object will be exporting test.view and N other views we don't know about
try (PyBuffer c = sub.getBuffer(flags)) { // = N+1 exports
try (PyBuffer b = sub.getBuffer(PyBUF.FULL_RO); PyBuffer d =c.getBuffer(flags)) {
checkExporting(sub);// = N+3 exports
}
checkExporting(sub); // = N+1 exports
}
checkExporting(sub); // = N export
}
/**
* Exercise the release semantics of one BufferTestPair. At the end, the view in the
* BufferTestPair should be fully released, ({@link PyBuffer#isReleased()}<code>==true</code>).
*/
private void doTestRelease(BufferTestPair test) {
if (verbosity > 0) {
System.out.println("release: " + test);
}
int flags = PyBUF.STRIDES | PyBUF.FORMAT;
BufferProtocol sub = test.subject;
// The object will be exporting test.view and N other views we don't know about
PyBuffer a = test.view; // = N+1 exports
PyBuffer b = sub.getBuffer(PyBUF.FULL_RO); // = N+2 export
PyBuffer c = sub.getBuffer(flags); // = N+3 exports
checkExporting(sub);
// Now see that releasing in some other order works correctly
b.release(); // = N+2 exports
a.release(); // = N+1 exports
checkExporting(sub);
// You can get a buffer from a buffer (c is unreleased)
PyBuffer d = c.getBuffer(flags); // = N+2 exports
c.release(); // = N+1 export
checkExporting(sub);
d.release(); // = N exports
}
/**
* The view argument should be a fully released buffer, ({@link PyBuffer#isReleased()}
* <code>==true</code>). We check that further releases raise an error.
*/
private void doTestOverRelease(PyBuffer view) {
// Was it released finally?
assertTrue("Buffer not finally released as expected", view.isReleased());
// Further releases are an error
try {
view.release(); // = -1 exports (oops)
fail("excess release not detected");
} catch (Exception e) {
// Success
}
}
/**
* The test in the argument is one where the subject is a real object (not another buffer) from
* which all buffer views should have been released in {@link #doTestRelease(BufferTestPair)}.
* We check this is true, and that a new buffer may still be acquired from the real object, but
* not from the released buffer.
*/
private void doTestGetAfterRelease(BufferTestPair test) {
if (verbosity > 0) {
System.out.println("get again: " + test);
}
BufferProtocol sub = test.subject;
// Fail here if doTestRelease did not fully release, or
checkNotExporting(sub);
// Further gets via the released buffer are an error
try {
test.view.getBuffer(PyBUF.FULL_RO);
fail("PyBuffer.getBuffer after final release not detected");
} catch (Exception e) {
// Detected *and* prevented?
checkNotExporting(sub);
}
// And so are sliced gets
try {
test.view.getBufferSlice(PyBUF.FULL_RO, 0, 0);
fail("PyBuffer.getBufferSlice after final release not detected");
} catch (Exception e) {
// Detected *and* prevented?
checkNotExporting(sub);
}
/*
* Even after some abuse, we can still get and release a buffer.
*/
PyBuffer b = sub.getBuffer(PyBUF.FULL_RO); // = 1 export
checkExporting(sub);
b.release(); // = 0 exports
checkNotExporting(sub);
}
/**
* Error if subject is a PyBuffer and is released, or is a real exporter that (we can tell) is
* not actually exporting.
*
* @param subject
*/
private void checkExporting(BufferProtocol subject) {
if (subject instanceof TestableExporter) {
assertTrue("exports not being counted", ((TestableExporter)subject).isExporting());
} else if (subject instanceof PyBuffer) {
assertFalse("exports not being counted (PyBuffer)", ((PyBuffer)subject).isReleased());
} else if (subject instanceof PyByteArray) {
// Size-changing access should fail
try {
((PyByteArray)subject).bytearray_extend(Py.One); // Appends one zero byte
fail("bytearray_extend with exports should fail");
} catch (Exception e) {
// Success
}
}
// Other types cannot be checked
}
/**
* Error if subject is a PyBuffer that is released, or is a real exporter (that we can tell) is
* locked.
*
* @param subject
*/
private void checkNotExporting(BufferProtocol subject) {
if (subject instanceof TestableExporter) {
assertFalse("exports counted incorrectly", ((TestableExporter)subject).isExporting());
} else if (subject instanceof PyBuffer) {
assertTrue("exports counted incorrectly (PyBuffer)", ((PyBuffer)subject).isReleased());
} else if (subject instanceof PyByteArray) {
// Size-changing access should succeed
try {
PyByteArray sub = ((PyByteArray)subject);
sub.bytearray_append(Py.Zero);
sub.del(sub.__len__() - 1);
} catch (Exception e) {
fail("bytearray unexpectedly locked");
}
}
// Other types cannot be checked
}
/**
* Test method for {@link org.python.core.PyBuffer#getBufferSlice(int, int, int, int)}.
*/
public void testGetBufferSliceWithStride() {
for (BufferTestPair test : buffersToRead) {
if (verbosity > 0) {
System.out.println("getBufferSliceWithStride: " + test);
}
ByteMaterial material = test.material;
PyBuffer view = test.view;
boolean readonly = test.readonly;
// Generate some slices from the material and the test view
int N = material.length;
int M = (N + 4) / 4; // At least one and about N/4
// For a range of start positions up to one beyond the end
for (int start = 0; start <= N; start += M) {
// For a range of lengths
for (int length : sliceLengths) {
if (length == 0) {
checkSlice(view, material, start, 0, 1, readonly);
checkSlice(view, material, start, 0, 2, readonly);
} else if (length == 1 && start < N) {
checkSlice(view, material, start, 1, 1, readonly);
checkSlice(view, material, start, 1, 2, readonly);
} else if (start < N) {
// And for a range of step sizes
for (int step : sliceSteps) {
// Check this is a feasible slice
if (start + (length - 1) * step < N) {
checkSlice(view, material, start, length, step, readonly);
}
}
// Now use all the step sizes negatively
for (int step : sliceSteps) {
// Check this is a feasible slice
if (start - (length - 1) * step >= 0) {
checkSlice(view, material, start, length, -step, readonly);
}
}
}
}
}
}
}
/**
* Helper for {@link #testGetBufferSliceWithStride()} that obtains one sliced buffer to
* specification and checks it against the material.
*/
private void checkSlice(PyBuffer view, ByteMaterial material, int start, int length, int step,
boolean readonly) {
int flags = readonly ? PyBUF.FULL_RO : PyBUF.FULL;
if (verbosity > 1) {
System.out.printf(" checkSlice: start=%4d, length=%4d, step=%4d \n", start, length,
step);
}
byte[] expected = sliceBytes(material.bytes, start, length, step);
PyBuffer sliceView = view.getBufferSlice(flags, start, length, step);
byte[] result = bytesFromByteAt(sliceView);
assertBytesEqual(" testGetBufferSliceWithStride failure: ", expected, result);
}
/**
* Test method for {@link org.python.core.PyBuffer#getBuf()}.
*/
public void testGetBuf() {
for (BufferTestPair test : buffersToRead) {
if (verbosity > 0) {
System.out.println("getBuf: " + test);
}
int stride = test.strides[0];
if (stride == 1) {
// The client should not have to support navigation with the strides array
int flags = test.readonly ? PyBUF.SIMPLE : PyBUF.SIMPLE + PyBUF.WRITABLE;
PyBuffer view = test.subject.getBuffer(flags);
PyBuffer.Pointer bp = view.getBuf();
assertBytesEqual("buffer does not match reference", test.material.bytes, bp);
} else {
// The client will have to navigate with the strides array
int flags = test.readonly ? PyBUF.STRIDED_RO : PyBUF.STRIDED;
PyBuffer view = test.subject.getBuffer(flags);
stride = view.getStrides()[0]; // Just possibly != test.strides when length<=1
PyBuffer.Pointer bp = view.getBuf();
assertBytesEqual("buffer does not match reference", test.material.bytes, bp, stride);
}
}
}
/**
* Test method for {@link org.python.core.PyBuffer#getPointer(int)}.
*/
public void testGetPointer() {
for (BufferTestPair test : buffersToRead) {
if (verbosity > 0) {