Ticket #17959: 17959-1.diff

File 17959-1.diff, 12.8 KB (added by Claude Paroz, 12 years ago)

Use logging to silence test output

  • django/contrib/gis/gdal/libgdal.py

    diff --git a/django/contrib/gis/gdal/libgdal.py b/django/contrib/gis/gdal/libgdal.py
    index f991388..9bd775d 100644
    a b  
     1import logging
    12import os
    23import re
    3 from ctypes import c_char_p, CDLL
     4from ctypes import c_char_p, c_int, CDLL, CFUNCTYPE
    45from ctypes.util import find_library
    56from django.contrib.gis.gdal.error import OGRException
    67
     8# Set module logging
     9logger = logging.getLogger('django.contrib.gis')
     10if not logger.handlers:
     11    ch = logging.StreamHandler()
     12    logger.addHandler(ch)
     13
    714# Custom library path set?
    815try:
    916    from django.conf import settings
    if GDAL_VERSION >= (1, 5):  
    103110else:
    104111    GEOJSON = False
    105112
     113CPLErrorHandler = CFUNCTYPE(None, c_int, c_int, c_char_p)
     114def err_handler(error_class, error_number, message):
     115    logger.error('GDAL_ERROR %d: %s' % (error_number, message))
     116err_handler = CPLErrorHandler(err_handler)
     117
     118def function(name, args, restype):
     119    func = std_call(name)
     120    func.argtypes = args
     121    func.restype = restype
     122    return func
     123
     124set_error_handler = function('CPLSetErrorHandler', [CPLErrorHandler], CPLErrorHandler)
     125set_error_handler(err_handler)
  • django/contrib/gis/gdal/tests/test_ds.py

    diff --git a/django/contrib/gis/gdal/tests/test_ds.py b/django/contrib/gis/gdal/tests/test_ds.py
    index 16d6e86..11f5c01 100644
    a b import unittest  
    33from django.contrib.gis.gdal import DataSource, Envelope, OGRGeometry, OGRException, OGRIndexError, GDAL_VERSION
    44from django.contrib.gis.gdal.field import OFTReal, OFTInteger, OFTString
    55from django.contrib.gis.geometry.test_data import get_ds_file, TestDS, TEST_DATA
     6from django.test.utils import capture_logging
    67
    78# List of acceptable data sources.
    89ds_list = (TestDS('test_point', nfeat=5, nfld=3, geom='POINT', gtype=1, driver='ESRI Shapefile',
    class DataSourceTest(unittest.TestCase):  
    5960
    6061    def test03a_layers(self):
    6162        "Testing Data Source Layers."
    62         print "\nBEGIN - expecting out of range feature id error; safe to ignore.\n"
    6363        for source in ds_list:
    6464            ds = DataSource(source.ds)
    6565
    class DataSourceTest(unittest.TestCase):  
    8989                flds = layer.fields
    9090                for f in flds: self.assertEqual(True, f in source.fields)
    9191
    92                 # Negative FIDs are not allowed.
    93                 self.assertRaises(OGRIndexError, layer.__getitem__, -1)
    94                 self.assertRaises(OGRIndexError, layer.__getitem__, 50000)
     92                # Negative FIDs are not allowed. Capture logs as it is expected
     93                # that an 'out of range' GDAL_ERROR will be emitted
     94                with capture_logging('django.contrib.gis'):
     95                    self.assertRaises(OGRIndexError, layer.__getitem__, -1)
     96                    self.assertRaises(OGRIndexError, layer.__getitem__, 50000)
    9597
    9698                if hasattr(source, 'field_values'):
    9799                    fld_names = source.field_values.keys()
    class DataSourceTest(unittest.TestCase):  
    108110                        # the feature values here while in this loop.
    109111                        for fld_name in fld_names:
    110112                            self.assertEqual(source.field_values[fld_name][i], feat.get(fld_name))
    111         print "\nEND - expecting out of range feature id error; safe to ignore."
    112113
    113114    def test03b_layer_slice(self):
    114115        "Test indexing and slicing on Layers."
  • django/contrib/gis/gdal/tests/test_geom.py

    diff --git a/django/contrib/gis/gdal/tests/test_geom.py b/django/contrib/gis/gdal/tests/test_geom.py
    index 656901b..ce8c0e7 100644
    a b from django.contrib.gis.gdal import (OGRGeometry, OGRGeomType, OGRException,  
    88    OGRIndexError, SpatialReference, CoordTransform, GDAL_VERSION)
    99from django.contrib.gis.gdal.prototypes.geom import GEOJSON
    1010from django.contrib.gis.geometry.test_data import TestDataMixin
     11from django.test.utils import capture_logging
    1112from django.utils import unittest
    1213
    1314class OGRGeomTest(unittest.TestCase, TestDataMixin):
    class OGRGeomTest(unittest.TestCase, TestDataMixin):  
    234235        # Both rings in this geometry are not closed.
    235236        poly = OGRGeometry('POLYGON((0 0, 5 0, 5 5, 0 5), (1 1, 2 1, 2 2, 2 1))')
    236237        self.assertEqual(8, poly.point_count)
    237         print "\nBEGIN - expecting IllegalArgumentException; safe to ignore.\n"
    238         try:
    239             c = poly.centroid
    240         except OGRException:
    241             # Should raise an OGR exception, rings are not closed
    242             pass
    243         else:
    244             self.fail('Should have raised an OGRException!')
    245         print "\nEND - expecting IllegalArgumentException; safe to ignore.\n"
     238
     239        # Capture logging as an IllegalArgumentException will be output by GDAL
     240        with capture_logging('django.contrib.gis'):
     241            # Rings are not closed
     242            self.assertRaises(OGRException, lambda: poly.centroid)
    246243
    247244        # Closing the rings -- doesn't work on GDAL versions 1.4.1 and below:
    248245        # http://trac.osgeo.org/gdal/ticket/1673
  • django/contrib/gis/geos/libgeos.py

    diff --git a/django/contrib/gis/geos/libgeos.py b/django/contrib/gis/geos/libgeos.py
    index a4f5adf..672f2b9 100644
    a b  
    66 This module also houses GEOS Pointer utilities, including
    77 get_pointer_arr(), and GEOM_PTR.
    88"""
     9import logging
    910import os
    1011import re
    11 import sys
    1212from ctypes import c_char_p, Structure, CDLL, CFUNCTYPE, POINTER
    1313from ctypes.util import find_library
    1414from django.contrib.gis.geos.error import GEOSException
    1515
     16# Set module logging
     17logger = logging.getLogger('django.contrib.gis')
     18if not logger.handlers:
     19    ch = logging.StreamHandler()
     20    logger.addHandler(ch)
     21
    1622# Custom library path set?
    1723try:
    1824    from django.conf import settings
    lgeos = CDLL(lib_path)  
    5662# Supposed to mimic the GEOS message handler (C below):
    5763#  typedef void (*GEOSMessageHandler)(const char *fmt, ...);
    5864NOTICEFUNC = CFUNCTYPE(None, c_char_p, c_char_p)
    59 def notice_h(fmt, lst, output_h=sys.stdout):
     65def notice_h(fmt, lst):
    6066    try:
    6167        warn_msg = fmt % lst
    6268    except:
    6369        warn_msg = fmt
    64     output_h.write('GEOS_NOTICE: %s\n' % warn_msg)
     70    logger.warn('GEOS_NOTICE: %s' % warn_msg)
    6571notice_h = NOTICEFUNC(notice_h)
    6672
    6773ERRORFUNC = CFUNCTYPE(None, c_char_p, c_char_p)
    68 def error_h(fmt, lst, output_h=sys.stderr):
     74def error_h(fmt, lst):
    6975    try:
    7076        err_msg = fmt % lst
    7177    except:
    7278        err_msg = fmt
    73     output_h.write('GEOS_ERROR: %s\n' % err_msg)
     79    logger.error('GEOS_ERROR: %s' % err_msg)
    7480error_h = ERRORFUNC(error_h)
    7581
    7682#### GEOS Geometry C data structures, and utility functions. ####
  • django/contrib/gis/geos/tests/test_geos.py

    diff --git a/django/contrib/gis/geos/tests/test_geos.py b/django/contrib/gis/geos/tests/test_geos.py
    index a8372b4..5d09be8 100644
    a b  
    11import ctypes
    22import random
    33import unittest
     4
    45from django.contrib.gis.geos import *
    56from django.contrib.gis.geos.base import gdal, numpy, GEOSBase
    67from django.contrib.gis.geos.libgeos import GEOS_PREPARE
    78from django.contrib.gis.geometry.test_data import TestDataMixin
     9from django.test.utils import capture_logging
     10
    811
    912class GEOSTest(unittest.TestCase, TestDataMixin):
    1013
    class GEOSTest(unittest.TestCase, TestDataMixin):  
    134137    def test01d_errors(self):
    135138        "Testing the Error handlers."
    136139        # string-based
    137         print "\nBEGIN - expecting GEOS_ERROR; safe to ignore.\n"
    138         for err in self.geometries.errors:
    139             try:
    140                 g = fromstr(err.wkt)
    141             except (GEOSException, ValueError):
    142                 pass
    143 
    144         # Bad WKB
    145         self.assertRaises(GEOSException, GEOSGeometry, buffer('0'))
    146 
    147         print "\nEND - expecting GEOS_ERROR; safe to ignore.\n"
     140        with capture_logging('django.contrib.gis') as out:
     141            for err in self.geometries.errors:
     142                try:
     143                    g = fromstr(err.wkt)
     144                except (GEOSException, ValueError):
     145                    pass
     146            # Two GEOS_ERRORs:
     147            self.assertEqual(len(out), 2)
     148
     149            # Bad WKB
     150            self.assertRaises(GEOSException, GEOSGeometry, buffer('0'))
    148151
    149152        class NotAGeometry(object):
    150153            pass
    class GEOSTest(unittest.TestCase, TestDataMixin):  
    439442
    440443    def test05b_multipolygons(self):
    441444        "Testing MultiPolygon objects."
    442         print "\nBEGIN - expecting GEOS_NOTICE; safe to ignore.\n"
    443445        prev = fromstr('POINT (0 0)')
    444         for mp in self.geometries.multipolygons:
    445             mpoly = fromstr(mp.wkt)
    446             self.assertEqual(mpoly.geom_type, 'MultiPolygon')
    447             self.assertEqual(mpoly.geom_typeid, 6)
    448             self.assertEqual(mp.valid, mpoly.valid)
    449 
    450             if mp.valid:
    451                 self.assertEqual(mp.num_geom, mpoly.num_geom)
    452                 self.assertEqual(mp.n_p, mpoly.num_coords)
    453                 self.assertEqual(mp.num_geom, len(mpoly))
    454                 self.assertRaises(GEOSIndexError, mpoly.__getitem__, len(mpoly))
    455                 for p in mpoly:
    456                     self.assertEqual(p.geom_type, 'Polygon')
    457                     self.assertEqual(p.geom_typeid, 3)
    458                     self.assertEqual(p.valid, True)
    459                 self.assertEqual(mpoly.wkt, MultiPolygon(*tuple(poly.clone() for poly in mpoly)).wkt)
    460 
    461         print "\nEND - expecting GEOS_NOTICE; safe to ignore.\n"
     446        with capture_logging('django.contrib.gis') as out:
     447            for mp in self.geometries.multipolygons:
     448                mpoly = fromstr(mp.wkt)
     449                self.assertEqual(mpoly.geom_type, 'MultiPolygon')
     450                self.assertEqual(mpoly.geom_typeid, 6)
     451                self.assertEqual(mp.valid, mpoly.valid)
     452
     453                if mp.valid:
     454                    self.assertEqual(mp.num_geom, mpoly.num_geom)
     455                    self.assertEqual(mp.n_p, mpoly.num_coords)
     456                    self.assertEqual(mp.num_geom, len(mpoly))
     457                    self.assertRaises(GEOSIndexError, mpoly.__getitem__, len(mpoly))
     458                    for p in mpoly:
     459                        self.assertEqual(p.geom_type, 'Polygon')
     460                        self.assertEqual(p.geom_typeid, 3)
     461                        self.assertEqual(p.valid, True)
     462                    self.assertEqual(mpoly.wkt, MultiPolygon(*tuple(poly.clone() for poly in mpoly)).wkt)
     463            self.assertTrue(out[0].msg,
     464                'GEOS_NOTICE: Duplicate Rings at or near point 60 300')
    462465
    463466    def test06a_memory_hijinks(self):
    464467        "Testing Geometry __del__() on rings and polygons."
    class GEOSTest(unittest.TestCase, TestDataMixin):  
    894897        """ Testing `transform` method (no SRID) """
    895898        # Raise a warning if SRID <0/None.
    896899        import warnings
    897         print "\nBEGIN - expecting Warnings; safe to ignore.\n"
    898900
    899901        # Test for do-nothing behavior.
    900         try:
    901             # Keeping line-noise down by only printing the relevant
    902             # warnings once.
    903             warnings.simplefilter('once', UserWarning)
    904             warnings.simplefilter('once', FutureWarning)
     902        with warnings.catch_warnings():
     903            warnings.simplefilter("ignore")
    905904
    906905            g = GEOSGeometry('POINT (-104.609 38.255)', srid=None)
    907906            g.transform(2774)
    class GEOSTest(unittest.TestCase, TestDataMixin):  
    921920            g1 = g.transform(2774, clone=True)
    922921            self.assertTrue(g1 is None)
    923922
    924         finally:
    925             warnings.simplefilter('default', UserWarning)
    926             warnings.simplefilter('default', FutureWarning)
    927 
    928         print "\nEND - expecting Warnings; safe to ignore.\n"
    929 
    930 
    931923        # test warning is raised
    932924        try:
    933925            warnings.simplefilter('error', FutureWarning)
    class GEOSTest(unittest.TestCase, TestDataMixin):  
    10391031        self.assertTrue(isinstance(g.valid_reason, basestring))
    10401032        self.assertEqual(g.valid_reason, "Valid Geometry")
    10411033
    1042         print "\nBEGIN - expecting GEOS_NOTICE; safe to ignore.\n"
    1043 
    10441034        g = GEOSGeometry("LINESTRING(0 0, 0 0)")
    10451035
    1046         self.assertTrue(not g.valid)
     1036        with capture_logging('django.contrib.gis') as out:
     1037            self.assertTrue(not g.valid)
     1038            self.assertEqual(out[0].msg,
     1039                'GEOS_NOTICE: Too few points in geometry component at or near point 0 0')
    10471040        self.assertTrue(isinstance(g.valid_reason, basestring))
    10481041        self.assertTrue(g.valid_reason.startswith("Too few points in geometry component"))
    10491042
    1050         print "\nEND - expecting GEOS_NOTICE; safe to ignore.\n"
    1051 
    10521043    def test28_geos_version(self):
    10531044        "Testing the GEOS version regular expression."
    10541045        from django.contrib.gis.geos.libgeos import version_regex
Back to Top