Commits

Lenard Lindstrom committed 949ac8c

Correct Event readonly attributes test for Python 3.x: the exception raised on assignment differs from 2.x.

  • Participants
  • Parent commits b206b62

Comments (0)

Files changed (7)

examples/scrap_clipboard.py

 import pygame
 from pygame.locals import *
 import pygame.scrap as scrap
-import StringIO
+from pygame.compat import as_bytes
+BytesIO = pygame.compat.get_BytesIO()
 
 def usage ():
     print ("Press the 'g' key to get all of the current clipboard data")
             for t in scrap.get_types ():
                 r = scrap.get (t)
                 if r and len (r) > 500:
-                    print ("Type %s : (large buffer)" % t)
+                    print ("Type %s : (large %i byte buffer)" % (t, len(r)))
+                elif r is None:
+                    print ("Type %s : None" % (t,))
                 else:
-                    print ("Type %s : %s" % (t, r))
+                    print ("Type %s : '%s'" % (t, r.decode('ascii', 'replace')))
                 if "image" in t:
                     namehint = t.split("/")[1]
                     if namehint in ['bmp', 'png', 'jpg']:
-                        f = StringIO.StringIO(r)
+                        f = BytesIO(r)
                         loaded_surf = pygame.image.load(f, "." + namehint)
                         screen.blit(loaded_surf, (0,0))
 
         elif e.type == KEYDOWN and e.key == K_p:
             # Place some text into the selection.
             print ("Placing clipboard text.")
-            scrap.put (SCRAP_TEXT, "Hello. This is a message from scrap.")
+            scrap.put (SCRAP_TEXT,
+                       as_bytes("Hello. This is a message from scrap."))
 
         elif e.type == KEYDOWN and e.key == K_a:
             # Get all available types.
             types = scrap.get_types ()
             print (types)
             if len (types) > 0:
-                print ("Contains %s: %s" % (types[0], scrap.contains (types[0])))
+                print ("Contains %s: %s" %
+                       (types[0], scrap.contains (types[0])))
                 print ("Contains _INVALID_: ", scrap.contains ("_INVALID_"))
 
         elif e.type == KEYDOWN and e.key == K_i:
 
 #python 3.x: remove modules not yet ported
 if sys.version_info >= (3, 0, 0):
-    python3_skip = ['scrap',
-                    '_movie',
+    python3_skip = ['_movie',
                     '_numericsurfarray',
                     '_numericsndarray',
-                    ]
+                   ]
+    if (sys.platform != 'linux2'):
+        python3_skip.append('scrap')
     tmp_extensions = extensions
     extensions = []
     for e in tmp_extensions:
 #include "scrap.h"
 #include "pygame.h"
 #include "doc/scrap_doc.h"
+#include "pgcompat.h"
 
 /**
  * Indicates, whether pygame.scrap was initialized or not.
 {
     int i = 0;
     char **types;
+    char *type;
     PyObject *list;
     PyObject *tmp;
     
         return list;
     while (types[i] != NULL)
     {
-        tmp = PyString_FromString (types[i]);
-        PyList_Append (list, tmp);
+        type = types[i];
+        tmp = PyUnicode_DecodeASCII (type, strlen (type), 0);
+        if (!tmp) {
+            Py_DECREF (list);
+            return 0;
+        }
+        if (PyList_Append (list, tmp)) {
+            Py_DECREF (list);
+            Py_DECREF (tmp);
+            return 0;
+        }
         Py_DECREF (tmp);
         i++;
     }
     if (!scrap)
         Py_RETURN_NONE;
 
-    retval = PyString_FromStringAndSize (scrap, count);
+    retval = Bytes_FromStringAndSize (scrap, count);
     return retval;
 }
 #endif
     char *scrap = NULL;
     char *scrap_type;
     PyObject *tmp;
+#if PY3
+    static const char argfmt[] = "sy#";
+#else
+    static char argfmt[] = "st#";
+#endif
 
     PYGAME_SCRAP_INIT_CHECK ();
 
-    if (!PyArg_ParseTuple (args, "st#", &scrap_type, &scrap, &scraplen))
+    if (!PyArg_ParseTuple (args, argfmt, &scrap_type, &scrap, &scraplen)) {
         return NULL;
+    }
 
     /* Set it in the clipboard. */
     if (!pygame_scrap_put (scrap_type, scraplen, scrap))
     {
     case SCRAP_SELECTION:
     {
-        tmp = PyString_FromStringAndSize (scrap, scraplen);
+        tmp = Bytes_FromStringAndSize (scrap, scraplen);
         PyDict_SetItemString (_selectiondata, scrap_type, tmp);
         Py_DECREF (tmp);
         break;
     case SCRAP_CLIPBOARD:
     default:
     {
-        tmp = PyString_FromStringAndSize (scrap, scraplen);
+        tmp = Bytes_FromStringAndSize (scrap, scraplen);
         PyDict_SetItemString (_clipdata, scrap_type, tmp);
         Py_DECREF (tmp);
         break;
     { NULL, NULL, 0, NULL}
 };
 
-PYGAME_EXPORT
-void initscrap (void)
+MODINIT_DEFINE (scrap)
 {
-    PyObject *mod;
+    PyObject *module;
+
+#if PY3
+    static struct PyModuleDef _module = {
+        PyModuleDef_HEAD_INIT,
+        "scrap",
+        "",
+        -1,
+        scrap_builtins,
+        NULL, NULL, NULL, NULL
+    };
+#endif
 
     /* imported needed apis; Do this first so if there is an error
        the module is not loaded.
     */
     import_pygame_base ();
     if (PyErr_Occurred ()) {
-        return;
+        MODINIT_ERROR;
     }
 
     /* create the module */
-    mod = Py_InitModule3 (MODPREFIX "scrap", scrap_builtins, NULL);
+#if PY3
+    module = PyModule_Create (&_module);
+#else
+    module = Py_InitModule3 (MODPREFIX "scrap", scrap_builtins, NULL);
+#endif
+
+    MODINIT_RETURN (module);
 }
     PyObject *tmp;
     char *key = _atom_to_string (cliptype);
 
-    tmp = PyString_FromStringAndSize (data, srclen);
+    tmp = Bytes_FromStringAndSize (data, srclen);
     PyDict_SetItemString (dict, key, tmp);
     Py_DECREF (tmp);
     XChangeProperty (SDL_Display, SDL_Window, clip, cliptype,
     int i;
     char *format;
     PyObject *list = PyDict_Keys (data);
+#if PY3
+    PyObject *chars;
+#endif
     int amount = PyList_Size (list);
     /* All types plus the TARGETS and a TIMESTAMP atom. */
     Atom *targets = malloc ((amount + 2) * sizeof (Atom));
     targets[1] = _atom_TIMESTAMP;
     for (i = 0; i < amount; i++)
     {
+#if PY3
+        chars = PyUnicode_AsASCIIString (PyList_GetItem (list, i));
+        if (!chars) {
+            return;
+        }
+        format = PyBytes_AsString (chars);
+#else
         format = PyString_AsString (PyList_GetItem(list, i));
+#endif
         targets[i + 2] = _convert_format (format);
+#if PY3
+	Py_DECREF (chars);
+#endif
     }
     XChangeProperty (display, window, property, XA_ATOM, 32, PropModeReplace,
                      (unsigned char*) targets, amount + 2);
         XFree (name);
         return 0;
     }
-    size = PyString_Size (val);
-    value = PyString_AsString (val);
+    size = Bytes_Size (val);
+    value = Bytes_AsString (val);
 
     /* Send data. */
     XChangeProperty (display, window, property, target, 8, PropModeReplace,
 static char*
 _get_data_as (Atom source, Atom format, unsigned long *length)
 {
-    char *retval = NULL;
+    unsigned char *retval = NULL;
     Window owner;
     time_t start;
     Atom sel_type;
         fmt = _atom_to_string (format);
 
         if (_currentmode == SCRAP_SELECTION)
-            data = PyString_AsString
+            data = Bytes_AsString
                 (PyDict_GetItemString (_selectiondata, fmt));
         else
-            data = PyString_AsString (PyDict_GetItemString (_clipdata, fmt));
+            data = Bytes_AsString (PyDict_GetItemString (_clipdata, fmt));
         free (fmt);
 
         return data;
             {
                 int i = 0;
                 int ioffset = 0;
-                char *tmp;
+                unsigned char *tmp;
 
                 free (retval);
                 retval = NULL;
     }
 
     Unlock_Display ();
-    return retval;
+    return (char *)retval;
 }
 
 int
     if (!pygame_scrap_lost ())
     {
         PyObject *key;
+#if PY3
+        PyObject *chars;
+#endif
         int pos = 0;
         int i = 0;
         PyObject *dict = (_currentmode == SCRAP_SELECTION) ? _selectiondata :
         memset (types, 0, (size_t) (PyDict_Size (dict) + 1));
         while (PyDict_Next (dict, &pos, &key, NULL))
         {
-            types[i] = strdup (PyString_AsString (key));
+#if PY3
+            chars = PyUnicode_AsASCIIString (key);
+            if (chars) {
+                types[i] = strdup (PyBytes_AsString (chars));
+                Py_DECREF (chars);
+            }
+            else {
+                types[i] = NULL;
+            }
+#else
+             types[i] = strdup (PyString_AsString (key));
+#endif
             if (!types[i])
             {
                 /* Could not allocate memory, free anything. */

test/event_test.py

         self.assertEquals(e.some_attr, 1)
         self.assertEquals(e.other_attr, "1")
 
-        # Event now uses tp_dictoffset and tp_members.
+        # Event now uses tp_dictoffset and tp_members: request 62
+        # on Motherhamster Bugzilla.
         self.assertEquals(e.type, pygame.USEREVENT)
         self.assert_(e.dict is e.__dict__)
         e.some_attr = 12
         self.assertEquals(e.some_attr, 12)
         e.new_attr = 15
         self.assertEquals(e.new_attr, 15)
-        self.assertRaises(TypeError, setattr, e, 'type', 0)
-        self.assertRaises(TypeError, setattr, e, 'dict', None)
+
+        # For Python 2.x a TypeError is raised for a readonly member;
+        # for Python 3.x it is an AttributeError.
+        self.assertRaises((TypeError, AttributeError), setattr, e, 'type', 0)
+        self.assertRaises((TypeError, AttributeError), setattr, e, 'dict', None)
+
+        # Ensure attributes are visible to dir(), part of the original
+        # posted request.
         d = dir(e)
+        self.assert_('type' in d)
+        self.assert_('dict' in d)
+        self.assert_('__dict__' in d)
         self.assert_('some_attr' in d)
         self.assert_('other_attr' in d)
         self.assert_('new_attr' in d)

test/scrap_tags.py

 
 exclude = False
 
-if ((sys.platform == 'win32' or sys.platform == 'linux2') and
-    sys.version_info < (3, 0, 0)):
+if sys.platform == 'win32' or sys.platform == 'linux2':
     try:
         import pygame
         pygame.scrap._NOT_IMPLEMENTED_

test/scrap_test.py

          import test_not_implemented, trunk_relative_path, unittest
 import pygame
 from pygame import scrap
+from pygame.compat import as_bytes
 import sys
 
 class ScrapModuleTest(unittest.TestCase):
         self.assertRaises (ValueError, scrap.set_mode, 1099)
 
     def test_scrap_put_text (self):
-        scrap.put (pygame.SCRAP_TEXT, "Hello world")
-        self.assertEquals (scrap.get (pygame.SCRAP_TEXT), "Hello world")
+        scrap.put (pygame.SCRAP_TEXT, as_bytes("Hello world"))
+        self.assertEquals (scrap.get (pygame.SCRAP_TEXT),
+                           as_bytes("Hello world"))
 
-        scrap.put (pygame.SCRAP_TEXT, "Another String")
-        self.assertEquals (scrap.get (pygame.SCRAP_TEXT), "Another String")
+        scrap.put (pygame.SCRAP_TEXT, as_bytes("Another String"))
+        self.assertEquals (scrap.get (pygame.SCRAP_TEXT),
+                           as_bytes("Another String"))
 
     def test_scrap_put_image (self):
         if 'pygame.image' not in sys.modules:
         self.assertEquals (scrap.get(pygame.SCRAP_BMP), string)
 
     def test_put (self):
-        scrap.put ("arbitrary buffer", "buf")
+        scrap.put ("arbitrary buffer", as_bytes("buf"))
         r = scrap.get ("arbitrary buffer")
-        self.assertEquals (r, "buf")
+        self.assertEquals (r, as_bytes("buf"))
 
 if __name__ == '__main__':
     unittest.main()