Skip to content
Permalink
Browse files

Convert print function to py3 style in tests

  • Loading branch information
m-kuhn committed Mar 31, 2016
1 parent 3c01f51 commit 18cdad9956dd01ee1f1411ee5e8b77e7f1eca842
@@ -60,15 +60,12 @@ PyQgsSymbolLayerV2
PyQgsSymbolV2
PyQgsSyntacticSugar
PyQgsTabfileProvider
PyQgsUnitTypes
PyQgsVectorColorRamp
PyQgsVectorFileWriter
PyQgsVectorLayer
PyQgsVirtualLayerDefinition
PyQgsVirtualLayerProvider
PyQgsZonalStatistics
qgis_alignrastertest
qgis_atlascompositiontest
qgis_composereffectstest
qgis_composerlabeltest
qgis_composermapgridtest
@@ -83,7 +80,6 @@ qgis_composershapestest
qgis_composertabletest
qgis_composertablev2test
qgis_composerutils
qgis_coordinatereferencesystemtest
qgis_ellipsemarkertest
qgis_fieldexpressionwidget
qgis_fieldtest
@@ -97,6 +93,5 @@ qgis_maprotationtest
qgis_markerlinessymboltest
qgis_painteffecttest
qgis_pointpatternfillsymboltest
qgis_rasterlayertest
qgis_simplemarkertest
qgis_svgmarkertest
@@ -0,0 +1 @@
from libfuturize.fixes.fix_print import FixPrint
@@ -122,11 +122,11 @@ def testGetFeaturesCompiled(self):
self.enableCompiler()
self.runGetFeatureTests(self.provider)
except AttributeError:
print 'Provider does not support compiling'
print('Provider does not support compiling')

def testSubsetString(self):
if not self.provider.supportsSubsetString():
print 'Provider does not support subset strings'
print('Provider does not support subset strings')
return

subset = self.getSubsetString()
@@ -177,7 +177,7 @@ def testOrderByCompiled(self):
self.enableCompiler()
self.runOrderByTests()
except AttributeError:
print 'Provider does not support compiling'
print('Provider does not support compiling')

def runOrderByTests(self):
request = QgsFeatureRequest().addOrderBy('cnt')
@@ -500,7 +500,7 @@ def get_map(self, params, browser=False):
)
else:
delta = time.time() - start_time
print 'Seconds elapsed for server GetMap: ' + str(delta)
print('Seconds elapsed for server GetMap: ' + str(delta))
break

if resp is not None:
@@ -776,7 +776,7 @@ def tearDown(self):

fcgi = os.path.realpath(args.fcgi)
if not os.path.isabs(fcgi) or not os.path.exists(fcgi):
print 'qgis_mapserv.fcgi not resolved to existing absolute path.'
print('qgis_mapserv.fcgi not resolved to existing absolute path.')
sys.exit(1)

local_srv = QgisLocalServer(fcgi)
@@ -83,7 +83,7 @@ def testDateTimeTypes(self):
def testQueryLayers(self):
def test_query(dbconn, query, key):
ql = QgsVectorLayer('%s srid=4326 table="%s" (geom) key=\'%s\' sql=' % (dbconn, query.replace('"', '\\"'), key), "testgeom", "postgres")
print query, key
print(query, key)
assert(ql.isValid())

test_query(self.dbconn, '(SELECT NULL::integer "Id1", NULL::integer "Id2", NULL::geometry(Point, 4326) geom LIMIT 0)', '"Id1","Id2"')
@@ -93,7 +93,7 @@ def test_table(dbconn, table_name, wkt):
vl = QgsVectorLayer('%s srid=4326 table="qgis_test".%s (geom) sql=' % (dbconn, table_name), "testgeom", "postgres")
assert(vl.isValid())
for f in vl.getFeatures():
print f.geometry().exportToWkt(), wkt
print(f.geometry().exportToWkt(), wkt)
assert f.geometry().exportToWkt() == wkt

test_table(self.dbconn, 'p2d', 'Polygon ((0 0, 1 0, 1 1, 0 1, 0 0))')
@@ -150,7 +150,7 @@ def test_unique(features, num_features):
def testSignedIdentifiers(self):
def test_query_attribute(dbconn, query, att, val, fidval):
ql = QgsVectorLayer('%s table="%s" (g) key=\'%s\' sql=' % (dbconn, query.replace('"', '\\"'), att), "testgeom", "postgres")
print query, att
print(query, att)
assert(ql.isValid())
features = ql.getFeatures()
att_idx = ql.fieldNameIndex(att)
@@ -28,7 +28,7 @@
try:
from pyspatialite import dbapi2 as sqlite3
except ImportError:
print "You should install pyspatialite to run the tests"
print("You should install pyspatialite to run the tests")
raise ImportError

# Convenience instances in case you may need them
@@ -35,7 +35,7 @@
try:
from pyspatialite import dbapi2 as sqlite3
except ImportError:
print "You should install pyspatialite to run the tests"
print("You should install pyspatialite to run the tests")
raise ImportError

import tempfile
@@ -75,9 +75,9 @@ def tearDownClass(cls):
def setUp(self):
"""Run before each test."""
self.testDataDir = unitTestDataPath()
print "****************************************************"
print "In method", self._testMethodName
print "****************************************************"
print("****************************************************")
print("In method", self._testMethodName)
print("****************************************************")
pass

def tearDown(self):
@@ -399,7 +399,7 @@ def test_refLayer(self):
# now delete the layer
QgsMapLayerRegistry.instance().removeMapLayer(l1.id())
# check that it does not crash
print sum([f.id() for f in l2.getFeatures()])
print(sum([f.id() for f in l2.getFeatures()]))

def test_refLayers(self):
l1 = QgsVectorLayer(QUrl.fromLocalFile(os.path.join(self.testDataDir, "delimitedtext/test.csv")).toString() + "?type=csv&geomType=none&subsetIndex=no&watchFile=no", "test", "delimitedtext", False)
@@ -25,7 +25,7 @@
import tempfile

if os.name == 'nt':
print "TestQgisLocalServer currently doesn't support windows"
print("TestQgisLocalServer currently doesn't support windows")
sys.exit(0)

from qgis.core import (
@@ -161,8 +161,8 @@ def run_suite(module, tests):
out = StringIO.StringIO()
res = unittest.TextTestRunner(stream=out, verbosity=verb).run(suite)
if verb:
print '\nIndividual test summary:'
print '\n' + out.getvalue()
print('\nIndividual test summary:')
print('\n' + out.getvalue())
out.close()

if QGIS_TEST_REPORT and len(TESTREPORTS) > 0:
@@ -47,7 +47,7 @@ def setUp(self):

def tearDown(self):
"""Run after each test."""
print "Tear down"
print("Tear down")

def htmlUrl(self):
"""Helper to get the url of the html doc."""
@@ -86,14 +86,14 @@ def testTableMultiFrame(self):
composerHtml.setUrl(self.htmlUrl())
composerHtml.frame(0).setFrameEnabled(True)

print "Checking page 1"
print("Checking page 1")
myPage = 0
checker1 = QgsCompositionChecker('composerhtml_multiframe1', self.mComposition)
checker1.setControlPathPrefix("composer_html")
myTestResult, myMessage = checker1.testComposition(myPage)
assert myTestResult, myMessage

print "Checking page 2"
print("Checking page 2")
myPage = 1
checker2 = QgsCompositionChecker('composerhtml_multiframe2', self.mComposition)
checker2.setControlPathPrefix("composer_html")
@@ -117,14 +117,14 @@ def testHtmlSmartBreaks(self):
composerHtml.setUrl(self.htmlUrl())
composerHtml.frame(0).setFrameEnabled(True)

print "Checking page 1"
print("Checking page 1")
myPage = 0
checker1 = QgsCompositionChecker('composerhtml_smartbreaks1', self.mComposition)
checker1.setControlPathPrefix("composer_html")
myTestResult, myMessage = checker1.testComposition(myPage, 200)
assert myTestResult, myMessage

print "Checking page 2"
print("Checking page 2")
myPage = 1
checker2 = QgsCompositionChecker('composerhtml_smartbreaks2', self.mComposition)
checker2.setControlPathPrefix("composer_html")
@@ -60,9 +60,8 @@ def testSubstitutionMap(self):
myComposition = QgsComposition(self.iface.mapCanvas().mapRenderer())
mySubstitutionMap = {'replace-me': myText}
myFile = os.path.join(TEST_DATA_DIR, 'template-for-substitution.qpt')
myTemplateFile = file(myFile, 'rt')
myTemplateContent = myTemplateFile.read()
myTemplateFile.close()
with open(myFile) as f:
myTemplateContent = f.read()
myDocument = QDomDocument()
myDocument.setContent(myTemplateContent)
myComposition.loadFromTemplate(myDocument, mySubstitutionMap)
@@ -76,9 +75,8 @@ def testNoSubstitutionMap(self):
"""Test that we can get a map if we use no text substitutions."""
myComposition = QgsComposition(self.iface.mapCanvas().mapRenderer())
myFile = os.path.join(TEST_DATA_DIR, 'template-for-substitution.qpt')
myTemplateFile = file(myFile, 'rt')
myTemplateContent = myTemplateFile.read()
myTemplateFile.close()
with open(myFile) as f:
myTemplateContent = f.read()
myDocument = QDomDocument()
myDocument.setContent(myTemplateContent)
myComposition.loadFromTemplate(myDocument)
@@ -111,9 +109,8 @@ def testPrintMapFromTemplate(self):

myComposition = QgsComposition(myMapRenderer)
myFile = os.path.join(TEST_DATA_DIR, 'template-for-substitution.qpt')
myTemplateFile = file(myFile, 'rt')
myTemplateContent = myTemplateFile.read()
myTemplateFile.close()
with open(myFile) as f:
myTemplateContent = f.read()
myDocument = QDomDocument()
myDocument.setContent(myTemplateContent)
myComposition.loadFromTemplate(myDocument)
@@ -145,11 +145,11 @@ def delimitedTextData(testname, filename, requests, verbose, **params):
log = []
with MessageLogger('DelimitedText') as logger:
if verbose:
print testname
print(testname)
layer = QgsVectorLayer(urlstr, 'test', 'delimitedtext')
uri = unicode(layer.dataProvider().dataSourceUri())
if verbose:
print uri
print(uri)
basename = os.path.basename(filepath)
if not basename.startswith('test'):
basename = 'file'
@@ -160,11 +160,11 @@ def delimitedTextData(testname, filename, requests, verbose, **params):
if layer.isValid():
for nr, r in enumerate(requests):
if verbose:
print "Processing request", nr + 1, repr(r)
print("Processing request", nr + 1, repr(r))
if callable(r):
r(layer)
if verbose:
print "Request function executed"
print("Request function executed")
if callable(r):
continue
rfields, rtypes, rdata = layerData(layer, r, nr * 1000)
@@ -175,7 +175,7 @@ def delimitedTextData(testname, filename, requests, verbose, **params):
if not rdata:
log.append("Request " + str(nr) + " did not return any data")
if verbose:
print "Request returned", len(rdata.keys()), "features"
print("Request returned", len(rdata.keys()), "features")
for msg in logger.messages():
filelogname = 'temp_file' if 'tmp' in filename.lower() else filename
msg = re.sub(r'file\s+.*' + re.escape(filename), 'file ' + filelogname, msg)
@@ -186,33 +186,33 @@ def delimitedTextData(testname, filename, requests, verbose, **params):

def printWanted(testname, result):
# Routine to export the result as a function definition
print
print "def {0}():".format(testname)
print()
print("def {0}():".format(testname))
data = result['data']
log = result['log']
fields = result['fields']
prefix = ' '

# Dump the data for a layer - used to construct unit tests
print prefix + "wanted={}"
print prefix + "wanted['uri']=" + repr(result['uri'])
print prefix + "wanted['fieldTypes']=" + repr(result['fieldTypes'])
print prefix + "wanted['geometryType']=" + repr(result['geometryType'])
print prefix + "wanted['data']={"
print(prefix + "wanted={}")
print(prefix + "wanted['uri']=" + repr(result['uri']))
print(prefix + "wanted['fieldTypes']=" + repr(result['fieldTypes']))
print(prefix + "wanted['geometryType']=" + repr(result['geometryType']))
print(prefix + "wanted['data']={")
for k in sorted(data.keys()):
row = data[k]
print prefix + " {0}: {{".format(repr(k))
print(prefix + " {0}: {{".format(repr(k)))
for f in fields:
print prefix + " " + repr(f) + ": " + repr(row[f]) + ","
print prefix + " },"
print prefix + " }"
print(prefix + " " + repr(f) + ": " + repr(row[f]) + ",")
print(prefix + " },")
print(prefix + " }")

print prefix + "wanted['log']=["
print(prefix + "wanted['log']=[")
for msg in log:
print prefix + ' ' + repr(msg) + ','
print prefix + ' ]'
print ' return wanted'
print
print(prefix + ' ' + repr(msg) + ',')
print(prefix + ' ]')
print(' return wanted')
print()


def recordDifference(record1, record2):
@@ -238,7 +238,7 @@ def runTest(file, requests, **params):
testname = inspect.stack()[1][3]
verbose = not rebuildTests
if verbose:
print "Running test:", testname
print("Running test:", testname)
result = delimitedTextData(testname, file, requests, verbose, **params)
if rebuildTests:
printWanted(testname, result)
@@ -255,7 +255,7 @@ def runTest(file, requests, **params):
if result['uri'] != wanted['uri']:
msg = "Layer Uri ({0}) doesn't match expected ({1})".format(
result['uri'], wanted['uri'])
print ' ' + msg
print(' ' + msg)
failures.append(msg)
if result['fieldTypes'] != wanted['fieldTypes']:
msg = "Layer field types ({0}) doesn't match expected ({1})".format(
@@ -276,14 +276,14 @@ def runTest(file, requests, **params):
print('getting difference')
difference = recordDifference(wrec, trec)
if not difference:
print ' {0}: Passed'.format(description)
print(' {0}: Passed'.format(description))
else:
print ' {0}: {1}'.format(description, difference)
print(' {0}: {1}'.format(description, difference))
failures.append(description + ': ' + difference)
for id in sorted(data.keys()):
if id not in wanted_data:
msg = "Layer contains unexpected extra data with id: \"{0}\"".format(id)
print ' ' + msg
print(' ' + msg)
failures.append(msg)
common = []
log_wanted = wanted['log']
@@ -293,15 +293,15 @@ def runTest(file, requests, **params):
for l in log_wanted:
if l not in common:
msg = 'Missing log message: ' + l
print ' ' + msg
print(' ' + msg)
failures.append(msg)
for l in log:
if l not in common:
msg = 'Extra log message: ' + l
print ' ' + msg
print(' ' + msg)
failures.append(msg)
if len(log) == len(common) and len(log_wanted) == len(common):
print ' Message log correct: Passed'
print(' Message log correct: Passed')

if failures:
printWanted(testname, result)

0 comments on commit 18cdad9

Please sign in to comment.
You can’t perform that action at this time.