File: TestTools.py

package info (click to toggle)
qgis 2.14.11%2Bdfsg-3%2Bdeb9u1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 991,448 kB
  • ctags: 73,105
  • sloc: cpp: 535,362; python: 162,580; xml: 16,494; ansic: 8,031; sh: 1,788; perl: 1,559; sql: 727; yacc: 319; lex: 269; makefile: 251
file content (217 lines) | stat: -rw-r--r-- 6,929 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# -*- coding: utf-8 -*-

"""
***************************************************************************
    TestTools.py
    ---------------------
    Date                 : February 2013
    Copyright            : (C) 2013 by Victor Olaya
    Email                : volayaf at gmail dot com
***************************************************************************
*                                                                         *
*   This program is free software; you can redistribute it and/or modify  *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*                                                                         *
***************************************************************************
"""

__author__ = 'Victor Olaya'
__date__ = 'February 2013'
__copyright__ = '(C) 2013, Victor Olaya'

# This will get replaced with a git SHA1 when you do a git archive

__revision__ = '$Format:%H$'

import os
import yaml
import hashlib

from osgeo import gdal
from osgeo.gdalconst import GA_ReadOnly

from PyQt4.QtCore import QCoreApplication, QMetaObject
from PyQt4.QtGui import QMessageBox, QDialog, QVBoxLayout, QTextEdit

from processing.core.Processing import Processing
from processing.core.outputs import (
    OutputNumber,
    OutputString,
    OutputRaster,
    OutputVector,
    OutputHTML
)

from processing.core.parameters import (
    ParameterRaster,
    ParameterVector,
    ParameterMultipleInput
)


def extractSchemaPath(filepath):
    """
    Trys to find where the file is relative to the QGIS source code directory.
    If it is already placed in the processing or QGIS testdata directory it will
    return an appropriate schema and relative filepath

    Args:
        filepath: The path of the file to examine

    Returns:
        A tuple (schema, relative_file_path) where the schema is 'qgs' or 'proc'
        if we can assume that the file is in this testdata directory.
    """
    parts = []
    schema = None
    localpath = ''
    path = filepath
    part = True

    while part:
        (path, part) = os.path.split(path)
        if part == 'testdata' and not localpath:
            localparts = parts
            localparts.reverse()
            localpath = os.path.join(*localparts)

        parts.append(part)

    parts.reverse()

    try:
        testsindex = parts.index('tests')
    except ValueError:
        return '', filepath

    if parts[testsindex - 1] == 'processing':
        schema = 'proc'

    return schema, localpath


def createTest(text):
    definition = {}

    tokens = text[len('processing.runalg('):-1].split(',')
    cmdname = (tokens[0])[1:-1]
    alg = Processing.getAlgorithm(cmdname)

    definition['name'] = 'Test ({})'.format(cmdname)
    definition['algorithm'] = cmdname

    params = {}
    results = {}

    i = 0
    for param in alg.parameters:
        if param.hidden:
            continue

        i += 1
        token = tokens[i]

        if isinstance(param, ParameterVector):
            filename = token[1:-1]
            schema, filepath = extractSchemaPath(filename)
            p = {
                'type': 'vector',
                'name': filepath
            }
            if not schema:
                p['location'] = '[The source data is not in the testdata directory. Please use data in the processing/tests/testdata folder.]'

            params[param.name] = p
        elif isinstance(param, ParameterRaster):
            filename = token[1:-1]
            schema, filepath = extractSchemaPath(filename)
            p = {
                'type': 'raster',
                'name': filepath
            }
            if not schema:
                p['location'] = '[The source data is not in the testdata directory. Please use data in the processing/tests/testdata folder.]'

            params[param.name] = p
        elif isinstance(param, ParameterMultipleInput):
            multiparams = token[1:-1].split(';')
            newparam = []
            for mp in multiparams:
                schema, filepath = extractSchemaPath(mp)
                newparam.append({
                    'type': 'vector',
                    'name': filepath
                })
            p = {
                'type': 'multi',
                'params': newparam
            }
            if not schema:
                p['location'] = '[The source data is not in the testdata directory. Please use data in the processing/tests/testdata folder.]'

            params[param.name] = p
        else:
            params[param.name] = token

    definition['params'] = params

    for i, out in enumerate([out for out in alg.outputs if not out.hidden]):
        token = tokens[i - alg.getVisibleOutputsCount()]

        if isinstance(out, (OutputNumber, OutputString)):
            results[out.name] = unicode(out)
        elif isinstance(out, OutputRaster):
            filename = token[1:-1]
            dataset = gdal.Open(filename, GA_ReadOnly)
            strhash = hashlib.sha224(dataset.ReadAsArray(0).data).hexdigest()

            results[out.name] = {
                'type': 'rasterhash',
                'hash': strhash
            }
        elif isinstance(out, OutputVector):
            filename = token[1:-1]
            schema, filepath = extractSchemaPath(filename)
            results[out.name] = {
                'type': 'vector',
                'name': filepath
            }
            if not schema:
                results[out.name]['location'] = '[The expected result data is not in the testdata directory. Please write it to processing/tests/testdata/expected. Prefer gml files.]'
        elif isinstance(out, OutputHTML):
            filename = token[1:-1]
            schema, filepath = extractSchemaPath(filename)
            results[out.name] = {
                'type': 'file',
                'name': filepath
            }
            if not schema:
                results[out.name]['location'] = '[The expected result file is not in the testdata directory. Please redirect the output to processing/tests/testdata/expected.]'

    definition['results'] = results

    dlg = ShowTestDialog(yaml.dump([definition], default_flow_style=False))
    dlg.exec_()


def tr(string):
    return QCoreApplication.translate('TestTools', string)


class ShowTestDialog(QDialog):

    def __init__(self, s):
        QDialog.__init__(self)
        self.setModal(True)
        self.resize(600, 400)
        self.setWindowTitle(self.tr('Unit test'))
        layout = QVBoxLayout()
        self.text = QTextEdit()
        self.text.setFontFamily("monospace")
        self.text.setEnabled(True)
        self.text.setText(s)
        layout.addWidget(self.text)
        self.setLayout(layout)
        QMetaObject.connectSlotsByName(self)