Beispiel #1
0
 def setUp(self):
     self.factory = RequestFactory()
     self.fakeClient = Client()
     self.cache = MyCache()
     self.ALLOWED_TILES = ALLOWED_TILES
     self.layout = getConfigFileForTest()
     print("[DEBUG] Choosing file to test:" + self.layout)
Beispiel #2
0
def get_tile(request, tile_key):
    """ Return Json from redis for tile_key """
    if not checkAccessToken(method='GET', request=request, unsecured=True):
        return HttpResponse('API KEY incorrect', status=401)
    redis = MyCache().redis
    if redis.exists(getRedisPrefix(tile_key)):
        return HttpResponse(redis.get(tile_key))
    return HttpResponseBadRequest(f'{tile_key} key does not exist.')
Beispiel #3
0
def delete_tile(request, tile_key):
    """ Delete in redis """
    if not checkAccessToken(method='DELETE', request=request, unsecured=True):
        return HttpResponse('API KEY incorrect', status=401)
    redis = MyCache().redis
    if redis.exists(getRedisPrefix(tile_key)):
        redis.delete(tile_key)
        return HttpResponse('Tile\'s data deleted.')
    return HttpResponseBadRequest(f'{tile_key} key does not exist.')
Beispiel #4
0
def demo_controller(request, flagSensors=None, tester=None):
    """ activate or not the sensors by api  """
    cache = MyCache()
    if flagSensors == 'on':
        scheduleYourSensors(cache.scheduler_sensors, tester)
    elif flagSensors == 'off':
        stopTheSensors(cache.scheduler_sensors)
        cache.scheduler_sensors = BackgroundScheduler()
    return HttpResponseRedirect('/')
Beispiel #5
0
 def update_tile_receive(self, tile_id, template_name=None):
     """ Create or update the tile with value and send to the client with websocket """
     tileData = MyCache().get(tile_id=getRedisPrefix(tile_id))
     if tileData is None:
         print(
             f'[DEBUG] Building fake data for {tile_id}. with template {template_name}',
             flush=True)
         tileData = buildFakeDataFromTemplate(tile_id, template_name,
                                              MyCache())
     self.send(text_data=tileData)
Beispiel #6
0
 def test_0005_cache(self):
     cache = MyCache()
     self.assertTrue(cache is not None)
     cache.listOfTilesCached()
     self.assertTrue(len(listOfTilesFromLayout()) > 0)
     cache.get(tile_id='test')
     cache.set(tile_id='test', dumped_value=json.dumps({'testValue': True}))
     cache.createTile(tile_id='test',
                      value={'test': True},
                      tile_template='test')
Beispiel #7
0
def project_info(request):
    """ Return infos about tipboard server """
    cache = MyCache()
    return JsonResponse(
        dict(is_redis_connected=cache.isRedisConnected,
             last_update=cache.getLastUpdateTime(),
             first_start=cache.getFirstTimeStarter(),
             project_default_config=BASIC_CONFIG,
             dashboard_list=getConfigNames(),
             redis_db=REDIS_DB))
Beispiel #8
0
def project_info(
    request
):  # TODO: add uptime and last update time and redis connected and numnber of tile in redis
    """ Return info of server tipboard """
    cache = MyCache()
    return JsonResponse(
        dict(is_redis_connected=cache.isRedisConnected,
             last_update=cache.getLastUpdateTime(),
             first_start=cache.getFirstTimeStarter(),
             project_default_config=BASIC_CONFIG,
             dashboard_list=getConfigNames(),
             redis_db=REDIS_DB))
Beispiel #9
0
 def test_1026_test_sensors(self):
     tilePrefix = getRedisPrefix('test_simple_percentage')
     lm = MyCache().get(tilePrefix)
     beforeUpdate = json.loads(lm)
     test_sensors(tester=self)
     scheduler = BackgroundScheduler()
     nbrSensors = scheduleYourSensors(scheduler=scheduler, tester=self)
     self.assertTrue(nbrSensors >= 21)
     time.sleep(5)
     scheduler.shutdown()
     time.sleep(3)
     afterUpdate = json.loads(MyCache().get(tilePrefix))['data']['big_value']
     isDiff = beforeUpdate != afterUpdate
     self.assertTrue(isDiff)
Beispiel #10
0
def testTileUpdate(tester=None, tileId='test_pie_chart', sonde=None, isChartJS=True):
    """
        1 - Get a tile from the redis cache, store this in tile_txt_data_before
        2 - execute the sensors to update the data of the tile
        3 - Again, get a tile from the redis cache store this in tile_txt_data_after
        4 - Compare the data of tile_txt_data_before vs tile_txt_data_after
        5 - If there are the same, update tile data is broken :)
    """
    tilePrefix = getRedisPrefix(tileId)
    beforeUpdate = json.loads(MyCache().redis.get(tilePrefix))
    if tileId == 'test_vbar_chart':
        sonde(tester=tester, tile_id=tileId, isHorizontal=True)
    sonde(tester=tester, tile_id=tileId)
    afterUpdate = json.loads(MyCache().redis.get(tilePrefix))
    if isChartJS:
        isDiff = beforeUpdate['data']['datasets'][0]['data'] != afterUpdate['data']['datasets'][0]['data']
    else:
        isDiff = beforeUpdate['data'] != afterUpdate['data']
    tester.assertTrue(isDiff)
Beispiel #11
0
 def receive(self, text_data, **kwargs):
     """ handle msg sended by client, by 2 way: update all tiles or update 1 specific tile """
     if 'first_connection:' in text_data:
         listOftiles = listOfTilesFromLayout(
             text_data.replace('first_connection:/', ''))
         for tileId in listOftiles:
             self.update_tile_receive(
                 tile_id=tileId,
                 template_name=listOftiles[tileId]['tile_template'])
     else:
         for tile_id in MyCache().listOfTilesCached():
             self.update_tile_receive(tile_id=tile_id)
Beispiel #12
0
def check_sanity_request(request):
    """ Test token, and presence of all data required """
    HttpData = request.POST
    tilePrefix = getRedisPrefix(HttpData.get('tile_id', None))
    cache = MyCache()
    fg = not HttpData.get('tile_id', None) or not HttpData.get(
        'tile_template', None) or not HttpData.get('data', None)
    if request.method != 'POST' or \
            fg or request.GET.get('API_KEY', 'NO_API_KEY_FOUND') != API_KEY and DEBUG is False or \
            HttpData.get('tile_template', None) not in ALLOWED_TILES or \
            not cache.redis.exists(tilePrefix) and not DEBUG:
        return False
    return True
Beispiel #13
0
def sanity_push_api(request, unsecured):
    """ Test token, all data present, correct tile_template and tile_id present in cache """
    if not checkAccessToken(
            method='POST', request=request, unsecured=unsecured):
        return False, HttpResponse('API KEY incorrect', status=401)
    HttpData = request.POST
    if not HttpData.get('tile_id', None) or not HttpData.get('tile_template', None) or \
            not HttpData.get('data', None):
        return False, HttpResponseBadRequest('Missing data')
    if HttpData.get('tile_template', None) not in ALLOWED_TILES:
        tile_template = HttpData.get('tile_template', None)
        return False, HttpResponseBadRequest(
            f'tile_template: {tile_template} is unknow')
    cache = MyCache()
    tilePrefix = getRedisPrefix(HttpData.get('tile_id', None))
    if not cache.redis.exists(tilePrefix) and not DEBUG:
        return False, HttpResponseBadRequest(
            f'tile_id: {tilePrefix} is unknow')
    return True, HttpData
Beispiel #14
0
def get_tile(request, tile_key):
    httpMessage = ''
    httpStatus_code = 200
    redis = MyCache().redis
    if redis.exists(getRedisPrefix(tile_key)):
        if request.method == 'DELETE':
            redis.delete(tile_key)
            httpMessage = 'Tile\'s data deleted.'
        if request.method == 'GET':
            httpMessage = redis.get(tile_key)
    else:
        httpMessage = f'{tile_key} key does not exist.'
        httpStatus_code = 400
    return httpMessage, httpStatus_code
Beispiel #15
0
def handleHttpError(request):
    output = 'error'
    if request.method != 'POST':
        output = 'Only accept Post request'
    if request.GET.get('API_KEY',
                       'NO_API_KEY_FOUND') != API_KEY and DEBUG is False:
        return HttpResponse('API KEY incorrect', status=401)
    cache = MyCache()
    HttpData = request.POST
    tile_id = HttpData.get('tile_id', None)
    tile_template = HttpData.get('tile_template', None)
    data = HttpData.get('data', None)
    tilePrefix = getRedisPrefix(tile_id)
    if output == 'error' and (not tile_id or not tile_template or not data):
        output = 'Missing data'
    elif output == 'error' and (tile_template not in ALLOWED_TILES):
        output = f'tile_template: {tile_template} is unknow'
    elif output == 'error' and (not cache.redis.exists(tilePrefix)
                                and not DEBUG):
        output = f'tile_id: {tilePrefix} is unknow'
    return HttpResponseBadRequest(output)
Beispiel #16
0
 def update_tile(self, data):
     """ send to client a single tile config """
     self.send(text_data=MyCache().get(
         tile_id=getRedisPrefix(data['tile_id'])))
Beispiel #17
0
class TestApp(SimpleTestCase):  # TODO: find a way to test the WebSocket inside django

    def setUp(self):
        self.factory = RequestFactory()
        self.fakeClient = Client()
        self.cache = MyCache()
        self.ALLOWED_TILES = ALLOWED_TILES
        self.layout = getConfigFileForTest()
        print("[DEBUG] Choosing file to test:" + self.layout)

    def test_0001_parse_dashboardXml(self):
        """ Test Parse all tiles, cols, rows from a specific .yaml """
        config = parseXmlLayout(layout_name=self.layout)
        self.assertTrue(config is not None)

    def test_0002_getAllDashboardFiles(self):
        """ Test all dashboard file name from Config/ """
        config = getConfigNames()
        self.assertTrue(len(config) > 0)

    def test_0003_parser_getTitleOfDashboard(self):
        """ Test XmlParser is able to get title of /config/default_config.yml """
        config = parseXmlLayout(layout_name=self.layout)
        title = config['details']['page_title']
        self.assertTrue(title is not None)

    def test_0004_parser_getDashboardColsFromXml(self):  # test if able to parse row
        """ Test XmlParser able to get cols dashboard of /config/default_config.yml """
        self.assertTrue(len(parseXmlLayout(layout_name=self.layout)['layout']) > 0)

    def test_0005_parser_getTilesNameFromXml(self):  # test if able to parse tiles template
        """ Test XmlParser able to get tiles name of /config/default_config.yml """
        tiles_conf = parseXmlLayout(layout_name=self.layout)['tiles_conf']
        self.assertTrue(tiles_conf[next(iter(tiles_conf))]['title'] is not None)

    def test_0006_parser_getTilesIdFromXml(self):
        """ Test XmlParser able to get tiles Id of tiles from /config/default_config.yml """
        tiles_conf = parseXmlLayout(layout_name=self.layout)['tiles_conf']
        self.assertTrue((tiles_conf[next(iter(tiles_conf))]['tile_id']) is not None)

    def test_0011_cache_redisConnection(self):
        """ Test redis connection """
        self.assertTrue(self.cache.isRedisConnected is True)

    def test_0012_cache_permissionTest(self):
        """ Test redis cache Handle when GET / SET """
        tilePrefix = getRedisPrefix('test')
        self.assertTrue(self.cache.set(tile_fullid=tilePrefix, dumped_value=json.dumps({'testValue': True})))
        self.assertTrue(json.loads(self.cache.redis.get(tilePrefix))['testValue'])

    def test_0013_cache_parsingTile(self):
        """ Test if cache is able to read directly on Config/dashboard.yml """
        self.cache.listOfTilesCached()
        self.assertTrue(len(listOfTilesFromLayout(layout_name=self.layout)) > 0)

    def test_0014_cache_ExceptionTest(self):
        """ Test if cache is able to handle an unknow tile without crash """
        self.assertTrue(self.cache.get(tile_id='test42') is None)

    def test_0015_cache_buildFakeData(self):
        """ Test fake_data generation: integrity of data + save in redis """
        for tile in self.ALLOWED_TILES:
            if tile != 'empty':
                tileData = buildFakeDataFromTemplate(tile_id=f'test_{tile}', template_name=tile, cache=self.cache)
                self.assertTrue(tileData is not None)
                self.assertTrue('data' in tileData)
                self.assertTrue('id' in tileData)
                self.assertTrue('tile_template' in tileData)
                isIdCorrect = json.loads(self.cache.redis.get(getRedisPrefix(f'test_{tile}')))['id'] == f'test_{tile}'
                self.assertTrue(isIdCorrect)
        testWithoutCache = buildFakeDataFromTemplate(tile_id='faketest', template_name='Fake_tile', cache=None)
        testWithCache = buildFakeDataFromTemplate(tile_id='faketest', template_name='Fake_tile', cache=self.cache)
        self.assertTrue(testWithoutCache is None and testWithCache is None)

    def test_0101_djangoTemplate_tiles(self):
        """ Test template generation for every ALLOWED_TILES """
        template_tile_dashboard(tile_id='id', layout_name=self.layout)
        for tile in self.ALLOWED_TILES:
            tile_data = dict(title=f'{tile}_ex', tile_template=tile)
            tileTemplate = template_tile_data(('layout', tile_data['title']), tile_data)
            if 'role="alert"' in tileTemplate:
                print(f"[EROR] DETECTED WITH TEMPLATE:{tile}")
            self.assertTrue('class="alert alert-danger text-center" role="alert"' not in tileTemplate)  # detect errors
        tileTemplate = template_tile_data(('layout', 'test_unknown_tile'), dict(title='unknown', tile_template='tile'))
        self.assertTrue(tileTemplate is not None)

    def test_0102_flipboard(self):
        """ Test Flipboard object """
        self.assertTrue(getDashboardName() is not None)
        self.assertTrue(getConfigNames() is not None)

    def test_0103_api(self):
        """ Test api /api/info & tests handle errors about API """
        reponse = self.fakeClient.get('/api/info')
        self.assertTrue(reponse.status_code == 200)

    def test_0103_api_flipboardGetDashboard(self):
        """ Test api /flipboard/getDashboardsPaths """
        reponse = self.fakeClient.get('/flipboard/getDashboardsPaths')
        self.assertTrue(reponse.status_code == 200)

    def test_0104_api_checkToken(self):  # TODO
        """ Test token mecanism """
        request = self.fakeClient.get('')
        checkAccessToken(method='GET', request=request, unsecured=False)
        # self.assertTrue(checkAccessToken(method='GET', request=request, unsecured=True))
        self.assertTrue(True)

    def test_0105_api_getHtmlDashboard(self):
        """ Test api getHtmlDashboard """
        reponse = self.fakeClient.get('/' + self.layout)
        self.assertTrue(reponse.status_code == 200)

    def test_0106_api_getHtmlDashboardNotFound(self):
        """ Test api getHtmlDashboardNotFound """
        reponse = self.fakeClient.get('/IfY0uF1ndMeY0ur0ut')
        self.assertTrue(reponse.status_code == 404)

    def test_0107_api_deleteTileFromApi(self):  # deleting first, cause when get => will be create with FakeData
        """ Test api delete Tile from api """
        reponse = self.fakeClient.delete('/api/tiledata/test_text')
        self.assertTrue(reponse.status_code == 200)

    def test_0108_api_getTileFromApi(self):
        """ Test api get tile data from api """
        reponse = self.fakeClient.get('/api/tiledata/test_text')
        self.assertTrue(reponse.status_code == 200)

    def test_0109_api_parseTitleHtmlFromDashboard(self):  # TODO: fix this by testing the flipboard.html
        """ Test if Yaml to dashboard.html know how to parse title """
        reponse = self.fakeClient.get('/dashboard/' + self.layout)
        title = b'__'  # TODO: need to put __ to test the split methode in template html
        self.assertTrue(title in reponse.content)  # can't work cause it's made by ws

    def test_0110_api_parseConfigHtmlFromDashboard(self):  # test with other file when row
        reponse = self.fakeClient.get('/dashboard/' + self.layout)
        configInYaml = b'id="row"'
        self.assertTrue(configInYaml in reponse.content)

    # def test_0111_api_parseConfigHtmlFromDashboard(self):  # TODO: take the tile id by yaml
    #     reponse = self.fakeClient.get('/dashboard/' + self.layout)
    #     IdTilePresenInYaml = b'id="' + bytes(self.layout, 'utf-8') + b'-pie_chartjs_ex"'
    #     self.assertTrue(IdTilePresenInYaml in reponse.content)

    def test_1011_updatetile_PieChart(self):
        """ Test PieChart tile update by api """
        testTileUpdate(tester=self, tileId='test_pie_chart', sonde=sonde2)

    def test_1012_updatetile_NormChart(self):
        """ Test NormChart tile update by api """
        testTileUpdate(tester=self, tileId='test_norm_chart', sonde=sonde12)

    def test_1013_updatetile_LineChart(self):
        """ Test LineChart tile update by api """
        testTileUpdate(tester=self, tileId='test_line_chart', sonde=sonde3)

    def test_1014_updatetile_CumulChart(self):
        """ Test CumulativeChart tile update by api """
        testTileUpdate(tester=self, tileId='test_cumulative_flow', sonde=sonde4)

    def test_1015_updatetile_BarChart(self):
        """ Test BarChart tile update by api """
        testTileUpdate(tester=self, tileId='test_bar_chart', sonde=sonde7)

    def test_1016_updatetile_VBarChart(self):
        """ Test Vertical BarChart tile update by api """
        testTileUpdate(tester=self, tileId='test_vbar_chart', sonde=sonde7)

    def test_1017_updatetile_HdoughnutChart(self):
        """ Test half_doughnut tile update by api """
        testTileUpdate(tester=self, tileId='test_half_doughnut_chart', sonde=sonde17)

    def test_1018_updatetile_doughnutChart(self):
        """ Test doughnut tile update by api """
        testTileUpdate(tester=self, tileId='test_doughnut_chart', sonde=sonde16)

    def test_1019_updatetile_RadarChart(self):
        """ Test radar tile update by api """
        testTileUpdate(tester=self, tileId='test_radar_chart', sonde=sonde14)

    def test_1020_updatetile_polarChart(self):
        """ Test polarChart tile update by api """
        testTileUpdate(tester=self, tileId='test_polararea_chart', sonde=sonde15)

    def test_1021_updatetile_txt(self):
        """ Test text tile update by api """
        testTileUpdate(tester=self, tileId='test_text', sonde=sonde1, isChartJS=False)

    def test_1022_updatetile_sp(self):
        """ Test simplePercentage tile update by api """
        testTileUpdate(tester=self, tileId='test_simple_percentage', sonde=sonde5, isChartJS=False)

    def test_1023_updatetile_listing(self):
        """ Test listing tile update by api """
        testTileUpdate(tester=self, tileId='test_listing', sonde=sonde6, isChartJS=False)

    def test_1024_updatetile_bigValue(self):
        """ Test big_value tile update by api """
        testTileUpdate(tester=self, tileId='test_big_value', sonde=sonde9, isChartJS=False)

    def test_1025_updatetile_justValue(self):
        """ Test just_value tile update by api """
        testTileUpdate(tester=self, tileId='test_just_value', sonde=sonde10, isChartJS=False)

    def test_1028_test_websocket(self):
        consumer = WSConsumer(scope=None)
        print(consumer)  # TODO: improve test

    def test_1026_test_sensors(self):
        tilePrefix = getRedisPrefix('test_simple_percentage')
        lm = MyCache().get(tilePrefix)
        beforeUpdate = json.loads(lm)
        test_sensors(tester=self)
        scheduler = BackgroundScheduler()
        nbrSensors = scheduleYourSensors(scheduler=scheduler, tester=self)
        self.assertTrue(nbrSensors >= 21)
        time.sleep(5)
        scheduler.shutdown()
        time.sleep(3)
        afterUpdate = json.loads(MyCache().get(tilePrefix))['data']['big_value']
        isDiff = beforeUpdate != afterUpdate
        self.assertTrue(isDiff)

    def test_1027_test_demo_mode(self):
        response = demo_controller(None, flagSensors='on', tester=self)
        self.assertTrue(response.status_code == 302)
        time.sleep(10)
        response = demo_controller(None, flagSensors='off', tester=self)
        self.assertTrue(response.status_code == 302)

    def test_1030_checkmanage(self):
        """ Test just_value tile update by api """
        show_help()

    def test_4242_nohided_code(self):
        """ Test if there is code hided from the coverage """
        os.system("grep --exclude='*.pyc' -rnw ./src -e 'pr" + "agma' > dumpPragmaGulty")
        errors = len(open("dumpPragmaGulty", "r").read().splitlines())
        self.assertTrue(errors == 0)
        if errors == 0:
            os.system("rm dumpPragmaGulty")