- Timestamp:
- May 19, 2020, 8:59:28 PM (7 years ago)
- Branches:
- debian/bullseye, master
- Children:
- 24617e1
- Parents:
- d5199c9
- Location:
- src/gnuboat
- Files:
-
- 3 added
- 23 edited
- 38 moved
-
common/__init__.py (modified) (1 diff)
-
common/bin/gnuboat-log-analyser (modified) (7 diffs)
-
common/bin/gnuboat-log-converter (modified) (7 diffs)
-
common/datahandler/__init__.py (modified) (1 diff)
-
common/datahandler/log_dataset.py (moved) (moved from src/gnuboat/common/datahandler/logdataset.py ) (1 diff)
-
common/datahandler/log_handler.py (moved) (moved from src/gnuboat/common/datahandler/loghandler.py ) (8 diffs)
-
common/datahandler/rrd_handler.py (moved) (moved from src/gnuboat/common/datahandler/rrdhandler.py ) (1 diff)
-
common/datahandler/rrd_schema.py (moved) (moved from src/gnuboat/common/datahandler/rrdschema.py )
-
common/spatial/__init__.py (modified) (1 diff)
-
common/spatial/tile_generator.py (moved) (moved from src/gnuboat/common/spatial/tilegenerator.py ) (1 diff)
-
common/tests/test_config.py (modified) (1 diff)
-
common/tests/test_tile_generator.py (moved) (moved from src/gnuboat/common/tests/test_tilegenerator.py ) (1 diff)
-
common/webservice/config.py (moved) (moved from src/gnuboat/common/webservice/Config.py )
-
common/webservice/http_errors.py (moved) (moved from src/gnuboat/common/webservice/HttpErrors.py )
-
device/bin/gnuboat-data-generator (modified) (1 diff)
-
device/bin/gnuboat-splashscreen (modified) (3 diffs)
-
device/config.py (moved) (moved from src/gnuboat/device/Config.py )
-
device/daemon/daemon.py (moved) (moved from src/gnuboat/device/daemon/Daemon.py ) (3 diffs)
-
device/daemon/display_handler.py (moved) (moved from src/gnuboat/device/daemon/displayhandler.py ) (2 diffs)
-
device/daemon/gpsd_poller.py (moved) (moved from src/gnuboat/device/daemon/gpsdpoller.py )
-
device/daemon/n2kd_poller.py (moved) (moved from src/gnuboat/device/daemon/n2kdpoller.py )
-
device/tests/conftest.py (modified) (2 diffs)
-
device/tests/n2kd_fake.py (moved) (moved from src/gnuboat/device/tests/n2kdfake.py )
-
device/tests/test_daemon.py (modified) (2 diffs)
-
device/tests/test_gpsd_poller.py (modified) (1 diff)
-
device/tests/test_n2kd_poller.py (modified) (1 diff)
-
deviceservice_impl/__init__.py (modified) (4 diffs)
-
deviceservice_impl/config.py (moved) (moved from src/gnuboat/deviceservice_impl/Config.py )
-
deviceservice_impl/controllers/device_controller.py (moved) (moved from src/gnuboat/deviceservice_impl/controllers/DeviceController.py ) (1 diff)
-
deviceservice_impl/controllers/device_logs_controller.py (moved) (moved from src/gnuboat/deviceservice_impl/controllers/DeviceLogsController.py ) (1 diff)
-
deviceservice_impl/controllers/device_maps_controller.py (moved) (moved from src/gnuboat/deviceservice_impl/controllers/DeviceMapsController.py ) (1 diff)
-
deviceservice_impl/controllers/mapservice_controller.py (moved) (moved from src/gnuboat/deviceservice_impl/controllers/MapserviceController.py ) (3 diffs)
-
deviceservice_impl/demo/__init__.py (modified) (1 diff)
-
deviceservice_impl/demo/demo_log.py (moved) (moved from src/gnuboat/deviceservice_impl/demo/DemoLog.py ) (1 diff)
-
deviceservice_impl/demo/demo_maps.py (moved) (moved from src/gnuboat/deviceservice_impl/demo/DemoMaps.py ) (1 diff)
-
deviceservice_impl/demo/demo_rrd.py (moved) (moved from src/gnuboat/deviceservice_impl/demo/DemoRrd.py ) (1 diff)
-
deviceservice_impl/demo/service_entry.py (moved) (moved from src/gnuboat/deviceservice_impl/demo/DeviceserviceEntry.py ) (1 diff)
-
deviceservice_impl/static/index.html (modified) (1 diff)
-
deviceservice_impl/tests/__init__.py (modified) (5 diffs)
-
deviceservice_impl/tests/conftest.py (added)
-
deviceservice_impl/validator_workaround.py (moved) (moved from src/gnuboat/deviceservice_impl/ValidatorWorkaround.py )
-
mapservice_impl/__init__.py (modified) (5 diffs)
-
mapservice_impl/celery_worker.py (moved) (moved from src/gnuboat/mapservice_impl/CeleryWorker.py ) (1 diff)
-
mapservice_impl/config.py (moved) (moved from src/gnuboat/mapservice_impl/Config.py ) (1 diff)
-
mapservice_impl/controllers/devices_controller.py (moved) (moved from src/gnuboat/mapservice_impl/controllers/DevicesController.py ) (2 diffs)
-
mapservice_impl/controllers/logs_controller.py (moved) (moved from src/gnuboat/mapservice_impl/controllers/LogsController.py ) (3 diffs)
-
mapservice_impl/controllers/tiles_controller.py (moved) (moved from src/gnuboat/mapservice_impl/controllers/TilesController.py ) (1 diff)
-
mapservice_impl/controllers/users_controller.py (moved) (moved from src/gnuboat/mapservice_impl/controllers/UsersController.py ) (1 diff)
-
mapservice_impl/controllers/waters_controller.py (moved) (moved from src/gnuboat/mapservice_impl/controllers/WatersController.py ) (3 diffs)
-
mapservice_impl/database/model.py (moved) (moved from src/gnuboat/mapservice_impl/database/Model.py )
-
mapservice_impl/demo/celery_entry.py (moved) (moved from src/gnuboat/mapservice_impl/demo/CeleryEntry.py ) (1 diff)
-
mapservice_impl/demo/db_setup.py (moved) (moved from src/gnuboat/mapservice_impl/demo/DbSetup.py ) (1 diff)
-
mapservice_impl/demo/service_entry.py (moved) (moved from src/gnuboat/mapservice_impl/demo/MapserviceEntry.py ) (1 diff)
-
mapservice_impl/mapservice.py (added)
-
mapservice_impl/security/security.py (moved) (moved from src/gnuboat/mapservice_impl/security/Security.py ) (1 diff)
-
mapservice_impl/tasks/tasks.py (modified) (1 diff)
-
mapservice_impl/tasks/tile_config.py (moved) (moved from src/gnuboat/mapservice_impl/tasks/tileconfig.py )
-
mapservice_impl/tests/__init__.py (modified) (1 diff)
-
mapservice_impl/tests/conftest.py (added)
-
mapservice_impl/tests/db_test_setup.py (modified) (3 diffs)
-
mapservice_impl/tests/test_logs.py (modified) (1 diff)
-
mapservice_impl/tests/test_users.py (modified) (1 diff)
-
mapservice_impl/tests/test_waters.py (modified) (1 diff)
-
mapservice_impl/validator_workaround.py (moved) (moved from src/gnuboat/mapservice_impl/ValidatorWorkaround.py )
Legend:
- Unmodified
- Added
- Removed
-
src/gnuboat/common/__init__.py
rd5199c9 r9f0f35e 16 16 along with this program. If not, see <http://www.gnu.org/licenses/>. 17 17 ''' 18 from gnuboat.common.datahandler.loghandler import LogHandler19 from gnuboat.common.datahandler.logdataset import LogDataset20 from gnuboat.common.spatial.tilegenerator import TileGenerator -
src/gnuboat/common/bin/gnuboat-log-analyser
rd5199c9 r9f0f35e 35 35 from time import process_time 36 36 37 from gnuboat_common.datahandler import loghandler, logdataset 38 from gnuboat_common.spatial import tilegenerator 37 from gnuboat.common.datahandler import ( 38 log_handler as loghandler, 39 log_dataset, 40 ) 41 from gnuboat.common.spatial import tile_generator 39 42 40 43 # -999 is a workaround, as long gdal python api does not handle addAlpha … … 238 241 print("Correcting and combining {} log files".format(len(logfiles))) 239 242 for logfile in logfiles: 240 gauge Height = logfile["gaugeHeight"]241 reference WaterLevelGaugeHeight = logfile[243 gauge_height = logfile["gaugeHeight"] 244 reference_water_level_gauge_height = logfile[ 242 245 "referenceWaterLevelGaugeHeight"] 243 246 log_file_path = logfile["file"] … … 250 253 # check stage 251 254 try: 252 gauge Height = float(gaugeHeight)255 gauge_height = float(gauge_height) 253 256 except ValueError: 254 257 print( … … 258 261 continue 259 262 try: 260 reference WaterLevelGaugeHeight = float(261 reference WaterLevelGaugeHeight263 reference_water_level_gauge_height = float( 264 reference_water_level_gauge_height 262 265 ) 263 266 except ValueError: … … 268 271 continue 269 272 # parse, correct and append log file 270 difference = reference WaterLevelGaugeHeight - gaugeHeight273 difference = reference_water_level_gauge_height - gauge_height 271 274 csv_callback.stage_set(difference) 272 275 result = log_handler.gnuboat_read_file( … … 359 362 ) 360 363 361 tilegen = tile generator.TileGenerator(364 tilegen = tile_generator.TileGenerator( 362 365 tile_sizes=tile_sizes, 363 366 densities=[density_min], … … 367 370 slices = tilegen.slices( 368 371 source_xml_file, 369 tile generator.ZoomRange(zoom_range[0], zoom_range[1]),372 tile_generator.ZoomRange(zoom_range[0], zoom_range[1]), 370 373 raster_file_size_max=raster_file_size_max * 1024 * 1024 * 8 371 374 ) -
src/gnuboat/common/bin/gnuboat-log-converter
rd5199c9 r9f0f35e 27 27 import subprocess 28 28 29 from gnuboat_common.datahandler import loghandler, logdataset 29 from gnuboat.common.datahandler import ( 30 log_handler as loghandler, 31 log_dataset, 32 ) 30 33 31 34 … … 44 47 45 48 46 def convert ToCsv(49 def convert_to_csv( 47 50 input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time 48 51 ): … … 57 60 'datetime', 'gps_status', 'latitude', 'latitude_direction', 58 61 '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' 60 64 ] 61 65 output_file_csv = csv.DictWriter( … … 78 82 79 83 80 def convert ToNmea0183(84 def convert_to_nmea0183( 81 85 input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time 82 86 ): … … 121 125 122 126 123 def convert ToGpx(127 def convert_to_gpx( 124 128 input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time 125 129 ): … … 128 132 [nmea_without_timestamps_handle, 129 133 nmea_without_timestamp_file_path] = tempfile.mkstemp(text=True) 130 convert ToNmea0183(134 convert_to_nmea0183( 131 135 input_file_path, nmea_without_timestamp_file_path, errors_ignore, 132 136 checksums_fix, True … … 248 252 249 253 if output_format == Format.CSV.value: 250 convert ToCsv(254 convert_to_csv( 251 255 input_file_path, output_file_path, errors_ignore, checksums_fix, 252 256 strip_time 253 257 ) 254 258 elif output_format == Format.NMEA0183.value: 255 convert ToNmea0183(259 convert_to_nmea0183( 256 260 input_file_path, output_file_path, errors_ignore, checksums_fix, 257 261 strip_time 258 262 ) 259 263 elif output_format == Format.GPX.value: 260 convert ToGpx(264 convert_to_gpx( 261 265 input_file_path, output_file_path, errors_ignore, checksums_fix, 262 266 strip_time -
src/gnuboat/common/datahandler/__init__.py
rd5199c9 r9f0f35e 16 16 along with this program. If not, see <http://www.gnu.org/licenses/>. 17 17 ''' 18 19 from .loghandler import LogHandler20 from .logdataset import LogDataset21 22 __all__ = ["loghandler", "logdataset"] -
src/gnuboat/common/datahandler/log_dataset.py
rd5199c9 r9f0f35e 1 1 # -*- coding: utf-8 -*- 2 2 ''' 3 Copyright (C) 2016 - 20 18EngSaS - Langenbach. All rights reserved.3 Copyright (C) 2016 - 2020 EngSaS - Langenbach. All rights reserved. 4 4 5 5 This program is free software: you can redistribute it and/or modify -
src/gnuboat/common/datahandler/log_handler.py
rd5199c9 r9f0f35e 24 24 from pathlib import Path 25 25 26 from gnuboat.common.datahandler import log dataset26 from gnuboat.common.datahandler import log_dataset 27 27 28 28 … … 108 108 nmea_log_file = self._nmea_file.name 109 109 110 latitude = self._degrees DecimalToNmea(dataset.latitude())111 longitude = self._degrees DecimalToNmea(dataset.longitude())110 latitude = self._degrees_decimal_to_nmea(dataset.latitude()) 111 longitude = self._degrees_decimal_to_nmea(dataset.longitude()) 112 112 113 113 logsystemtime = "" … … 274 274 if last_row is not None: 275 275 callback(last_row) 276 last_row = log dataset.LogDataset()276 last_row = log_dataset.LogDataset() 277 277 last_row.datetime_set( 278 278 '{} {}'.format( … … 282 282 last_row.gps_status_set(nmea_sentence.status) 283 283 last_row.latitude_set( 284 self._nmea LatitudeToDecimalDegrees(284 self._nmea_latitude_to_decimal_degrees( 285 285 nmea_sentence.lat, current_row 286 286 ) … … 288 288 last_row.latitude_direction_set(nmea_sentence.lat_dir) 289 289 last_row.longitude_set( 290 self._nmea LongitudeToDecimalDegrees(290 self._nmea_longitude_to_decimal_degrees( 291 291 nmea_sentence.lon, current_row 292 292 ) … … 344 344 return 0 345 345 346 def _nmea LatitudeToDecimalDegrees(self, nmea_value, current_row):346 def _nmea_latitude_to_decimal_degrees(self, nmea_value, current_row): 347 347 if self._to_float(nmea_value, current_row) == 0: 348 348 return 0 … … 355 355 ) 356 356 return 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 + (decimalMinutes / 60.0)360 361 def _nmea LongitudeToDecimalDegrees(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): 362 362 if self._to_float(nmea_value, current_row) == 0: 363 363 return 0 … … 370 370 ) 371 371 return 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 + (decimalMinutes / 60.0)375 376 def _degrees DecimalToNmea(self, decimalDegrees):377 degrees = int(math.floor(decimal Degrees))378 minutes = 60.0 * (decimal Degrees - 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) 379 379 return {'degrees': degrees, 'minutes': minutes} -
src/gnuboat/common/datahandler/rrd_handler.py
rd5199c9 r9f0f35e 21 21 from pathlib import Path 22 22 23 import gnuboat.common.datahandler.rrd schema as rrdschema23 import gnuboat.common.datahandler.rrd_schema as rrdschema 24 24 25 25 -
src/gnuboat/common/spatial/__init__.py
rd5199c9 r9f0f35e 16 16 along with this program. If not, see <http://www.gnu.org/licenses/>. 17 17 ''' 18 19 from .tilegenerator import TileGenerator20 21 __all__ = ["tilegenerator"] -
src/gnuboat/common/spatial/tile_generator.py
rd5199c9 r9f0f35e 659 659 return False 660 660 return True 661 662 # def contours_create():663 # @todo Cut Tifs / warp664 # contour_input = gdal.Open(gdal_file, gdalconst.GA_ReadOnly)665 # contour_input_band = contour_input.GetRasterBand(1)666 # Generate layer to save Contourlines in667 # 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 Contourlines679 # gdal.ContourGenerate(contour_input_band, depth, 0, [], 0, 0,680 # contour_layer, 0, 1)681 # contour_output = None682 # del contour_output683 # print(" Created contour lines {}".format(gdal_file_contours))684 685 # def crop():686 # cropping the tifs687 # 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 21 21 import os 22 22 23 from gnuboat.common.webservice import Config as configure23 from gnuboat.common.webservice import config as configure 24 24 25 25 -
src/gnuboat/common/tests/test_tile_generator.py
rd5199c9 r9f0f35e 27 27 from osgeo import osr 28 28 29 from gnuboat.common.spatial import tile generator29 from gnuboat.common.spatial import tile_generator as tilegenerator 30 30 31 31 -
src/gnuboat/device/bin/gnuboat-data-generator
rd5199c9 r9f0f35e 25 25 import os 26 26 27 from gnuboat. device.daemon import rrdhandler as rrdhandler27 from gnuboat.common.datahandler import rrd_handler as rrdhandler 28 28 29 29 # default values for command line arguments -
src/gnuboat/device/bin/gnuboat-splashscreen
rd5199c9 r9f0f35e 24 24 from PIL import ImageOps 25 25 from EPD import EPD 26 epd Enabled = True26 epd_enabled = True 27 27 except: 28 epd Enabled = False28 epd_enabled = False 29 29 30 30 31 def display Image(epd, imageFilePath):31 def display_image(epd, imageFilePath): 32 32 image = Image.open(imageFilePath) 33 33 image = ImageOps.grayscale(image) 34 image Resized = image.resize((epd.width, epd.height))35 imageBlackWhite = image Resized.convert("1", dither=Image.FLOYDSTEINBERG)34 image_resized = image.resize((epd.width, epd.height)) 35 imageBlackWhite = image_resized.convert("1", dither=Image.FLOYDSTEINBERG) 36 36 epd.display(imageBlackWhite) 37 37 epd.update() … … 69 69 sys.exit(2) 70 70 71 if not epd Enabled:71 if not epd_enabled: 72 72 print("Could not initialize EPD or PIL python packages") 73 73 sys.exit(2) … … 75 75 epd = EPD() 76 76 epd.clear() 77 display Image(epd, image)77 display_image(epd, image) 78 78 79 79 -
src/gnuboat/device/daemon/daemon.py
rd5199c9 r9f0f35e 26 26 27 27 from gnuboat.device.daemon import ( 28 n2kd poller as n2kdpoller,29 gpsd poller as gpsdpoller,30 display handler as displayhandler,28 n2kd_poller as n2kdpoller, 29 gpsd_poller as gpsdpoller, 30 display_handler as displayhandler, 31 31 ) 32 from gnuboat.common.datahandler import loghandler, logdataset, rrdhandler 33 from gnuboat.common.webservice.Config import ( 32 from gnuboat.common.datahandler import ( 33 log_handler as loghandler, 34 log_dataset as logdataset, 35 rrd_handler as rrdhandler 36 ) 37 from gnuboat.common.webservice.config import ( 34 38 config_from_file, config_get 35 39 ) … … 184 188 log_systemtime = config_get(config_object, 'LOG_SYSTEMTIME', False) 185 189 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) 188 194 189 195 parser = argparse.ArgumentParser( … … 286 292 rrd_file, log_directory, 287 293 gpsd_host=gpsd_host, gpsd_port=gpsd_port, 294 n2kd_host=n2kd_host, n2kd_port=n2kd_port, 288 295 log_period=log_period, 289 296 log_systemtime=log_systemtime, log_verbose=log_verbose, -
src/gnuboat/device/daemon/display_handler.py
rd5199c9 r9f0f35e 1 1 # -*- coding: utf-8 -*- 2 2 ''' 3 Copyright (C) 2016 - 20 17EngSaS - Langenbach. All rights reserved.3 Copyright (C) 2016 - 2020 EngSaS - Langenbach. All rights reserved. 4 4 5 5 This program is free software: you can redistribute it and/or modify … … 26 26 from PIL import ImageDraw 27 27 from PIL import ImageFont 28 epd Enabled = True28 epd_enabled = True 29 29 except: 30 epd Enabled = False30 epd_enabled = False 31 31 32 32 -
src/gnuboat/device/tests/conftest.py
rd5199c9 r9f0f35e 19 19 import time 20 20 21 from . import n2kd fake21 from . import n2kd_fake as n2kdfake 22 22 23 23 24 @pytest.fixture(scope=' module')24 @pytest.fixture(scope='function') 25 25 def gps_fake(): 26 26 """ … … 48 48 49 49 50 @pytest.fixture(scope=' module')50 @pytest.fixture(scope='function') 51 51 def n2kd_fake(): 52 52 """ -
src/gnuboat/device/tests/test_daemon.py
rd5199c9 r9f0f35e 27 27 import threading 28 28 29 from gnuboat.device.daemon import Daemon29 from gnuboat.device.daemon.daemon import Daemon 30 30 31 31 from . import gpsd_fakehook … … 37 37 rrd_file = test_dir.joinpath('rrd.db') 38 38 39 daemon = Daemon .Daemon(39 daemon = Daemon( 40 40 rrd_file, test_dir, 41 41 gpsd_host='127.0.0.1', gpsd_port=2947, -
src/gnuboat/device/tests/test_gpsd_poller.py
rd5199c9 r9f0f35e 24 24 import pytz 25 25 26 from gnuboat.device.daemon import gpsd poller26 from gnuboat.device.daemon import gpsd_poller as gpsdpoller 27 27 28 28 from . import gpsd_fakehook -
src/gnuboat/device/tests/test_n2kd_poller.py
rd5199c9 r9f0f35e 19 19 import os 20 20 21 from gnuboat.device.daemon import n2kd poller21 from gnuboat.device.daemon import n2kd_poller as n2kdpoller 22 22 23 23 -
src/gnuboat/deviceservice_impl/__init__.py
rd5199c9 r9f0f35e 24 24 from pathlib import Path 25 25 26 from gnuboat.deviceservice_impl. ValidatorWorkaround import ValidatorWorkaround26 from gnuboat.deviceservice_impl.validator_workaround import ValidatorWorkaround 27 27 from gnuboat.deviceservice import encoder 28 28 … … 30 30 def load_config_object(config_name): 31 31 return import_string( 32 'gnuboat.deviceservice_impl. Config.{}Config'.format(config_name)32 'gnuboat.deviceservice_impl.config.{}Config'.format(config_name) 33 33 ) 34 34 … … 47 47 app = connexion.App(__name__, specification_dir='../deviceservice/openapi/') 48 48 application = app.app 49 CORS(application)50 49 51 50 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( 51 def setup_app(app_name, config, template_folder=None, connexion_app=app): 52 connexion_app.app.json_encoder = encoder.JSONEncoder 53 connexion_app.add_api( 60 54 'openapi.yaml', 61 55 arguments={'title': app_name}, … … 64 58 validator_map={'response': ValidatorWorkaround} 65 59 ) 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') 67 63 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' 69 73 # 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) 72 77 73 78 # Remove the old rule from Map._rules_by_endpoint. In this case we can just 74 79 # start fresh. 75 application.url_map._rules_by_endpoint['static'] = []80 connexion_app.app.url_map._rules_by_endpoint['static'] = [] 76 81 77 82 # 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>', 80 85 endpoint='static', 81 view_func= application.send_static_file86 view_func=connexion_app.app.send_static_file 82 87 ) 83 88 84 if 'DEMO' in application.config and application.config['DEMO']:89 if 'DEMO' in connexion_app.app.config and connexion_app.app.config['DEMO']: 85 90 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 22 22 import datetime 23 23 24 import gnuboat.common.datahandler.rrd schema as rrdschema25 from gnuboat.common.webservice. HttpErrors import (24 import gnuboat.common.datahandler.rrd_schema as rrdschema 25 from gnuboat.common.webservice.http_errors import ( 26 26 GnuboatNotFound, GnuboatInternalServerError 27 27 ) -
src/gnuboat/deviceservice_impl/controllers/device_logs_controller.py
rd5199c9 r9f0f35e 24 24 from datetime import datetime, timezone 25 25 26 from gnuboat.common.webservice. HttpErrors import (26 from gnuboat.common.webservice.http_errors import ( 27 27 GnuboatBadRequest, GnuboatUnauthorized, 28 28 GnuboatNotFound, GnuboatInternalServerError 29 29 ) 30 from gnuboat.common.datahandler import log handler30 from gnuboat.common.datahandler import log_handler as loghandler 31 31 32 32 -
src/gnuboat/deviceservice_impl/controllers/device_maps_controller.py
rd5199c9 r9f0f35e 26 26 import base64 27 27 28 from gnuboat.common.webservice. HttpErrors import (28 from gnuboat.common.webservice.http_errors import ( 29 29 GnuboatNotFound, GnuboatInternalServerError, 30 30 GnuboatBadRequest -
src/gnuboat/deviceservice_impl/controllers/mapservice_controller.py
rd5199c9 r9f0f35e 26 26 import os 27 27 28 from gnuboat.common.webservice. HttpErrors import (28 from gnuboat.common.webservice.http_errors import ( 29 29 GnuboatBadRequest, GnuboatUnauthorized, 30 30 GnuboatNotFound, GnuboatInternalServerError, … … 32 32 GnuboatBadGateway 33 33 ) 34 from gnuboat.deviceservice_impl.controllers. DeviceLogsController import (34 from gnuboat.deviceservice_impl.controllers.device_logs_controller import ( 35 35 logdirectory_get 36 36 ) … … 302 302 if status == 500: 303 303 raise GnuboatInternalServerError(detail=detail) 304 if status == 502: 305 raise GnuboatBadGateway(detail=detail) 304 306 if status == 504: 305 307 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 17 17 18 18 from gnuboat.deviceservice_impl.demo import ( 19 DemoLog as demolog, DemoRrd as demorrd,20 DemoMaps as demomaps19 demo_log as demolog, demo_rrd as demorrd, 20 demo_maps as demomaps 21 21 ) 22 22 -
src/gnuboat/deviceservice_impl/demo/demo_log.py
rd5199c9 r9f0f35e 22 22 import shutil 23 23 24 import gnuboat.common.datahandler.log handler as loghandler25 import gnuboat.common.datahandler.log dataset as logdataset24 import gnuboat.common.datahandler.log_handler as loghandler 25 import gnuboat.common.datahandler.log_dataset as logdataset 26 26 27 27 logperiod = 2 -
src/gnuboat/deviceservice_impl/demo/demo_maps.py
rd5199c9 r9f0f35e 23 23 import os 24 24 25 from gnuboat.deviceservice_impl.controllers. DeviceMapsController import (25 from gnuboat.deviceservice_impl.controllers.device_maps_controller import ( 26 26 _map_name_to_hash 27 27 ) -
src/gnuboat/deviceservice_impl/demo/demo_rrd.py
rd5199c9 r9f0f35e 23 23 import rrdtool 24 24 25 import gnuboat.common.datahandler.rrd handler as rrdhandler25 import gnuboat.common.datahandler.rrd_handler as rrdhandler 26 26 27 27 logperiod = 2 -
src/gnuboat/deviceservice_impl/demo/service_entry.py
rd5199c9 r9f0f35e 42 42 sys.argv.append('--bind=localhost:8090') 43 43 sys.argv.append( 44 'gnuboat.deviceservice_impl.demo. DeviceserviceEntry:gunicorn_app()')44 'gnuboat.deviceservice_impl.demo.service_entry:gunicorn_app()') 45 45 46 46 # Copied from /usr/bin/gunicorn -
src/gnuboat/deviceservice_impl/static/index.html
rd5199c9 r9f0f35e 21 21 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 22 22 <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> 24 24 25 25 <link rel="stylesheet" href="/client/common/lib/css/pure/pure-min.css" type="text/css"/> -
src/gnuboat/deviceservice_impl/tests/__init__.py
rd5199c9 r9f0f35e 17 17 18 18 import logging 19 import connexion 20 from flask_cors import CORS 19 21 import flask 20 22 from flask import request_started, request 21 import connexion 22 from flask_cors import CORS 23 from werkzeug.utils import import_string 23 24 import rrdtool 24 25 import os … … 29 30 import datetime 30 31 import shutil 31 import subprocess32 import socket33 from urllib.parse import urlparse34 from werkzeug.utils import import_string35 32 36 33 from gnuboat.common.datahandler import ( 37 rrdhandler, loghandler, logdataset, 34 rrd_handler as rrdhandler, 35 log_handler as loghandler, 36 log_dataset as logdataset, 38 37 ) 39 from gnuboat.common.webservice. Config import (38 from gnuboat.common.webservice.config import ( 40 39 config_get 41 40 ) 42 41 43 from gnuboat.deviceservice_impl.controllers. DeviceMapsController import (42 from gnuboat.deviceservice_impl.controllers.device_maps_controller import ( 44 43 _map_name_to_hash 45 44 ) 46 from gnuboat.deviceservice .encoder import JSONEncoder45 from gnuboat.deviceservice_impl import setup_app 47 46 48 47 logperiod = 2 … … 58 57 def create_app(testcase): 59 58 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/') 64 61 application = app.app 65 62 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) 75 66 application.app_context().push() 76 67 … … 79 70 _create_maps(testcase, application) 80 71 81 _mapservice_start(testcase, application) 82 83 return application 72 return app 84 73 85 74 86 def set Up(testcase):75 def setup(app, testcase): 87 76 pass 88 77 89 78 90 def tear Down(testcase):79 def teardown(app, testcase): 91 80 os.remove(testcase.rrdfile) 92 81 shutil.rmtree(testcase.logdir) 93 82 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))104 83 105 84 … … 217 196 mapdir.joinpath('{}.mbtiles'.format(_map_name_to_hash('Forggensee'))) 218 197 ) 219 220 221 def _mapservice_start(testcase, application):222 if 'TestMapserviceController' not in testcase.id():223 testcase.mapservice_process = None224 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_config250 # the timeout is needed, because of the spatiallite table creation,251 # which is pretty slow252 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.PIPE260 )261 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)262 # we need to give mapservice a chance to start before calling263 # connect_ex264 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 20 20 from flask_cors import CORS 21 21 from flask_mail import Mail 22 from flask_migrate import Migrate 22 23 from sqlalchemy import event 23 24 from celery import Celery … … 26 27 27 28 from gnuboat.mapservice import encoder 28 from gnuboat.mapservice_impl.database. Model import (29 from gnuboat.mapservice_impl.database.model import ( 29 30 db, User, ApiKey, 30 31 db_setup, load_spatialite 31 32 ) 32 from gnuboat.mapservice_impl. ValidatorWorkaround import ValidatorWorkaround33 from gnuboat.mapservice_impl.validator_workaround import ValidatorWorkaround 33 34 34 35 35 36 def load_config_object(config_name): 36 37 return import_string( 37 'gnuboat.mapservice_impl. Config.{}Config'.format(config_name)38 'gnuboat.mapservice_impl.config.{}Config'.format(config_name) 38 39 ) 39 40 … … 54 55 app = connexion.App(__name__, specification_dir='../mapservice/openapi/') 55 56 application = app.app 56 CORS(application)57 57 mail = Mail() 58 58 celery = Celery(__name__, broker=config_object.CELERY_BROKER_URL) 59 59 60 60 61 def setup_app(app_name, config, template_folder=None ):62 application.json_encoder = encoder.JSONEncoder63 app.add_api(61 def setup_app(app_name, config, template_folder=None, connexion_app=app): 62 connexion_app.app.json_encoder = encoder.JSONEncoder 63 connexion_app.add_api( 64 64 'openapi.yaml', 65 65 arguments={'title': app_name}, … … 68 68 validator_map={'response': ValidatorWorkaround} 69 69 ) 70 application.config.from_object(config)70 connexion_app.app.config.from_object(config) 71 71 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'] 74 75 elif template_folder: 75 application.template_folder = template_folder76 connexion_app.app.template_folder = template_folder 76 77 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) 79 83 celery.config_from_object(config) 80 with application.app_context(): 84 85 with connexion_app.app.app_context(): 81 86 @event.listens_for(db.engine, "connect") 82 87 def load_spatialite_extension(dbapi_conn, connection_record): … … 84 89 85 90 if flask.current_app.config['CREATE_TEST_DATABASE'] is True: 86 from gnuboat.mapservice_impl.demo import DbSetup as demoDbSetup87 demo DbSetup.setup()91 from gnuboat.mapservice_impl.demo import db_setup as demodbsetup 92 demodbsetup.setup() 88 93 else: 89 94 db_setup() -
src/gnuboat/mapservice_impl/celery_worker.py
rd5199c9 r9f0f35e 22 22 config_object, app, application, celery, setup_app 23 23 ) 24 from gnuboat.mapservice_impl.database. Model import db, load_spatialite24 from gnuboat.mapservice_impl.database.model import db, load_spatialite 25 25 from gnuboat.mapservice_impl.tasks import tasks 26 26 -
src/gnuboat/mapservice_impl/config.py
rd5199c9 r9f0f35e 89 89 TESTING = True 90 90 DEBUG = False 91 CELERY_BROKER_URL = ''91 CELERY_BROKER_URL = None 92 92 SQLALCHEMY_DATABASE_URI = 'sqlite:////tmp/gnuboat-ci-tests.db' 93 CREATE_TEST_DATABASE = False -
src/gnuboat/mapservice_impl/controllers/devices_controller.py
rd5199c9 r9f0f35e 17 17 import connexion 18 18 19 from gnuboat.mapservice_impl.database. Model import User, Device, db20 from gnuboat.common.webservice. HttpErrors import (19 from gnuboat.mapservice_impl.database.model import User, Device, db 20 from gnuboat.common.webservice.http_errors import ( 21 21 GnuboatBadRequest, GnuboatUnauthorized, GnuboatNotFound 22 22 ) … … 68 68 db.session.add(device) 69 69 db.session.commit() 70 return device.to_dict() 70 return device.to_dict(), 201 71 71 72 72 -
src/gnuboat/mapservice_impl/controllers/logs_controller.py
rd5199c9 r9f0f35e 17 17 import connexion 18 18 19 from gnuboat.mapservice_impl.database. Model import (19 from gnuboat.mapservice_impl.database.model import ( 20 20 User, Log, LogEntry, 21 21 Water, Device, Gauge, ProcessingStatus, Queue, db 22 22 ) 23 from gnuboat.common.webservice. HttpErrors import (23 from gnuboat.common.webservice.http_errors import ( 24 24 GnuboatBadRequest, GnuboatUnauthorized, GnuboatNotFound 25 25 ) … … 116 116 db.session.add(log) 117 117 db.session.commit() 118 return log.meta_data() 118 return log.meta_data(), 201 119 119 120 120 … … 158 158 log_process.delay(log.id, body.decode()) 159 159 160 return log.meta_data() 160 return log.meta_data(), 201 161 161 162 162 -
src/gnuboat/mapservice_impl/controllers/tiles_controller.py
rd5199c9 r9f0f35e 20 20 import os 21 21 22 from gnuboat.common.webservice. HttpErrors import (22 from gnuboat.common.webservice.http_errors import ( 23 23 GnuboatInternalServerError, GnuboatBadRequest, GnuboatNotFound 24 24 ) -
src/gnuboat/mapservice_impl/controllers/users_controller.py
rd5199c9 r9f0f35e 25 25 26 26 from gnuboat.mapservice_impl import mail 27 from gnuboat.mapservice_impl.database. Model import User, ApiKey, db28 from gnuboat.common.webservice. HttpErrors import (27 from gnuboat.mapservice_impl.database.model import User, ApiKey, db 28 from gnuboat.common.webservice.http_errors import ( 29 29 GnuboatBadRequest, GnuboatUnauthorized, GnuboatNotFound 30 30 ) -
src/gnuboat/mapservice_impl/controllers/waters_controller.py
rd5199c9 r9f0f35e 17 17 import connexion 18 18 19 from gnuboat.mapservice_impl.database. Model import User, Water, Gauge, Log, db20 from gnuboat.common.webservice. HttpErrors import (19 from gnuboat.mapservice_impl.database.model import User, Water, Gauge, Log, db 20 from gnuboat.common.webservice.http_errors import ( 21 21 GnuboatBadRequest, 22 22 GnuboatUnauthorized, GnuboatNotFound … … 108 108 db.session.add(water) 109 109 db.session.commit() 110 return water.to_dict() 110 return water.to_dict(), 201 111 111 112 112 … … 158 158 db.session.add(gauge) 159 159 db.session.commit() 160 return gauge.to_dict() 160 return gauge.to_dict(), 201 161 161 162 162 -
src/gnuboat/mapservice_impl/demo/celery_entry.py
rd5199c9 r9f0f35e 25 25 # Add need configuration options 26 26 sys.argv.append('-A') 27 sys.argv.append('gnuboat.mapservice_impl. CeleryWorker:celery')27 sys.argv.append('gnuboat.mapservice_impl.celery_worker:celery') 28 28 sys.argv.append('worker') 29 29 sys.argv.append('-l') -
src/gnuboat/mapservice_impl/demo/db_setup.py
rd5199c9 r9f0f35e 20 20 import flask 21 21 22 from gnuboat.mapservice_impl.database. Model import (22 from gnuboat.mapservice_impl.database.model import ( 23 23 db, User, ApiKey, Water, 24 24 OsmType, Gauge, Device, Log, Queue, ProcessingStatus, db_setup 25 25 ) 26 from gnuboat.common.webservice. HttpErrors import (26 from gnuboat.common.webservice.http_errors import ( 27 27 GnuboatBadRequest 28 28 ) -
src/gnuboat/mapservice_impl/demo/service_entry.py
rd5199c9 r9f0f35e 44 44 sys.argv.append('--bind=localhost:8080') 45 45 sys.argv.append( 46 'gnuboat.mapservice_impl.demo. MapserviceEntry:gunicorn_app()')46 'gnuboat.mapservice_impl.demo.service_entry:gunicorn_app()') 47 47 48 48 # Copied from /usr/bin/gunicorn -
src/gnuboat/mapservice_impl/security/security.py
rd5199c9 r9f0f35e 15 15 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 16 ''' 17 from ..database. Model import ApiKey, User17 from ..database.model import ApiKey, User 18 18 19 19 -
src/gnuboat/mapservice_impl/tasks/tasks.py
rd5199c9 r9f0f35e 34 34 import mercantile 35 35 36 from gnuboat.common.datahandler import log handler37 from gnuboat.common.spatial import tile generator38 from gnuboat.common.spatial.tile generator import (36 from gnuboat.common.datahandler import log_handler as loghandler 37 from gnuboat.common.spatial import tile_generator as tilegenerator 38 from gnuboat.common.spatial.tile_generator import ( 39 39 RasterSlice, LngLatBbox, ZoomRange 40 40 ) 41 41 42 42 from gnuboat.mapservice_impl import mail, celery as celery_app 43 from gnuboat.mapservice_impl.database. Model import (43 from gnuboat.mapservice_impl.database.model import ( 44 44 User, Log, LogEntry, Water, ProcessingStatus, Queue, db 45 45 ) 46 from gnuboat.mapservice_impl.tasks.tile config import TileConfig46 from gnuboat.mapservice_impl.tasks.tile_config import TileConfig 47 47 48 48 -
src/gnuboat/mapservice_impl/tests/__init__.py
rd5199c9 r9f0f35e 17 17 18 18 import logging 19 20 import flask21 19 import connexion 22 20 from flask_cors import CORS 23 21 from flask_mail import Mail 22 from celery import Celery 24 23 from sqlalchemy.event import listen 25 from celery import Celery24 from werkzeug.utils import import_string 26 25 import tempfile 27 26 import os 28 27 from PIL import Image 29 import shutil30 28 31 from gnuboat.mapservice.encoder import JSONEncoder 32 from gnuboat.mapservice_impl.database.Model import ( 29 from gnuboat.mapservice_impl.database.model import ( 33 30 db, db_setup, load_spatialite 34 31 ) 35 32 from gnuboat.mapservice_impl.tests import db_test_setup 33 from gnuboat.mapservice_impl import setup_app 36 34 37 35 38 def create_app(testcase): 36 def 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 41 def create_app(): 39 42 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/') 44 45 application = app.app 45 46 CORS(application) 46 47 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) 49 54 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) 61 56 62 _create_test_tile(testcase, application) 63 64 return application 57 return app 65 58 66 59 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() 60 def 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() 74 68 75 69 76 def tear Down(testcase):77 db.session.remove()78 db.drop_all()79 shutil.rmtree(testcase.tiles_cache)70 def teardown(application): 71 with application.app_context(): 72 db.session.remove() 73 db.drop_all() 80 74 81 75 82 def _create_test_tile( testcase,application):83 testcase.tiles_cache = tempfile.mkdtemp(prefix='gnuboat-tests')84 application.config['TILES_CACHE_PATH'] = testcase.tiles_cache76 def _create_test_tile(application): 77 application.config.tiles_cache = tempfile.mkdtemp(prefix='gnuboat-tests') 78 application.config['TILES_CACHE_PATH'] = application.config.tiles_cache 85 79 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/') 87 82 os.makedirs(tile_path) 88 83 img = Image.new('RGBA', (100, 100), (255, 0, 0, 0)) -
src/gnuboat/mapservice_impl/tests/db_test_setup.py
rd5199c9 r9f0f35e 20 20 import flask 21 21 22 from gnuboat.mapservice_impl.database. Model import (22 from gnuboat.mapservice_impl.database.model import ( 23 23 db, User, ApiKey, Water, 24 24 OsmType, Gauge, Device, Log, Queue, ProcessingStatus, db_setup 25 25 ) 26 from gnuboat.mapservice_impl.demo import DbSetup as demoDbSetup26 from gnuboat.mapservice_impl.demo import db_setup as demodbsetup 27 27 from gnuboat.mapservice_impl.tasks.tasks import log_process 28 28 … … 41 41 print("CREATING DATABASE TEST CONTENT...") 42 42 with db.session.no_autoflush: 43 self.test_user = User.factory(43 test_user = User.factory( 44 44 'autotests', 'autotests', 'auto@example.org' 45 45 ) 46 self.test_user.activated = True47 self.test_user.first_name = 'Autotests'48 self.test_user.license_accepted = True49 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) 50 50 db.session.commit() 51 self.test_user = test_user.to_dict() 51 52 52 53 user_activation = User.factory( … … 62 63 db.session.commit() 63 64 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')) 66 67 db.session.commit() 67 68 68 self.test_water = Water(69 test_water = Water( 69 70 name='Test Water', 70 manager= self.test_user,71 manager=test_user, 71 72 osm_id=1756854, 72 73 osm_type=OsmType.Relation 73 74 ) 74 db.session.add( self.test_water)75 db.session.add(test_water) 75 76 db.session.commit() 77 self.test_water = test_water.to_dict() 76 78 77 self.test_gauge = Gauge(79 test_gauge = Gauge( 78 80 name='test_gauge', 79 manager= self.test_user,80 water= self.test_water,81 manager=test_user, 82 water=test_water, 81 83 location='SRID=4326;POINT(-90.136111 29.934722)', 82 84 reference_water_level_gauge_height=3 83 85 ) 84 db.session.add( self.test_gauge)86 db.session.add(test_gauge) 85 87 db.session.commit() 88 self.test_gauge = test_gauge.to_dict() 86 89 87 self.test_device = Device(88 name='Test Device', owner= self.test_user, sensor_depth=0.290 test_device = Device( 91 name='Test Device', owner=test_user, sensor_depth=0.2 89 92 ) 90 db.session.add( self.test_device)93 db.session.add(test_device) 91 94 db.session.commit() 95 self.test_device = test_device.to_dict() 92 96 93 97 log_file = os.path.join( 94 98 os.path.dirname(__file__), 'data/nmea0183-2017-12-09.log' 95 99 ) 96 self.test_log = demoDbSetup._sample_log_add(97 self.test_water, self.test_gauge, 0, self.test_device,98 self.test_user, log_file100 test_log = demodbsetup._sample_log_add( 101 test_water, test_gauge, 0, test_device, 102 test_user, log_file 99 103 ) 104 self.test_log = test_log.meta_data() 100 105 101 106 print("...Finished") -
src/gnuboat/mapservice_impl/tests/test_logs.py
rd5199c9 r9f0f35e 16 16 ''' 17 17 18 import unittest18 import pytest 19 19 import json 20 import os21 20 22 from gnuboat.mapservice.test import BaseTestCase21 from . import check_key 23 22 24 23 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 24 base_url = '/mapservice/v1/logs' 170 25 171 26 172 if __name__ == '__main__': 173 unittest.main() 27 def 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 75 def 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 125 def 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 16 16 ''' 17 17 18 import unittest18 import pytest 19 19 import json 20 20 21 from gnuboat.mapservice.test import BaseTestCase 21 from . import check_key 22 23 base_url = '/mapservice/v1/user' 22 24 23 25 24 class TestUsers(BaseTestCase): 25 @classmethod 26 def setUpClass(self): 27 self.base_url = '/mapservice/v1/user' 26 def 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 28 34 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) 37 46 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" 49 50 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 91 54 92 55 93 if __name__ == '__main__': 94 unittest.main() 56 def 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 16 16 ''' 17 17 18 import unittest 19 import json 18 import pytest 20 19 21 from gnuboat.mapservice.test import BaseTestCase 20 from . import check_key 21 22 base_url = '/mapservice/v1/waters' 22 23 23 24 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 ) 25 def 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 ) 162 45 163 46 164 if __name__ == '__main__': 165 unittest.main() 47 def 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 81 def 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 117 def 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 )
Note:
See TracChangeset
for help on using the changeset viewer.
