Beispiel #1
0
def test_list_json_v2():
    try:
        grid = shaystack.Grid(version=shaystack.VER_2_0)
        grid.column['comment'] = {}
        grid.column['value'] = {}
        grid.extend([{
            'comment': 'An empty list',
            'value': [],
        }])
        shaystack.dump(grid, mode=shaystack.MODE_JSON)
        assert False, 'Project Haystack 2.0 doesn\'t support lists'
    except ValueError:
        pass
Beispiel #2
0
def test_dict_csv_v2():
    try:
        grid = shaystack.Grid(version=shaystack.VER_2_0)
        grid.column['comment'] = {}
        grid.column['value'] = {}
        grid.extend([{
            'comment': 'An empty dict',
            'value': {},
        }])
        shaystack.dump(grid, mode=shaystack.MODE_CSV)
        assert False, 'Project Haystack 2.0 doesn\'t support dict'
    except ValueError:
        pass
Beispiel #3
0
def test_watch_poll_with_zinc(mock) -> None:
    # GIVEN
    """
    Args:
        mock:
    """
    envs = {'HAYSTACK_PROVIDER': 'shaystack.providers.ping'}
    mock.return_value = ping._PingGrid
    mime_type = shaystack.MODE_ZINC
    request = HaystackHttpRequest()
    grid: Grid = shaystack.Grid(
        metadata={'watchId': "0123456789ABCDEF",
                  'refresh': MARKER
                  },
        columns=["empty"])
    grid.append({})
    request.headers["Content-Type"] = mime_type
    request.headers["Accept"] = mime_type
    request.body = shaystack.dump(grid, mode=shaystack.MODE_ZINC)

    # WHEN
    response = shaystack.watch_poll(envs, request, "dev")

    # THEN
    mock.assert_called_once_with("0123456789ABCDEF", True)
    assert response.status_code == 200
    assert response.headers["Content-Type"].startswith(mime_type)
    assert shaystack.parse(response.body, shaystack.MODE_ZINC) is not None
def test_point_write_write_with_zinc(mock) -> None:
    # GIVEN
    """
    Args:
        mock:
    """
    envs = {'HAYSTACK_PROVIDER': 'shaystack.providers.ping'}
    mock.return_value = Grid(version=VER_3_0,
                             columns=["level", "levelDis", "val", "who"])
    mime_type = shaystack.MODE_ZINC
    request = HaystackHttpRequest()
    grid = shaystack.Grid(columns=['id', "level", "val", "who", "duration"])
    grid.append({
        "id": Ref("1234"),
        "level": 1,
        "val": 100.0,
        "who": "PPR",
        "duration": Quantity(1, "min")
    })
    request.headers["Content-Type"] = mime_type
    request.headers["Accept"] = mime_type
    request.body = shaystack.dump(grid, mode=mime_type)

    # WHEN
    response = shaystack.point_write(envs, request, "dev")

    # THEN
    mock.assert_called_once_with(Ref("1234"), 1, 100, "PPR",
                                 Quantity(1, "min"), None)
    assert response.status_code == 200
    assert response.headers["Content-Type"].startswith(mime_type)
    assert shaystack.parse(response.body, mime_type) is not None
Beispiel #5
0
def test_watch_unsub_with_zinc(mock) -> None:
    # GIVEN
    """
    Args:
        mock:
    """
    envs = {'HAYSTACK_PROVIDER': 'shaystack.providers.ping'}
    mock.return_value = ping._PingGrid
    mime_type = shaystack.MODE_ZINC
    request = HaystackHttpRequest()
    grid = shaystack.Grid(metadata={"close": True,
                                    "watchId": "0123456789ABCDEF"},
                          columns=['id'])
    grid.append({"id": Ref("id1")})
    grid.append({"id": Ref("id2")})
    request.headers["Content-Type"] = mime_type
    request.headers["Accept"] = mime_type
    request.body = shaystack.dump(grid, mode=shaystack.MODE_ZINC)

    # WHEN
    response = shaystack.watch_unsub(envs, request, "dev")

    # THEN
    mock.assert_called_once_with("0123456789ABCDEF", [Ref("id1"), Ref("id2")], True)
    assert response.status_code == 200
    assert response.headers["Content-Type"].startswith(mime_type)
    assert shaystack.parse(response.body, shaystack.MODE_ZINC) is not None
Beispiel #6
0
def test_invoke_action_with_zinc(mock) -> None:
    # GIVEN
    """
    Args:
        mock:
    """
    envs = {'HAYSTACK_PROVIDER': 'shaystack.providers.ping'}
    mock.return_value = ping._PingGrid
    mime_type = shaystack.MODE_ZINC
    request = HaystackHttpRequest()
    grid = shaystack.Grid(metadata={
        'id': Ref('123'),
        'action': 'doIt'
    },
                          columns={
                              'key': {},
                              'value': {}
                          })
    grid.append({'param': 'value'})
    request.headers["Content-Type"] = mime_type
    request.headers["Accept"] = mime_type
    request.body = shaystack.dump(grid, mode=shaystack.MODE_ZINC)

    # WHEN
    response = shaystack.invoke_action(envs, request, "dev")

    # THEN
    mock.assert_called_once_with(Ref("123"), "doIt", {})
    assert response.status_code == 200
    assert response.headers["Content-Type"].startswith(mime_type)
    assert shaystack.parse(response.body, shaystack.MODE_ZINC) is not None
Beispiel #7
0
def test_his_read_with_zinc(mock, no_cache) -> None:
    # GIVEN
    """
    Args:
        mock:
        no_cache:
    """
    envs = {'HAYSTACK_PROVIDER': 'shaystack.providers.ping'}
    mock.return_value = ping._PingGrid
    no_cache.return_value = True
    mime_type = shaystack.MODE_ZINC
    request = HaystackHttpRequest()
    grid = shaystack.Grid(columns={'id': {}})
    grid.append({"id": Ref("1234")})
    request.headers["Content-Type"] = mime_type
    request.headers["Accept"] = mime_type
    request.body = shaystack.dump(grid, mode=mime_type)

    # WHEN
    response = shaystack.his_read(envs, request, "dev")

    # THEN
    mock.assert_called_once_with(Ref("1234"),
                                 (datetime.min.replace(tzinfo=pytz.UTC),
                                  datetime.max.replace(tzinfo=pytz.UTC)), None)
    assert response.status_code == 200
    assert response.headers["Content-Type"].startswith(mime_type)
    assert shaystack.parse(response.body, mime_type) is not None
Beispiel #8
0
def test_data_types_zinc_v3():
    grid_str = shaystack.dump(grid_full_types, mode=shaystack.MODE_ZINC)
    ref_str = '''
ver:"2.0"
comment,value
"A null value",N
"A marker",M
"A \\"remove\\" object",R
"A boolean, indicating False",F
"A boolean, indicating True",T
"A reference, without value",@a-ref
"A reference, with value",@a-ref "a value"
"A binary blob",Bin(text/plain)
"A quantity",500miles
"A quantity without unit",500
"A coordinate",C(-27.472500,153.003000)
"A URI",`http://www.example.com#unicode:\u0109\u1000`
"A string","This is a test\\nLine two of test\\n\\tIndented with \\"quotes\\", \\\\backslashes\\\\\\n"
"A unicode string","This is a Unicode characters: \u0109\u1000"
"A date",2016-01-13
"A time",07:51:43.012345
"A timestamp (non-UTC)",2016-01-13T07:51:42.012345+01:00 Berlin
"A timestamp (UTC)",2016-01-13T07:51:42.012345+00:00 UTC
'''[1:]
    assert grid_str == ref_str
Beispiel #9
0
def test_his_read_with_range_today(mock) -> None:
    # GIVEN
    """
    Args:
        mock:
    """
    envs = {'HAYSTACK_PROVIDER': 'shaystack.providers.ping'}
    mock.return_value = ping._PingGrid
    mime_type = shaystack.MODE_ZINC
    request = HaystackHttpRequest()
    grid = shaystack.Grid(columns=['id', 'range'])
    grid.append({"id": Ref("1234"), "range": "today"})
    request.headers["Content-Type"] = mime_type
    request.headers["Accept"] = mime_type
    request.body = shaystack.dump(grid, mode=mime_type)

    # WHEN
    response = shaystack.his_read(envs, request, "dev")

    # THEN
    today = datetime.combine(date.today(), datetime.min.time()).replace(tzinfo=get_localzone())
    mock.assert_called_once_with(Ref("1234"),
                                 (today,
                                  today + timedelta(days=1)
                                  ), None)
    assert response.status_code == 200
    assert response.headers["Content-Type"].startswith(mime_type)
    assert shaystack.parse(response.body, mime_type) is not None
Beispiel #10
0
def test_read_with_zinc_and_id(mock) -> None:
    # GIVEN
    """
    Args:
        mock:
    """
    envs = {'HAYSTACK_PROVIDER': 'shaystack.providers.ping'}
    mock.return_value = ping._PingGrid
    mime_type = shaystack.MODE_ZINC
    request = HaystackHttpRequest()
    grid = shaystack.Grid(columns=['id'])
    grid.append({"id": Ref("me")})
    request.headers["Content-Type"] = mime_type
    request.headers["Accept"] = mime_type
    request.body = shaystack.dump(grid, mode=mime_type)

    # WHEN
    response = shaystack.read(envs, request, "dev")

    # THEN
    ids = [Ref("me")]
    mock.assert_called_once_with(0, None, ids, '', None)
    assert response.status_code == 200
    assert response.headers["Content-Type"].startswith(mime_type)
    assert shaystack.parse(response.body, mime_type) is not None
Beispiel #11
0
def test_data_types_csv_v3():
    grid_csv = shaystack.dump(grid_full_types, mode=shaystack.MODE_CSV)
    assert list(reader(grid_csv.splitlines()))
    ref_str = '''
comment,value
"A null value",
"A marker",✓
"A ""remove"" object",R
"A boolean, indicating False",false
"A boolean, indicating True",true
"A reference, without value",@a-ref
"A reference, with value",@a-ref a value
"A binary blob",Bin(text/plain)
"A quantity",500miles
"A quantity without unit",500
"A coordinate","C(-27.472500,153.003000)"
"A URI","`http://www.example.com#unicode:\u0109\u1000`"
"A string","This is a test\nLine two of test\n\tIndented with ""quotes"", \\backslashes\\\n"
"A unicode string","This is a Unicode characters: \u0109\u1000"
"A date",2016-01-13
"A time",07:51:43.012345
"A timestamp (non-UTC)",2016-01-13T07:51:42.012345+01:00
"A timestamp (UTC)",2016-01-13T07:51:42.012345+00:00
'''[1:]
    assert grid_csv == ref_str
Beispiel #12
0
def test_data_types_json_v3():
    grid_json = json.loads(
        shaystack.dump(grid_full_types, mode=shaystack.MODE_JSON))
    assert grid_json == \
           {'meta': {'ver': '2.0'},
            'cols': [{'name': 'comment'}, {'name': 'value'}],
            'rows':
                [{'comment': 's:A null value', 'value': None},
                 {'comment': 's:A marker', 'value': 'm:'},
                 {'comment': 's:A "remove" object', 'value': 'x:'},
                 {'comment': 's:A boolean, indicating False', 'value': False},
                 {'comment': 's:A boolean, indicating True', 'value': True},
                 {'comment': 's:A reference, without value', 'value': 'r:a-ref'},
                 {'comment': 's:A reference, with value', 'value': 'r:a-ref a value'},
                 {'comment': 's:A binary blob', 'value': 'b:text/plain'},
                 {'comment': 's:A quantity', 'value': 'n:500.000000 miles'},
                 {'comment': 's:A quantity without unit', 'value': 'n:500.000000'},
                 {'comment': 's:A coordinate', 'value': 'c:-27.472500,153.003000'},
                 {'comment': 's:A URI', 'value': 'u:http://www.example.com#unicode:\u0109\u1000'},
                 {'comment': 's:A string',
                  'value': 's:This is a test\nLine two of test\n'
                           '\tIndented with "quotes", \\backslashes\\\n'},
                 {'comment': 's:A unicode string', 'value': 's:This is a Unicode characters: \u0109\u1000'},
                 {'comment': 's:A date', 'value': 'd:2016-01-13'},
                 {'comment': 's:A time', 'value': 'h:07:51:43.012345'},
                 {'comment': 's:A timestamp (non-UTC)',
                  'value': 't:2016-01-13T07:51:42.012345+01:00 Berlin'},
                 {'comment': 's:A timestamp (UTC)',
                  'value': 't:2016-01-13T07:51:42.012345+00:00 UTC'}]}
Beispiel #13
0
def test_his_read_with_range_one_datetime(mock) -> None:
    # GIVEN
    """
    Args:
        mock:
    """
    envs = {'HAYSTACK_PROVIDER': 'shaystack.providers.ping'}
    mock.return_value = ping._PingGrid
    mime_type = shaystack.MODE_ZINC
    request = HaystackHttpRequest()
    grid = shaystack.Grid(columns=['id', 'range'])
    datetime_1 = datetime(2020, 1, 1, 0, 0, 0, tzinfo=pytz.UTC)
    grid.append({"id": Ref("1234"), "range": datetime_1.isoformat()})
    request.headers["Content-Type"] = mime_type
    request.headers["Accept"] = mime_type
    request.body = shaystack.dump(grid, mode=mime_type)

    # WHEN
    response = shaystack.his_read(envs, request, "dev")

    # THEN
    cur_datetime = datetime.combine(datetime_1, datetime.min.time()).replace(tzinfo=pytz.UTC)
    mock.assert_called_once_with(Ref("1234"),
                                 (cur_datetime,
                                  datetime.max.replace(tzinfo=pytz.UTC)
                                  ), None)
    assert response.status_code == 200
    assert response.headers["Content-Type"].startswith(mime_type)
    assert shaystack.parse(response.body, mime_type) is not None
Beispiel #14
0
def test_scalar_dict_trio_v3():
    grid = shaystack.Grid(version=shaystack.VER_3_0)
    grid.column['comment'] = {}
    grid.column['value'] = {}
    grid.extend([
        {
            'comment': 'An empty dict',
            'value': {},
        },
        {
            'comment': 'A marker in a dict',
            'value': {
                "marker": shaystack.MARKER
            },
        },
        {
            'comment': 'A references in a dict',
            'value': {
                "ref": shaystack.Ref('a-ref'),
                "ref2": shaystack.Ref('a-ref', 'a value')
            },
        },
        {
            'comment': 'A quantity in a dict',
            'value': {
                "quantity": shaystack.Quantity(500, 'miles')
            },
        },
    ])
    grid_str = shaystack.dump(grid, mode=shaystack.MODE_TRIO)
    # noinspection PyPep8,PyPep8
    ref_str = textwrap.dedent('''
        comment: An empty dict
        value: {}
        ---
        comment: A marker in a dict
        value: {marker:M}
        ---
        comment: A references in a dict
        value: {'''[1:]) + \
              (" ".join([str(k) + ":" + str(v)
                         for k, v in {"ref": "@a-ref", "ref2": "@a-ref"}.items()])
               .replace("ref2:@a-ref", "ref2:@a-ref \"a value\"")) + \
              textwrap.dedent('''
        }
        ---
        comment: A quantity in a dict
        value: {quantity:500miles}
        '''[1:])
    assert grid_str == ref_str
Beispiel #15
0
 def get_object(self, Bucket, Key, IfNoneMatch):  # pylint: disable=unused-argument, no-self-use
     if Key == 'sample/carytown.zinc':
         grid = Grid(columns=["hisURI"])
         grid.append({"hisURL": "ts.zinc"})
     else:
         grid = Grid(columns=["tz", "value"])
         grid.append({
             "ts":
             datetime(2020, 1, 1, 0, 0, 2, 0, tzinfo=pytz.UTC),
             "value":
             100
         })
     data = dump(grid, MODE_ZINC).encode("UTF8")
     return {"Body": BytesIO(data)}
def test_negociation_without_accept() -> None:
    # GIVEN
    envs = {'HAYSTACK_PROVIDER': 'shaystack.providers.ping'}
    mime_type = shaystack.MODE_CSV
    request = HaystackHttpRequest()
    grid = Grid(columns={'filter': {}, 'limit': {}})
    grid.append({'filter': '', 'limit': -1})
    del request.headers["Accept"]
    request.headers["Content-Type"] = mime_type
    request.body = shaystack.dump(grid, mode=mime_type)

    # WHEN
    try:
        shaystack.read(envs, request, "dev")
        assert False, "Must generate exception"
    except HttpError as ex:
        assert ex.error == 406
def test_negociation_json_without_content_type() -> None:
    # GIVEN
    envs = {'HAYSTACK_PROVIDER': 'shaystack.providers.ping'}
    mime_type = shaystack.MODE_JSON
    request = HaystackHttpRequest()
    grid: Grid = Grid(columns={'id': {}})
    request.headers["Accept"] = mime_type
    del request.headers["Content-Type"]
    request.body = shaystack.dump(grid, mode=mime_type)

    # WHEN
    response = shaystack.read(envs, request, "dev")

    # THEN
    assert response.status_code == 200
    assert response.headers["Content-Type"].startswith(mime_type)
    shaystack.parse(response.body, mime_type)
def test_negociation_with_complex_accept() -> None:
    # GIVEN
    envs = {'HAYSTACK_PROVIDER': 'shaystack.providers.ping'}
    mime_type = shaystack.MODE_ZINC
    request = HaystackHttpRequest()
    grid = Grid(columns={'filter': {}, 'limit': {}})
    grid.append({'filter': '', 'limit': -1})
    request.headers["Accept"] = "text/json;q=0.9,text/zinc;q=1"
    request.headers["Content-Type"] = mime_type
    request.body = shaystack.dump(grid, mode=mime_type)

    # WHEN
    response = shaystack.read(envs, request, "dev")

    # THEN
    assert response.status_code == 200
    assert response.headers["Content-Type"].startswith(mime_type)
Beispiel #19
0
def test_grid_types_json():
    innergrid = shaystack.Grid(version=shaystack.VER_3_0)
    innergrid.column['comment'] = {}
    innergrid.extend([
        {
            'comment': 'A innergrid',
        },
    ])
    grid = shaystack.Grid(version=shaystack.VER_3_0)
    grid.column['inner'] = {}
    grid.extend(cast(List[Entity], [
        {
            'inner': innergrid,
        },
    ]))
    grid_str = shaystack.dump(grid, mode=shaystack.MODE_JSON)
    grid_json = json.loads(grid_str)
    assert grid_json == {
        'meta': {
            'ver': '3.0'
        },
        'cols': [
            {
                'name': 'inner'
            },
        ],
        'rows': [
            {
                'inner': {
                    'meta': {
                        'ver': '3.0'
                    },
                    'cols': [
                        {
                            'name': 'comment'
                        },
                    ],
                    'rows': [
                        {
                            'comment': 's:A innergrid'
                        },
                    ],
                }
            },
        ],
    }
def test_negociation_json_with_unknown_content_type() -> None:
    # GIVEN
    envs = {'HAYSTACK_PROVIDER': 'shaystack.providers.ping'}
    mime_type = shaystack.MODE_ZINC
    request = HaystackHttpRequest()
    grid: Grid = Grid(columns={'id': {}})
    request.headers["Accept"] = mime_type
    request.headers["Content-Type"] = "text/html"
    request.body = shaystack.dump(grid, mode=mime_type)

    # WHEN
    response = shaystack.read(envs, request, "dev")

    # THEN
    assert response.status_code == 406
    assert response.headers["Content-Type"].startswith(mime_type)
    error_grid: Grid = shaystack.parse(response.body, mime_type)
    assert "err" in error_grid.metadata
Beispiel #21
0
def test_col_meta_json():
    grid_json = json.loads(
        shaystack.dump(make_col_meta(), mode=shaystack.MODE_JSON))
    assert grid_json == {
        'meta': {
            'ver': '2.0',
        },
        'cols': [
            {
                'name': 'empty',
                'aString': 's:aValue',
                'aNumber': 'n:3.141590',
                'aNull': None,
                'aMarker': 'm:',
                'aQuantity': 'n:123.000000 Hz',
            },
        ],
        'rows': [],
    }
Beispiel #22
0
def test_scalar_dict_zinc_v3():
    grid = shaystack.Grid(version=shaystack.VER_3_0)
    grid.column['comment'] = {}
    grid.column['value'] = {}
    grid.extend([
        {
            'comment': 'An empty dict',
            'value': {},
        },
        {
            'comment': 'A marker in a dict',
            'value': {
                "marker": shaystack.MARKER
            },
        },
        {
            'comment': 'A references in a dict',
            'value': {
                "ref": shaystack.Ref('a-ref'),
                "ref2": shaystack.Ref('a-ref', 'a value')
            },
        },
        {
            'comment': 'A quantity in a dict',
            'value': {
                "quantity": shaystack.Quantity(500, 'miles')
            },
        },
    ])
    grid_str = shaystack.dump(grid, mode=shaystack.MODE_ZINC)
    assert grid_str == ("ver:\"3.0\"\n"
                        "comment,value\n"
                        "\"An empty dict\",{}\n"
                        "\"A marker in a dict\",{marker:M}\n"
                        "\"A references in a dict\",{" + " ".join([
                            str(k) + ":" + str(v) for k, v in {
                                "ref": "@a-ref",
                                "ref2": "@a-ref"
                            }.items()
                        ]).replace("ref2:@a-ref", "ref2:@a-ref \"a value\"") +
                        "}\n"
                        "\"A quantity in a dict\",{quantity:500miles}\n")
Beispiel #23
0
def test_grid_types_zinc():
    innergrid = shaystack.Grid(version=shaystack.VER_3_0)
    innergrid.column['comment'] = {}
    innergrid.extend([
        {
            'comment': 'A innergrid',
        },
    ])
    grid = shaystack.Grid(version=shaystack.VER_3_0)
    grid.column['inner'] = {}
    grid.extend(cast(List[Entity], [
        {
            'inner': innergrid,
        },
    ]))
    grid_str = shaystack.dump(grid, mode=shaystack.MODE_ZINC)
    assert grid_str == ('ver:"3.0"\n'
                        'inner\n'
                        '<<ver:"3.0"\n'
                        'comment\n'
                        '"A innergrid"\n'
                        '>>\n')
Beispiel #24
0
def test_scalar_dict_csv_v3():
    grid = shaystack.Grid(version=shaystack.VER_3_0)
    grid.column['comment'] = {}
    grid.column['value'] = {}
    grid.extend([
        {
            'comment': 'An empty dict',
            'value': {},
        },
        {
            'comment': 'A marker in a dict',
            'value': {
                "marker": shaystack.MARKER
            },
        },
        {
            'comment': 'A references in a dict',
            'value': {
                "ref": shaystack.Ref('a-ref'),
                "ref2": shaystack.Ref('a-ref', 'a value')
            },
        },
        {
            'comment': 'A quantity in a dict',
            'value': {
                "quantity": shaystack.Quantity(500, 'miles')
            },
        },
    ])
    grid_csv = shaystack.dump(grid, mode=shaystack.MODE_CSV)
    assert list(reader(grid_csv.splitlines()))
    assert grid_csv == u'''comment,value
"An empty dict","{}"
"A marker in a dict","{marker:M}"
"A references in a dict","{''' + \
           " ".join([k + ":" + v
                     for k, v in {'ref': '@a-ref', 'ref2': '@a-ref ""a value""'}.items()]) + \
           '''}"
def test_negociation_with_zinc(no_cache) -> None:
    # GIVEN
    """
    Args:
        no_cache:
    """
    envs = {'HAYSTACK_PROVIDER': 'shaystack.providers.ping'}
    no_cache.return_value = True
    mime_type = shaystack.MODE_ZINC
    request = HaystackHttpRequest()
    grid = Grid(columns={'filter': {}, "limit": {}})
    grid.append({"filter": "id==@me", "limit": 1})
    request.headers["Content-Type"] = mime_type
    request.headers["Accept"] = mime_type
    request.body = shaystack.dump(grid, mode=mime_type)

    # WHEN
    response = shaystack.read(envs, request, "dev")

    # THEN
    assert response.status_code == 200
    assert response.headers["Content-Type"].startswith(mime_type)
    shaystack.parse(response.body, shaystack.MODE_ZINC)
def test_negociation_with_navigator_accept() -> None:
    # GIVEN
    envs = {'HAYSTACK_PROVIDER': 'shaystack.providers.ping'}
    mime_type = shaystack.MODE_CSV
    request = HaystackHttpRequest()
    grid = Grid(columns={'filter': {}, 'limit': {}})
    grid.append({'filter': '', 'limit': -1})
    request.headers[
        "Accept"] = "Accept:text/html,application/xhtml+xml," \
                    "application/xml;q=0.9," \
                    "image/webp,image/apng," \
                    "*/*;q=0.8," \
                    "application/signed-exchange;v=b3;q=0.9"
    request.headers["Content-Type"] = mime_type
    request.body = shaystack.dump(grid, mode=mime_type)

    # WHEN
    response = shaystack.read(envs, request, "dev")

    # THEN
    assert response.status_code == 200
    assert response.headers["Content-Type"].startswith(mime_type)
    shaystack.parse(response.body, mime_type)
Beispiel #27
0
def test_grid_types_trio():
    innergrid = shaystack.Grid(version=shaystack.VER_3_0)
    innergrid.column['comment'] = {}
    innergrid.extend([
        {
            'comment': 'A innergrid',
        },
    ])
    grid = shaystack.Grid(version=shaystack.VER_3_0)
    grid.column['inner'] = {}
    grid.extend(cast(List[Entity], [
        {
            'inner': innergrid,
        },
    ]))
    grid_str = shaystack.dump(grid, mode=shaystack.MODE_TRIO)
    ref_str = textwrap.dedent('''
        inner: Zinc:
          ver:"3.0"
          comment
          "A innergrid"
        '''[1:])
    assert grid_str == ref_str
def test_watch_sub_with_zinc(mock):
    # GIVEN
    """
    Args:
        mock:
    """
    envs = {'HAYSTACK_PROVIDER': 'shaystack.providers.ping'}
    mock.return_value = Grid(version=VER_3_0,
                             metadata={
                                 "watchId": "0123456789ABCDEF",
                                 "lease": 1
                             },
                             columns=["empty"])
    mock.return_value.append({})
    mime_type = shaystack.MODE_ZINC
    request = HaystackHttpRequest()
    grid = shaystack.Grid(metadata={
        "watchDis": "myWatch",
        "watchId": "myid",
        "lease": 1
    },
                          columns=['id'])
    grid.append({"id": Ref("id1")})
    grid.append({"id": Ref("id2")})
    request.headers["Content-Type"] = mime_type
    request.headers["Accept"] = mime_type
    request.body = shaystack.dump(grid, mode=shaystack.MODE_ZINC)

    # WHEN
    response = shaystack.watch_sub(envs, request, "dev")

    # THEN
    mock.assert_called_once_with("myWatch", "myid",
                                 [Ref("id1"), Ref("id2")], 1)
    assert response.status_code == 200
    assert response.headers["Content-Type"].startswith(mime_type)
    assert shaystack.parse(response.body, shaystack.MODE_ZINC) is not None
Beispiel #29
0
def test_grid_types_csv():
    innergrid = shaystack.Grid(version=shaystack.VER_3_0)
    innergrid.column['comment'] = {}
    innergrid.extend([
        {
            'comment': 'A innergrid',
        },
    ])
    grid = shaystack.Grid(version=shaystack.VER_3_0)
    grid.column['inner'] = {}
    grid.extend(cast(List[Entity], [
        {
            'inner': innergrid,
        },
    ]))
    grid_csv = shaystack.dump(grid, mode=shaystack.MODE_CSV)
    assert list(reader(grid_csv.splitlines()))
    assert grid_csv == '''
inner
"<<ver:""3.0""
comment
""A innergrid""
>>"
'''[1:]
Beispiel #30
0
def test_read_with_zinc_and_filter(mock) -> None:
    # GIVEN
    """
    Args:
        mock:
    """
    envs = {'HAYSTACK_PROVIDER': 'shaystack.providers.ping'}
    mock.return_value = ping._PingGrid
    mime_type = shaystack.MODE_ZINC
    request = HaystackHttpRequest()
    grid = shaystack.Grid(columns={'filter': {}, "limit": {}})
    grid.append({"filter": "id==@me", "limit": 1})
    request.headers["Content-Type"] = mime_type
    request.headers["Accept"] = mime_type
    request.body = shaystack.dump(grid, mode=shaystack.MODE_ZINC)

    # WHEN
    response = shaystack.read(envs, request, "dev")

    # THEN
    mock.assert_called_once_with(1, None, None, 'id==@me', None)
    assert response.status_code == 200
    assert response.headers["Content-Type"].startswith(mime_type)
    assert not shaystack.parse(response.body, mime_type)