public void testCreateInstrumentedProxyWithDefaults() throws Exception { final MasterInstrumenter masterInstrumenter = new MasterInstrumenter(m_loggerStubFactory.getLogger(), false); assertEquals( "traditional Jython instrumenter; " + "byte code transforming instrumenter for Java", masterInstrumenter.getDescription()); m_loggerStubFactory.assertOutputMessageContains("traditional Jython"); m_loggerStubFactory.assertNoMoreCalls(); try { masterInstrumenter.createInstrumentedProxy(null, m_recorder, null); fail("Expected NotWrappableTypeException"); } catch (NotWrappableTypeException e) { } final Object foo = new Object(); final PyObject proxy = (PyObject) masterInstrumenter.createInstrumentedProxy(m_test, m_recorder, foo); assertSame(proxy.__getattr__("__target__").__tojava__(Object.class), foo); try { masterInstrumenter.createInstrumentedProxy(m_test, m_recorder, new PyObject()); fail("Expected NotWrappableTypeException"); } catch (NotWrappableTypeException e) { } }
@Test public void testCreateInstrumentedProxy() throws Exception { final GrinderProperties properties = new GrinderProperties(); final DCRContext context = DCRContextImplementation.create(null); final List<Instrumenter> instrumenters = new JythonScriptEngineService(properties, context, m_pyScript).createInstrumenters(); assertEquals(1, instrumenters.size()); final Instrumenter instrumenter = instrumenters.get(0); assertEquals("traditional Jython instrumenter", instrumenter.getDescription()); final Object foo = new Object(); PySystemState.initialize(); final PyObject proxy = (PyObject) instrumenter.createInstrumentedProxy(m_test, m_recorder, foo); assertSame(proxy.__getattr__("__target__").__tojava__(Object.class), foo); try { instrumenter.createInstrumentedProxy(m_test, m_recorder, new PyObject()); fail("Expected NotWrappableTypeException"); } catch (NotWrappableTypeException e) { } }
/** * This method is called when the module is loaded, to populate the namespace (dictionary) of the * module. The dictionary has been initialised at this point reflectively from the methods of this * class and this method nulls those entries that ought not to be exposed. * * @param dict namespace of the module */ public static void classDictInit(PyObject dict) { dict.__setitem__("__name__", new PyString("_io")); dict.__setitem__("__doc__", new PyString(__doc__)); dict.__setitem__("DEFAULT_BUFFER_SIZE", DEFAULT_BUFFER_SIZE); dict.__setitem__("_IOBase", PyIOBase.TYPE); dict.__setitem__("_RawIOBase", PyRawIOBase.TYPE); dict.__setitem__("FileIO", PyFileIO.TYPE); // Define UnsupportedOperation exception by constructing the type PyObject exceptions = imp.load("exceptions"); PyObject ValueError = exceptions.__getattr__("ValueError"); PyObject IOError = exceptions.__getattr__("IOError"); // Equivalent to class UnsupportedOperation(ValueError, IOError) : pass // UnsupportedOperation = makeException(dict, "UnsupportedOperation", ValueError, IOError); // XXX Work-around: slots not properly initialised unless IOError comes first UnsupportedOperation = makeException(dict, "UnsupportedOperation", IOError, ValueError); // Hide from Python dict.__setitem__("classDictInit", null); dict.__setitem__("makeException", null); }
public Object visitTryExcept(TryExcept node) throws Exception { String cleanup = getUnique("tryExceptCleanup"); String totalEnd = getUnique("tryExceptEnd"); java.util.List<String> exceptStarts = new ArrayList<>(); for (excepthandler handler : node.getInternalHandlers()) { String exceptStart = getUnique("exceptStart"); exceptStarts.add(exceptStart); String exceptType = null; PyObject type = handler.__getattr__("type"); if (type == Py.None) { exceptType = "All$"; } else { exceptType = type.__getattr__("id").asString(); } addLine("EXCEPT " + exceptType + " " + exceptStart); } // EXCEPT TYPE BLOCK // EXCEPT TYPE2 BLOCK2 // ETC... CompiledCode body = new CompiledCode(node.getInternalBody()); insert(body); // skip to cleanup addLine("JUMP " + cleanup); for (int i = 0; i < node.getInternalHandlers().size(); i++) { excepthandler handler = node.getInternalHandlers().get(i); addLine("LABEL " + exceptStarts.get(i)); // We need to manually end the excepts for handlers which were declared before the one which // caught the exception // if we catch the first one, we don't need to end anything. If we catch the last one, we need // to end all but one of them for (int i2 = 0; i2 < i; i2++) // 0, do 0, 1 do 1, n, do n { addLine("ENDEXCEPT"); } // to the state it was in at the time the EXCEPT was declared if (handler.__getattr__("name") != Py.None) { String name = handler.__getattr__("name").__getattr__("id").asString(); addLine("POP " + name); } else { addLine("POP $"); // otherwise pop to a dummy name } @SuppressWarnings("unchecked") CompiledCode exceptBody = new CompiledCode((AstList) handler.__getattr__("body")); insert(exceptBody); // we cleaned up the exception handlers at the start of the block, so we need not clean them // up here. addLine("JUMP " + totalEnd); } addLine("LABEL " + cleanup); for (int i = 0; i < node.getInternalHandlers().size(); i++) { addLine("ENDEXCEPT"); } // and, since no exceptions were called, we might as well just execute the orElse block CompiledCode orElseBody = new CompiledCode(node.getInternalOrelse()); insert(orElseBody); addLine("LABEL " + totalEnd); return null; }
/** * Open file and return a stream. Raise IOError upon failure. This is a port to Java of the * CPython _io.open (Modules/_io/_iomodule.c) following the same logic, but expressed with the * benefits of Java syntax. * * @param args array of arguments from Python call via Jython framework * @param kwds array of keywords from Python call via Jython framework * @return the stream object */ public static PyObject open(PyObject[] args, String[] kwds) { // Get the arguments to variables ArgParser ap = new ArgParser("open", args, kwds, openKwds, 1); PyObject file = ap.getPyObject(0); String m = ap.getString(1, "r"); int buffering = ap.getInt(2, -1); final String encoding = ap.getString(3, null); final String errors = ap.getString(4, null); final String newline = ap.getString(5, null); boolean closefd = Py.py2boolean(ap.getPyObject(6, Py.True)); // Decode the mode string OpenMode mode = new OpenMode(m) { @Override public void validate() { super.validate(); validate(encoding, errors, newline); } }; mode.checkValid(); /* * Create the Raw file stream. Let the constructor deal with the variants and argument * checking. */ PyFileIO raw = new PyFileIO(file, mode, closefd); /* * From the Python documentation for io.open() buffering = 0 to switch buffering off (only * allowed in binary mode), 1 to select line buffering (only usable in text mode), and an * integer > 1 to indicate the size of a fixed-size buffer. * * When no buffering argument is given, the default buffering policy works as follows: * Binary files are buffered in fixed-size chunks; "Interactive" text files (files for which * isatty() returns True) use line buffering. Other text files use the policy described * above for binary files. * * In Java, it seems a stream never is *known* to be interactive, but we ask anyway, and * maybe one day we shall know. */ boolean line_buffering = false; if (buffering == 0) { if (!mode.binary) { throw Py.ValueError("can't have unbuffered text I/O"); } return raw; } else if (buffering == 1) { // The stream is to be read line-by-line. line_buffering = true; // Force default size for actual buffer buffering = -1; } else if (buffering < 0 && raw.isatty()) { // No buffering argument given but stream is inteeractive. line_buffering = true; } if (buffering < 0) { /* * We are still being asked for the default buffer size. CPython establishes the default * buffer size using fstat(fd), but Java appears to give no clue. A useful study of * buffer sizes in NIO is http://www.evanjones.ca/software/java-bytebuffers.html . This * leads us to the fixed choice of _DEFAULT_BUFFER_SIZE (=8KB). */ buffering = _DEFAULT_BUFFER_SIZE; } /* * We now know just what particular class of file we are opening, and therefore what stack * (buffering and text encoding) we should build. */ if (buffering == 0) { // Not buffering, return the raw file object return raw; } else { // We are buffering, so wrap raw into a buffered file PyObject bufferType = null; PyObject io = imp.load("io"); if (mode.updating) { bufferType = io.__getattr__("BufferedRandom"); } else if (mode.writing || mode.appending) { bufferType = io.__getattr__("BufferedWriter"); } else { // = reading bufferType = io.__getattr__("BufferedReader"); } PyInteger pyBuffering = new PyInteger(buffering); PyObject buffer = bufferType.__call__(raw, pyBuffering); if (mode.binary) { // If binary, return the just the buffered file return buffer; } else { // We are opening in text mode, so wrap buffered file in a TextIOWrapper. PyObject textType = io.__getattr__("TextIOWrapper"); PyObject[] textArgs = { buffer, ap.getPyObject(3, Py.None), ap.getPyObject(4, Py.None), ap.getPyObject(5, Py.None), Py.newBoolean(line_buffering) }; PyObject wrapper = textType.__call__(textArgs); wrapper.__setattr__("mode", new PyString(m)); return wrapper; } } }