File: TestBase.java

package info (click to toggle)
jython 2.5.3-16%2Bdeb9u1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 43,772 kB
  • ctags: 106,434
  • sloc: python: 351,322; java: 216,349; xml: 1,584; sh: 330; perl: 114; ansic: 102; makefile: 45
file content (419 lines) | stat: -rw-r--r-- 14,450 bytes parent folder | download | duplicates (4)
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
/**
 * Copyright 2009, Google Inc.  All rights reserved.
 * Licensed to PSF under a Contributor Agreement.
 */
package org.python.indexer;

import junit.framework.TestCase;

import org.python.indexer.Def;
import org.python.indexer.Ref;
import org.python.indexer.ast.NNode;
import org.python.indexer.types.NType;
import org.python.indexer.types.NUnknownType;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

/**
 * Test utilities for {@link IndexerTest}.
 */
public class TestBase extends TestCase {

    static protected final String TEST_SOURCE_DIR;
    static protected final String TEST_DATA_DIR;
    static protected final String TEST_LIB_DIR;

    static {
        TEST_SOURCE_DIR =
            System.getProperties().getProperty("python.test.source.dir")
            + "/org/python/indexer/";
        TEST_DATA_DIR = TEST_SOURCE_DIR + "data/";
        TEST_LIB_DIR = System.getProperties().getProperty("python.home") + "/Lib/";
    }

    protected Indexer idx;

    public TestBase() {
    }

    @Override
    protected void setUp() throws Exception {
        idx = new Indexer();
        idx.enableAggressiveAssertions(true);
        idx.setProjectDir(TEST_DATA_DIR);
        AstCache.get().clearDiskCache();
        AstCache.get().clear();
    }

    /**
     * Call this at the beginning of a test to permit the test code to import
     * modules from the Python standard library.
     */
    protected void includeStandardLibrary() throws Exception {
        idx.addPath(TEST_LIB_DIR);
    }

    protected String abspath(String file) {
        return getTestFilePath(file);
    }

    /**
     * Return absolute path for {@code file}, a relative path under the
     * data/ directory.
     */
    protected String getTestFilePath(String file) {
        return TEST_DATA_DIR + file;
    }

    protected String getSource(String file) throws Exception {
        String path = getTestFilePath(file);
        StringBuilder sb = new StringBuilder();
        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
        String line;
        while ((line = in.readLine()) != null) {
            sb.append(line);
            sb.append("\n");
        }
        in.close();  // not overly worried about resource cleanup in unit tests
        return sb.toString();
    }

    /**
     * Construct python source by joining the specified lines.
     */
    protected String makeModule(String... lines) {
        StringBuilder sb = new StringBuilder();
        for (String line : lines) {
            sb.append(line).append("\n");
        }
        return sb.toString();
    }

    /**
     * Build an index out of the specified file and content lines,
     * and return the resulting module source.
     */
    protected String index(String filename, String... lines) throws Exception {
        String src = makeModule(lines);
        idx.loadString(filename, src);
        idx.ready();
        return src;
    }

    /**
     * Return offset in {@code s} of {@code n}th occurrence of {@code find}.
     * {@code n} is 1-indexed.
     * @throws IllegalArgumentException if the {@code n}th occurrence does not exist
     */
    protected int nthIndexOf(String s, String find, int n) {
        if (n <= 0)
            throw new IllegalArgumentException();
        int index = -1;
        for (int i = 0; i < n; i++) {
            index = s.indexOf(find, index == -1 ? 0 : index + 1);
            if (index == -1)
                throw new IllegalArgumentException();
        }
        return index;
    }

    // meta-tests

    public void testHandleExceptionLoggingNulls() throws Exception {
        try {
            idx.enableAggressiveAssertions(false);
            idx.getLogger().setLevel(java.util.logging.Level.OFF);
            idx.handleException(null, new Exception());
            idx.handleException("oops", null);
        } catch (Throwable t) {
            fail("should not have thrown: " + t);
        }
    }

    public void testDataFileFindable() throws Exception {
        assertTrue("Test file not found", new java.io.File(TEST_DATA_DIR).exists());
    }

    public void testLoadDataFile() throws Exception {
        String path = abspath("test-load.txt");
        BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(path)));
        assertEquals(in.readLine().trim(), "hello");
        in.close();
    }

    public void testGetSource() throws Exception {
        String src = getSource("testsrc.txt");
        assertEquals("one\ntwo\n\nthree\n", src);
    }

    public void testStringModule() throws Exception {
        idx.loadString("test-string-module.py", makeModule(
            "def foo():",
            "  pass"));
        idx.ready();
        assertFunctionBinding("test-string-module.foo");
    }

    public void testNthIndexOf() throws Exception {
        String s = "ab a b ab a\nb aab";
        assertEquals(0, nthIndexOf(s, "ab", 1));
        assertEquals(7, nthIndexOf(s, "ab", 2));
        assertEquals(15, nthIndexOf(s, "ab", 3));
        try {
            assertEquals(-1, nthIndexOf(s, "ab", 0));
            assertTrue(false);
        } catch (IllegalArgumentException ix) {
            assertTrue(true);
        }
        try {
            assertEquals(-1, nthIndexOf(s, "ab", 4));
            assertTrue(false);
        } catch (IllegalArgumentException ix) {
            assertTrue(true);
        }
    }

    public void testIndexerDefaults() throws Exception {
        includeStandardLibrary();
        assertEquals("wrong project dir", TEST_DATA_DIR, idx.projDir);
        assertEquals("unexpected load path entries", 1, idx.path.size());
        assertEquals(TEST_LIB_DIR, idx.path.get(0));
    }

    // utilities

    public String buildIndex(String... files) throws Exception {
        for (String f : files) {
            idx.loadFile(abspath(f));
        }
        idx.ready();
        return getSource(files[0]);
    }

    public NBinding getBinding(String qname) throws Exception {
        NBinding b = idx.lookupQname(qname);
        assertNotNull("no binding found for " + qname, b);
        return b;
    }

    public NBinding assertBinding(String qname, NBinding.Kind kind) throws Exception {
        NBinding b = getBinding(qname);
        assertEquals(kind, b.getKind());
        return b;
    }

    public void assertNoBinding(String qname) throws Exception {
        NBinding b = idx.lookupQname(qname);
        assertNull("Should not have found binding for " + qname, b);
    }

    public NBinding assertAttributeBinding(String qname) throws Exception {
        return assertBinding(qname, NBinding.Kind.ATTRIBUTE);
    }

    public NBinding assertBuiltinBinding(String qname) throws Exception {
        NBinding b = getBinding(qname);
        assertTrue(b.isBuiltin());
        return b;
    }

    public NBinding assertClassBinding(String qname) throws Exception {
        return assertBinding(qname, NBinding.Kind.CLASS);
    }

    public NBinding assertConstructorBinding(String qname) throws Exception {
        return assertBinding(qname, NBinding.Kind.CONSTRUCTOR);
    }

    public NBinding assertFunctionBinding(String qname) throws Exception {
        return assertBinding(qname, NBinding.Kind.FUNCTION);
    }

    public NBinding assertMethodBinding(String qname) throws Exception {
        return assertBinding(qname, NBinding.Kind.METHOD);
    }

    public NBinding assertModuleBinding(String qname) throws Exception {
        return assertBinding(qname, NBinding.Kind.MODULE);
    }

    public NBinding assertScopeBinding(String qname) throws Exception {
        return assertBinding(qname, NBinding.Kind.SCOPE);
    }

    public NBinding assertVariableBinding(String qname) throws Exception {
        return assertBinding(qname, NBinding.Kind.VARIABLE);
    }

    public NBinding assertParamBinding(String qname) throws Exception {
        return assertBinding(qname, NBinding.Kind.PARAMETER);
    }

    public void assertStaticSynthetic(NBinding b) {
        assertTrue(b.isStatic());
        assertTrue(b.isSynthetic());
    }

    public Def getDefinition(String qname, int offset, int length) throws Exception {
        NBinding b = getBinding(qname);
        assertNotNull(b.getDefs());
        for (Def def : b.getDefs()) {
            if (offset == def.start() && length == def.end() - def.start()) {
                return def;
            }
        }
        return null;
    }

    public void assertDefinition(String qname, int offset, int length) throws Exception {
        Def def = getDefinition(qname, offset, length);
        if (def == null) {
            fail("No definition for " + qname + " at " + offset + " of len " + length);
        }
    }

    public void assertNoDefinition(String msg, String qname, int pos, int len) throws Exception {
        Def def = getDefinition(qname, pos, len);
        assertNull(msg, def);
    }

    public void assertDefinition(String qname, int offset) throws Exception {
        String[] names = qname.split("[.&@]");
        assertDefinition(qname, offset, names[names.length-1].length());
    }

    public void assertDefinition(String qname, String name, int offset) throws Exception {
        assertDefinition(qname, offset, name.length());
    }

    public Ref getRefOrNull(String qname, int offset, int length) throws Exception {
        NBinding b = getBinding(qname);
        assertNotNull("Null refs list for " + qname, b.getRefs());
        for (Ref ref : b.getRefs()) {
            if (offset == ref.start() && length == ref.length()) {
                return ref;
            }
        }
        return null;
    }

    public Ref getRefOrFail(String qname, int offset, int length) throws Exception {
        Ref ref = getRefOrNull(qname, offset, length);
        assertNotNull("No reference to " + qname + " at offset " + offset + " of length " + length,
                      ref);
        return ref;
    }

    public void assertReference(String qname, int offset, int length) throws Exception {
        assertTrue(getRefOrFail(qname, offset, length).isRef());
    }

    public void assertReference(String qname, int offset, String refname) throws Exception {
        assertReference(qname, offset, refname.length());
    }

    // assume reference to "a.b.c" is called "c" -- the normal case
    public void assertReference(String qname, int offset) throws Exception {
        String[] names = qname.split("[.&@]");
        assertReference(qname, offset, names[names.length-1]);
    }

    public void assertNoReference(String msg, String qname, int pos, int len) throws Exception {
        assertNull(msg, getRefOrNull(qname, pos, len));
    }

    public void assertCall(String qname, int offset, int length) throws Exception {
        assertTrue(getRefOrFail(qname, offset, length).isCall());
    }

    public void assertCall(String qname, int offset, String refname) throws Exception {
        assertCall(qname, offset, refname.length());
    }

    // "a.b.c()" => look for call reference at "c"
    public void assertCall(String qname, int offset) throws Exception {
        String[] names = qname.split("[.&@]");
        assertCall(qname, offset, names[names.length-1]);
    }

    public void assertConstructed(String qname, int offset, int length) throws Exception {
        assertTrue(getRefOrFail(qname, offset, length).isNew());
    }

    public void assertConstructed(String qname, int offset, String refname) throws Exception {
        assertConstructed(qname, offset, refname.length());
    }

    // "a.b.c()" => look for call reference at "c"
    public void assertConstructed(String qname, int offset) throws Exception {
        String[] names = qname.split("[.&@]");
        assertConstructed(qname, offset, names[names.length-1]);
    }

    public NType getTypeBinding(String typeQname) throws Exception {
        NType type = idx.lookupQnameType(typeQname);
        assertNotNull("No recorded type for " + typeQname, type);
        return type;
    }

    // Assert that binding for qname has exactly one type (not a union),
    // and that type has a binding with typeQname.
    public NBinding assertBindingType(String bindingQname, String typeQname) throws Exception {
        NBinding b = getBinding(bindingQname);
        NType expected = getTypeBinding(typeQname);
        assertEquals("Wrong binding type", expected, NUnknownType.follow(b.getType()));
        return b;
    }

    public NBinding assertBindingType(String bindingQname, Class type) throws Exception {
        NBinding b = getBinding(bindingQname);
        NType btype = NUnknownType.follow(b.getType());
        assertTrue("Wrong type: expected " + type + " but was " + btype,
                   type.isInstance(btype));
        return b;
    }

    public void assertListType(String bindingQname) throws Exception {
        assertListType(bindingQname, null);
    }

    /**
     * Asserts that the binding named by {@code bindingQname} exists and
     * its type is a List type.  If {@code eltTypeQname} is non-{@code null},
     * asserts that the List type's element type is an existing binding with
     * {@code eltTypeQname}.
     */
    public void assertListType(String bindingQname, String eltTypeQname) throws Exception {
        NBinding b = getBinding(bindingQname);
        NType btype = b.followType();
        assertTrue(btype.isListType());
        if (eltTypeQname != null) {
            NType eltType = getTypeBinding(eltTypeQname);
            assertEquals(eltType, NUnknownType.follow(btype.asListType().getElementType()));
        }
    }

    public void assertStringType(String bindingQname) throws Exception {
        assertBindingType(bindingQname, "__builtin__.str");
    }

    public void assertNumType(String bindingQname) throws Exception {
        assertBindingType(bindingQname, "__builtin__.float");
    }

    public void assertInstanceType(String bindingQname, String classQname) throws Exception {
        if (true) {
            assertBindingType(bindingQname, classQname);
            return;
        }

        // XXX:  we've disabled support for NInstanceType for now
        NBinding b = getBinding(bindingQname);
        NType btype = b.followType();
        assertTrue(btype.isInstanceType());
        NType ctype = getTypeBinding(classQname);
        assertEquals(btype.asInstanceType().getClassType(), ctype);
    }
}