Changeset 9f0f35e


Ignore:
Timestamp:
May 19, 2020, 8:59:28 PM (7 years ago)
Author:
Joachim Langenbach <joachim.langenbach@…>
Branches:
debian/bullseye, master
Children:
24617e1
Parents:
d5199c9
Message:
  • Switched from CamelCase to camel_case naming
    • Added mapservice-webclient to configure script (Closes #33)
    • Switched from unittest to pytest tests
    • Fixed testing errors with post datas by introducing x-fail vendor extension
    • Added x-vendor extension to mark a dependency on mapservice for an operation and the controller_test.mustache adds needed fixtures
    • Copying conftest.py from *_impl/tests into */test (it's a workaround to get the flask app fixtures)
    • Fixed controller_test.mustache, to test the first response with set status code
Files:
3 added
32 edited
38 moved

Legend:

Unmodified
Added
Removed
  • apis/deviceservice.yaml

    rd5199c9 r9f0f35e  
    184184        - deviceMaps
    185185      operationId: mapsTileGet
     186      x-xfail-test:
     187        reason: 'URL Ending with {{y_tile}}.png is not resolved correctly by openapi-generator'
    186188      parameters:
    187189        - name: mapname
    … …  
    235237        - mapservice
    236238      operationId: mapserviceStatus
     239      x-mapservice-required: True
    237240      responses:
    238241        '200':
    … …  
    259262      summary: Find own waters
    260263      operationId: watersGet
     264      x-mapservice-required: True
    261265      parameters:
    262266        - name: name
    … …  
    264268          schema:
    265269            $ref: '#/components/schemas/itemName'
    266           example: Test
     270          example: Miss
    267271        - $ref: '#/components/parameters/orderBy'
    268272        - $ref: '#/components/parameters/offset'
    … …  
    298302      summary: Add a new log
    299303      operationId: logCreate
     304      x-mapservice-required: True
     305      x-xfail-test:
     306        reason: 'Timesout because of not running celery broker during the tests'
    300307      requestBody:
    301308        content:
  • apis/mapservice.yaml

    rd5199c9 r9f0f35e  
    5353      summary: Registers a new user
    5454      operationId: usersRegister
     55      x-xfail-test:
     56        reason: 'Boolean value True could not converted by openapi-generator'
    5557      requestBody:
    5658        content:
    … …  
    681683      summary: Represents a tile
    682684      operationId: tilesTileGet
     685      x-xfail-test:
     686        reason: 'URL Ending with {{y_tile}}.png is not resolved correctly by openapi-generator'
    683687      parameters:
    684688        - name: accuracy
    … …  
    750754      type: http
    751755      scheme: basic
    752       x-basicInfoFunc: gnuboat.mapservice_impl.security.Security.auth_basic
     756      x-basicInfoFunc: gnuboat.mapservice_impl.security.security.auth_basic
    753757    apiKeyAuth:
    754758      type: apiKey
    755759      in: header
    756760      name: X-API-KEY
    757       x-apikeyInfoFunc: gnuboat.mapservice_impl.security.Security.auth_api
     761      x-apikeyInfoFunc: gnuboat.mapservice_impl.security.security.auth_api
    758762  schemas:
    759763    username:
  • buildhelpers/codegen/templates/__init__test.mustache

    rd5199c9 r9f0f35e  
    1 from flask_testing import TestCase
    2 
    3 from {{packageName}}_impl.tests import (
    4     create_app as orig_create_app,
    5     setUp as orig_setUp,
    6     tearDown as orig_tearDown
    7 )
    8 
    9 class BaseTestCase(TestCase):
    10         def create_app(self):
    11                 return orig_create_app(self)
    12 
    13         def setUp(self):
    14                 orig_setUp(self)
    15        
    16         def tearDown(self):
    17                 orig_tearDown(self)
    18                
    19         def check_key(self, key, value, data):
    20                 assert key in data, "{} not in data {}".format(key, data)
    21                 assert data[key] == value, "{} = {}".format(value, data[key])
  • buildhelpers/codegen/templates/controller.mustache

    rd5199c9 r9f0f35e  
    55{{/imports}}
    66from {{packageName}} import util
     7from {{packageName}}_impl.controllers import {{classFilename}}
    78{{#operations}}
    89{{#operation}}
    9 
    10 from {{packageName}}_impl.controllers import {{classname}}
    1110
    1211def {{operationId}}({{#allParams}}{{paramName}}{{^required}}=None{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}):  # noqa: E501
    … …  
    109108        {{/isMapContainer}}
    110109    {{/allParams}}
    111     return {{classname}}.{{operationId}}({{#allParams}}{{paramName}}{{^required}}={{paramName}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}})
     110    return {{classFilename}}.{{operationId}}({{#allParams}}{{paramName}}{{^required}}={{paramName}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}})
    112111{{/operation}}
    113112{{/operations}}
  • buildhelpers/codegen/templates/controller_test.mustache

    rd5199c9 r9f0f35e  
    11# coding: utf-8
    22
    3 from __future__ import absolute_import
    4 import unittest
    5 
    6 from flask import json
    7 from six import BytesIO
     3import pytest
     4import json
    85
    96{{#imports}}{{import}}  # noqa: E501
    107{{/imports}}
    11 from . import BaseTestCase
    128
     9# {{classFilename}} integration test stubs
     10{{#operations}}
     11{{#operation}}
     12{{#vendorExtensions.x-skip-test}}
     13@pytest.mark.skip(reason="{{reason}}")
     14{{/vendorExtensions.x-skip-test}}
     15{{#vendorExtensions.x-xfail-test}}
     16@pytest.mark.xfail(reason=('Reason: '
     17    '{{reason}}'))  # noqa: E501
     18{{/vendorExtensions.x-xfail-test}}
     19def test_{{operationId}}({{#vendorExtensions.x-mapservice-required}}mapservice, {{/vendorExtensions.x-mapservice-required}}client):
     20    """Test case for {{{operationId}}}
     21    {{{summary}}}
     22    """
     23    {{#bodyParam}}
     24    {{paramName}} = {{{example}}}
     25    {{/bodyParam}}
     26    {{#queryParams}}
     27    {{#-first}}query_string = [{{/-first}}{{^-first}}                {{/-first}}('{{paramName}}', '{{{example}}}'){{#hasMore}},{{/hasMore}}{{#-last}}]{{/-last}}
     28    {{/queryParams}}
     29    headers = { {{#vendorExtensions.x-prefered-produce}}
     30        'Accept': '{{mediaType}}',{{/vendorExtensions.x-prefered-produce}}{{#vendorExtensions.x-prefered-consume}}
     31        'Content-Type': '{{mediaType}}',{{/vendorExtensions.x-prefered-consume}}{{#headerParams}}
     32        '{{paramName}}': '{{{example}}}',{{/headerParams}}{{#authMethods}}
     33        {{#isBasicBasic}}'Authorization': 'Basic YXV0b3Rlc3RzOmF1dG90ZXN0cw==',{{/isBasicBasic}}
     34        {{/authMethods}}
     35    }
     36    {{#formParams}}
     37    {{#-first}}data = dict({{/-first}}{{^-first}}            {{/-first}}{{paramName}}={{{example}}}{{#hasMore}},{{/hasMore}}{{#-last}}){{/-last}}
     38    {{/formParams}}
    1339
    14 class {{#operations}}Test{{classname}}(BaseTestCase):
    15     """{{classname}} integration test stubs"""
    16 
    17     {{#operation}}
    18     {{#vendorExtensions.x-skip-test}}
    19     @unittest.skip("{{reason}}")
    20     {{/vendorExtensions.x-skip-test}}
    21     def test_{{operationId}}(self):
    22         """Test case for {{{operationId}}}
    23         {{{summary}}}
    24         """
    25         {{#bodyParam}}
    26         {{paramName}} = {{{example}}}
    27         {{/bodyParam}}
    28         {{#queryParams}}
    29         {{#-first}}query_string = [{{/-first}}{{^-first}}                {{/-first}}('{{paramName}}', '{{{example}}}'){{#hasMore}},{{/hasMore}}{{#-last}}]{{/-last}}
    30         {{/queryParams}}
    31         headers = { {{#vendorExtensions.x-prefered-produce}}
    32             'Accept': '{{mediaType}}',{{/vendorExtensions.x-prefered-produce}}{{#vendorExtensions.x-prefered-consume}}
    33             'Content-Type': '{{mediaType}}',{{/vendorExtensions.x-prefered-consume}}{{#headerParams}}
    34             '{{paramName}}': '{{{example}}}',{{/headerParams}}{{#authMethods}}
    35             {{#isBasicBasic}}'Authorization': 'Basic YXV0b3Rlc3RzOmF1dG90ZXN0cw==',{{/isBasicBasic}}
    36             {{/authMethods}}
    37         }
    38         {{#formParams}}
    39         {{#-first}}data = dict({{/-first}}{{^-first}}            {{/-first}}{{paramName}}={{{example}}}{{#hasMore}},{{/hasMore}}{{#-last}}){{/-last}}
    40         {{/formParams}}
    41         response = self.client.open(
    42             '{{#contextPath}}{{{.}}}{{/contextPath}}{{{path}}}'{{#pathParams}}{{#-first}}.format({{/-first}}{{paramName}}='{{{example}}}'{{#hasMore}}, {{/hasMore}}{{^hasMore}}){{/hasMore}}{{/pathParams}},
    43             method='{{httpMethod}}',
    44             headers=headers{{#bodyParam}},
    45             data=json.dumps({{paramName}}){{^consumes}},
    46             content_type='application/json'{{/consumes}}{{/bodyParam}}{{#formParams}}{{#-first}},
    47             data=data{{/-first}}{{/formParams}}{{#consumes}}{{#-first}},
    48             content_type='{{{mediaType}}}'{{/-first}}{{/consumes}}{{#queryParams}}{{#-first}},
    49             query_string=query_string{{/-first}}{{/queryParams}})
    50         self.assert200(response,
    51                        'Response body is : ' + response.data.decode('utf-8'))
    52 
    53    {{/operation}}
     40    {{#responses}}
     41    {{#-first}}
     42    response = client.open(
     43        '{{#contextPath}}{{{.}}}{{/contextPath}}{{{path}}}'{{#pathParams}}{{#-first}}.format({{/-first}}{{paramName}}='{{{example}}}'{{#hasMore}}, {{/hasMore}}{{^hasMore}}){{/hasMore}}{{/pathParams}},
     44        method='{{httpMethod}}',
     45        headers=headers{{#bodyParam}},
     46        data=json.dumps({{paramName}}){{^consumes}},
     47        content_type='application/json'{{/consumes}}{{/bodyParam}}{{#formParams}}{{#-first}},
     48        data=data{{/-first}}{{/formParams}}{{#consumes}}{{#-first}},
     49        content_type='{{{mediaType}}}'{{/-first}}{{/consumes}}{{#queryParams}}{{#-first}},
     50        query_string=query_string{{/-first}}{{/queryParams}})
     51    try:
     52        response_data = response.data.decode('utf-8')
     53    except Exception as e:
     54        response_data = 'Failed to decode body with {}'.format(repr(e))
     55    assert response.status_code == {{code}}, \
     56        'Response body is : {}'.format(response_data)
     57    {{/-first}}
     58    {{^-first}}
     59    # Skipping responses with status code {{code}}
     60    {{/-first}}
     61    {{/responses}}
     62   
     63   
     64{{/operation}}
    5465{{/operations}}
    55 
    56 if __name__ == '__main__':
    57     unittest.main()
  • buildhelpers/configure

    rd5199c9 r9f0f35e  
    1111CURRENT_DIR = Path(os.path.dirname(__file__))
    1212SRC = CURRENT_DIR.joinpath('../src/gnuboat')
    13 SRC_GEN = CURRENT_DIR.joinpath('../src/gnuboat/')
     13SRC_GEN = CURRENT_DIR.joinpath('../src')
    1414APIS_DIR = CURRENT_DIR.joinpath('../apis')
    1515version_file = open(CURRENT_DIR.joinpath('../VERSION').resolve(), 'r')
    … …  
    5151    Package('mapservice', 'python-flask', CURRENT_DIR.joinpath('codegen/templates'), None),
    5252    Package('deviceservice', 'python-flask', CURRENT_DIR.joinpath('codegen/templates'), None),
    53     Package('mapservice', 'python', None, 'mapservice_client'),
     53    Package('mapservice', 'python', None, 'gnuboat/mapservice_client'),
     54    Package('mapservice', 'typescript-angular', None, 'mapservice-webclient/src-gen/gnuboat-mapservice'),
    5455]
    5556
    56 def generate_stub(package, generator, template_folder, target):
     57def generate_stub(package, generator, template_folder, target_dir):
    5758    target_tmp = SRC_GEN.joinpath('{}_tmp'.format(package))
    5859    service_specification_file = APIS_DIR.joinpath('{}.yaml'.format(package)).resolve()
    5960    server_port = 8080
    6061   
     62    target = target_dir.stem
    6163    package_name_gen = 'gnuboat.{}'.format(target)
    6264    target_tmp = SRC_GEN.joinpath('{}_tmp'.format(package))
    63     target_dir = SRC_GEN.joinpath(target)
     65    target_dir = SRC_GEN.joinpath(target_dir)
    6466    service_specification_file = APIS_DIR.joinpath('{}.yaml'.format(package)).resolve()
    6567    server_port = 8080
    … …  
    104106        return
    105107
    106     shutil.move(target_tmp.joinpath('gnuboat/{}'.format(target)).resolve(), target_dir.resolve())
    107     shutil.rmtree(target_tmp.resolve())
     108    if 'python' in generator:
     109        shutil.move(target_tmp.joinpath('gnuboat/{}'.format(target)).resolve(), target_dir.resolve())
     110        shutil.rmtree(target_tmp.resolve())
     111        # running yapf
     112        print('  Formatting the generated code accoring to style file')
     113        subprocess.run(['yapf', '--style', 'python-style.yapf', '-r', '-i',
     114            target_dir.resolve()])
     115        if 'python-flask' == generator:
     116            # copy conftest in place
     117            shutil.copy(target_dir.joinpath(
     118                '../{}_impl/tests/conftest.py'.format(package)).resolve(),
     119                target_dir.joinpath('test').resolve()
     120            )
     121    else:
     122        shutil.move(target_tmp, target_dir.resolve())
    108123
    109     # running yapf
    110     print('  Formatting the generated code accoring to style file')
    111     subprocess.run(['yapf', '--style', 'python-style.yapf', '-r', '-i',
    112         target_dir.resolve()])
    113124
    114125print('Generating the {} services:'.format(len(PACKAGES)))
    115126for package in PACKAGES:
    116127    print('  {}'.format(package.package))
    117 
    118128for package in PACKAGES:
    119129    package_name_gen = 'gnuboat.{}'.format(package)
    120130    if package.target is None:
    121         package.target = package.package
     131        package.target = Path('gnuboat').joinpath(package.package)
     132    else:
     133        package.target = Path(package.target)
    122134    generate_stub(package.package, package.generator, package.template_folder, package.target)
    123135   
  • setup.py

    rd5199c9 r9f0f35e  
    1919    'flask-cors',
    2020    'flask-mail',
     21    'flask-migrate',
    2122    'shapely',
    2223    'geoalchemy2',
    … …  
    8182        'console_scripts': [
    8283            ('gnuboat-dev-mapservice='
    83              'gnuboat.mapservice_impl.demo.MapserviceEntry:main'),
     84             'gnuboat.mapservice_impl.demo.service_entry:main'),
    8485            ('gnuboat-dev-mapservice-worker='
    85              'gnuboat.mapservice_impl.demo.CeleryEntry:main'),
     86             'gnuboat.mapservice_impl.demo.celery_entry:main'),
    8687            ('gnuboat-dev-deviceservice='
    87              'gnuboat.deviceservice_impl.demo.DeviceserviceEntry:main'),
     88             'gnuboat.deviceservice_impl.demo.service_entry:main'),
    8889            ('gnuboat-device-daemon='
    89              'gnuboat.device.daemon.Daemon:main'),
     90             'gnuboat.device.daemon.daemon:main'),
    9091        ]
    9192    },
  • src/gnuboat/common/__init__.py

    rd5199c9 r9f0f35e  
    1616    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    1717'''
    18 from gnuboat.common.datahandler.loghandler import LogHandler
    19 from gnuboat.common.datahandler.logdataset import LogDataset
    20 from gnuboat.common.spatial.tilegenerator import TileGenerator
  • src/gnuboat/common/bin/gnuboat-log-analyser

    rd5199c9 r9f0f35e  
    3535from time import process_time
    3636
    37 from gnuboat_common.datahandler import loghandler, logdataset
    38 from gnuboat_common.spatial import tilegenerator
     37from gnuboat.common.datahandler import (
     38    log_handler as loghandler,
     39    log_dataset,
     40)
     41from gnuboat.common.spatial import tile_generator
    3942
    4043# -999 is a workaround, as long gdal python api does not handle addAlpha
    … …  
    238241    print("Correcting and combining {} log files".format(len(logfiles)))
    239242    for logfile in logfiles:
    240         gaugeHeight = logfile["gaugeHeight"]
    241         referenceWaterLevelGaugeHeight = logfile[
     243        gauge_height = logfile["gaugeHeight"]
     244        reference_water_level_gauge_height = logfile[
    242245            "referenceWaterLevelGaugeHeight"]
    243246        log_file_path = logfile["file"]
    … …  
    250253        # check stage
    251254        try:
    252             gaugeHeight = float(gaugeHeight)
     255            gauge_height = float(gauge_height)
    253256        except ValueError:
    254257            print(
    … …  
    258261            continue
    259262        try:
    260             referenceWaterLevelGaugeHeight = float(
    261                 referenceWaterLevelGaugeHeight
     263            reference_water_level_gauge_height = float(
     264                reference_water_level_gauge_height
    262265            )
    263266        except ValueError:
    … …  
    268271            continue
    269272        # parse, correct and append log file
    270         difference = referenceWaterLevelGaugeHeight - gaugeHeight
     273        difference = reference_water_level_gauge_height - gauge_height
    271274        csv_callback.stage_set(difference)
    272275        result = log_handler.gnuboat_read_file(
    … …  
    359362    )
    360363
    361     tilegen = tilegenerator.TileGenerator(
     364    tilegen = tile_generator.TileGenerator(
    362365        tile_sizes=tile_sizes,
    363366        densities=[density_min],
    … …  
    367370    slices = tilegen.slices(
    368371        source_xml_file,
    369         tilegenerator.ZoomRange(zoom_range[0], zoom_range[1]),
     372        tile_generator.ZoomRange(zoom_range[0], zoom_range[1]),
    370373        raster_file_size_max=raster_file_size_max * 1024 * 1024 * 8
    371374    )
  • src/gnuboat/common/bin/gnuboat-log-converter

    rd5199c9 r9f0f35e  
    2727import subprocess
    2828
    29 from gnuboat_common.datahandler import loghandler, logdataset
     29from gnuboat.common.datahandler import (
     30    log_handler as loghandler,
     31    log_dataset,
     32)
    3033
    3134
    … …  
    4447
    4548
    46 def convertToCsv(
     49def convert_to_csv(
    4750    input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time
    4851):
    … …  
    5760        'datetime', 'gps_status', 'latitude', 'latitude_direction',
    5861        'longitude', 'longitude_direction', 'speed_over_ground',
    59         'course_over_ground', 'water_depth', 'water_temperature'
     62        'course_over_ground', 'water_depth', 'water_temperature',
     63        'error_horizontal', 'error_vertical', 'error_spherical'
    6064    ]
    6165    output_file_csv = csv.DictWriter(
    … …  
    7882
    7983
    80 def convertToNmea0183(
     84def convert_to_nmea0183(
    8185    input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time
    8286):
    … …  
    121125
    122126
    123 def convertToGpx(
     127def convert_to_gpx(
    124128    input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time
    125129):
    … …  
    128132    [nmea_without_timestamps_handle,
    129133     nmea_without_timestamp_file_path] = tempfile.mkstemp(text=True)
    130     convertToNmea0183(
     134    convert_to_nmea0183(
    131135        input_file_path, nmea_without_timestamp_file_path, errors_ignore,
    132136        checksums_fix, True
    … …  
    248252
    249253    if output_format == Format.CSV.value:
    250         convertToCsv(
     254        convert_to_csv(
    251255            input_file_path, output_file_path, errors_ignore, checksums_fix,
    252256            strip_time
    253257        )
    254258    elif output_format == Format.NMEA0183.value:
    255         convertToNmea0183(
     259        convert_to_nmea0183(
    256260            input_file_path, output_file_path, errors_ignore, checksums_fix,
    257261            strip_time
    258262        )
    259263    elif output_format == Format.GPX.value:
    260         convertToGpx(
     264        convert_to_gpx(
    261265            input_file_path, output_file_path, errors_ignore, checksums_fix,
    262266            strip_time
  • src/gnuboat/common/datahandler/__init__.py

    rd5199c9 r9f0f35e  
    1616    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    1717'''
    18 
    19 from .loghandler import LogHandler
    20 from .logdataset import LogDataset
    21 
    22 __all__ = ["loghandler", "logdataset"]
  • src/gnuboat/common/datahandler/log_dataset.py

    rd5199c9 r9f0f35e  
    11# -*- coding: utf-8 -*-
    22'''
    3     Copyright (C) 2016 - 2018 EngSaS - Langenbach. All rights reserved.
     3    Copyright (C) 2016 - 2020 EngSaS - Langenbach. All rights reserved.
    44
    55    This program is free software: you can redistribute it and/or modify
  • src/gnuboat/common/datahandler/log_handler.py

    rd5199c9 r9f0f35e  
    2424from pathlib import Path
    2525
    26 from gnuboat.common.datahandler import logdataset
     26from gnuboat.common.datahandler import log_dataset
    2727
    2828
    … …  
    108108            nmea_log_file = self._nmea_file.name
    109109
    110         latitude = self._degreesDecimalToNmea(dataset.latitude())
    111         longitude = self._degreesDecimalToNmea(dataset.longitude())
     110        latitude = self._degrees_decimal_to_nmea(dataset.latitude())
     111        longitude = self._degrees_decimal_to_nmea(dataset.longitude())
    112112
    113113        logsystemtime = ""
    … …  
    274274                    if last_row is not None:
    275275                        callback(last_row)
    276                     last_row = logdataset.LogDataset()
     276                    last_row = log_dataset.LogDataset()
    277277                    last_row.datetime_set(
    278278                        '{} {}'.format(
    … …  
    282282                    last_row.gps_status_set(nmea_sentence.status)
    283283                    last_row.latitude_set(
    284                         self._nmeaLatitudeToDecimalDegrees(
     284                        self._nmea_latitude_to_decimal_degrees(
    285285                            nmea_sentence.lat, current_row
    286286                        )
    … …  
    288288                    last_row.latitude_direction_set(nmea_sentence.lat_dir)
    289289                    last_row.longitude_set(
    290                         self._nmeaLongitudeToDecimalDegrees(
     290                        self._nmea_longitude_to_decimal_degrees(
    291291                            nmea_sentence.lon, current_row
    292292                        )
    … …  
    344344                return 0
    345345
    346     def _nmeaLatitudeToDecimalDegrees(self, nmea_value, current_row):
     346    def _nmea_latitude_to_decimal_degrees(self, nmea_value, current_row):
    347347        if self._to_float(nmea_value, current_row) == 0:
    348348            return 0
    … …  
    355355            )
    356356            return
    357         decimalDegrees = self._to_float(matches.group(1), current_row)
    358         decimalMinutes = self._to_float(matches.group(2), current_row)
    359         return decimalDegrees + (decimalMinutes / 60.0)
    360 
    361     def _nmeaLongitudeToDecimalDegrees(self, nmea_value, current_row):
     357        decimal_degrees = self._to_float(matches.group(1), current_row)
     358        decimal_minutes = self._to_float(matches.group(2), current_row)
     359        return decimal_degrees + (decimal_minutes / 60.0)
     360
     361    def _nmea_longitude_to_decimal_degrees(self, nmea_value, current_row):
    362362        if self._to_float(nmea_value, current_row) == 0:
    363363            return 0
    … …  
    370370            )
    371371            return
    372         decimalDegrees = self._to_float(matches.group(1), current_row)
    373         decimalMinutes = self._to_float(matches.group(2), current_row)
    374         return decimalDegrees + (decimalMinutes / 60.0)
    375 
    376     def _degreesDecimalToNmea(self, decimalDegrees):
    377         degrees = int(math.floor(decimalDegrees))
    378         minutes = 60.0 * (decimalDegrees - degrees)
     372        decimal_degrees = self._to_float(matches.group(1), current_row)
     373        decimal_minutes = self._to_float(matches.group(2), current_row)
     374        return decimal_degrees + (decimal_minutes / 60.0)
     375
     376    def _degrees_decimal_to_nmea(self, decimal_degrees):
     377        degrees = int(math.floor(decimal_degrees))
     378        minutes = 60.0 * (decimal_degrees - degrees)
    379379        return {'degrees': degrees, 'minutes': minutes}
  • src/gnuboat/common/datahandler/rrd_handler.py

    rd5199c9 r9f0f35e  
    2121from pathlib import Path
    2222
    23 import gnuboat.common.datahandler.rrdschema as rrdschema
     23import gnuboat.common.datahandler.rrd_schema as rrdschema
    2424
    2525
  • src/gnuboat/common/spatial/__init__.py

    rd5199c9 r9f0f35e  
    1616    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    1717'''
    18 
    19 from .tilegenerator import TileGenerator
    20 
    21 __all__ = ["tilegenerator"]
  • src/gnuboat/common/spatial/tile_generator.py

    rd5199c9 r9f0f35e  
    659659                    return False
    660660        return True
    661 
    662     # def contours_create():
    663     # @todo Cut Tifs / warp
    664     # contour_input = gdal.Open(gdal_file, gdalconst.GA_ReadOnly)
    665     # contour_input_band = contour_input.GetRasterBand(1)
    666     # Generate layer to save Contourlines in
    667     # contour_output = ogr.GetDriverByName("ESRI Shapefile")
    668     #    .CreateDataSource(gdal_file_contours)
    669     # proj = osr.SpatialReference()
    670     # proj.SetWellKnownGeogCS(input_epsg)
    671     # for depth in colors:
    672     # contour_layer = contour_output.CreateLayer('contour_{}_{}_{}'
    673     #    .format(density_min, density_base, depth), srs = proj)
    674     # field_definition = ogr.FieldDefn("ID", ogr.OFTInteger)
    675     # contour_layer.CreateField(field_definition)
    676     # field_definition = ogr.FieldDefn("elev", ogr.OFTReal)
    677     # contour_layer.CreateField(field_definition)
    678     # Generate Contourlines
    679     # gdal.ContourGenerate(contour_input_band, depth, 0, [], 0, 0,
    680     #    contour_layer, 0, 1)
    681     # contour_output = None
    682     # del contour_output
    683     # print("  Created contour lines {}".format(gdal_file_contours))
    684 
    685     # def crop():
    686     #  cropping the tifs
    687     # gdal.Warp('/tmp/gnuboat/test.tif', gdal_file_color_relief,
    688     #    options = gdal.WarpOptions(format = 'GTiff', dstAlpha = True,
    689     #        srcNodata = "255 255 255", dstNodata = target_nodata_value,
    690     #        cutlineDSName = '/tmp/gnuboat/c contours/contour-0.shp',
    691     #        cutlineLayer="contour-0", cropToCutline=True))
  • src/gnuboat/common/tests/test_config.py

    rd5199c9 r9f0f35e  
    2121import os
    2222
    23 from gnuboat.common.webservice import Config as configure
     23from gnuboat.common.webservice import config as configure
    2424
    2525
  • src/gnuboat/common/tests/test_tile_generator.py

    rd5199c9 r9f0f35e  
    2727from osgeo import osr
    2828
    29 from gnuboat.common.spatial import tilegenerator
     29from gnuboat.common.spatial import tile_generator as tilegenerator
    3030
    3131
  • src/gnuboat/device/bin/gnuboat-data-generator

    rd5199c9 r9f0f35e  
    2525import os
    2626
    27 from gnuboat.device.daemon import rrdhandler as rrdhandler
     27from gnuboat.common.datahandler import rrd_handler as rrdhandler
    2828
    2929# default values for command line arguments
  • src/gnuboat/device/bin/gnuboat-splashscreen

    rd5199c9 r9f0f35e  
    2424    from PIL import ImageOps
    2525    from EPD import EPD
    26     epdEnabled = True
     26    epd_enabled = True
    2727except:
    28     epdEnabled = False
     28    epd_enabled = False
    2929
    3030
    31 def displayImage(epd, imageFilePath):
     31def display_image(epd, imageFilePath):
    3232    image = Image.open(imageFilePath)
    3333    image = ImageOps.grayscale(image)
    34     imageResized = image.resize((epd.width, epd.height))
    35     imageBlackWhite = imageResized.convert("1", dither=Image.FLOYDSTEINBERG)
     34    image_resized = image.resize((epd.width, epd.height))
     35    imageBlackWhite = image_resized.convert("1", dither=Image.FLOYDSTEINBERG)
    3636    epd.display(imageBlackWhite)
    3737    epd.update()
    … …  
    6969        sys.exit(2)
    7070
    71     if not epdEnabled:
     71    if not epd_enabled:
    7272        print("Could not initialize EPD or PIL python packages")
    7373        sys.exit(2)
    … …  
    7575    epd = EPD()
    7676    epd.clear()
    77     displayImage(epd, image)
     77    display_image(epd, image)
    7878
    7979
  • src/gnuboat/device/daemon/daemon.py

    rd5199c9 r9f0f35e  
    2626
    2727from gnuboat.device.daemon import (
    28     n2kdpoller as n2kdpoller,
    29     gpsdpoller as gpsdpoller,
    30     displayhandler as displayhandler,
     28    n2kd_poller as n2kdpoller,
     29    gpsd_poller as gpsdpoller,
     30    display_handler as displayhandler,
    3131)
    32 from gnuboat.common.datahandler import loghandler, logdataset, rrdhandler
    33 from gnuboat.common.webservice.Config import (
     32from gnuboat.common.datahandler import (
     33    log_handler as loghandler,
     34    log_dataset as logdataset,
     35    rrd_handler as rrdhandler
     36)
     37from gnuboat.common.webservice.config import (
    3438    config_from_file, config_get
    3539)
    … …  
    184188    log_systemtime = config_get(config_object, 'LOG_SYSTEMTIME', False)
    185189    display_period = config_get(config_object, 'DISPLAY_PERIOD', 5)
    186     gpsd_host = config_get(config_object, 'GPSD_HOST', 'localhost')
    187     gpsd_port = config_get(config_object, 'GPSD_PORT', '2947')
     190    gpsd_host = config_get(config_object, 'GPSD_HOST', '127.0.0.1')
     191    gpsd_port = config_get(config_object, 'GPSD_PORT', 2947)
     192    n2kd_host = config_get(config_object, 'N2KD_HOST', '127.0.0.1')
     193    n2kd_port = config_get(config_object, 'N2KD_PORT', 2597)
    188194
    189195    parser = argparse.ArgumentParser(
    … …  
    286292        rrd_file, log_directory,
    287293        gpsd_host=gpsd_host, gpsd_port=gpsd_port,
     294        n2kd_host=n2kd_host, n2kd_port=n2kd_port,
    288295        log_period=log_period,
    289296        log_systemtime=log_systemtime, log_verbose=log_verbose,
  • src/gnuboat/device/daemon/display_handler.py

    rd5199c9 r9f0f35e  
    11# -*- coding: utf-8 -*-
    22'''
    3     Copyright (C) 2016 - 2017 EngSaS - Langenbach. All rights reserved.
     3    Copyright (C) 2016 - 2020 EngSaS - Langenbach. All rights reserved.
    44
    55    This program is free software: you can redistribute it and/or modify
    … …  
    2626    from PIL import ImageDraw
    2727    from PIL import ImageFont
    28     epdEnabled = True
     28    epd_enabled = True
    2929except:
    30     epdEnabled = False
     30    epd_enabled = False
    3131
    3232
  • src/gnuboat/device/tests/conftest.py

    rd5199c9 r9f0f35e  
    1919import time
    2020
    21 from . import n2kdfake
     21from . import n2kd_fake as n2kdfake
    2222
    2323
    24 @pytest.fixture(scope='module')
     24@pytest.fixture(scope='function')
    2525def gps_fake():
    2626    """
    … …  
    4848
    4949
    50 @pytest.fixture(scope='module')
     50@pytest.fixture(scope='function')
    5151def n2kd_fake():
    5252    """
  • src/gnuboat/device/tests/test_daemon.py

    rd5199c9 r9f0f35e  
    2727import threading
    2828
    29 from gnuboat.device.daemon import Daemon
     29from gnuboat.device.daemon.daemon import Daemon
    3030
    3131from . import gpsd_fakehook
    … …  
    3737    rrd_file = test_dir.joinpath('rrd.db')
    3838
    39     daemon = Daemon.Daemon(
     39    daemon = Daemon(
    4040        rrd_file, test_dir,
    4141        gpsd_host='127.0.0.1', gpsd_port=2947,
  • src/gnuboat/device/tests/test_gpsd_poller.py

    rd5199c9 r9f0f35e  
    2424import pytz
    2525
    26 from gnuboat.device.daemon import gpsdpoller
     26from gnuboat.device.daemon import gpsd_poller as gpsdpoller
    2727
    2828from . import gpsd_fakehook
  • src/gnuboat/device/tests/test_n2kd_poller.py

    rd5199c9 r9f0f35e  
    1919import os
    2020
    21 from gnuboat.device.daemon import n2kdpoller
     21from gnuboat.device.daemon import n2kd_poller as n2kdpoller
    2222
    2323
  • src/gnuboat/deviceservice_impl/__init__.py

    rd5199c9 r9f0f35e  
    2424from pathlib import Path
    2525
    26 from gnuboat.deviceservice_impl.ValidatorWorkaround import ValidatorWorkaround
     26from gnuboat.deviceservice_impl.validator_workaround import ValidatorWorkaround
    2727from gnuboat.deviceservice import encoder
    2828
    … …  
    3030def load_config_object(config_name):
    3131    return import_string(
    32         'gnuboat.deviceservice_impl.Config.{}Config'.format(config_name)
     32        'gnuboat.deviceservice_impl.config.{}Config'.format(config_name)
    3333    )
    3434
    … …  
    4747app = connexion.App(__name__, specification_dir='../deviceservice/openapi/')
    4848application = app.app
    49 CORS(application)
    5049
    5150
    52 @app.route("/")
    53 def index():
    54     return redirect("/client/index.html", code=302)
    55 
    56 
    57 def setup_app(app_name, config, template_folder=None):
    58     application.json_encoder = encoder.JSONEncoder
    59     app.add_api(
     51def setup_app(app_name, config, template_folder=None, connexion_app=app):
     52    connexion_app.app.json_encoder = encoder.JSONEncoder
     53    connexion_app.add_api(
    6054        'openapi.yaml',
    6155        arguments={'title': app_name},
    … …  
    6458        validator_map={'response': ValidatorWorkaround}
    6559    )
    66     application.config.from_object(config)
     60    connexion_app.app.config.from_object(config)
     61    connexion_app.app.static_folder = os.path.join(
     62        os.path.dirname(__file__), 'static')
    6763
    68     application.static_url_path = '/client'
     64    app = connexion_app.app
     65    CORS(app)
     66
     67
     68    @app.route("/")
     69    def index():
     70        return redirect("/client/index.html", code=302)
     71
     72    connexion_app.app.static_url_path = '/client'
    6973    # Remove the old rule from Map._rules.
    70     for rule in application.url_map.iter_rules('static'):
    71         application.url_map._rules.remove(rule)  # There is probably only one.
     74    for rule in connexion_app.app.url_map.iter_rules('static'):
     75        # There is probably only one.
     76        connexion_app.app.url_map._rules.remove(rule)
    7277
    7378    # Remove the old rule from Map._rules_by_endpoint. In this case we can just
    7479    # start fresh.
    75     application.url_map._rules_by_endpoint['static'] = []
     80    connexion_app.app.url_map._rules_by_endpoint['static'] = []
    7681
    7782    # Add the updated rule.
    78     application.add_url_rule(
    79         f'{application.static_url_path}/<path:filename>',
     83    connexion_app.app.add_url_rule(
     84        f'{connexion_app.app.static_url_path}/<path:filename>',
    8085        endpoint='static',
    81         view_func=application.send_static_file
     86        view_func=connexion_app.app.send_static_file
    8287    )
    8388
    84     if 'DEMO' in application.config and application.config['DEMO']:
     89    if 'DEMO' in connexion_app.app.config and connexion_app.app.config['DEMO']:
    8590        from gnuboat.deviceservice_impl.demo import create_demo
    86         create_demo(application)
     91        create_demo(connexion_app.app)
  • src/gnuboat/deviceservice_impl/controllers/device_controller.py

    rd5199c9 r9f0f35e  
    2222import datetime
    2323
    24 import gnuboat.common.datahandler.rrdschema as rrdschema
    25 from gnuboat.common.webservice.HttpErrors import (
     24import gnuboat.common.datahandler.rrd_schema as rrdschema
     25from gnuboat.common.webservice.http_errors import (
    2626    GnuboatNotFound, GnuboatInternalServerError
    2727)
  • src/gnuboat/deviceservice_impl/controllers/device_logs_controller.py

    rd5199c9 r9f0f35e  
    2424from datetime import datetime, timezone
    2525
    26 from gnuboat.common.webservice.HttpErrors import (
     26from gnuboat.common.webservice.http_errors import (
    2727    GnuboatBadRequest, GnuboatUnauthorized,
    2828    GnuboatNotFound, GnuboatInternalServerError
    2929)
    30 from gnuboat.common.datahandler import loghandler
     30from gnuboat.common.datahandler import log_handler as loghandler
    3131
    3232
  • src/gnuboat/deviceservice_impl/controllers/device_maps_controller.py

    rd5199c9 r9f0f35e  
    2626import base64
    2727
    28 from gnuboat.common.webservice.HttpErrors import (
     28from gnuboat.common.webservice.http_errors import (
    2929    GnuboatNotFound, GnuboatInternalServerError,
    3030    GnuboatBadRequest
  • src/gnuboat/deviceservice_impl/controllers/mapservice_controller.py

    rd5199c9 r9f0f35e  
    2626import os
    2727
    28 from gnuboat.common.webservice.HttpErrors import (
     28from gnuboat.common.webservice.http_errors import (
    2929    GnuboatBadRequest, GnuboatUnauthorized,
    3030    GnuboatNotFound, GnuboatInternalServerError,
    … …  
    3232    GnuboatBadGateway
    3333)
    34 from gnuboat.deviceservice_impl.controllers.DeviceLogsController import (
     34from gnuboat.deviceservice_impl.controllers.device_logs_controller import (
    3535    logdirectory_get
    3636)
    … …  
    302302    if status == 500:
    303303        raise GnuboatInternalServerError(detail=detail)
     304    if status == 502:
     305        raise GnuboatBadGateway(detail=detail)
    304306    if status == 504:
    305307        raise GnuboatGatewayTimeout(detail=detail)
     308    else:
     309        raise GnuboatInternalServerError(
     310            detail='Unknown error code {} with message {}'.format(
     311                status, detail
     312            )
     313        )
  • src/gnuboat/deviceservice_impl/demo/__init__.py

    rd5199c9 r9f0f35e  
    1717
    1818from gnuboat.deviceservice_impl.demo import (
    19     DemoLog as demolog, DemoRrd as demorrd,
    20     DemoMaps as demomaps
     19    demo_log as demolog, demo_rrd as demorrd,
     20    demo_maps as demomaps
    2121)
    2222
  • src/gnuboat/deviceservice_impl/demo/demo_log.py

    rd5199c9 r9f0f35e  
    2222import shutil
    2323
    24 import gnuboat.common.datahandler.loghandler as loghandler
    25 import gnuboat.common.datahandler.logdataset as logdataset
     24import gnuboat.common.datahandler.log_handler as loghandler
     25import gnuboat.common.datahandler.log_dataset as logdataset
    2626
    2727logperiod = 2
  • src/gnuboat/deviceservice_impl/demo/demo_maps.py

    rd5199c9 r9f0f35e  
    2323import os
    2424
    25 from gnuboat.deviceservice_impl.controllers.DeviceMapsController import (
     25from gnuboat.deviceservice_impl.controllers.device_maps_controller import (
    2626    _map_name_to_hash
    2727)
  • src/gnuboat/deviceservice_impl/demo/demo_rrd.py

    rd5199c9 r9f0f35e  
    2323import rrdtool
    2424
    25 import gnuboat.common.datahandler.rrdhandler as rrdhandler
     25import gnuboat.common.datahandler.rrd_handler as rrdhandler
    2626
    2727logperiod = 2
  • src/gnuboat/deviceservice_impl/demo/service_entry.py

    rd5199c9 r9f0f35e  
    4242        sys.argv.append('--bind=localhost:8090')
    4343    sys.argv.append(
    44         'gnuboat.deviceservice_impl.demo.DeviceserviceEntry:gunicorn_app()')
     44        'gnuboat.deviceservice_impl.demo.service_entry:gunicorn_app()')
    4545
    4646    # Copied from /usr/bin/gunicorn
  • src/gnuboat/deviceservice_impl/static/index.html

    rd5199c9 r9f0f35e  
    2121                <meta name="viewport" content="width=device-width, initial-scale=1.0">
    2222                <link rel="icon" type="image/png" href="/client/common/icon/gnuboat-256-256-transparent.png"/>
    23                 <title>GNUBoat Web Application</title>
     23                <title>GNUBoat Device Web Application</title>
    2424               
    2525                <link rel="stylesheet" href="/client/common/lib/css/pure/pure-min.css" type="text/css"/>
  • src/gnuboat/deviceservice_impl/tests/__init__.py

    rd5199c9 r9f0f35e  
    1717
    1818import logging
     19import connexion
     20from flask_cors import CORS
    1921import flask
    2022from flask import request_started, request
    21 import connexion
    22 from flask_cors import CORS
     23from werkzeug.utils import import_string
    2324import rrdtool
    2425import os
    … …  
    2930import datetime
    3031import shutil
    31 import subprocess
    32 import socket
    33 from urllib.parse import urlparse
    34 from werkzeug.utils import import_string
    3532
    3633from gnuboat.common.datahandler import (
    37     rrdhandler, loghandler, logdataset,
     34    rrd_handler as rrdhandler,
     35    log_handler as loghandler,
     36    log_dataset as logdataset,
    3837)
    39 from gnuboat.common.webservice.Config import (
     38from gnuboat.common.webservice.config import (
    4039    config_get
    4140)
    4241
    43 from gnuboat.deviceservice_impl.controllers.DeviceMapsController import (
     42from gnuboat.deviceservice_impl.controllers.device_maps_controller import (
    4443    _map_name_to_hash
    4544)
    46 from gnuboat.deviceservice.encoder import JSONEncoder
     45from gnuboat.deviceservice_impl import setup_app
    4746
    4847logperiod = 2
    … …  
    5857def create_app(testcase):
    5958    logging.getLogger('connexion.operation').setLevel('ERROR')
    60     app = connexion.App(
    61         __name__,
    62         specification_dir='../../deviceservice/openapi/'
    63     )
     59    app = connexion.App(__name__,
     60                        specification_dir='../../deviceservice/openapi/')
    6461    application = app.app
    6562    CORS(application)
    66     application.json_encoder = JSONEncoder
    67     app.add_api(
    68         'openapi.yaml',
    69         validate_responses=True,
    70         strict_validation=True,
    71     )
    72 
    73     application.config.from_object(
    74         'gnuboat.deviceservice_impl.Config.TestingConfig')
     63    setup_app(__name__,
     64              import_string('gnuboat.deviceservice_impl.config.TestingConfig'),
     65              connexion_app=app)
    7566    application.app_context().push()
    7667
    … …  
    7970    _create_maps(testcase, application)
    8071
    81     _mapservice_start(testcase, application)
    82 
    83     return application
     72    return app
    8473
    8574
    86 def setUp(testcase):
     75def setup(app, testcase):
    8776    pass
    8877
    8978
    90 def tearDown(testcase):
     79def teardown(app, testcase):
    9180    os.remove(testcase.rrdfile)
    9281    shutil.rmtree(testcase.logdir)
    9382    shutil.rmtree(testcase.mapdir)
    94     if testcase.mapservice_process is not None:
    95         testcase.mapservice_process.terminate()
    96         (stdout_data, stderr_data) = \
    97             testcase.mapservice_process.communicate(timeout=10)
    98         if stdout_data:
    99             stdout_data = stdout_data.decode('utf-8')
    100             print('MAPSERVICE STDOUT: {}'.format(stdout_data))
    101         if stderr_data:
    102             stderr_data = stderr_data.decode('utf-8')
    103             print('MAPSERVICE STDERR: {}'.format(stderr_data))
    10483
    10584
    … …  
    217196        mapdir.joinpath('{}.mbtiles'.format(_map_name_to_hash('Forggensee')))
    218197    )
    219 
    220 
    221 def _mapservice_start(testcase, application):
    222     if 'TestMapserviceController' not in testcase.id():
    223         testcase.mapservice_process = None
    224     else:
    225         print('MAPSERVICE Starting')
    226         mapservice_url = config_get(application.config, 'MAPSERVICE', None)
    227         if mapservice_url is None:
    228             raise LookupError('MAPSERVICE not configured')
    229         fragments = urlparse(mapservice_url)
    230         if fragments.hostname is None:
    231             raise LookupError('MAPSERVICE host not found')
    232         if fragments.port is None:
    233             raise LookupError('MAPSERVICE port not found')
    234 
    235         mapservice_config = 'Testing'
    236         mapservice_config_object = import_string(
    237             'gnuboat.mapservice_impl.Config.{}Config'.format(mapservice_config)
    238         )
    239         database_uri = config_get(mapservice_config_object,
    240                                   'SQLALCHEMY_DATABASE_URI', None)
    241         if database_uri is None:
    242             raise LookupError(
    243                 'SQLALCHEMY_DATABASE_URI not in MAPSERVICE Testing config')
    244         database_uri = database_uri.replace('sqlite:///', '')
    245         if os.path.isfile(database_uri):
    246             os.remove(database_uri)
    247 
    248         mapservice_env = dict(os.environ)
    249         mapservice_env['FLASK_ENV'] = mapservice_config
    250         # the timeout is needed, because of the spatiallite table creation,
    251         # which is pretty slow
    252         testcase.mapservice_process = subprocess.Popen(
    253             [
    254                 'gnuboat-dev-mapservice',
    255                 '--bind={}:{}'.format(fragments.hostname, fragments.port),
    256                 '--log-level=debug'
    257             ],
    258             env=mapservice_env, shell=True,
    259             stdout=subprocess.PIPE, stderr=subprocess.PIPE
    260         )
    261         s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    262         # we need to give mapservice a chance to start before calling
    263         # connect_ex
    264         time.sleep(2)
    265         s.settimeout(10)
    266         if s.connect_ex((fragments.hostname, int(fragments.port))) == 0:
    267             print('MAPSERVICE running at {}:{}'.format(
    268                 fragments.hostname, fragments.port))
    269             s.shutdown(socket.SHUT_RDWR)
    270         else:
    271             print('MAPSERVICE Failed to start at {}:{}'.format(
    272                 fragments.hostname, fragments.port))
    273             testcase.mapservice_process.terminate()
    274             (stdout_data, stderr_data) = \
    275                 testcase.mapservice_process.communicate(timeout=10)
    276             if stdout_data:
    277                 stdout_data = stdout_data.decode('utf-8')
    278                 print('MAPSERVICE STDOUT: {}'.format(stdout_data))
    279             if stderr_data:
    280                 stderr_data = stderr_data.decode('utf-8')
    281                 print('MAPSERVICE STDERR: {}'.format(stderr_data))
    282             testcase.mapservice_process = None
  • src/gnuboat/mapservice_impl/__init__.py

    rd5199c9 r9f0f35e  
    2020from flask_cors import CORS
    2121from flask_mail import Mail
     22from flask_migrate import Migrate
    2223from sqlalchemy import event
    2324from celery import Celery
    … …  
    2627
    2728from gnuboat.mapservice import encoder
    28 from gnuboat.mapservice_impl.database.Model import (
     29from gnuboat.mapservice_impl.database.model import (
    2930    db, User, ApiKey,
    3031    db_setup, load_spatialite
    3132)
    32 from gnuboat.mapservice_impl.ValidatorWorkaround import ValidatorWorkaround
     33from gnuboat.mapservice_impl.validator_workaround import ValidatorWorkaround
    3334
    3435
    3536def load_config_object(config_name):
    3637    return import_string(
    37         'gnuboat.mapservice_impl.Config.{}Config'.format(config_name)
     38        'gnuboat.mapservice_impl.config.{}Config'.format(config_name)
    3839    )
    3940
    … …  
    5455app = connexion.App(__name__, specification_dir='../mapservice/openapi/')
    5556application = app.app
    56 CORS(application)
    5757mail = Mail()
    5858celery = Celery(__name__, broker=config_object.CELERY_BROKER_URL)
    5959
    6060
    61 def setup_app(app_name, config, template_folder=None):
    62     application.json_encoder = encoder.JSONEncoder
    63     app.add_api(
     61def setup_app(app_name, config, template_folder=None, connexion_app=app):
     62    connexion_app.app.json_encoder = encoder.JSONEncoder
     63    connexion_app.add_api(
    6464        'openapi.yaml',
    6565        arguments={'title': app_name},
    … …  
    6868        validator_map={'response': ValidatorWorkaround}
    6969    )
    70     application.config.from_object(config)
     70    connexion_app.app.config.from_object(config)
    7171
    72     if 'TEMPLATE_FOLDER' in application.config:
    73         application.template_folder = application.config['TEMPLATE_FOLDER']
     72    if 'TEMPLATE_FOLDER' in connexion_app.app.config:
     73        connexion_app.app.template_folder = \
     74            connexion_app.app.config['TEMPLATE_FOLDER']
    7475    elif template_folder:
    75         application.template_folder = template_folder
     76        connexion_app.app.template_folder = template_folder
    7677
    77     db.init_app(application)
    78     mail.init_app(application)
     78    CORS(connexion_app.app)
     79    db.init_app(connexion_app.app)
     80    migrate = Migrate(connexion_app.app, db,
     81                      directory='migrations/mapservice_impl')
     82    mail.init_app(connexion_app.app)
    7983    celery.config_from_object(config)
    80     with application.app_context():
     84
     85    with connexion_app.app.app_context():
    8186        @event.listens_for(db.engine, "connect")
    8287        def load_spatialite_extension(dbapi_conn, connection_record):
    … …  
    8489
    8590        if flask.current_app.config['CREATE_TEST_DATABASE'] is True:
    86             from gnuboat.mapservice_impl.demo import DbSetup as demoDbSetup
    87             demoDbSetup.setup()
     91            from gnuboat.mapservice_impl.demo import db_setup as demodbsetup
     92            demodbsetup.setup()
    8893        else:
    8994            db_setup()
  • src/gnuboat/mapservice_impl/celery_worker.py

    rd5199c9 r9f0f35e  
    2222    config_object, app, application, celery, setup_app
    2323)
    24 from gnuboat.mapservice_impl.database.Model import db, load_spatialite
     24from gnuboat.mapservice_impl.database.model import db, load_spatialite
    2525from gnuboat.mapservice_impl.tasks import tasks
    2626
  • src/gnuboat/mapservice_impl/config.py

    rd5199c9 r9f0f35e  
    8989    TESTING = True
    9090    DEBUG = False
    91     CELERY_BROKER_URL = ''
     91    CELERY_BROKER_URL = None
    9292    SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/gnuboat-ci-tests.db'
     93    CREATE_TEST_DATABASE = False
  • src/gnuboat/mapservice_impl/controllers/devices_controller.py

    rd5199c9 r9f0f35e  
    1717import connexion
    1818
    19 from gnuboat.mapservice_impl.database.Model import User, Device, db
    20 from gnuboat.common.webservice.HttpErrors import (
     19from gnuboat.mapservice_impl.database.model import User, Device, db
     20from gnuboat.common.webservice.http_errors import (
    2121    GnuboatBadRequest, GnuboatUnauthorized, GnuboatNotFound
    2222)
    … …  
    6868    db.session.add(device)
    6969    db.session.commit()
    70     return device.to_dict()
     70    return device.to_dict(), 201
    7171
    7272
  • src/gnuboat/mapservice_impl/controllers/logs_controller.py

    rd5199c9 r9f0f35e  
    1717import connexion
    1818
    19 from gnuboat.mapservice_impl.database.Model import (
     19from gnuboat.mapservice_impl.database.model import (
    2020    User, Log, LogEntry,
    2121    Water, Device, Gauge, ProcessingStatus, Queue, db
    2222)
    23 from gnuboat.common.webservice.HttpErrors import (
     23from gnuboat.common.webservice.http_errors import (
    2424    GnuboatBadRequest, GnuboatUnauthorized, GnuboatNotFound
    2525)
    … …  
    116116    db.session.add(log)
    117117    db.session.commit()
    118     return log.meta_data()
     118    return log.meta_data(), 201
    119119
    120120
    … …  
    158158    log_process.delay(log.id, body.decode())
    159159
    160     return log.meta_data()
     160    return log.meta_data(), 201
    161161
    162162
  • src/gnuboat/mapservice_impl/controllers/tiles_controller.py

    rd5199c9 r9f0f35e  
    2020import os
    2121
    22 from gnuboat.common.webservice.HttpErrors import (
     22from gnuboat.common.webservice.http_errors import (
    2323    GnuboatInternalServerError, GnuboatBadRequest, GnuboatNotFound
    2424)
  • src/gnuboat/mapservice_impl/controllers/users_controller.py

    rd5199c9 r9f0f35e  
    2525
    2626from gnuboat.mapservice_impl import mail
    27 from gnuboat.mapservice_impl.database.Model import User, ApiKey, db
    28 from gnuboat.common.webservice.HttpErrors import (
     27from gnuboat.mapservice_impl.database.model import User, ApiKey, db
     28from gnuboat.common.webservice.http_errors import (
    2929    GnuboatBadRequest, GnuboatUnauthorized, GnuboatNotFound
    3030)
  • src/gnuboat/mapservice_impl/controllers/waters_controller.py

    rd5199c9 r9f0f35e  
    1717import connexion
    1818
    19 from gnuboat.mapservice_impl.database.Model import User, Water, Gauge, Log, db
    20 from gnuboat.common.webservice.HttpErrors import (
     19from gnuboat.mapservice_impl.database.model import User, Water, Gauge, Log, db
     20from gnuboat.common.webservice.http_errors import (
    2121    GnuboatBadRequest,
    2222    GnuboatUnauthorized, GnuboatNotFound
    … …  
    108108    db.session.add(water)
    109109    db.session.commit()
    110     return water.to_dict()
     110    return water.to_dict(), 201
    111111
    112112
    … …  
    158158    db.session.add(gauge)
    159159    db.session.commit()
    160     return gauge.to_dict()
     160    return gauge.to_dict(), 201
    161161
    162162
  • src/gnuboat/mapservice_impl/demo/celery_entry.py

    rd5199c9 r9f0f35e  
    2525    # Add need configuration options
    2626    sys.argv.append('-A')
    27     sys.argv.append('gnuboat.mapservice_impl.CeleryWorker:celery')
     27    sys.argv.append('gnuboat.mapservice_impl.celery_worker:celery')
    2828    sys.argv.append('worker')
    2929    sys.argv.append('-l')
  • src/gnuboat/mapservice_impl/demo/db_setup.py

    rd5199c9 r9f0f35e  
    2020import flask
    2121
    22 from gnuboat.mapservice_impl.database.Model import (
     22from gnuboat.mapservice_impl.database.model import (
    2323    db, User, ApiKey, Water,
    2424    OsmType, Gauge, Device, Log, Queue, ProcessingStatus, db_setup
    2525)
    26 from gnuboat.common.webservice.HttpErrors import (
     26from gnuboat.common.webservice.http_errors import (
    2727    GnuboatBadRequest
    2828)
  • src/gnuboat/mapservice_impl/demo/service_entry.py

    rd5199c9 r9f0f35e  
    4444        sys.argv.append('--bind=localhost:8080')
    4545    sys.argv.append(
    46         'gnuboat.mapservice_impl.demo.MapserviceEntry:gunicorn_app()')
     46        'gnuboat.mapservice_impl.demo.service_entry:gunicorn_app()')
    4747
    4848    # Copied from /usr/bin/gunicorn
  • src/gnuboat/mapservice_impl/security/security.py

    rd5199c9 r9f0f35e  
    1515    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    1616'''
    17 from ..database.Model import ApiKey, User
     17from ..database.model import ApiKey, User
    1818
    1919
  • src/gnuboat/mapservice_impl/tasks/tasks.py

    rd5199c9 r9f0f35e  
    3434import mercantile
    3535
    36 from gnuboat.common.datahandler import loghandler
    37 from gnuboat.common.spatial import tilegenerator
    38 from gnuboat.common.spatial.tilegenerator import (
     36from gnuboat.common.datahandler import log_handler as loghandler
     37from gnuboat.common.spatial import tile_generator as tilegenerator
     38from gnuboat.common.spatial.tile_generator import (
    3939    RasterSlice, LngLatBbox, ZoomRange
    4040)
    4141
    4242from gnuboat.mapservice_impl import mail, celery as celery_app
    43 from gnuboat.mapservice_impl.database.Model import (
     43from gnuboat.mapservice_impl.database.model import (
    4444    User, Log, LogEntry, Water, ProcessingStatus, Queue, db
    4545)
    46 from gnuboat.mapservice_impl.tasks.tileconfig import TileConfig
     46from gnuboat.mapservice_impl.tasks.tile_config import TileConfig
    4747
    4848
  • src/gnuboat/mapservice_impl/tests/__init__.py

    rd5199c9 r9f0f35e  
    1717
    1818import logging
    19 
    20 import flask
    2119import connexion
    2220from flask_cors import CORS
    2321from flask_mail import Mail
     22from celery import Celery
    2423from sqlalchemy.event import listen
    25 from celery import Celery
     24from werkzeug.utils import import_string
    2625import tempfile
    2726import os
    2827from PIL import Image
    29 import shutil
    3028
    31 from gnuboat.mapservice.encoder import JSONEncoder
    32 from gnuboat.mapservice_impl.database.Model import (
     29from gnuboat.mapservice_impl.database.model import (
    3330    db, db_setup, load_spatialite
    3431)
    3532from gnuboat.mapservice_impl.tests import db_test_setup
     33from gnuboat.mapservice_impl import setup_app
    3634
    3735
    38 def create_app(testcase):
     36def check_key(key, value, data):
     37    assert key in data, "{} not in data {}".format(key, data)
     38    assert data[key] == value, "{} = {}".format(value, data[key])
     39
     40
     41def create_app():
    3942    logging.getLogger('connexion.operation').setLevel('ERROR')
    40     app = connexion.App(
    41         __name__,
    42         specification_dir='../../mapservice/openapi/'
    43     )
     43    app = connexion.App(__name__,
     44                        specification_dir='../../mapservice/openapi/')
    4445    application = app.app
    4546    CORS(application)
    4647    mail = Mail()
    47     application.json_encoder = JSONEncoder
    48     app.add_api('openapi.yaml')
     48    celery = Celery(__name__, broker='')
     49    setup_app(__name__,
     50              import_string('gnuboat.mapservice_impl.config.TestingConfig'),
     51              os.path.join(os.path.dirname(__file__),
     52                           '../../mapservice_impl/templates'),
     53              connexion_app=app)
    4954
    50     application.config.from_object(
    51         'gnuboat.mapservice_impl.Config.TestingConfig')
    52     application.template_folder = os.path.join(
    53         os.path.dirname(__file__),
    54         '../../mapservice_impl/templates'
    55     )
    56     celery = Celery(__name__, broker=application.config['CELERY_BROKER_URL'])
    57     celery.config_from_object(application.config)
    58     mail.init_app(application)
    59     db.init_app(application)
    60     application.app_context().push()
     55    _create_test_tile(application)
    6156
    62     _create_test_tile(testcase, application)
    63 
    64     return application
     57    return app
    6558
    6659
    67 def setUp(testcase):
    68     listen(db.engine, 'connect', load_spatialite)
    69     db.drop_all()
    70     # create the tables whether the database already exists or not
    71     db_setup(True)
    72     testcase.db_content = db_test_setup.DatabaseContent()
    73     testcase.db_content.setup()
     60def setup(application):
     61    with application.app_context():
     62        listen(db.engine, 'connect', load_spatialite)
     63        db.drop_all()
     64        # create the tables whether the database already exists or not
     65        db_setup(True)
     66        application.config.db_content = db_test_setup.DatabaseContent()
     67        application.config.db_content.setup()
    7468
    7569
    76 def tearDown(testcase):
    77     db.session.remove()
    78     db.drop_all()
    79     shutil.rmtree(testcase.tiles_cache)
     70def teardown(application):
     71    with application.app_context():
     72        db.session.remove()
     73        db.drop_all()
    8074
    8175
    82 def _create_test_tile(testcase, application):
    83     testcase.tiles_cache = tempfile.mkdtemp(prefix='gnuboat-tests')
    84     application.config['TILES_CACHE_PATH'] = testcase.tiles_cache
     76def _create_test_tile(application):
     77    application.config.tiles_cache = tempfile.mkdtemp(prefix='gnuboat-tests')
     78    application.config['TILES_CACHE_PATH'] = application.config.tiles_cache
    8579
    86     tile_path = os.path.join(testcase.tiles_cache, '100_100/256/15/17298/')
     80    tile_path = os.path.join(application.config.tiles_cache,
     81                             '100_100/256/15/17298/')
    8782    os.makedirs(tile_path)
    8883    img = Image.new('RGBA', (100, 100), (255, 0, 0, 0))
  • src/gnuboat/mapservice_impl/tests/db_test_setup.py

    rd5199c9 r9f0f35e  
    2020import flask
    2121
    22 from gnuboat.mapservice_impl.database.Model import (
     22from gnuboat.mapservice_impl.database.model import (
    2323    db, User, ApiKey, Water,
    2424    OsmType, Gauge, Device, Log, Queue, ProcessingStatus, db_setup
    2525)
    26 from gnuboat.mapservice_impl.demo import DbSetup as demoDbSetup
     26from gnuboat.mapservice_impl.demo import db_setup as demodbsetup
    2727from gnuboat.mapservice_impl.tasks.tasks import log_process
    2828
    … …  
    4141        print("CREATING DATABASE TEST CONTENT...")
    4242        with db.session.no_autoflush:
    43             self.test_user = User.factory(
     43            test_user = User.factory(
    4444                'autotests', 'autotests', 'auto@example.org'
    4545            )
    46             self.test_user.activated = True
    47             self.test_user.first_name = 'Autotests'
    48             self.test_user.license_accepted = True
    49             db.session.add(self.test_user)
     46            test_user.activated = True
     47            test_user.first_name = 'Autotests'
     48            test_user.license_accepted = True
     49            db.session.add(test_user)
    5050            db.session.commit()
     51            self.test_user = test_user.to_dict()
    5152
    5253            user_activation = User.factory(
    … …  
    6263            db.session.commit()
    6364
    64             db.session.add(ApiKey(user=self.test_user, key='test_key'))
    65             db.session.add(ApiKey(user=self.test_user, key='test_key_delete'))
     65            db.session.add(ApiKey(user=test_user, key='test_key'))
     66            db.session.add(ApiKey(user=test_user, key='test_key_delete'))
    6667            db.session.commit()
    6768
    68             self.test_water = Water(
     69            test_water = Water(
    6970                name='Test Water',
    70                 manager=self.test_user,
     71                manager=test_user,
    7172                osm_id=1756854,
    7273                osm_type=OsmType.Relation
    7374            )
    74             db.session.add(self.test_water)
     75            db.session.add(test_water)
    7576            db.session.commit()
     77            self.test_water = test_water.to_dict()
    7678
    77             self.test_gauge = Gauge(
     79            test_gauge = Gauge(
    7880                name='test_gauge',
    79                 manager=self.test_user,
    80                 water=self.test_water,
     81                manager=test_user,
     82                water=test_water,
    8183                location='SRID=4326;POINT(-90.136111 29.934722)',
    8284                reference_water_level_gauge_height=3
    8385            )
    84             db.session.add(self.test_gauge)
     86            db.session.add(test_gauge)
    8587            db.session.commit()
     88            self.test_gauge = test_gauge.to_dict()
    8689
    87             self.test_device = Device(
    88                 name='Test Device', owner=self.test_user, sensor_depth=0.2
     90            test_device = Device(
     91                name='Test Device', owner=test_user, sensor_depth=0.2
    8992            )
    90             db.session.add(self.test_device)
     93            db.session.add(test_device)
    9194            db.session.commit()
     95            self.test_device = test_device.to_dict()
    9296
    9397            log_file = os.path.join(
    9498                os.path.dirname(__file__), 'data/nmea0183-2017-12-09.log'
    9599            )
    96             self.test_log = demoDbSetup._sample_log_add(
    97                 self.test_water, self.test_gauge, 0, self.test_device,
    98                 self.test_user, log_file
     100            test_log = demodbsetup._sample_log_add(
     101                test_water, test_gauge, 0, test_device,
     102                test_user, log_file
    99103            )
     104            self.test_log = test_log.meta_data()
    100105
    101106            print("...Finished")
  • src/gnuboat/mapservice_impl/tests/test_logs.py

    rd5199c9 r9f0f35e  
    1616'''
    1717
    18 import unittest
     18import pytest
    1919import json
    20 import os
    2120
    22 from gnuboat.mapservice.test import BaseTestCase
     21from . import check_key
    2322
    2423
    25 class TestLogs(BaseTestCase):
    26     @classmethod
    27     def setUpClass(self):
    28         self.base_url = '/mapservice/v1/logs'
    29 
    30     def test_get(self):
    31         """Test case getting log (src)
    32         """
    33         headers = {'Accept': 'application/json'}
    34         response = self.client.open(
    35             '{}/{}'.format(self.base_url, self.db_content.test_log.id),
    36             method='GET',
    37             headers=headers
    38         )
    39         assert response.status_code == 200
    40         data = json.loads(response.data)
    41         assert len(data) == 2
    42         assert 'entries' in data
    43         assert 'metaData' in data
    44         metaData = data['metaData']
    45         assert "submitter" in metaData
    46         self.check_key(
    47             "submitter", self.db_content.test_log.submitter.username, metaData
    48         )
    49         assert 'water' in metaData
    50         self.check_key(
    51             "id", self.db_content.test_log.water.id, metaData['water']
    52         )
    53         self.check_key(
    54             "label", self.db_content.test_log.water.name, metaData['water']
    55         )
    56         assert 'device' in metaData
    57         self.check_key(
    58             "id", self.db_content.test_log.device.id, metaData['device']
    59         )
    60         self.check_key(
    61             "label", self.db_content.test_log.device.name, metaData['device']
    62         )
    63         assert 'gauge' in metaData
    64         self.check_key(
    65             "id", self.db_content.test_log.gauge.id, metaData['gauge']
    66         )
    67         self.check_key(
    68             "label", self.db_content.test_log.gauge.name, metaData['gauge']
    69         )
    70         self.check_key(
    71             "gaugeHeight", self.db_content.test_log.gauge_height, metaData
    72         )
    73 
    74     def test_get_by_manager(self):
    75         """Test case getting log by submitter (src)
    76         """
    77         headers = {'Accept': 'application/json'}
    78 
    79         response = self.client.open(
    80             '{}?submitter=not_existent'.format(self.base_url),
    81             method='GET',
    82             headers=headers
    83         )
    84         assert response.status_code == 404, '{} != {}'.format(
    85             response.status_code, 404
    86         )
    87 
    88         response = self.client.open(
    89             '{}?submitter={}'.format(
    90                 self.base_url, self.db_content.test_log.submitter.username
    91             ),
    92             method='GET',
    93             headers=headers
    94         )
    95         assert response.status_code == 200
    96         data = json.loads(response.data)
    97         assert len(data) == 1
    98         data = data[0]
    99         self.check_key(
    100             "submitter", self.db_content.test_log.submitter.username, data
    101         )
    102         assert 'water' in data
    103         self.check_key("id", self.db_content.test_log.water.id, data['water'])
    104         self.check_key(
    105             "label", self.db_content.test_log.water.name, data['water']
    106         )
    107         assert 'device' in data
    108         self.check_key(
    109             "id", self.db_content.test_log.device.id, data['device']
    110         )
    111         self.check_key(
    112             "label", self.db_content.test_log.device.name, data['device']
    113         )
    114         assert 'gauge' in data
    115         self.check_key("id", self.db_content.test_log.gauge.id, data['gauge'])
    116         self.check_key(
    117             "label", self.db_content.test_log.gauge.name, data['gauge']
    118         )
    119         self.check_key(
    120             "gaugeHeight", self.db_content.test_log.gauge_height, data
    121         )
    122 
    123     def test_create_log(self):
    124         """Test case create log (src)
    125         """
    126         headers = {
    127             'X-API-KEY': 'test_key',
    128             'Accept': 'application/json',
    129             'Content-Type': 'application/json'
    130         }
    131         logCreation = {
    132             'water': 1,
    133             'device': 1,
    134             'gauge': 1,
    135             'gaugeHeight': 1.0,
    136             'comment': 'Log from unit test'
    137         }
    138 
    139         response = self.client.open(
    140             self.base_url,
    141             method='POST',
    142             headers=headers,
    143             data=json.dumps(logCreation),
    144             content_type='application/json'
    145         )
    146         assert response.status_code == 200
    147         data = response.get_json()
    148         assert len(data) >= 7
    149         self.check_key("logId", 2, data)
    150         assert 'water' in data
    151         self.check_key("id", logCreation['water'], data['water'])
    152         assert 'device' in data
    153         self.check_key("id", logCreation['device'], data['device'])
    154         assert 'gauge' in data
    155         self.check_key("id", logCreation['gauge'], data['gauge'])
    156         self.check_key("gaugeHeight", logCreation['gaugeHeight'], data)
    157         self.check_key("comment", logCreation['comment'], data)
    158 
    159         # could not be tested without running CELERY_BROKER
    160         # filename = '{}/data/nmea0183-2017-12-09.log'.format(
    161         #   os.path.dirname(os.path.abspath(__file__)))
    162         # fileContent = open(filename, 'rb')
    163         # headers["Accept"] = "application/geo+json"
    164         # response = self.client.post(
    165         # "{}/{}".format(self.base_url, data["logId"]),
    166         # data = fileContent,
    167         # headers = headers
    168         # )
    169         # assert response.status_code == 200
     24base_url = '/mapservice/v1/logs'
    17025
    17126
    172 if __name__ == '__main__':
    173     unittest.main()
     27def test_get(client, config):
     28    """Test case getting log (src)
     29    """
     30    headers = {'Accept': 'application/json'}
     31    response = client.open(
     32        '{}/{}'.format(base_url, config.db_content.test_log['logId']),
     33        method='GET',
     34        headers=headers
     35    )
     36    assert response.status_code == 200
     37    data = response.json
     38    assert len(data) == 2
     39    assert 'entries' in data
     40    assert 'metaData' in data
     41    metaData = data['metaData']
     42    assert "submitter" in metaData
     43    check_key(
     44        "submitter", config.db_content.test_log['submitter'], metaData
     45    )
     46    assert 'water' in metaData
     47    check_key(
     48        "id", config.db_content.test_log['water']['id'], metaData['water']
     49    )
     50    check_key(
     51        "label", config.db_content.test_log['water']['label'],
     52        metaData['water']
     53    )
     54    assert 'device' in metaData
     55    check_key(
     56        "id", config.db_content.test_log['device']['id'], metaData['device']
     57    )
     58    check_key(
     59        "label", config.db_content.test_log['device']['label'],
     60        metaData['device']
     61    )
     62    assert 'gauge' in metaData
     63    check_key(
     64        "id", config.db_content.test_log['gauge']['id'], metaData['gauge']
     65    )
     66    check_key(
     67        "label", config.db_content.test_log['gauge']['label'],
     68        metaData['gauge']
     69    )
     70    check_key(
     71        "gaugeHeight", config.db_content.test_log['gaugeHeight'], metaData
     72    )
     73
     74
     75def test_get_by_manager(client, config):
     76    """Test case getting log by submitter (src)
     77    """
     78    headers = {'Accept': 'application/json'}
     79
     80    response = client.open(
     81        '{}?submitter=not_existent'.format(base_url),
     82        method='GET',
     83        headers=headers
     84    )
     85    assert response.status_code == 404, '{} != {}'.format(
     86        response.status_code, 404
     87    )
     88
     89    response = client.open(
     90        '{}?submitter={}'.format(
     91            base_url, config.db_content.test_log['submitter']
     92        ),
     93        method='GET',
     94        headers=headers
     95    )
     96    assert response.status_code == 200
     97    data = response.json
     98    assert len(data) == 1
     99    data = data[0]
     100    check_key(
     101        "submitter", config.db_content.test_log['submitter'], data
     102    )
     103    assert 'water' in data
     104    check_key("id", config.db_content.test_log['water']['id'], data['water'])
     105    check_key(
     106        "label", config.db_content.test_log['water']['label'], data['water']
     107    )
     108    assert 'device' in data
     109    check_key(
     110        "id", config.db_content.test_log['device']['id'], data['device']
     111    )
     112    check_key(
     113        "label", config.db_content.test_log['device']['label'], data['device']
     114    )
     115    assert 'gauge' in data
     116    check_key("id", config.db_content.test_log['gauge']['id'], data['gauge'])
     117    check_key(
     118        "label", config.db_content.test_log['gauge']['label'], data['gauge']
     119    )
     120    check_key(
     121        "gaugeHeight", config.db_content.test_log['gaugeHeight'], data
     122    )
     123
     124
     125def test_create_log(client):
     126    """Test case create log (src)
     127    """
     128    headers = {
     129        'X-API-KEY': 'test_key',
     130        'Accept': 'application/json',
     131        'Content-Type': 'application/json'
     132    }
     133    logCreation = {
     134        'water': 1,
     135        'device': 1,
     136        'gauge': 1,
     137        'gaugeHeight': 1.0,
     138        'comment': 'Log from unit test'
     139    }
     140
     141    response = client.open(
     142        base_url,
     143        method='POST',
     144        headers=headers,
     145        data=json.dumps(logCreation),
     146        content_type='application/json'
     147    )
     148    assert response.status_code == 201
     149    data = response.json
     150    assert len(data) >= 7
     151    check_key("logId", 2, data)
     152    assert 'water' in data
     153    check_key("id", logCreation['water'], data['water'])
     154    assert 'device' in data
     155    check_key("id", logCreation['device'], data['device'])
     156    assert 'gauge' in data
     157    check_key("id", logCreation['gauge'], data['gauge'])
     158    check_key("gaugeHeight", logCreation['gaugeHeight'], data)
     159    check_key("comment", logCreation['comment'], data)
     160
     161    # could not be tested without running CELERY_BROKER
     162    # filename = '{}/data/nmea0183-2017-12-09.log'.format(
     163    #   os.path.dirname(os.path.abspath(__file__)))
     164    # fileContent = open(filename, 'rb')
     165    # headers["Accept"] = "application/geo+json"
     166    # response = self.client.post(
     167    # "{}/{}".format(self.base_url, data["logId"]),
     168    # data = fileContent,
     169    # headers = headers
     170    # )
     171    # assert response.status_code == 200
  • src/gnuboat/mapservice_impl/tests/test_users.py

    rd5199c9 r9f0f35e  
    1616'''
    1717
    18 import unittest
     18import pytest
    1919import json
    2020
    21 from gnuboat.mapservice.test import BaseTestCase
     21from . import check_key
     22
     23base_url = '/mapservice/v1/user'
    2224
    2325
    24 class TestUsers(BaseTestCase):
    25     @classmethod
    26     def setUpClass(self):
    27         self.base_url = '/mapservice/v1/user'
     26def test_users_get(client):
     27    """Test case for getting users (src)
     28    """
     29    headers = {}
     30    response = client.open(
     31        base_url, method='GET', headers=headers
     32    )
     33    assert response.status_code == 401
    2834
    29     def test_users_get(self):
    30         """Test case for getting users (src)
    31         """
    32         headers = {}
    33         response = self.client.open(
    34             self.base_url, method='GET', headers=headers
    35         )
    36         assert response.status_code == 401
     35    response = client.open(
     36        base_url, method='GET', headers={'X-API-KEY': 'test_key'}
     37    )
     38    assert response.status_code == 200
     39    data = response.json
     40    check_key("username", "autotests", data)
     41    check_key("firstName", "Autotests", data)
     42    check_key("lastName", "", data)
     43    check_key("email", "auto@example.org", data)
     44    check_key("activated", True, data)
     45    check_key("licenseAccepted", True, data)
    3746
    38         response = self.client.open(
    39             self.base_url, method='GET', headers={'X-API-KEY': 'test_key'}
    40         )
    41         assert response.status_code == 200
    42         data = json.loads(response.data)
    43         self.check_key("username", "autotests", data)
    44         self.check_key("firstName", "Autotests", data)
    45         self.check_key("lastName", "", data)
    46         self.check_key("email", "auto@example.org", data)
    47         self.check_key("activated", True, data)
    48         self.check_key("licenseAccepted", True, data)
     47    assert "apiKeys" in data
     48    assert data["apiKeys"][0] == "test_key"
     49    assert data["apiKeys"][1] == "test_key_delete"
    4950
    50         assert "apiKeys" in data
    51         assert data["apiKeys"][0] == "test_key"
    52         assert data["apiKeys"][1] == "test_key_delete"
    53 
    54         assert "password" not in data
    55         assert "salt" not in data
    56         assert "activationCode" not in data
    57 
    58     def test_impl_users_register(self):
    59         """Test case for users_register (Src)
    60            Register a new user
    61         """
    62         user_creation = {
    63             "username": "jane_doe",
    64             "firstName": "Jane",
    65             "lastName": "Doe",
    66             "password": "1234",
    67             "licenseAccepted": True,
    68             "email": "jane.doe@example.org"
    69         }
    70         headers = {
    71             'Accept': 'application/json',
    72         }
    73         response = self.client.open(
    74             self.base_url,
    75             method='POST',
    76             headers=headers,
    77             data=json.dumps(user_creation),
    78             content_type='application/json'
    79         )
    80         assert response.status_code == 200
    81         data = json.loads(response.data)
    82         self.check_key("username", user_creation['username'], data)
    83         self.check_key("firstName", user_creation['firstName'], data)
    84         self.check_key("lastName", user_creation['lastName'], data)
    85         self.check_key("email", user_creation['email'], data)
    86         self.check_key("activated", False, data)
    87         self.check_key("licenseAccepted", True, data)
    88 
    89         assert 'apiKeys' in data
    90         assert len(data['apiKeys']) == 0
     51    assert "password" not in data
     52    assert "salt" not in data
     53    assert "activationCode" not in data
    9154
    9255
    93 if __name__ == '__main__':
    94     unittest.main()
     56def test_impl_users_register(client):
     57    """Test case for users_register (Src)
     58        Register a new user
     59    """
     60    user_creation = {
     61        "username": "jane_doe",
     62        "firstName": "Jane",
     63        "lastName": "Doe",
     64        "password": "1234",
     65        "licenseAccepted": True,
     66        "email": "jane.doe@example.org"
     67    }
     68    headers = {
     69        'Accept': 'application/json',
     70    }
     71    response = client.open(
     72        base_url,
     73        method='POST',
     74        headers=headers,
     75        data=json.dumps(user_creation),
     76        content_type='application/json'
     77    )
     78    assert response.status_code == 200
     79    data = response.json
     80    check_key("username", user_creation['username'], data)
     81    check_key("firstName", user_creation['firstName'], data)
     82    check_key("lastName", user_creation['lastName'], data)
     83    check_key("email", user_creation['email'], data)
     84    check_key("activated", False, data)
     85    check_key("licenseAccepted", True, data)
     86
     87    assert 'apiKeys' in data
     88    assert len(data['apiKeys']) == 0
  • src/gnuboat/mapservice_impl/tests/test_waters.py

    rd5199c9 r9f0f35e  
    1616'''
    1717
    18 import unittest
    19 import json
     18import pytest
    2019
    21 from gnuboat.mapservice.test import BaseTestCase
     20from . import check_key
     21
     22base_url = '/mapservice/v1/waters'
    2223
    2324
    24 class TestWaters(BaseTestCase):
    25     @classmethod
    26     def setUpClass(self):
    27         self.base_url = '/mapservice/v1/waters'
    28 
    29     def test_get(self):
    30         """Test case getting waters (src)
    31         """
    32         headers = {}
    33         response = self.client.open(
    34             self.base_url, method='GET', headers=headers
    35         )
    36         assert response.status_code == 200
    37         data = json.loads(response.data)
    38         assert len(data) == 1
    39         data = data[0]
    40         self.check_key(
    41             "manager", self.db_content.test_water.manager.username, data
    42         )
    43         self.check_key("name", self.db_content.test_water.name, data)
    44         self.check_key("waterId", self.db_content.test_water.id, data)
    45         self.check_key("osmId", self.db_content.test_water.osm_id, data)
    46         self.check_key(
    47             "osmType", self.db_content.test_water.osm_type.name, data
    48         )
    49 
    50     def test_get_by_name(self):
    51         """Test case getting waters by name (src)
    52         """
    53         headers = {}
    54 
    55         response = self.client.open(
    56             '{}?name=Bla'.format(self.base_url), method='GET', headers=headers
    57         )
    58         assert response.status_code == 200
    59         data = json.loads(response.data)
    60         assert len(data) == 0
    61 
    62         response = self.client.open(
    63             '{}?name={}'.format(
    64                 self.base_url, self.db_content.test_water.name[:3]
    65             ),
    66             method='GET',
    67             headers=headers
    68         )
    69         assert response.status_code == 200
    70         data = json.loads(response.data)
    71         assert len(data) == 1
    72         data = data[0]
    73         self.check_key(
    74             "manager", self.db_content.test_water.manager.username, data
    75         )
    76         self.check_key("name", self.db_content.test_water.name, data)
    77         self.check_key("waterId", self.db_content.test_water.id, data)
    78         self.check_key("osmId", self.db_content.test_water.osm_id, data)
    79         self.check_key(
    80             "osmType", self.db_content.test_water.osm_type.name, data
    81         )
    82 
    83     def test_get_by_manager(self):
    84         """Test case getting waters by manager (src)
    85         """
    86         headers = {}
    87 
    88         response = self.client.open(
    89             '{}?manager=not_existent'.format(self.base_url),
    90             method='GET',
    91             headers=headers
    92         )
    93         assert response.status_code == 404, '{} != {}'.format(
    94             response.status_code, 404
    95         )
    96 
    97         response = self.client.open(
    98             '{}?manager={}'.format(
    99                 self.base_url, self.db_content.test_user.username
    100             ),
    101             method='GET',
    102             headers=headers
    103         )
    104         assert response.status_code == 200
    105         data = json.loads(response.data)
    106         assert len(data) == 1
    107         data = data[0]
    108         self.check_key(
    109             "manager", self.db_content.test_water.manager.username, data
    110         )
    111         self.check_key("name", self.db_content.test_water.name, data)
    112         self.check_key("waterId", self.db_content.test_water.id, data)
    113         self.check_key("osmId", self.db_content.test_water.osm_id, data)
    114         self.check_key(
    115             "osmType", self.db_content.test_water.osm_type.name, data
    116         )
    117 
    118     def test_get_by_name_manager(self):
    119         """Test case getting waters by manager and water name (src)
    120         """
    121         headers = {}
    122 
    123         response = self.client.open(
    124             '{}?manager={}&name=Bla'.format(
    125                 self.base_url, self.db_content.test_user.username
    126             ),
    127             method='GET',
    128             headers=headers
    129         )
    130         assert response.status_code == 200
    131 
    132         response = self.client.open(
    133             '{}?manager=john&name={}'.format(
    134                 self.base_url, self.db_content.test_water.name[:3]
    135             ),
    136             method='GET',
    137             headers=headers
    138         )
    139         assert response.status_code == 404
    140 
    141         response = self.client.open(
    142             '{}?name={}&manager={}'.format(
    143                 self.base_url, self.db_content.test_water.name,
    144                 self.db_content.test_user.username
    145             ),
    146             method='GET',
    147             headers=headers
    148         )
    149         assert response.status_code == 200
    150         data = json.loads(response.data)
    151         assert len(data) == 1
    152         data = data[0]
    153         self.check_key(
    154             "manager", self.db_content.test_water.manager.username, data
    155         )
    156         self.check_key("name", self.db_content.test_water.name, data)
    157         self.check_key("waterId", self.db_content.test_water.id, data)
    158         self.check_key("osmId", self.db_content.test_water.osm_id, data)
    159         self.check_key(
    160             "osmType", self.db_content.test_water.osm_type.name, data
    161         )
     25def test_get(client, config):
     26    """Test case getting waters (src)
     27    """
     28    headers = {}
     29    response = client.open(
     30        base_url, method='GET', headers=headers
     31    )
     32    assert response.status_code == 200
     33    data = response.json
     34    assert len(data) == 1
     35    data = data[0]
     36    check_key(
     37        "manager", config.db_content.test_water['manager'], data
     38    )
     39    check_key("name", config.db_content.test_water['name'], data)
     40    check_key("waterId", config.db_content.test_water['waterId'], data)
     41    check_key("osmId", config.db_content.test_water['osmId'], data)
     42    check_key(
     43        "osmType", config.db_content.test_water['osmType'], data
     44    )
    16245
    16346
    164 if __name__ == '__main__':
    165     unittest.main()
     47def test_get_by_name(client, config):
     48    """Test case getting waters by name (src)
     49    """
     50    headers = {}
     51
     52    response = client.open(
     53        '{}?name=Bla'.format(base_url), method='GET', headers=headers
     54    )
     55    assert response.status_code == 200
     56    data = response.json
     57    assert len(data) == 0
     58
     59    response = client.open(
     60        '{}?name={}'.format(
     61            base_url, config.db_content.test_water['name'][:3]
     62        ),
     63        method='GET',
     64        headers=headers
     65    )
     66    assert response.status_code == 200
     67    data = response.json
     68    assert len(data) == 1
     69    data = data[0]
     70    check_key(
     71        "manager", config.db_content.test_water['manager'], data
     72    )
     73    check_key("name", config.db_content.test_water['name'], data)
     74    check_key("waterId", config.db_content.test_water['waterId'], data)
     75    check_key("osmId", config.db_content.test_water['osmId'], data)
     76    check_key(
     77        "osmType", config.db_content.test_water['osmType'], data
     78    )
     79
     80
     81def test_get_by_manager(client, config):
     82    """Test case getting waters by manager (src)
     83    """
     84    headers = {}
     85
     86    response = client.open(
     87        '{}?manager=not_existent'.format(base_url),
     88        method='GET',
     89        headers=headers
     90    )
     91    assert response.status_code == 404, '{} != {}'.format(
     92        response.status_code, 404
     93    )
     94
     95    response = client.open(
     96        '{}?manager={}'.format(
     97            base_url, config.db_content.test_user['username']
     98        ),
     99        method='GET',
     100        headers=headers
     101    )
     102    assert response.status_code == 200
     103    data = response.json
     104    assert len(data) == 1
     105    data = data[0]
     106    check_key(
     107        "manager", config.db_content.test_water['manager'], data
     108    )
     109    check_key("name", config.db_content.test_water['name'], data)
     110    check_key("waterId", config.db_content.test_water['waterId'], data)
     111    check_key("osmId", config.db_content.test_water['osmId'], data)
     112    check_key(
     113        "osmType", config.db_content.test_water['osmType'], data
     114    )
     115
     116
     117def test_get_by_name_manager(client, config):
     118    """Test case getting waters by manager and water name (src)
     119    """
     120    headers = {}
     121
     122    response = client.open(
     123        '{}?manager={}&name=Bla'.format(
     124            base_url, config.db_content.test_user['username']
     125        ),
     126        method='GET',
     127        headers=headers
     128    )
     129    assert response.status_code == 200
     130
     131    response = client.open(
     132        '{}?manager=john&name={}'.format(
     133            base_url, config.db_content.test_water['name'][:3]
     134        ),
     135        method='GET',
     136        headers=headers
     137    )
     138    assert response.status_code == 404
     139
     140    response = client.open(
     141        '{}?name={}&manager={}'.format(
     142            base_url, config.db_content.test_water['name'],
     143            config.db_content.test_user['username']
     144        ),
     145        method='GET',
     146        headers=headers
     147    )
     148    assert response.status_code == 200
     149    data = response.json
     150    assert len(data) == 1
     151    data = data[0]
     152    check_key(
     153        "manager", config.db_content.test_water['manager'], data
     154    )
     155    check_key("name", config.db_content.test_water['name'], data)
     156    check_key("waterId", config.db_content.test_water['waterId'], data)
     157    check_key("osmId", config.db_content.test_water['osmId'], data)
     158    check_key(
     159        "osmType", config.db_content.test_water['osmType'], data
     160    )
  • test-requirements.txt

    rd5199c9 r9f0f35e  
    55pytest-cov
    66pytest-pep8
     7pytest-flask
  • tox.ini

    rd5199c9 r9f0f35e  
    4848    build/*
    4949pep8ignore =
    50     src/gnuboat/common/spatial/tilegenerator.py E701
    51     src/gnuboat/common/datahandler/rrdschema.py E701
     50    src/gnuboat/common/spatial/tile_generator.py E701
     51    src/gnuboat/common/datahandler/rrd_schema.py E701
    5252    src/gnuboat/common/bin/gdal2tiles-gnuboat.py ALL
    53     src/gnuboat/mapservice_impl/tasks/tileconfig.py E701
     53    src/gnuboat/mapservice_impl/tasks/tile_config.py E701
    5454    src/gnuboat/mapservice/controllers/*.py E501
    5555    src/gnuboat/mapservice/models/*.py E501
Note: See TracChangeset for help on using the changeset viewer.