changeset 17:0812422ec99e

Added a context.get_property() method.
author Atul Varma <varmaa@toolness.com>
date Sun, 28 Jun 2009 19:44:13 -0700
parents 532b7ddca616
children f3223debd70b
files context.c test_pymonkey.py
diffstat 2 files changed, 54 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/context.c	Sun Jun 28 19:01:43 2009 -0700
+++ b/context.c	Sun Jun 28 19:44:13 2009 -0700
@@ -48,6 +48,47 @@
 }
 
 static PyObject *
+PYM_getProperty(PYM_JSContextObject *self, PyObject *args)
+{
+  // TODO: We're making a lot of copies of the string here, which
+  // can't be very efficient.
+
+  PYM_JSObject *object;
+  char *string;
+
+  if (!JS_CStringsAreUTF8()) {
+    PyErr_SetString(PyExc_NotImplementedError,
+                    "Data type conversion not implemented.");
+    return NULL;
+  }
+
+  if (!PyArg_ParseTuple(args, "O!es", &PYM_JSObjectType, &object,
+                        "utf-8", &string))
+    return NULL;
+
+  JSString *jsString = JS_NewStringCopyZ(self->cx, string);
+  if (jsString == NULL) {
+    PyMem_Free(string);
+    PyErr_SetString(PYM_error, "JS_NewStringCopyZ() failed");
+    return NULL;
+  }
+
+  jsval val;
+  if (!JS_GetUCProperty(self->cx, object->obj,
+                        JS_GetStringChars(jsString),
+                        JS_GetStringLength(jsString), &val)) {
+    // TODO: Get the actual JS exception. Any exception that exists
+    // here will probably still be pending on the JS context.
+    PyMem_Free(string);
+    PyErr_SetString(PYM_error, "Getting property failed.");
+    return NULL;
+  }
+
+  PyMem_Free(string);
+  return PYM_jsvalToPyObject(val);
+}
+
+static PyObject *
 PYM_initStandardClasses(PYM_JSContextObject *self, PyObject *args)
 {
   PYM_JSObject *object;
@@ -107,7 +148,8 @@
    "Evaluate the given JavaScript code in the context of the given "
    "global object, using the given filename"
    "and line number information."},
-
+  {"get_property", (PyCFunction) PYM_getProperty, METH_VARARGS,
+   "Gets the given property for the given JavaScript object."},
   {NULL, NULL, 0, NULL}
 };
 
--- a/test_pymonkey.py	Sun Jun 28 19:01:43 2009 -0700
+++ b/test_pymonkey.py	Sun Jun 28 19:44:13 2009 -0700
@@ -9,6 +9,17 @@
         cx.init_standard_classes(obj)
         return cx.evaluate_script(obj, code, '<string>', 1)
 
+    def testObjectGetattrWorks(self):
+        cx = pymonkey.Runtime().new_context()
+        obj = cx.new_object()
+        cx.init_standard_classes(obj)
+        cx.evaluate_script(obj, 'boop = 5', '<string>', 1)
+        cx.evaluate_script(obj, 'this["blarg\u2026"] = 5', '<string>', 1)
+        self.assertEqual(cx.get_property(obj, "beans"),
+                         pymonkey.undefined)
+        self.assertEqual(cx.get_property(obj, u"blarg\u2026"), 5)
+        self.assertEqual(cx.get_property(obj, "boop"), 5)
+
     def testContextIsInstance(self):
         cx = pymonkey.Runtime().new_context()
         self.assertTrue(isinstance(cx, pymonkey.Context))