code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
194
| url
stringlengths 46
254
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
async def test_edgeql_rewrites_26(self):
async with self.assertRaisesRegexTx(
edgedb.SchemaDefinitionError,
r"rewrites on link properties are not supported",
):
await self.con.execute(
'''
create type X {
create link foo -> std::Object {
create property bar: int32 {
create rewrite insert using ('hello');
};
};
};
'''
) | create type X {
create link foo -> std::Object {
create property bar: int32 {
create rewrite insert using ('hello');
};
};
}; | test_edgeql_rewrites_26 | python | geldata/gel | tests/test_edgeql_rewrites.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_rewrites.py | Apache-2.0 |
async def test_edgeql_rewrites_27(self):
await self.con.execute(
'''
create type Foo {
create property will_be_true: bool {
create rewrite update using (__subject__ = __old__);
};
};
insert Foo { will_be_true := false };
'''
)
await self.assert_query_result(
'select Foo { will_be_true }',
[{'will_be_true': False}]
)
await self.con.execute('update Foo set { };')
await self.assert_query_result(
'select Foo { will_be_true }',
[{'will_be_true': True}]
) | create type Foo {
create property will_be_true: bool {
create rewrite update using (__subject__ = __old__);
};
};
insert Foo { will_be_true := false }; | test_edgeql_rewrites_27 | python | geldata/gel | tests/test_edgeql_rewrites.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_rewrites.py | Apache-2.0 |
async def test_edgeql_rewrites_28(self):
await self.con.execute(
'''
create type Address {
create property coordinates: tuple<lat: float32, lng: float32>;
create property updated_at: str {
create rewrite insert using ('now')
};
};
insert Address {
coordinates := (
lat := <std::float32>40.07987,
lng := <std::float32>20.56509
)
};
'''
)
await self.assert_query_result(
'select Address { coordinates, updated_at }',
[
{
'coordinates': {'lat': 40.07987, 'lng': 20.56509},
'updated_at': 'now'
}
]
) | create type Address {
create property coordinates: tuple<lat: float32, lng: float32>;
create property updated_at: str {
create rewrite insert using ('now')
};
};
insert Address {
coordinates := (
lat := <std::float32>40.07987,
lng := <std::float32>20.56509
)
}; | test_edgeql_rewrites_28 | python | geldata/gel | tests/test_edgeql_rewrites.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_rewrites.py | Apache-2.0 |
async def test_edgeql_rewrites_29(self):
# see https://github.com/edgedb/edgedb/issues/7048
# these tests check that subject of an update rewrite is the child
# object and not parent that is being updated
await self.con.execute(
'''
update std::Object set { };
'''
)
await self.con.execute(
'''
update Project set { name := '## redacted ##' }
'''
) | update std::Object set { }; | test_edgeql_rewrites_29 | python | geldata/gel | tests/test_edgeql_rewrites.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_rewrites.py | Apache-2.0 |
async def test_edgeql_userddl_20(self):
await self.con.execute('''
CREATE FUNCTION func_20(
a: str
) -> SET OF str
USING EdgeQL $$
SELECT {a, 'a'}
$$;
''')
await self.assert_query_result(
r'''
SELECT func_20('q');
''',
{'q', 'a'},
)
await self.assert_query_result(
r'''
SELECT count(func_20({'q', 'w'}));
''',
{4},
) | )
await self.assert_query_result(
r | test_edgeql_userddl_20 | python | geldata/gel | tests/test_edgeql_userddl.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_userddl.py | Apache-2.0 |
async def test_edgeql_userddl_22(self):
await self.con.execute('''
CREATE ABSTRACT CONSTRAINT uppercase {
CREATE ANNOTATION title := "Upper case constraint";
USING (str_upper(__subject__) = __subject__);
SET errmessage := "{__subject__} is not in upper case";
};
CREATE SCALAR TYPE upper_str EXTENDING str {
CREATE CONSTRAINT uppercase
};
''')
await self.assert_query_result(
r'''
SELECT <upper_str>'123_HELLO';
''',
{'123_HELLO'},
) | )
await self.assert_query_result(
r | test_edgeql_userddl_22 | python | geldata/gel | tests/test_edgeql_userddl.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_userddl.py | Apache-2.0 |
async def test_edgeql_userddl_24(self):
await self.con.execute('''
CREATE SCALAR TYPE Slug EXTENDING str {
CREATE CONSTRAINT regexp(r'^[a-z0-9][.a-z0-9-]+$')
};
CREATE ABSTRACT TYPE Named {
CREATE REQUIRED PROPERTY name -> Slug
};
CREATE TYPE User EXTENDING Named;
''')
await self.con.execute('''
ALTER TYPE Named {
CREATE INDEX ON (__subject__.name)
};
''') | )
await self.con.execute( | test_edgeql_userddl_24 | python | geldata/gel | tests/test_edgeql_userddl.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_userddl.py | Apache-2.0 |
async def test_edgeql_userddl_26(self):
# testing fallback
await self.con.execute(r'''
CREATE FUNCTION func_26(
a: bool
) -> bool {
USING (
NOT a
);
}
''')
with self.assertRaisesRegex(
edgedb.SchemaDefinitionError,
r"'fallback' is not a valid field"):
await self.con.execute(r'''
ALTER FUNCTION func_26(
a: bool
) {
SET fallback := true;
}
''') | )
with self.assertRaisesRegex(
edgedb.SchemaDefinitionError,
r"'fallback' is not a valid field"):
await self.con.execute(r | test_edgeql_userddl_26 | python | geldata/gel | tests/test_edgeql_userddl.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_userddl.py | Apache-2.0 |
async def test_edgeql_userddl_27(self):
# testing fallback
await self.con.execute(r'''
CREATE FUNCTION func_27(
a: bool
) -> bool {
USING (
NOT a
);
}
''')
with self.assertRaisesRegex(
edgedb.SchemaDefinitionError,
r"'fallback' is not a valid field"):
await self.con.execute(r'''
ALTER FUNCTION func_27(
a: bool
) {
# Even altering to set fallback to False should not be
# allowed in user-space.
SET fallback := false;
}
''') | )
with self.assertRaisesRegex(
edgedb.SchemaDefinitionError,
r"'fallback' is not a valid field"):
await self.con.execute(r | test_edgeql_userddl_27 | python | geldata/gel | tests/test_edgeql_userddl.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_userddl.py | Apache-2.0 |
async def test_edgeql_userddl_29(self):
await self.con.execute('''
configure session set __internal_testmode := true;
create module ext::_test;
create type ext::_test::X extending std::BaseObject;
configure session reset __internal_testmode;
''')
async with self.assertRaisesRegexTx(
edgedb.SchemaDefinitionError, "module ext is read-only"):
await self.con.execute('''
create module ext::_test::foo;
''')
async with self.assertRaisesRegexTx(
edgedb.SchemaDefinitionError, "module ext is read-only"):
await self.con.execute('''
create type ext::_test::foo;
''')
async with self.assertRaisesRegexTx(
edgedb.SchemaDefinitionError, "module ext is read-only"):
await self.con.execute('''
alter type ext::_test::X { create property x -> str };
''')
async with self.assertRaisesRegexTx(
edgedb.SchemaDefinitionError, "module ext is read-only"):
await self.con.execute('''
drop type ext::_test::X;
''') | )
async with self.assertRaisesRegexTx(
edgedb.SchemaDefinitionError, "module ext is read-only"):
await self.con.execute( | test_edgeql_userddl_29 | python | geldata/gel | tests/test_edgeql_userddl.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_userddl.py | Apache-2.0 |
async def test_edgeql_userddl_all_extensions_01(self):
# Install all extensions and then delete them all
exts = await self.con.query('''
select distinct sys::ExtensionPackage.name
''')
# This tests that toggling scoping futures works with
# extensions, and that the extensions work if it is enabled
# first.
await self.con.execute(f"""
START MIGRATION TO {{
using future warn_old_scoping;
module default {{ }}
}};
POPULATE MIGRATION;
COMMIT MIGRATION;
""")
ext_commands = ''.join(f'using extension {ext};\n' for ext in exts)
await self.con.execute(f"""
START MIGRATION TO {{
using future warn_old_scoping;
{ext_commands}
module default {{ }}
}};
POPULATE MIGRATION;
COMMIT MIGRATION;
""")
await self.con.query("""
describe current database config as ddl
""")
await self.con.query("""
describe instance config as ddl
""")
await self.con.execute(f"""
START MIGRATION TO {{
{ext_commands}
module default {{ }}
}};
POPULATE MIGRATION;
COMMIT MIGRATION;
""")
await self.con.execute(f"""
START MIGRATION TO {{
using future warn_old_scoping;
{ext_commands}
module default {{ }}
}};
POPULATE MIGRATION;
COMMIT MIGRATION;
""")
await self.con.execute(f"""
START MIGRATION TO {{
module default {{ }}
}};
POPULATE MIGRATION;
COMMIT MIGRATION;
""") | )
# This tests that toggling scoping futures works with
# extensions, and that the extensions work if it is enabled
# first.
await self.con.execute(f | test_edgeql_userddl_all_extensions_01 | python | geldata/gel | tests/test_edgeql_userddl.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_userddl.py | Apache-2.0 |
async def test_edgeql_json_cast_07(self):
"""Check that JSON of array preserves order."""
await self.assert_query_result(
r'''
SELECT <json>array_agg(
(SELECT JSONTest{number}
FILTER .number IN {0, 1}
ORDER BY .j_string)
) = to_json(
'[{"number": 1}, {"number": 0}]'
)
''',
[True]
) | Check that JSON of array preserves order. | test_edgeql_json_cast_07 | python | geldata/gel | tests/test_edgeql_json.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_json.py | Apache-2.0 |
async def test_edgeql_json_accessor_02(self):
await self.assert_query_result(
r'''
SELECT (to_json('{"a": 1, "b": null}'))["a"] =
to_json('1');
''',
[True],
)
await self.assert_query_result(
r'''
SELECT (to_json('{"a": 1, "b": null}'))["b"] =
to_json('null');
''',
[True],
) | ,
[True],
)
await self.assert_query_result(
r | test_edgeql_json_accessor_02 | python | geldata/gel | tests/test_edgeql_json.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_json.py | Apache-2.0 |
async def test_edgeql_json_accessor_13(self):
await self.assert_query_result(
r"""
WITH JT3 := (SELECT JSONTest FILTER .number = 3)
SELECT JT3.data[4]['b']['bar'][2]['bingo'];
""",
['42!'],
['"42!"'],
)
await self.assert_query_result(
r"""
WITH JT3 := (SELECT JSONTest FILTER .number = 3)
SELECT JT3.data[4]['b']['bar'][-1]['bingo'];
""",
['42!'],
['"42!"'],
) | ,
['42!'],
['"42!"'],
)
await self.assert_query_result(
r | test_edgeql_json_accessor_13 | python | geldata/gel | tests/test_edgeql_json.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_json.py | Apache-2.0 |
async def test_edgeql_json_accessor_24(self):
async with self.assertRaisesRegexTx(
edgedb.InvalidValueError,
r'JSON index 10 is out of bounds'):
await self.con.query(r"""
select to_json('"hello"')[10];
""")
async with self.assertRaisesRegexTx(
edgedb.InvalidValueError,
r'JSON index -10 is out of bounds'):
await self.con.query(r"""
select to_json('"hello"')[-10];
""")
async with self.assertRaisesRegexTx(
edgedb.InvalidValueError,
r'JSON index 10 is out of bounds'):
await self.con.query(r"""
WITH
JT3 := (SELECT JSONTest FILTER .number = 3)
SELECT JT3.data[4]['c'][10];
""")
async with self.assertRaisesRegexTx(
edgedb.InvalidValueError,
r'JSON index -10 is out of bounds'):
await self.con.query(r"""
WITH
JT3 := (SELECT JSONTest FILTER .number = 3)
SELECT JT3.data[4]['c'][-10];
""") | )
async with self.assertRaisesRegexTx(
edgedb.InvalidValueError,
r'JSON index -10 is out of bounds'):
await self.con.query(r | test_edgeql_json_accessor_24 | python | geldata/gel | tests/test_edgeql_json.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_json.py | Apache-2.0 |
async def test_edgeql_json_null_01(self):
await self.assert_query_result(
r'''
SELECT (
SELECT JSONTest FILTER .number = 0
).data ?= <json>{};
''',
{False},
)
await self.assert_query_result(
r'''
SELECT (
SELECT JSONTest FILTER .number = 0
).data ?= to_json('null');
''',
{True},
)
await self.assert_query_result(
r'''
SELECT (
SELECT JSONTest FILTER .number = 2
).data ?= <json>{};
''',
{True},
)
await self.assert_query_result(
r'''
SELECT (
SELECT JSONTest FILTER .number = 2
).data ?= to_json('null');
''',
{False},
) | ,
{False},
)
await self.assert_query_result(
r | test_edgeql_json_null_01 | python | geldata/gel | tests/test_edgeql_json.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_json.py | Apache-2.0 |
async def test_edgeql_json_array_unpack_04(self):
await self.assert_query_result(
r'''
SELECT json_array_unpack(to_json('[2,3,4]')) IN
<json>{2, 3, 4};
''',
[True, True, True],
)
await self.assert_query_result(
r'''
SELECT json_array_unpack(to_json('[2,3,4]')) NOT IN
<json>{2, 3, 4};
''',
[False, False, False],
) | ,
[True, True, True],
)
await self.assert_query_result(
r | test_edgeql_json_array_unpack_04 | python | geldata/gel | tests/test_edgeql_json.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_json.py | Apache-2.0 |
async def test_edgeql_json_object_01(self):
await self.assert_query_result(
r'''
SELECT to_json('{"a":1,"b":2}') =
to_json('{"b":2,"a":1}');
''',
[True],
)
await self.assert_query_result(
r'''
SELECT to_json('{"a":1,"b":2}') =
to_json('{"b":3,"a":1,"b":2}');
''',
[True],
) | ,
[True],
)
await self.assert_query_result(
r | test_edgeql_json_object_01 | python | geldata/gel | tests/test_edgeql_json.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_json.py | Apache-2.0 |
async def test_edgeql_json_object_unpack_02(self):
await self.assert_query_result(
r'''
SELECT
_ := json_object_unpack(JSONTest.j_object)
ORDER BY _.0 THEN _.1;
''',
# JSON:
[['a', 1], ['b', 1], ['b', 2], ['c', 2]],
# Binary:
[['a', '1'], ['b', '1'], ['b', '2'], ['c', '2']],
)
await self.assert_query_result(
r'''
SELECT json_object_unpack(JSONTest.j_object) =
('c', to_json('1'));
''',
[False, False, False, False],
)
await self.assert_query_result(
r'''
SELECT json_object_unpack(JSONTest.j_object).0 IN
{'a', 'b', 'c'};
''',
[True, True, True, True],
)
await self.assert_query_result(
r'''
SELECT json_object_unpack(JSONTest.j_object).1 IN
<json>{1, 2};
''',
[True, True, True, True],
)
await self.assert_query_result(
r'''
SELECT json_object_unpack(JSONTest.j_object).1 IN
<json>{'1', '2'};
''',
[False, False, False, False],
) | ,
# JSON:
[['a', 1], ['b', 1], ['b', 2], ['c', 2]],
# Binary:
[['a', '1'], ['b', '1'], ['b', '2'], ['c', '2']],
)
await self.assert_query_result(
r | test_edgeql_json_object_unpack_02 | python | geldata/gel | tests/test_edgeql_json.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_json.py | Apache-2.0 |
async def test_edgeql_json_object_pack(self):
await self.assert_query_result(
r'''
select std::json_object_pack({
("foo", to_json("1")),
("bar", to_json("null")),
("baz", to_json("[]"))
})
''',
[{'bar': None, 'baz': [], 'foo': 1}],
['{"bar": null, "baz": [], "foo": 1}'],
)
await self.assert_query_result(
r"""
select std::json_object_pack(
<tuple<str, json>>{}
)
""",
[{}],
["{}"],
)
await self.assert_query_result(
r"""
select std::json_object_pack(
array_unpack([
('foo', <json>1),
('bar', <json>2),
('baz', <json>3)
])
)
""",
[{"bar": 2, "baz": 3, "foo": 1}],
['{"bar": 2, "baz": 3, "foo": 1}'],
) | ,
[{'bar': None, 'baz': [], 'foo': 1}],
['{"bar": null, "baz": [], "foo": 1}'],
)
await self.assert_query_result(
r | test_edgeql_json_object_pack | python | geldata/gel | tests/test_edgeql_json.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_json.py | Apache-2.0 |
async def test_edgeql_json_get_01(self):
await self.assert_query_result(
r'''
WITH JT3 := (SELECT JSONTest FILTER .number = 3)
SELECT json_get(JT3.data, '2');
''',
# JSON
{'Fraka'},
# Binary
{'"Fraka"'}
)
await self.assert_query_result(
r'''
WITH JT3 := (SELECT JSONTest FILTER .number = 3)
SELECT json_get(JT3.data, '-1');
''',
# JSON
{True},
# Binary
{"true"}
)
await self.assert_query_result(
r'''
WITH JT3 := (SELECT JSONTest FILTER .number = 3)
SELECT json_get(JT3.data, '100');
''',
[],
)
await self.assert_query_result(
r'''
WITH JT3 := (SELECT JSONTest FILTER .number = 3)
SELECT json_get(JT3.data, 'foo');
''',
[],
)
await self.assert_query_result(
r'''
WITH JT3 := (SELECT JSONTest FILTER .number = 3)
SELECT json_get(JT3.data, '0', 'b', 'bar', '2', 'bingo');
''',
[],
)
await self.assert_query_result(
r'''
WITH JT3 := (SELECT JSONTest FILTER .number = 3)
SELECT json_get(JT3.data, '1', 'b', 'bar', '2', 'bingo');
''',
[],
)
await self.assert_query_result(
r'''
WITH JT3 := (SELECT JSONTest FILTER .number = 3)
SELECT json_get(JT3.data, '2', 'b', 'bar', '2', 'bingo');
''',
[],
)
await self.assert_query_result(
r'''
WITH JT3 := (SELECT JSONTest FILTER .number = 3)
SELECT json_get(JT3.data, '3', 'b', 'bar', '2', 'bingo');
''',
[],
)
await self.assert_query_result(
r'''
WITH JT3 := (SELECT JSONTest FILTER .number = 3)
SELECT json_get(JT3.data, '4', 'b', 'bar', '2', 'bingo');
''',
# JSON
{'42!'},
# Binary
{'"42!"'}
)
await self.assert_query_result(
r'''
WITH JT3 := (SELECT JSONTest FILTER .number = 3)
SELECT json_get(JT3.data, '4', 'b', 'foo', '2', 'bingo');
''',
[]
) | ,
# JSON
{'Fraka'},
# Binary
{'"Fraka"'}
)
await self.assert_query_result(
r | test_edgeql_json_get_01 | python | geldata/gel | tests/test_edgeql_json.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_json.py | Apache-2.0 |
async def test_edgeql_json_get_02(self):
# since only one JSONTest has a non-trivial `data`, we
# don't need to filter to get the same results as above
await self.assert_query_result(
r'''SELECT json_get(JSONTest.data, '2');''',
{'Fraka'},
{'"Fraka"'},
)
await self.assert_query_result(
r'''SELECT json_get(JSONTest.data, '-1');''',
{True},
{'true'},
)
await self.assert_query_result(
r'''SELECT json_get(JSONTest.data, '100');''',
[],
)
await self.assert_query_result(
r'''SELECT json_get(JSONTest.data, 'foo');''',
[],
)
await self.assert_query_result(
r'''
SELECT json_get(JSONTest.data, '0', 'b', 'bar', '2', 'bingo');
''',
[],
)
await self.assert_query_result(
r'''
SELECT json_get(JSONTest.data, '1', 'b', 'bar', '2', 'bingo');
''',
[],
)
await self.assert_query_result(
r'''
SELECT json_get(JSONTest.data, '2', 'b', 'bar', '2', 'bingo');
''',
[],
)
await self.assert_query_result(
r'''
SELECT json_get(JSONTest.data, '3', 'b', 'bar', '2', 'bingo');
''',
[],
)
await self.assert_query_result(
r'''
SELECT json_get(JSONTest.data, '4', 'b', 'bar', '2', 'bingo');
''',
{'42!'},
{'"42!"'},
)
await self.assert_query_result(
r'''
SELECT json_get(JSONTest.data, '4', 'b', 'foo', '2', 'bingo');
''',
[]
) | ,
[],
)
await self.assert_query_result(
r | test_edgeql_json_get_02 | python | geldata/gel | tests/test_edgeql_json.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_json.py | Apache-2.0 |
async def test_edgeql_json_get_03(self):
# chaining json_get should get the same effect as a single call
await self.assert_query_result(
r'''
SELECT json_get(JSONTest.data, '4', 'b', 'bar', '2', 'bingo');
''',
{'42!'},
{'"42!"'},
)
await self.assert_query_result(
r'''
SELECT json_get(json_get(json_get(json_get(json_get(
JSONTest.data, '4'), 'b'), 'bar'), '2'), 'bingo');
''',
{'42!'},
{'"42!"'},
)
await self.assert_query_result(
r'''
SELECT json_get(json_get(
JSONTest.data, '4', 'b'), 'bar', '2', 'bingo');
''',
{'42!'},
{'"42!"'},
) | ,
{'42!'},
{'"42!"'},
)
await self.assert_query_result(
r | test_edgeql_json_get_03 | python | geldata/gel | tests/test_edgeql_json.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_json.py | Apache-2.0 |
async def test_edgeql_json_get_04(self):
await self.assert_query_result(
r'''SELECT json_get(JSONTest.data, 'bogus') ?? <json>'oups';''',
# JSON
['oups'],
# Binary
['"oups"'],
)
await self.assert_query_result(
r'''
SELECT json_get(
JSONTest.data, '4', 'b', 'bar', '2', 'bogus',
default := <json>'hello'
) ?? <json>'oups';
''',
['hello', 'hello', 'hello'],
['"hello"', '"hello"', '"hello"'],
)
await self.assert_query_result(
r'''
SELECT json_get(
JSONTest.data, '4', 'b', 'bar', '2', 'bogus',
default := <json>''
) ?? <json>'oups';
''',
['', '', ''],
['""', '""', '""'],
)
await self.assert_query_result(
r'''
SELECT json_get(
JSONTest.data, '4', 'b', 'bar', '2', 'bogus',
default := to_json('null')
) ?? <json>'oups';
''',
[None, None, None],
['null', 'null', 'null'],
)
await self.assert_query_result(
r'''
SELECT json_get(
JSONTest.data, '4', 'b', 'bar', '2', 'bogus',
default := <json>{}
) ?? <json>'oups';
''',
['oups'],
['"oups"'],
)
await self.assert_query_result(
r'''
SELECT json_get(
JSONTest.data, '4', 'b', 'bar', '2', 'bingo',
default := <json>''
) ?? <json>'oups';
''',
['', '', '42!'],
['""', '""', '"42!"'],
)
await self.assert_query_result(
r'''
SELECT json_get(
JSONTest.data, '4', 'b', 'bar', '2', 'bingo'
) ?? <json>'oups';
''',
['42!'],
['"42!"']
) | ,
['hello', 'hello', 'hello'],
['"hello"', '"hello"', '"hello"'],
)
await self.assert_query_result(
r | test_edgeql_json_get_04 | python | geldata/gel | tests/test_edgeql_json.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_json.py | Apache-2.0 |
async def test_edgeql_json_set_01(self):
await self.assert_query_result(
r'''
WITH JT0 := (SELECT JSONTest FILTER .number = 0)
SELECT json_set(JT0.j_object, 'a', value := <json>42);
''',
[{"a": 42, "b": 2}],
['{"a": 42, "b": 2}'],
)
# by default create_if_missing should create new value
await self.assert_query_result(
r'''
WITH JT0 := (SELECT JSONTest FILTER .number = 0)
SELECT json_set(JT0.j_object, 'c', value := <json>42);
''',
[{"a": 1, "b": 2, "c": 42}],
['{"a": 1, "b": 2, "c": 42}'],
)
# create_if_missing should also work inside of nested objects
# by variadic path
await self.assert_query_result(
r'''
WITH j_object := to_json('{"a": {"b": {}}}')
SELECT json_set(j_object, 'a', 'b', 'c', value := <json>42);
''',
[{"a": {"b": {"c": 42}}}],
['{"a": {"b": {"c": 42}}}'],
)
await self.assert_query_result(
r'''
WITH JT0 := (SELECT JSONTest FILTER .number = 0)
SELECT json_set(
JT0.j_object,
'c',
value := <json>42,
create_if_missing := false,
);
''',
[{"a": 1, "b": 2}],
['{"a": 1, "b": 2}'],
)
# by default empty_treatment should return empty set
await self.assert_query_result(
r'''
WITH JT0 := (SELECT JSONTest FILTER .number = 0)
SELECT json_set(JT0.j_object, 'a', value := <json>{});
''',
[],
[],
)
await self.assert_query_result(
r'''
WITH JT0 := (SELECT JSONTest FILTER .number = 0)
SELECT json_set(
JT0.j_object,
'a',
value := <json>{},
empty_treatment := JsonEmpty.ReturnEmpty,
);
''',
[],
[],
)
await self.assert_query_result(
r'''
WITH JT0 := (SELECT JSONTest FILTER .number = 0)
SELECT json_set(
JT0.j_object,
'a',
value := <json>{},
empty_treatment := JsonEmpty.ReturnTarget,
);
''',
[{"a": 1, "b": 2}],
['{"a": 1, "b": 2}'],
)
await self.assert_query_result(
r'''
WITH JT0 := (SELECT JSONTest FILTER .number = 0)
SELECT json_set(
JT0.j_object,
'a',
value := <json>{},
empty_treatment := JsonEmpty.UseNull,
);
''',
[{"a": None, "b": 2}],
['{"a": null, "b": 2}'],
)
await self.assert_query_result(
r'''
WITH JT0 := (SELECT JSONTest FILTER .number = 0)
SELECT json_set(
JT0.j_object,
'a',
value := <json>{},
empty_treatment := JsonEmpty.DeleteKey,
);
''',
[{"b": 2}],
['{"b": 2}'],
)
with self.assertRaisesRegex(
edgedb.InvalidValueError,
r"invalid empty JSON value"):
await self.con.execute(
r'''
WITH JT0 := (SELECT JSONTest FILTER .number = 0)
SELECT json_set(
JT0.j_object,
'a',
value := <json>{},
empty_treatment := JsonEmpty.Error,
);
''',
) | ,
[{"a": 42, "b": 2}],
['{"a": 42, "b": 2}'],
)
# by default create_if_missing should create new value
await self.assert_query_result(
r | test_edgeql_json_set_01 | python | geldata/gel | tests/test_edgeql_json.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_json.py | Apache-2.0 |
async def test_edgeql_json_cast_object_to_json_05(self):
await self.assert_query_result(
r"""
# base case
SELECT
JSONTest {number, edb_string};
""",
[
{'number': 0, 'edb_string': 'jumps'},
{'number': 1, 'edb_string': 'over'},
{'number': 2, 'edb_string': None},
{'number': 3, 'edb_string': None},
],
sort=lambda x: x['number'],
)
await self.assert_query_result(
r"""
SELECT
JSONTest {number, edb_string}
FILTER
# casting all the way to the original type with a
# strict `=` will discard objects with empty `edb_string`
.edb_string =
<str>(<json>(JSONTest{edb_string}))['edb_string'];
""",
[
{'number': 0, 'edb_string': 'jumps'},
{'number': 1, 'edb_string': 'over'},
],
sort=lambda x: x['number'],
)
await self.assert_query_result(
r"""
SELECT
JSONTest {number, edb_string}
FILTER
# strict `=` will discard objects with empty `edb_string`
<json>.edb_string =
(<json>(JSONTest{edb_string}))['edb_string'];
""",
[
{'number': 0, 'edb_string': 'jumps'},
{'number': 1, 'edb_string': 'over'},
],
sort=lambda x: x['number'],
)
await self.assert_query_result(
r"""
SELECT
JSONTest {number, edb_string}
FILTER
# casting all the way to the original type with a
# weak `?=` will not discard anything
.edb_string ?=
<str>(<json>(JSONTest{edb_string}))['edb_string'];
""",
[
{'number': 0, 'edb_string': 'jumps'},
{'number': 1, 'edb_string': 'over'},
{'number': 2, 'edb_string': None},
{'number': 3, 'edb_string': None},
],
sort=lambda x: x['number'],
)
await self.assert_query_result(
r"""
SELECT
JSONTest {number, edb_string}
FILTER
# casting both sides into json combined with a
# weak `?=` will discard objects with empty `edb_string`
<json>.edb_string ?=
(<json>(JSONTest{edb_string}))['edb_string'];
""",
[
{'number': 0, 'edb_string': 'jumps'},
{'number': 1, 'edb_string': 'over'},
],
sort=lambda x: x['number'],
) | ,
[
{'number': 0, 'edb_string': 'jumps'},
{'number': 1, 'edb_string': 'over'},
{'number': 2, 'edb_string': None},
{'number': 3, 'edb_string': None},
],
sort=lambda x: x['number'],
)
await self.assert_query_result(
r | test_edgeql_json_cast_object_to_json_05 | python | geldata/gel | tests/test_edgeql_json.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_json.py | Apache-2.0 |
async def test_edgeql_json_cast_object_to_json_07(self):
await self.con.execute('''
create function _get(idx: int64) -> set of json {
using (
select <json> (
select JSONTest {
number, edb_string
} filter .number = idx
)
)
};
''')
await self.assert_query_result(
r"""
SELECT _get(0)
""",
[
{'number': 0, 'edb_string': 'jumps'},
],
json_only=True,
) | )
await self.assert_query_result(
r | test_edgeql_json_cast_object_to_json_07 | python | geldata/gel | tests/test_edgeql_json.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_json.py | Apache-2.0 |
async def test_edgeql_json_slice_02(self):
await self.assert_query_result(
r'''
WITH JT2 := (SELECT JSONTest FILTER .number = 2)
SELECT JT2.j_array[:1];
''',
[[2]],
['[2]'],
)
await self.assert_query_result(
r'''
WITH JT2 := (SELECT JSONTest FILTER .number = 2)
SELECT JT2.j_array[:-1];
''',
[[2, "q", [3], {}]],
['[2, "q", [3], {}]'],
)
await self.assert_query_result(
r'''
WITH JT2 := (SELECT JSONTest FILTER .number = 2)
SELECT JT2.j_array[1:-1];
''',
[["q", [3], {}]],
['["q", [3], {}]'],
)
await self.assert_query_result(
r'''
WITH JT2 := (SELECT JSONTest FILTER .number = 2)
SELECT JT2.j_array[-1:1];
''',
[[]],
['[]'],
)
await self.assert_query_result(
r'''
WITH JT2 := (SELECT JSONTest FILTER .number = 2)
SELECT JT2.j_array[-100:100];
''',
[[2, "q", [3], {}, None]],
['[2, "q", [3], {}, null]'],
)
await self.assert_query_result(
r'''
WITH JT2 := (SELECT JSONTest FILTER .number = 2)
SELECT JT2.j_array[100:-100];
''',
[[]],
['[]'],
) | ,
[[2]],
['[2]'],
)
await self.assert_query_result(
r | test_edgeql_json_slice_02 | python | geldata/gel | tests/test_edgeql_json.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_json.py | Apache-2.0 |
async def test_edgeql_json_alias_01(self):
await self.assert_query_result(
r'''
SELECT _ := json_get(JSONTest.j_array, '0')
ORDER BY _;
''',
# JSON
[1, 2],
# Binary
['1', '2'],
)
await self.assert_query_result(
r'''
SELECT _ := json_get(JSONTest.j_array, '10')
ORDER BY _;
''',
[],
)
await self.assert_query_result(
r'''
SELECT _ := json_get(JSONTest.j_array, {'-1', '4'})
ORDER BY _;
''',
# JSON
[None, None, 1],
# Binary
['null', 'null', '1'],
)
await self.assert_query_result(
r'''
SELECT _ := json_get(
JSONTest.data,
# Each of the variadic "steps" is a set, so we should
# get a cross-product of all the possibilities. It so
# happens that the only 2 valid paths are:
# - '4', 'b', 'bar', '1' -> null
# - '4', 'b', 'bar', '2' -> {"bingo": "42!"}
{'2', '4', '4'}, {'0', 'b'}, {'bar', 'foo'}, {'1', '2'}
)
ORDER BY _;
''',
# JSON
[None, None, {'bingo': '42!'}, {'bingo': '42!'}],
# Binary
['null', 'null', '{"bingo": "42!"}', '{"bingo": "42!"}']
) | ,
# JSON
[1, 2],
# Binary
['1', '2'],
)
await self.assert_query_result(
r | test_edgeql_json_alias_01 | python | geldata/gel | tests/test_edgeql_json.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_json.py | Apache-2.0 |
async def test_edgeql_json_str_function_02(self):
async with self.assertRaisesRegexTx(
edgedb.InvalidValueError,
r"format 'foo' is invalid"):
async with self.con.transaction():
await self.con.query(r'''
SELECT to_str(<json>[1, 2, 3, 4], 'foo');
''')
async with self.assertRaisesRegexTx(
edgedb.InvalidValueError,
r'"fmt" argument must be a non-empty string'):
async with self.con.transaction():
await self.con.query_json(r'''
SELECT to_str(<json>[1, 2, 3, 4], '');
''')
async with self.assertRaisesRegexTx(
edgedb.InvalidValueError,
r"format 'PRETTY' is invalid"):
async with self.con.transaction():
await self.con.query(r'''
SELECT to_str(<json>[1, 2, 3, 4], 'PRETTY');
''')
async with self.assertRaisesRegexTx(
edgedb.InvalidValueError,
r"format 'Pretty' is invalid"):
async with self.con.transaction():
await self.con.query_json(r'''
SELECT to_str(<json>[1, 2, 3, 4], 'Pretty');
''')
async with self.assertRaisesRegexTx(
edgedb.InvalidValueError,
r"format 'p' is invalid"):
async with self.con.transaction():
await self.con.query(r'''
SELECT to_str(<json>[1, 2, 3, 4], 'p');
''') | )
async with self.assertRaisesRegexTx(
edgedb.InvalidValueError,
r'"fmt" argument must be a non-empty string'):
async with self.con.transaction():
await self.con.query_json(r | test_edgeql_json_str_function_02 | python | geldata/gel | tests/test_edgeql_json.py | https://github.com/geldata/gel/blob/master/tests/test_edgeql_json.py | Apache-2.0 |
async def _ensure_schema_integrity(self):
# check that all the type annotations are in place
await self.assert_query_result(
r'''
WITH MODULE schema
SELECT ObjectType {
name,
annotations: {
name,
@value,
} ORDER BY .name
}
FILTER
EXISTS .annotations
AND
.name LIKE 'default::%'
ORDER BY .name;
''',
[
{
'name': 'default::A',
'annotations': [
{
'name': 'std::title',
'@value': 'A',
},
],
},
{
'name': 'default::B',
'annotations': [
{
'name': 'std::title',
'@value': 'B',
},
],
},
{
'name': 'default::C',
'annotations': [
{
'name': 'std::title',
'@value': 'C',
},
],
},
{
'name': 'default::D',
'annotations': [
{
'name': 'default::heritable_user_anno',
'@value': 'all D',
},
{
'name': 'default::user_anno',
'@value': 'D only',
},
{
'name': 'std::title',
'@value': 'D',
},
],
},
{
'name': 'default::E',
'annotations': [
{
'name': 'default::heritable_user_anno',
'@value': 'all D',
},
{
'name': 'std::title',
'@value': 'E',
},
],
},
{
'name': 'default::F',
'annotations': [
{
'name': 'default::heritable_user_anno',
'@value': 'all D',
},
{
'name': 'std::title',
'@value': 'F',
},
],
},
]
)
# check that all the prop/link annotations are in place
await self.assert_query_result(
r'''
WITH MODULE schema
SELECT ObjectType {
name,
properties: {
name,
annotations: {
name,
@value,
},
} # keep only annotated props
FILTER EXISTS .annotations
ORDER BY .name,
links: {
name,
annotations: {
name,
@value,
},
} # keep only annotated links
FILTER EXISTS .annotations
ORDER BY .name,
}
FILTER
# keep only types with annotated pointers
EXISTS .pointers.annotations
AND
.name LIKE 'default::%'
ORDER BY .name;
''',
[
{
'name': 'default::A',
'properties': [
{
'name': 'p_bool',
'annotations': [
{
'name': 'std::title',
'@value': 'single bool',
},
],
},
],
'links': [],
},
{
'name': 'default::B',
'properties': [
{
'name': 'p_bool',
'annotations': [
{
'name': 'std::title',
'@value': 'multi bool',
},
],
},
],
'links': []
},
{
'name': 'default::C',
'properties': [
{
'name': 'val',
'annotations': [
{
'name': 'std::title',
'@value': 'val',
},
],
},
],
'links': []
},
{
'name': 'default::D',
'properties': [],
'links': [
{
'name': 'multi_link',
'annotations': [
{
'name': 'std::title',
'@value': 'multi link to C',
},
],
},
{
'name': 'single_link',
'annotations': [
{
'name': 'std::title',
'@value': 'single link to C',
},
],
},
]
}
]
)
# check that all link prop annotations are in place
await self.assert_query_result(
r'''
WITH MODULE schema
SELECT ObjectType {
name,
links: {
name,
properties: {
name,
annotations: {
name,
@value,
},
}
FILTER EXISTS .annotations
ORDER BY .name,
} # keep only links with user-annotated props
FILTER 'std::title' IN .properties.annotations.name
ORDER BY .name,
}
FILTER
.name = 'default::E'
ORDER BY .name;
''',
[
{
'name': 'default::E',
'links': [
{
'name': 'multi_link',
'properties': [
{
'name': 'lp1',
'annotations': [
{
'name': 'std::title',
'@value': 'single lp1',
},
],
},
]
},
{
'name': 'single_link',
'properties': [
{
'name': 'lp0',
'annotations': [
{
'name': 'std::title',
'@value': 'single lp0',
},
],
},
]
},
]
}
]
)
# check that all constraint annotations are in place
await self.assert_query_result(
r'''
WITH MODULE schema
SELECT ObjectType {
name,
properties: {
name,
constraints: {
name,
annotations: {
name,
@value,
},
},
}
ORDER BY .name,
}
FILTER
.name = 'default::C'
ORDER BY .name;
''',
[
{
'name': 'default::C',
'properties': [
{
'name': 'id',
'constraints': [{
'annotations': [],
}],
},
{
'name': 'val',
'constraints': [{
'annotations': [
{
'name': 'std::title',
'@value': 'exclusive C val',
},
],
}],
},
]
}
]
)
# check that all constraint annotations are in place
await self.assert_query_result(
r'''
WITH MODULE schema
SELECT `Constraint` {
name,
annotations: {
name,
@value,
},
errmessage,
expr,
}
FILTER
.abstract
AND
.name LIKE 'default::%'
ORDER BY .name;
''',
[
{
'name': 'default::user_int_constr',
'annotations': [
{
'name': 'std::title',
'@value': 'user_int_constraint constraint',
},
],
'errmessage': '{__subject__} must be greater than {x}',
'expr': '(__subject__ > x)',
},
]
)
# check that all function annotations are in place
await self.assert_query_result(
r'''
WITH MODULE schema
SELECT Function {
name,
annotations: {
name,
@value,
},
vol := <str>.volatility,
}
FILTER
EXISTS .annotations
AND
.name LIKE 'default::%'
ORDER BY .name;
''',
[
{
'name': 'default::user_func_0',
'annotations': [
{
'name': 'std::title',
'@value': 'user_func(int64) -> str',
},
],
'vol': 'Immutable',
},
]
)
# check that indexes are in place
await self.assert_query_result(
r'''
WITH MODULE schema
SELECT ObjectType {
name,
indexes: {
expr
},
}
FILTER
EXISTS .indexes
AND
.name LIKE 'default::%'
ORDER BY .name;
''',
[
{
'name': 'default::K',
'indexes': [{'expr': '.k'}],
},
{
'name': 'default::L',
'indexes': [{'expr': '(.l0 ++ .l1)'}],
}
]
)
# check the custom scalars
await self.assert_query_result(
r'''
WITH MODULE schema
SELECT ScalarType {
name,
ancestors: {
name,
} ORDER BY @index,
constraints: {
name,
params: {
name,
@value,
} FILTER .name != '__subject__',
},
}
FILTER
.name LIKE 'default::User%'
ORDER BY .name;
''',
[
{
'name': 'default::UserEnum',
'ancestors': [
{'name': 'std::anyenum'},
{'name': 'std::anyscalar'},
],
'constraints': [],
},
{
'name': 'default::UserInt',
'ancestors': [
{'name': 'std::int64'},
{'name': 'std::anyint'},
{'name': 'std::anyreal'},
{'name': 'std::anydiscrete'},
{'name': 'std::anypoint'},
{'name': 'std::anyscalar'},
],
'constraints': [
{
'name': 'default::user_int_constr',
'params': [{'name': 'x', '@value': '5'}],
},
],
},
{
'name': 'default::UserStr',
'ancestors': [
{'name': 'std::str'},
{'name': 'std::anyscalar'}
],
'constraints': [
{
'name': 'std::max_len_value',
'params': [{'name': 'max', '@value': '5'}],
},
],
},
]
)
# check the custom scalars
await self.assert_query_result(
r'''
WITH MODULE schema
SELECT ObjectType {
name,
properties: {
name,
constraints: {
name,
params: {
name,
@value,
} FILTER .name != '__subject__',
},
}
FILTER .name IN {'m0', 'm1'}
ORDER BY .name,
}
FILTER
.name = 'default::M';
''',
[
{
'name': 'default::M',
'properties': [
{
'name': 'm0',
'constraints': [
{
'name': 'default::user_int_constr',
'params': [{
'name': 'x',
'@value': '3'
}],
},
],
},
{
'name': 'm1',
'constraints': [
{
'name': 'std::max_len_value',
'params': [{
'name': 'max',
'@value': '3'
}],
},
],
}
],
},
]
)
# check the custom scalars
await self.assert_query_result(
r'''
WITH MODULE schema
SELECT ObjectType {
name,
properties: {
name,
target: {
name,
},
}
FILTER .name IN {'n0', 'n1'}
ORDER BY .name,
}
FILTER
.name = 'default::N';
''',
[
{
'name': 'default::N',
'properties': [
{
'name': 'n0',
'target': {'name': 'default::UserInt'},
},
{
'name': 'n1',
'target': {'name': 'default::UserStr'},
},
],
},
]
)
# check that the bases and ancestors order is preserved
await self.assert_query_result(
r'''
WITH MODULE schema
SELECT ObjectType {
name,
bases: {
name,
@index,
} ORDER BY @index,
ancestors: {
name,
@index,
} ORDER BY @index,
}
FILTER
.name = 'default::V';
''',
[
{
'name': 'default::V',
'bases': [
{'name': 'default::U', '@index': 0},
{'name': 'default::S', '@index': 1},
{'name': 'default::T', '@index': 2},
],
'ancestors': [
{'name': 'default::U', '@index': 0},
{'name': 'default::S', '@index': 1},
{'name': 'default::T', '@index': 2},
{'name': 'default::R', '@index': 3},
{'name': 'std::Object', '@index': 4},
{'name': 'std::BaseObject', '@index': 5},
],
}
]
)
# check delegated constraint
await self.assert_query_result(
r'''
WITH MODULE schema
SELECT ObjectType {
name,
properties: {
name,
constraints: {
name,
delegated,
},
} ORDER BY .name,
}
FILTER
.name = 'default::R'
OR
.name = 'default::S'
ORDER BY .name;
''',
[
{
'name': 'default::R',
'properties': [
{
'name': 'id',
'constraints': [
{
'name': 'std::exclusive',
'delegated': False,
}
],
},
{
'name': 'name',
'constraints': [
{
'name': 'std::exclusive',
'delegated': True,
}
],
},
],
},
{
'name': 'default::S',
'properties': [
{
'name': 'id',
'constraints': [
{
'name': 'std::exclusive',
'delegated': False,
}
],
},
{
'name': 'name',
'constraints': [
{
'name': 'std::exclusive',
'delegated': False,
}
],
},
{
'name': 's',
'constraints': [],
},
],
}
]
) | ,
[
{
'name': 'default::A',
'annotations': [
{
'name': 'std::title',
'@value': 'A',
},
],
},
{
'name': 'default::B',
'annotations': [
{
'name': 'std::title',
'@value': 'B',
},
],
},
{
'name': 'default::C',
'annotations': [
{
'name': 'std::title',
'@value': 'C',
},
],
},
{
'name': 'default::D',
'annotations': [
{
'name': 'default::heritable_user_anno',
'@value': 'all D',
},
{
'name': 'default::user_anno',
'@value': 'D only',
},
{
'name': 'std::title',
'@value': 'D',
},
],
},
{
'name': 'default::E',
'annotations': [
{
'name': 'default::heritable_user_anno',
'@value': 'all D',
},
{
'name': 'std::title',
'@value': 'E',
},
],
},
{
'name': 'default::F',
'annotations': [
{
'name': 'default::heritable_user_anno',
'@value': 'all D',
},
{
'name': 'std::title',
'@value': 'F',
},
],
},
]
)
# check that all the prop/link annotations are in place
await self.assert_query_result(
r | _ensure_schema_integrity | python | geldata/gel | tests/test_dump01.py | https://github.com/geldata/gel/blob/master/tests/test_dump01.py | Apache-2.0 |
async def _ensure_data_integrity(self):
# validate single props for all basic scalar types
await self.assert_query_result(
r'''
SELECT A {
p_bool,
p_str,
p_int16,
p_int32,
p_int64,
p_float32,
p_float64,
p_bigint,
p_decimal,
};
''',
[{
'p_bool': True,
'p_str': 'Hello',
'p_int16': 12345,
'p_int32': 1234567890,
'p_int64': 1234567890123,
'p_float32': 2.5,
'p_float64': 2.5,
'p_bigint': 123456789123456789123456789,
'p_decimal':
123456789123456789123456789.123456789123456789123456789,
}]
)
await self.assert_query_result(
r'''
SELECT (
<str>A.p_datetime,
<str>A.p_local_datetime,
<str>A.p_local_date,
<str>A.p_local_time,
<str>A.p_duration,
);
''',
[[
'2018-05-07T20:01:22.306916+00:00',
'2018-05-07T20:01:22.306916',
'2018-05-07',
'20:01:22.306916',
'PT20H',
]]
)
await self.assert_query_result(
r'''
SELECT A.p_json;
''',
[[{"a": None, "b": True}, 1, 2.5, "foo"]],
['[{"a": null, "b": true}, 1, 2.5, "foo"]'],
)
# validate multi props for all basic scalar types
await self.assert_query_result(
r'''
SELECT B {
p_bool,
p_str,
p_int16,
p_int32,
p_int64,
p_float32,
p_float64,
p_bigint,
p_decimal,
};
''',
[{
'p_bool': {True, False},
'p_str': {'Hello', 'world'},
'p_int16': {12345, -42},
'p_int32': {1234567890, -42},
'p_int64': {1234567890123, -42},
'p_float32': {2.5, -42},
'p_float64': {2.5, -42},
'p_bigint': {123456789123456789123456789, -42},
'p_decimal': {
123456789123456789123456789.123456789123456789123456789,
-42,
},
}]
)
await self.assert_query_result(
r'''
SELECT B {
str_datetime := <str>.p_datetime,
str_local_datetime := <str>.p_local_datetime,
str_local_date := <str>.p_local_date,
str_local_time := <str>.p_local_time,
str_duration := <str>.p_duration,
};
''',
[{
'str_datetime': {
'2018-05-07T20:01:22.306916+00:00',
'2019-05-07T20:01:22.306916+00:00',
},
'str_local_datetime': {
'2018-05-07T20:01:22.306916',
'2019-05-07T20:01:22.306916',
},
'str_local_date': {
'2018-05-07',
'2019-05-07',
},
'str_local_time': {
'20:01:22.306916',
'20:02:22.306916',
},
'str_duration': {
'PT20H',
'PT20S',
},
}]
)
await self.assert_query_result(
r'''
SELECT B.p_json
ORDER BY B.p_json;
''',
[
"bar",
False,
[{"a": None, "b": True}, 1, 2.5, "foo"],
],
[
'"bar"',
'false',
'[{"a": null, "b": true}, 1, 2.5, "foo"]',
],
)
# bytes don't play nice with being cast into other types, so
# we want to test them using binary fetch
self.assertEqual(
await self.con.query(r'SELECT A.p_bytes;'),
edgedb.Set((b'Hello',))
)
self.assertEqual(
await self.con.query(r'SELECT B.p_bytes ORDER BY B.p_bytes;'),
edgedb.Set((b'Hello', b'world'))
)
# validate the data for types used to test links
await self.assert_query_result(
r'''
SELECT C {val}
ORDER BY .val;
''',
[
{'val': 'D00'},
{'val': 'D01'},
{'val': 'D02'},
{'val': 'D03'},
{'val': 'E00'},
{'val': 'E01'},
{'val': 'E02'},
{'val': 'E03'},
{'val': 'F00'},
{'val': 'F01'},
{'val': 'F02'},
{'val': 'F03'},
],
)
await self.assert_query_result(
r'''
SELECT D {
num,
single_link: {
val,
},
multi_link: {
val,
} ORDER BY .val,
}
FILTER .__type__.name = 'default::D'
ORDER BY .num;
''',
[
{
'num': 0,
'single_link': None,
'multi_link': [],
},
{
'num': 1,
'single_link': {'val': 'D00'},
'multi_link': [],
},
{
'num': 2,
'single_link': None,
'multi_link': [
{'val': 'D01'}, {'val': 'D02'},
],
},
{
'num': 3,
'single_link': {'val': 'D00'},
'multi_link': [
{'val': 'D01'}, {'val': 'D02'}, {'val': 'D03'},
],
},
],
)
await self.assert_query_result(
r'''
SELECT E {
num,
single_link: {
val,
},
multi_link: {
val,
} ORDER BY .val,
}
ORDER BY .num;
''',
[
{
'num': 4,
'single_link': None,
'multi_link': [],
},
{
'num': 5,
'single_link': {'val': 'E00'},
'multi_link': [],
},
{
'num': 6,
'single_link': None,
'multi_link': [
{'val': 'E01'}, {'val': 'E02'},
],
},
{
'num': 7,
'single_link': {'val': 'E00'},
'multi_link': [
{'val': 'E01'}, {'val': 'E02'}, {'val': 'E03'},
],
},
],
)
await self.assert_query_result(
r'''
SELECT F {
num,
single_link: {
val,
},
multi_link: {
val,
} ORDER BY .val,
}
ORDER BY .num;
''',
[
{
'num': 8,
'single_link': {'val': 'F00'},
'multi_link': [
{'val': 'F01'}, {'val': 'F02'}, {'val': 'F03'},
],
},
],
)
# validate link prop values
await self.assert_query_result(
r'''
SELECT E {
num,
single_link: {
val,
@lp0,
},
multi_link: {
val,
@lp1,
} ORDER BY .val,
} ORDER BY .num;
''',
[
{
'num': 4,
'single_link': None,
'multi_link': [],
},
{
'num': 5,
'single_link': {
'val': 'E00',
'@lp0': None,
},
'multi_link': [],
},
{
'num': 6,
'single_link': None,
'multi_link': [
{
'val': 'E01',
'@lp1': None,
},
{
'val': 'E02',
'@lp1': None,
},
],
},
{
'num': 7,
'single_link': {
'val': 'E00',
'@lp0': 'E00',
},
'multi_link': [
{
'val': 'E01',
'@lp1': 'E01',
},
{
'val': 'E02',
'@lp1': 'E02',
},
{
'val': 'E03',
'@lp1': 'E03',
},
],
},
],
)
# validate existence of data for types with computables and defaults
await self.assert_query_result(
r'''
SELECT K {
k,
};
''',
[
{
'k': 'k0',
},
],
)
await self.assert_query_result(
r'''
SELECT L {
l0,
l1,
};
''',
[
{
'l0': 'l0_0',
'l1': 'l1_0',
},
],
)
# validate existence of data for indexed types
await self.assert_query_result(
r'''
SELECT G {g0, g1, g2};
''',
[
{'g0': 'fixed', 'g1': 'func1', 'g2': '2'},
],
)
await self.assert_query_result(
r'''
SELECT H {h0, h1, h2};
''',
[
{'h0': 'fixed', 'h1': 'func1', 'h2': '2'},
],
)
await self.assert_query_result(
r'''
SELECT I {
i0: {val},
i1: {val},
i2: {val},
};
''',
[
{
'i0': {'val': 'D00'},
'i1': {'val': 'D01'},
'i2': {'val': 'D02'},
}
],
)
await self.assert_query_result(
r'''
SELECT J {
j0: {val},
j1: {val},
j2: {val},
};
''',
[
{
'j0': {'val': 'D00'},
'j1': {'val': 'D01'},
'j2': {'val': 'D02'},
}
],
)
# validate existence of data for types with constraints
await self.assert_query_result(
r'''
SELECT M {
m0,
m1,
};
''',
[
{
'm0': 10,
'm1': 'm1',
},
],
)
await self.assert_query_result(
r'''
SELECT N {
n0,
n1,
};
''',
[
{
'n0': 10,
'n1': 'n1',
},
],
)
# validate user functions
await self.assert_query_result(
r'''
SELECT user_func_0(99);
''',
['func99'],
)
await self.assert_query_result(
r'''
SELECT user_func_1([1, 3, -88], '+');
''',
['1+3+-88'],
)
await self.assert_query_result(
r'''
SELECT user_func_2(<int64>{});
''',
{'x'},
)
await self.assert_query_result(
r'''
SELECT user_func_2(11);
''',
{'11', 'x'},
)
await self.assert_query_result(
r'''
SELECT user_func_2(22, 'a');
''',
{'22', 'a'},
)
# validate user enum
await self.assert_query_result(
r'''
WITH w := {'Lorem', 'ipsum', 'dolor', 'sit', 'amet'}
SELECT w
ORDER BY str_lower(w);
''',
['amet', 'dolor', 'ipsum', 'Lorem', 'sit'],
)
await self.assert_query_result(
r'''
WITH w := {'Lorem', 'ipsum', 'dolor', 'sit', 'amet'}
SELECT w
ORDER BY <UserEnum>w;
''',
# the enum ordering is not like str, but like the real phrase
['Lorem', 'ipsum', 'dolor', 'sit', 'amet'],
)
# validate user enum
await self.assert_query_result(
r'''
SELECT <str>{O.o0, O.o1, O.o2};
''',
{'ipsum', 'Lorem', 'dolor'},
)
await self.assert_query_result(
r'''
SELECT <str>(
SELECT _ := {O.o0, O.o1, O.o2}
ORDER BY _
);
''',
[
'Lorem', 'ipsum', 'dolor',
]
)
await self.assert_query_result(
r'''
SELECT {O.o0, O.o1, O.o2} IS UserEnum;
''',
[True, True, True],
)
# validate collection properties
await self.assert_query_result(
r'''
SELECT P {
plink0: {val, @p0},
plink1: {val, @p1},
p2,
p3,
};
''',
[
{
'plink0': {'val': 'E00', '@p0': ['hello', 'world']},
'plink1': {'val': 'E00', '@p1': [2.5, -4.25]},
'p2': ['hello', 'world'],
'p3': [2.5, -4.25]
}
],
)
await self.assert_query_result(
r'''
SELECT Q {q0, q1, q2, q3};
''',
[
{
'q0': [2, False],
'q1': ['p3', 3.33],
'q2': {'x': 2, 'y': False},
'q3': {'x': 'p11', 'y': 3.33},
}
],
)
# validate multiple inheritance
await self.assert_query_result(
r'''
SELECT S {name, s}
ORDER BY .name;
''',
[
{'name': 'name0', 's': 's0'},
{'name': 'name1', 's': 's1'},
],
)
await self.assert_query_result(
r'''
SELECT T {name, t}
ORDER BY .name;
''',
[
{'name': 'name0', 't': 't0'},
{'name': 'name1', 't': 't1'},
],
)
await self.assert_query_result(
r'''
SELECT V {name, s, t, u};
''',
[
{
'name': 'name1',
's': 's1',
't': 't1',
'u': 'u1',
},
],
)
# validate aliases
await self.assert_query_result(
r'''
SELECT Primes;
''',
{2, 3, 5, 7},
)
await self.assert_query_result(
r'''
SELECT AliasP {
name,
plink0: {val, @p0},
plink1: {val, @p1},
p2,
p3,
f: {
num,
single_link: {val},
multi_link: {val} ORDER BY .val,
k: {k},
},
};
''',
[
{
'name': 'alias P',
'plink0': {'val': 'E00', '@p0': ['hello', 'world']},
'plink1': {'val': 'E00', '@p1': [2.5, -4.25]},
'p2': ['hello', 'world', '!'],
'p3': [2.5, -4.25],
'f': [
{
'num': 8,
'single_link': {'val': 'F00'},
'multi_link': [
{'val': 'F01'},
{'val': 'F02'},
{'val': 'F03'},
],
'k': {'k': 'k0'},
},
],
}
],
)
# validate self/mutually-referencing types
await self.assert_query_result(
r'''
SELECT W {
name,
w: {
name
}
}
ORDER BY .name;
''',
[
{'name': 'w0', 'w': None},
{'name': 'w1', 'w': {'name': 'w2'}},
{'name': 'w2', 'w': None},
{'name': 'w3', 'w': {'name': 'w4'}},
{'name': 'w4', 'w': {'name': 'w3'}},
],
)
# validate self/mutually-referencing types
await self.assert_query_result(
r'''
SELECT X {
name,
y: {
name,
x: {
name
}
}
}
ORDER BY .name;
''',
[
{
'name': 'x0',
'y': {
'name': 'y0',
'x': {
'name': 'x0',
},
},
},
],
)
# validate self/mutually-referencing types
await self.assert_query_result(
r'''
SELECT Z {
ck: {
typename := .__type__.name,
},
stw: {
name,
typename := .__type__.name,
} ORDER BY .typename,
}
ORDER BY .ck.typename;
''',
[
{
'ck': {'typename': 'default::C'},
'stw': [
{'name': 'name0', 'typename': 'default::S'}
],
},
{
'ck': {'typename': 'default::K'},
'stw': [
{'name': 'name0', 'typename': 'default::S'},
{'name': 'name0', 'typename': 'default::T'},
{'name': 'w1', 'typename': 'default::W'},
],
},
],
)
# validate cross module types
await self.assert_query_result(
r'''
SELECT DefA {a};
''',
[
{
'a': 'DefA',
},
],
)
await self.assert_query_result(
r'''
SELECT DefB {
name,
other: {
b,
blink: {
a
}
}
};
''',
[
{
'name': 'test0',
'other': {
'b': 'TestB',
'blink': {
'a': 'DefA',
},
},
},
],
)
await self.assert_query_result(
r'''
SELECT DefC {
name,
other: {
c,
clink: {
name
}
}
};
''',
[
{
'name': 'test1',
'other': {
'c': 'TestC',
'clink': {
'name': 'test1',
},
},
},
],
)
# validate on delete settings
await self.assert_query_result(
r'''
SELECT SourceA {
name,
link1: {
name,
},
}
FILTER .name = 's1';
''',
[
{
'name': 's1',
'link1': {
'name': 't1',
},
},
],
)
await self.con.execute(r'DELETE TargetA FILTER .name = "t1"')
await self.assert_query_result(
r'''
SELECT SourceA {name}
FILTER .name = 's1';
''',
[],
)
# validate on delete settings
await self.assert_query_result(
r'''
SELECT SourceA {
name,
link2: {
name,
},
}
FILTER .name = 's2';
''',
[
{
'name': 's2',
'link2': {
'name': 't2',
},
},
],
)
await self.con.execute(r'DELETE TargetA FILTER .name = "t2"')
await self.assert_query_result(
r'''
SELECT SourceA {
name,
link2: {
name,
},
}
FILTER .name = 's2';
''',
[
{
'name': 's2',
'link2': None,
},
],
)
# validate on delete settings
await self.assert_query_result(
r'''
SELECT SourceA {
name,
link0: {
name,
},
}
FILTER .name = 's0';
''',
[
{
'name': 's0',
'link0': {
'name': 't0',
},
},
],
)
with self.assertRaisesRegex(
edgedb.ConstraintViolationError,
r'prohibited by link target policy'):
async with self.con.transaction():
await self.con.execute(r'DELETE TargetA FILTER .name = "t0"')
# validate constraints
with self.assertRaisesRegex(
edgedb.ConstraintViolationError,
r'must be greater than 5'):
async with self.con.transaction():
await self.con.execute(r'SELECT <UserInt>1;')
# validate constraints
with self.assertRaisesRegex(
edgedb.ConstraintViolationError,
r'must be no longer than 5 characters'):
async with self.con.transaction():
await self.con.execute(r'SELECT <UserStr>"qwerty";')
# validate constraints
with self.assertRaisesRegex(
edgedb.ConstraintViolationError,
r'must be greater than 3'):
async with self.con.transaction():
await self.con.execute(r"INSERT M {m0 := 1, m1 := '1'};")
# validate constraints
with self.assertRaisesRegex(
edgedb.ConstraintViolationError,
r'must be no longer than 3 characters'):
async with self.con.transaction():
await self.con.execute(r"INSERT M {m0 := 4, m1 := '12345'};")
# validate constraints
with self.assertRaisesRegex(
edgedb.ConstraintViolationError,
r'name violates exclusivity constraint'):
async with self.con.transaction():
await self.con.execute(r"INSERT W {name := 'w0'};")
# validate constraints
with self.assertRaisesRegex(
edgedb.MissingRequiredError,
r'missing value for required property'):
async with self.con.transaction():
await self.con.execute(r"INSERT C;")
# validate constraints
with self.assertRaisesRegex(
edgedb.MissingRequiredError,
r'missing value for required link'):
async with self.con.transaction():
await self.con.execute(r"INSERT F {num := 999};")
# validate read-only
await self.assert_query_result(
r'''
SELECT ROPropsA {
name,
rop0,
rop1,
}
ORDER BY .name;
''',
[
{
'name': 'ro0',
'rop0': None,
'rop1': int,
},
{
'name': 'ro1',
'rop0': 100,
'rop1': int,
},
{
'name': 'ro2',
'rop0': None,
'rop1': -2,
},
],
)
# validate read-only
with self.assertRaisesRegex(
edgedb.QueryError,
r'rop0.*read-only'):
async with self.con.transaction():
await self.con.execute(
r'''
UPDATE ROPropsA
SET {
rop0 := 99,
};
''')
# validate read-only
with self.assertRaisesRegex(
edgedb.QueryError,
r'rop1.*read-only'):
async with self.con.transaction():
await self.con.execute(
r'''
UPDATE ROPropsA
SET {
rop1 := 99,
};
''')
# validate read-only
await self.assert_query_result(
r'''
SELECT ROLinksA {
name,
rol0: {val},
rol1: {val},
rol2: {val} ORDER BY .val,
}
ORDER BY .name;
''',
[
{
'name': 'ro0',
'rol0': None,
'rol1': {'val': 'D00'},
'rol2': [{'val': 'D01'}, {'val': 'D02'}]
},
{
'name': 'ro1',
'rol0': {'val': 'F00'},
'rol1': {'val': 'D00'},
'rol2': [{'val': 'D01'}, {'val': 'D02'}],
},
{
'name': 'ro2',
'rol0': None,
'rol1': {'val': 'F00'},
'rol2': [{'val': 'D01'}, {'val': 'D02'}]
},
{
'name': 'ro3',
'rol0': None,
'rol1': {'val': 'D00'},
'rol2': [{'val': 'F01'}, {'val': 'F02'}]
},
],
)
# validate read-only
with self.assertRaisesRegex(
edgedb.QueryError,
r'rol0.*read-only'):
async with self.con.transaction():
await self.con.execute(
r'''
UPDATE ROLinksA
SET {
rol0 := <C>{},
};
''')
# validate read-only
with self.assertRaisesRegex(
edgedb.QueryError,
r'rol1.*read-only'):
async with self.con.transaction():
await self.con.execute(
r'''
UPDATE ROLinksA
SET {
rol1 := <C>{},
};
''')
# validate read-only
with self.assertRaisesRegex(
edgedb.QueryError,
r'rol2.*read-only'):
async with self.con.transaction():
await self.con.execute(
r'''
UPDATE ROLinksA
SET {
rol2 := <C>{},
};
''')
# validate read-only
await self.assert_query_result(
r'''
SELECT ROLinksB {
name,
rol0: {val, @rolp00, @rolp01},
rol1: {val, @rolp10, @rolp11} ORDER BY .val,
}
ORDER BY .name;
''',
[
{
'name': 'ro0',
'rol0': {'val': 'D00', '@rolp00': None, '@rolp01': int},
'rol1': [
{'val': 'D01', '@rolp10': None, '@rolp11': int},
{'val': 'D02', '@rolp10': None, '@rolp11': int},
],
},
{
'name': 'ro1',
'rol0': {'val': 'D00', '@rolp00': 99, '@rolp01': int},
'rol1': [
{'val': 'D01', '@rolp10': 99, '@rolp11': int},
{'val': 'D02', '@rolp10': 98, '@rolp11': int},
],
},
{
'name': 'ro2',
'rol0': {'val': 'E00', '@rolp00': None, '@rolp01': -10},
'rol1': [
{'val': 'E01', '@rolp10': None, '@rolp11': -1},
{'val': 'E02', '@rolp10': None, '@rolp11': -2},
],
},
],
)
"""XXX: uncomment the below once direct link property updates are
implemented
# validate read-only
with self.assertRaisesRegex(
edgedb.QueryError,
r'rolp00.*read-only'):
async with self.con.transaction():
await self.con.execute(
r'''
UPDATE ROLinksB
SET {
rol0: {@rolp00 := 1},
};
''')
# validate read-only
with self.assertRaisesRegex(
edgedb.QueryError,
r'rolp01.*read-only'):
async with self.con.transaction():
await self.con.execute(
r'''
UPDATE ROLinksB
SET {
rol0: {@rolp01 := 1},
};
''')
# validate read-only
with self.assertRaisesRegex(
edgedb.QueryError,
r'rolp10.*read-only'):
async with self.con.transaction():
await self.con.execute(
r'''
UPDATE ROLinksB
SET {
rol1: {@rolp10 := 1},
};
''')
# validate read-only
with self.assertRaisesRegex(
edgedb.QueryError,
r'rolp11.*read-only'):
async with self.con.transaction():
await self.con.execute(
r'''
UPDATE ROLinksB
SET {
rol1: {@rolp11 := 1},
};
''')
""" | ,
[{
'p_bool': True,
'p_str': 'Hello',
'p_int16': 12345,
'p_int32': 1234567890,
'p_int64': 1234567890123,
'p_float32': 2.5,
'p_float64': 2.5,
'p_bigint': 123456789123456789123456789,
'p_decimal':
123456789123456789123456789.123456789123456789123456789,
}]
)
await self.assert_query_result(
r | _ensure_data_integrity | python | geldata/gel | tests/test_dump01.py | https://github.com/geldata/gel/blob/master/tests/test_dump01.py | Apache-2.0 |
def get_setup_script(cls):
res = super().get_setup_script()
import os.path
# HACK: As a debugging cycle hack, when RELOAD is true, we reload the
# extension package from the file, so we can test without a bootstrap.
RELOAD = False
if RELOAD:
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
with open(os.path.join(root, 'edb/lib/ext/auth.edgeql')) as f:
contents = f.read()
to_add = (
'''
drop extension package auth version '1.0';
create extension auth;
'''
+ contents
)
splice = '__internal_testmode := true;'
res = res.replace(splice, splice + to_add)
return res | drop extension package auth version '1.0';
create extension auth; | get_setup_script | python | geldata/gel | tests/test_http_ext_auth.py | https://github.com/geldata/gel/blob/master/tests/test_http_ext_auth.py | Apache-2.0 |
def http_con_send_request(self, *args, headers=None, **kwargs):
"""Inject a test header.
It's recognized by the server when explicitly run in the test mode.
http_con_request() calls this method.
"""
test_port = HTTP_TEST_PORT.get(None)
if test_port is not None:
if headers is None:
headers = {}
headers['x-edgedb-oauth-test-server'] = test_port
return super().http_con_send_request(*args, headers=headers, **kwargs) | Inject a test header.
It's recognized by the server when explicitly run in the test mode.
http_con_request() calls this method. | http_con_send_request | python | geldata/gel | tests/test_http_ext_auth.py | https://github.com/geldata/gel/blob/master/tests/test_http_ext_auth.py | Apache-2.0 |
async def test_http_auth_ext_github_authorize_01(self):
with self.http_con() as http_con:
provider_config = await self.get_builtin_provider_config_by_name(
"oauth_github"
)
provider_name = provider_config.name
client_id = provider_config.client_id
redirect_to = f"{self.http_addr}/some/path"
callback_url = f"{self.http_addr}/some/callback/url"
challenge = (
base64.urlsafe_b64encode(
hashlib.sha256(
base64.urlsafe_b64encode(os.urandom(43)).rstrip(b'=')
).digest()
)
.rstrip(b'=')
.decode()
)
query = {
"provider": provider_name,
"redirect_to": redirect_to,
"challenge": challenge,
"callback_url": callback_url,
}
_, headers, status = self.http_con_request(
http_con,
query,
path="authorize",
)
self.assertEqual(status, 302)
location = headers.get("location")
assert location is not None
url = urllib.parse.urlparse(location)
qs = urllib.parse.parse_qs(url.query, keep_blank_values=True)
self.assertEqual(url.scheme, "https")
self.assertEqual(url.hostname, "github.com")
self.assertEqual(url.path, "/login/oauth/authorize")
self.assertEqual(qs.get("scope"), ["read:user user:email "])
state = qs.get("state")
assert state is not None
claims = auth_jwt.OAuthStateToken.verify(
state[0], self.signing_key()
)
self.assertEqual(claims.provider, provider_name)
self.assertEqual(claims.redirect_to, redirect_to)
self.assertEqual(
qs.get("redirect_uri"), [callback_url]
)
self.assertEqual(qs.get("client_id"), [client_id])
pkce = await self.con.query(
"""
select ext::auth::PKCEChallenge
filter .challenge = <str>$challenge
""",
challenge=challenge,
)
self.assertEqual(len(pkce), 1)
_, _, repeat_status = self.http_con_request(
http_con,
query,
path="authorize",
)
self.assertEqual(repeat_status, 302)
repeat_pkce = await self.con.query_single(
"""
select ext::auth::PKCEChallenge
filter .challenge = <str>$challenge
""",
challenge=challenge,
)
self.assertEqual(pkce[0].id, repeat_pkce.id) | select ext::auth::PKCEChallenge
filter .challenge = <str>$challenge
""",
challenge=challenge,
)
self.assertEqual(len(pkce), 1)
_, _, repeat_status = self.http_con_request(
http_con,
query,
path="authorize",
)
self.assertEqual(repeat_status, 302)
repeat_pkce = await self.con.query_single( | test_http_auth_ext_github_authorize_01 | python | geldata/gel | tests/test_http_ext_auth.py | https://github.com/geldata/gel/blob/master/tests/test_http_ext_auth.py | Apache-2.0 |
async def test_http_auth_ext_github_callback_01(self):
with self.http_con() as http_con:
provider_config = await self.get_builtin_provider_config_by_name(
"oauth_github"
)
provider_name = provider_config.name
client_id = provider_config.client_id
client_secret = GITHUB_SECRET
now = utcnow()
token_request = (
"POST",
"https://github.com",
"login/oauth/access_token",
)
self.mock_oauth_server.register_route_handler(*token_request)(
(
json.dumps(
{
"access_token": "github_access_token",
"scope": "read:user",
"token_type": "bearer",
}
),
200,
)
)
user_request = ("GET", "https://api.github.com", "user")
self.mock_oauth_server.register_route_handler(*user_request)(
(
json.dumps(
{
"id": 1,
"login": "octocat",
"name": "monalisa octocat",
"email": "[email protected]",
"avatar_url": "https://example.com/example.jpg",
"updated_at": now.isoformat(),
}
),
200,
)
)
challenge = (
base64.urlsafe_b64encode(
hashlib.sha256(
base64.urlsafe_b64encode(os.urandom(43)).rstrip(b'=')
).digest()
)
.rstrip(b'=')
.decode()
)
await self.con.query(
"""
insert ext::auth::PKCEChallenge {
challenge := <str>$challenge,
}
""",
challenge=challenge,
)
state_claims = auth_jwt.OAuthStateToken(
provider=provider_name,
redirect_to=f"{self.http_addr}/some/path",
challenge=challenge,
)
state_token = state_claims.sign(self.signing_key())
data, headers, status = self.http_con_request(
http_con,
{"state": state_token, "code": "abc123"},
path="callback",
)
self.assertEqual(data, b"")
self.assertEqual(status, 302)
location = headers.get("location")
assert location is not None
server_url = urllib.parse.urlparse(self.http_addr)
url = urllib.parse.urlparse(location)
self.assertEqual(url.scheme, server_url.scheme)
self.assertEqual(url.hostname, server_url.hostname)
self.assertEqual(url.path, f"{server_url.path}/some/path")
requests_for_token = self.mock_oauth_server.requests[token_request]
self.assertEqual(len(requests_for_token), 1)
body = requests_for_token[0].body
assert body is not None
self.assertEqual(
json.loads(body),
{
"grant_type": "authorization_code",
"code": "abc123",
"client_id": client_id,
"client_secret": client_secret,
"redirect_uri": f"{self.http_addr}/callback",
},
)
requests_for_user = self.mock_oauth_server.requests[user_request]
self.assertEqual(len(requests_for_user), 1)
self.assertEqual(
requests_for_user[0].headers["authorization"],
"Bearer github_access_token",
)
identity = await self.con.query(
"""
SELECT ext::auth::Identity
FILTER .subject = '1'
AND .issuer = 'https://github.com'
"""
)
self.assertEqual(len(identity), 1)
pkce_object = await self.con.query(
"""
SELECT ext::auth::PKCEChallenge
{ id, auth_token, refresh_token }
filter .identity.id = <uuid>$identity_id
""",
identity_id=identity[0].id,
)
self.assertEqual(len(pkce_object), 1)
self.assertEqual(pkce_object[0].auth_token, "github_access_token")
self.assertIsNone(pkce_object[0].refresh_token)
self.mock_oauth_server.register_route_handler(*user_request)(
(
json.dumps(
{
"id": 1,
"login": "octocat",
"name": "monalisa octocat",
"email": "[email protected]",
"avatar_url": "https://example.com/example.jpg",
"updated_at": now.isoformat(),
}
),
200,
)
)
self.http_con_request(
http_con,
{"state": state_token, "code": "abc123"},
path="callback",
)
same_identity = await self.con.query(
"""
SELECT ext::auth::Identity
FILTER .subject = '1'
AND .issuer = 'https://github.com'
"""
)
self.assertEqual(len(same_identity), 1)
self.assertEqual(identity[0].id, same_identity[0].id) | insert ext::auth::PKCEChallenge {
challenge := <str>$challenge,
}
""",
challenge=challenge,
)
state_claims = auth_jwt.OAuthStateToken(
provider=provider_name,
redirect_to=f"{self.http_addr}/some/path",
challenge=challenge,
)
state_token = state_claims.sign(self.signing_key())
data, headers, status = self.http_con_request(
http_con,
{"state": state_token, "code": "abc123"},
path="callback",
)
self.assertEqual(data, b"")
self.assertEqual(status, 302)
location = headers.get("location")
assert location is not None
server_url = urllib.parse.urlparse(self.http_addr)
url = urllib.parse.urlparse(location)
self.assertEqual(url.scheme, server_url.scheme)
self.assertEqual(url.hostname, server_url.hostname)
self.assertEqual(url.path, f"{server_url.path}/some/path")
requests_for_token = self.mock_oauth_server.requests[token_request]
self.assertEqual(len(requests_for_token), 1)
body = requests_for_token[0].body
assert body is not None
self.assertEqual(
json.loads(body),
{
"grant_type": "authorization_code",
"code": "abc123",
"client_id": client_id,
"client_secret": client_secret,
"redirect_uri": f"{self.http_addr}/callback",
},
)
requests_for_user = self.mock_oauth_server.requests[user_request]
self.assertEqual(len(requests_for_user), 1)
self.assertEqual(
requests_for_user[0].headers["authorization"],
"Bearer github_access_token",
)
identity = await self.con.query( | test_http_auth_ext_github_callback_01 | python | geldata/gel | tests/test_http_ext_auth.py | https://github.com/geldata/gel/blob/master/tests/test_http_ext_auth.py | Apache-2.0 |
async def test_http_auth_ext_discord_authorize_01(self):
with self.http_con() as http_con:
provider_config = await self.get_builtin_provider_config_by_name(
"oauth_discord"
)
provider_name = provider_config.name
client_id = provider_config.client_id
redirect_to = f"{self.http_addr}/some/path"
challenge = (
base64.urlsafe_b64encode(
hashlib.sha256(
base64.urlsafe_b64encode(os.urandom(43)).rstrip(b'=')
).digest()
)
.rstrip(b'=')
.decode()
)
query = {
"provider": provider_name,
"redirect_to": redirect_to,
"code_challenge": challenge,
}
_, headers, status = self.http_con_request(
http_con,
query,
path="authorize",
)
self.assertEqual(status, 302)
location = headers.get("location")
assert location is not None
url = urllib.parse.urlparse(location)
qs = urllib.parse.parse_qs(url.query, keep_blank_values=True)
self.assertEqual(url.scheme, "https")
self.assertEqual(url.hostname, "discord.com")
self.assertEqual(url.path, "/oauth2/authorize")
self.assertEqual(qs.get("scope"), ["email identify "])
state = qs.get("state")
assert state is not None
claims = auth_jwt.OAuthStateToken.verify(
state[0], self.signing_key()
)
self.assertEqual(claims.provider, provider_name)
self.assertEqual(claims.redirect_to, redirect_to)
self.assertEqual(
qs.get("redirect_uri"), [f"{self.http_addr}/callback"]
)
self.assertEqual(qs.get("client_id"), [client_id])
pkce = await self.con.query(
"""
select ext::auth::PKCEChallenge
filter .challenge = <str>$challenge
""",
challenge=challenge,
)
self.assertEqual(len(pkce), 1)
_, _, repeat_status = self.http_con_request(
http_con,
query,
path="authorize",
)
self.assertEqual(repeat_status, 302)
repeat_pkce = await self.con.query_single(
"""
select ext::auth::PKCEChallenge
filter .challenge = <str>$challenge
""",
challenge=challenge,
)
self.assertEqual(pkce[0].id, repeat_pkce.id) | select ext::auth::PKCEChallenge
filter .challenge = <str>$challenge
""",
challenge=challenge,
)
self.assertEqual(len(pkce), 1)
_, _, repeat_status = self.http_con_request(
http_con,
query,
path="authorize",
)
self.assertEqual(repeat_status, 302)
repeat_pkce = await self.con.query_single( | test_http_auth_ext_discord_authorize_01 | python | geldata/gel | tests/test_http_ext_auth.py | https://github.com/geldata/gel/blob/master/tests/test_http_ext_auth.py | Apache-2.0 |
async def test_http_auth_ext_discord_callback_01(self):
with self.http_con() as http_con:
provider_config = await self.get_builtin_provider_config_by_name(
"oauth_discord"
)
provider_name = provider_config.name
client_id = provider_config.client_id
client_secret = DISCORD_SECRET
now = utcnow()
token_request = (
"POST",
"https://discord.com",
"api/oauth2/token",
)
self.mock_oauth_server.register_route_handler(*token_request)(
(
json.dumps(
{
"access_token": "discord_access_token",
"scope": "read:user",
"token_type": "bearer",
}
),
200,
)
)
user_request = ("GET", "https://discord.com", "api/v10/users/@me")
self.mock_oauth_server.register_route_handler(*user_request)(
(
json.dumps(
{
"id": 1,
"username": "dischord",
"global_name": "Ian MacKaye",
"email": "[email protected]",
"picture": "https://example.com/example.jpg",
}
),
200,
)
)
challenge = (
base64.urlsafe_b64encode(
hashlib.sha256(
base64.urlsafe_b64encode(os.urandom(43)).rstrip(b'=')
).digest()
)
.rstrip(b'=')
.decode()
)
await self.con.query(
"""
insert ext::auth::PKCEChallenge {
challenge := <str>$challenge,
}
""",
challenge=challenge,
)
state_claims = auth_jwt.OAuthStateToken(
provider=provider_name,
redirect_to=f"{self.http_addr}/some/path",
challenge=challenge,
)
state_token = state_claims.sign(self.signing_key())
data, headers, status = self.http_con_request(
http_con,
{"state": state_token, "code": "abc123"},
path="callback",
)
self.assertEqual(data, b"")
self.assertEqual(status, 302)
location = headers.get("location")
assert location is not None
server_url = urllib.parse.urlparse(self.http_addr)
url = urllib.parse.urlparse(location)
self.assertEqual(url.scheme, server_url.scheme)
self.assertEqual(url.hostname, server_url.hostname)
self.assertEqual(url.path, f"{server_url.path}/some/path")
requests_for_token = self.mock_oauth_server.requests[token_request]
self.assertEqual(len(requests_for_token), 1)
self.assertEqual(
urllib.parse.parse_qs(requests_for_token[0].body),
{
"grant_type": ["authorization_code"],
"code": ["abc123"],
"client_id": [client_id],
"client_secret": [client_secret],
"redirect_uri": [f"{self.http_addr}/callback"],
},
)
requests_for_user = self.mock_oauth_server.requests[user_request]
self.assertEqual(len(requests_for_user), 1)
self.assertEqual(
requests_for_user[0].headers["authorization"],
"Bearer discord_access_token",
)
identity = await self.con.query(
"""
SELECT ext::auth::Identity
FILTER .subject = '1'
AND .issuer = 'https://discord.com'
"""
)
self.assertEqual(len(identity), 1)
pkce_object = await self.con.query(
"""
SELECT ext::auth::PKCEChallenge
{ id, auth_token, refresh_token }
filter .identity.id = <uuid>$identity_id
""",
identity_id=identity[0].id,
)
self.assertEqual(len(pkce_object), 1)
self.assertEqual(pkce_object[0].auth_token, "discord_access_token")
self.assertIsNone(pkce_object[0].refresh_token)
self.mock_oauth_server.register_route_handler(*user_request)(
(
json.dumps(
{
"id": 1,
"login": "octocat",
"name": "monalisa octocat",
"email": "[email protected]",
"avatar_url": "https://example.com/example.jpg",
"updated_at": now.isoformat(),
}
),
200,
)
)
self.http_con_request(
http_con,
{"state": state_token, "code": "abc123"},
path="callback",
)
same_identity = await self.con.query(
"""
SELECT ext::auth::Identity
FILTER .subject = '1'
AND .issuer = 'https://discord.com'
"""
)
self.assertEqual(len(same_identity), 1)
self.assertEqual(identity[0].id, same_identity[0].id) | insert ext::auth::PKCEChallenge {
challenge := <str>$challenge,
}
""",
challenge=challenge,
)
state_claims = auth_jwt.OAuthStateToken(
provider=provider_name,
redirect_to=f"{self.http_addr}/some/path",
challenge=challenge,
)
state_token = state_claims.sign(self.signing_key())
data, headers, status = self.http_con_request(
http_con,
{"state": state_token, "code": "abc123"},
path="callback",
)
self.assertEqual(data, b"")
self.assertEqual(status, 302)
location = headers.get("location")
assert location is not None
server_url = urllib.parse.urlparse(self.http_addr)
url = urllib.parse.urlparse(location)
self.assertEqual(url.scheme, server_url.scheme)
self.assertEqual(url.hostname, server_url.hostname)
self.assertEqual(url.path, f"{server_url.path}/some/path")
requests_for_token = self.mock_oauth_server.requests[token_request]
self.assertEqual(len(requests_for_token), 1)
self.assertEqual(
urllib.parse.parse_qs(requests_for_token[0].body),
{
"grant_type": ["authorization_code"],
"code": ["abc123"],
"client_id": [client_id],
"client_secret": [client_secret],
"redirect_uri": [f"{self.http_addr}/callback"],
},
)
requests_for_user = self.mock_oauth_server.requests[user_request]
self.assertEqual(len(requests_for_user), 1)
self.assertEqual(
requests_for_user[0].headers["authorization"],
"Bearer discord_access_token",
)
identity = await self.con.query( | test_http_auth_ext_discord_callback_01 | python | geldata/gel | tests/test_http_ext_auth.py | https://github.com/geldata/gel/blob/master/tests/test_http_ext_auth.py | Apache-2.0 |
async def test_http_auth_ext_google_callback_01(self) -> None:
with self.http_con() as http_con:
provider_config = await self.get_builtin_provider_config_by_name(
"oauth_google"
)
provider_name = provider_config.name
client_id = provider_config.client_id
client_secret = GOOGLE_SECRET
discovery_request = (
"GET",
"https://accounts.google.com",
".well-known/openid-configuration",
)
self.mock_oauth_server.register_route_handler(*discovery_request)(
(
json.dumps(GOOGLE_DISCOVERY_DOCUMENT),
200,
{"cache-control": "max-age=3600"},
)
)
token_request = self.generate_and_serve_jwk(
client_id,
"https://www.googleapis.com/oauth2/v3/certs",
"https://oauth2.googleapis.com/token",
"https://accounts.google.com",
"google_access_token",
)
challenge = (
base64.urlsafe_b64encode(
hashlib.sha256(
base64.urlsafe_b64encode(os.urandom(43)).rstrip(b'=')
).digest()
)
.rstrip(b'=')
.decode()
)
await self.con.query(
"""
insert ext::auth::PKCEChallenge {
challenge := <str>$challenge,
}
""",
challenge=challenge,
)
state_claims = auth_jwt.OAuthStateToken(
provider=provider_name,
redirect_to=f"{self.http_addr}/some/path",
challenge=challenge,
)
state_token = state_claims.sign(self.signing_key())
data, headers, status = self.http_con_request(
http_con,
{"state": state_token, "code": "abc123"},
path="callback",
)
self.assertEqual(data, b"")
self.assertEqual(status, 302)
location = headers.get("location")
assert location is not None
server_url = urllib.parse.urlparse(self.http_addr)
url = urllib.parse.urlparse(location)
self.assertEqual(url.scheme, server_url.scheme)
self.assertEqual(url.hostname, server_url.hostname)
self.assertEqual(url.path, f"{server_url.path}/some/path")
requests_for_discovery = self.mock_oauth_server.requests[
discovery_request
]
self.assertEqual(len(requests_for_discovery), 1)
requests_for_token = self.mock_oauth_server.requests[token_request]
self.assertEqual(len(requests_for_token), 1)
self.assertEqual(
urllib.parse.parse_qs(requests_for_token[0].body),
{
"grant_type": ["authorization_code"],
"code": ["abc123"],
"client_id": [client_id],
"client_secret": [client_secret],
"redirect_uri": [f"{self.http_addr}/callback"],
},
)
identity = await self.con.query(
"""
SELECT ext::auth::Identity
FILTER .subject = '1'
AND .issuer = 'https://accounts.google.com'
"""
)
self.assertEqual(len(identity), 1) | insert ext::auth::PKCEChallenge {
challenge := <str>$challenge,
}
""",
challenge=challenge,
)
state_claims = auth_jwt.OAuthStateToken(
provider=provider_name,
redirect_to=f"{self.http_addr}/some/path",
challenge=challenge,
)
state_token = state_claims.sign(self.signing_key())
data, headers, status = self.http_con_request(
http_con,
{"state": state_token, "code": "abc123"},
path="callback",
)
self.assertEqual(data, b"")
self.assertEqual(status, 302)
location = headers.get("location")
assert location is not None
server_url = urllib.parse.urlparse(self.http_addr)
url = urllib.parse.urlparse(location)
self.assertEqual(url.scheme, server_url.scheme)
self.assertEqual(url.hostname, server_url.hostname)
self.assertEqual(url.path, f"{server_url.path}/some/path")
requests_for_discovery = self.mock_oauth_server.requests[
discovery_request
]
self.assertEqual(len(requests_for_discovery), 1)
requests_for_token = self.mock_oauth_server.requests[token_request]
self.assertEqual(len(requests_for_token), 1)
self.assertEqual(
urllib.parse.parse_qs(requests_for_token[0].body),
{
"grant_type": ["authorization_code"],
"code": ["abc123"],
"client_id": [client_id],
"client_secret": [client_secret],
"redirect_uri": [f"{self.http_addr}/callback"],
},
)
identity = await self.con.query( | test_http_auth_ext_google_callback_01 | python | geldata/gel | tests/test_http_ext_auth.py | https://github.com/geldata/gel/blob/master/tests/test_http_ext_auth.py | Apache-2.0 |
async def test_http_auth_ext_slack_callback_01(self) -> None:
with self.http_con() as http_con:
provider_config = await self.get_builtin_provider_config_by_name(
"oauth_slack"
)
provider_name = provider_config.name
client_id = provider_config.client_id
client_secret = SLACK_SECRET
discovery_request = (
"GET",
"https://slack.com",
".well-known/openid-configuration",
)
self.mock_oauth_server.register_route_handler(*discovery_request)(
(
json.dumps(SLACK_DISCOVERY_DOCUMENT),
200,
{"cache-control": "max-age=3600"},
)
)
token_request = self.generate_and_serve_jwk(
client_id,
"https://slack.com/openid/connect/keys",
"https://slack.com/api/openid.connect.token",
"https://slack.com",
"slack_access_token",
)
challenge = (
base64.urlsafe_b64encode(
hashlib.sha256(
base64.urlsafe_b64encode(os.urandom(43)).rstrip(b'=')
).digest()
)
.rstrip(b'=')
.decode()
)
await self.con.query(
"""
insert ext::auth::PKCEChallenge {
challenge := <str>$challenge,
}
""",
challenge=challenge,
)
state_claims = auth_jwt.OAuthStateToken(
provider=provider_name,
redirect_to=f"{self.http_addr}/some/path",
challenge=challenge,
)
state_token = state_claims.sign(self.signing_key())
data, headers, status = self.http_con_request(
http_con,
{"state": state_token, "code": "abc123"},
path="callback",
)
self.assertEqual(data, b"")
self.assertEqual(status, 302)
location = headers.get("location")
assert location is not None
server_url = urllib.parse.urlparse(self.http_addr)
url = urllib.parse.urlparse(location)
self.assertEqual(url.scheme, server_url.scheme)
self.assertEqual(url.hostname, server_url.hostname)
self.assertEqual(url.path, f"{server_url.path}/some/path")
requests_for_discovery = self.mock_oauth_server.requests[
discovery_request
]
self.assertEqual(len(requests_for_discovery), 1)
requests_for_token = self.mock_oauth_server.requests[token_request]
self.assertEqual(len(requests_for_token), 1)
self.assertEqual(
urllib.parse.parse_qs(requests_for_token[0].body),
{
"grant_type": ["authorization_code"],
"code": ["abc123"],
"client_id": [client_id],
"client_secret": [client_secret],
"redirect_uri": [f"{self.http_addr}/callback"],
},
)
identity = await self.con.query(
"""
SELECT ext::auth::Identity
FILTER .subject = '1'
AND .issuer = 'https://slack.com'
"""
)
self.assertEqual(len(identity), 1) | insert ext::auth::PKCEChallenge {
challenge := <str>$challenge,
}
""",
challenge=challenge,
)
state_claims = auth_jwt.OAuthStateToken(
provider=provider_name,
redirect_to=f"{self.http_addr}/some/path",
challenge=challenge,
)
state_token = state_claims.sign(self.signing_key())
data, headers, status = self.http_con_request(
http_con,
{"state": state_token, "code": "abc123"},
path="callback",
)
self.assertEqual(data, b"")
self.assertEqual(status, 302)
location = headers.get("location")
assert location is not None
server_url = urllib.parse.urlparse(self.http_addr)
url = urllib.parse.urlparse(location)
self.assertEqual(url.scheme, server_url.scheme)
self.assertEqual(url.hostname, server_url.hostname)
self.assertEqual(url.path, f"{server_url.path}/some/path")
requests_for_discovery = self.mock_oauth_server.requests[
discovery_request
]
self.assertEqual(len(requests_for_discovery), 1)
requests_for_token = self.mock_oauth_server.requests[token_request]
self.assertEqual(len(requests_for_token), 1)
self.assertEqual(
urllib.parse.parse_qs(requests_for_token[0].body),
{
"grant_type": ["authorization_code"],
"code": ["abc123"],
"client_id": [client_id],
"client_secret": [client_secret],
"redirect_uri": [f"{self.http_addr}/callback"],
},
)
identity = await self.con.query( | test_http_auth_ext_slack_callback_01 | python | geldata/gel | tests/test_http_ext_auth.py | https://github.com/geldata/gel/blob/master/tests/test_http_ext_auth.py | Apache-2.0 |
async def test_http_auth_ext_generic_oidc_callback_01(self):
with self.http_con() as http_con:
provider_config = await self.get_provider_config_by_name(
"generic_oidc"
)
provider_name = provider_config.name
client_id = provider_config.client_id
client_secret = GENERIC_OIDC_SECRET
discovery_request = (
"GET",
"https://example.com",
".well-known/openid-configuration",
)
self.mock_oauth_server.register_route_handler(*discovery_request)(
(
json.dumps(GENERIC_OIDC_DISCOVERY_DOCUMENT),
200,
{"cache-control": "max-age=3600"},
)
)
token_request = self.generate_and_serve_jwk(
client_id,
"https://example.com/jwks",
"https://example.com/token",
"https://example.com",
"oidc_access_token",
)
challenge = (
base64.urlsafe_b64encode(
hashlib.sha256(
base64.urlsafe_b64encode(os.urandom(43)).rstrip(b'=')
).digest()
)
.rstrip(b'=')
.decode()
)
await self.con.query(
"""
insert ext::auth::PKCEChallenge {
challenge := <str>$challenge,
}
""",
challenge=challenge,
)
state_claims = auth_jwt.OAuthStateToken(
provider=provider_name,
redirect_to=f"{self.http_addr}/some/path",
challenge=challenge,
)
state_token = state_claims.sign(self.signing_key())
data, headers, status = self.http_con_request(
http_con,
{"state": state_token, "code": "abc123"},
path="callback",
)
self.assertEqual(data, b"")
self.assertEqual(status, 302)
location = headers.get("location")
assert location is not None
server_url = urllib.parse.urlparse(self.http_addr)
url = urllib.parse.urlparse(location)
self.assertEqual(url.scheme, server_url.scheme)
self.assertEqual(url.hostname, server_url.hostname)
self.assertEqual(url.path, f"{server_url.path}/some/path")
requests_for_discovery = self.mock_oauth_server.requests[
discovery_request
]
self.assertEqual(len(requests_for_discovery), 1)
requests_for_token = self.mock_oauth_server.requests[token_request]
self.assertEqual(len(requests_for_token), 1)
self.assertEqual(
urllib.parse.parse_qs(requests_for_token[0].body),
{
"grant_type": ["authorization_code"],
"code": ["abc123"],
"client_id": [client_id],
"client_secret": [client_secret],
"redirect_uri": [f"{self.http_addr}/callback"],
},
)
identity = await self.con.query(
"""
SELECT ext::auth::Identity
FILTER .subject = '1'
AND .issuer = 'https://example.com'
"""
)
self.assertEqual(len(identity), 1) | insert ext::auth::PKCEChallenge {
challenge := <str>$challenge,
}
""",
challenge=challenge,
)
state_claims = auth_jwt.OAuthStateToken(
provider=provider_name,
redirect_to=f"{self.http_addr}/some/path",
challenge=challenge,
)
state_token = state_claims.sign(self.signing_key())
data, headers, status = self.http_con_request(
http_con,
{"state": state_token, "code": "abc123"},
path="callback",
)
self.assertEqual(data, b"")
self.assertEqual(status, 302)
location = headers.get("location")
assert location is not None
server_url = urllib.parse.urlparse(self.http_addr)
url = urllib.parse.urlparse(location)
self.assertEqual(url.scheme, server_url.scheme)
self.assertEqual(url.hostname, server_url.hostname)
self.assertEqual(url.path, f"{server_url.path}/some/path")
requests_for_discovery = self.mock_oauth_server.requests[
discovery_request
]
self.assertEqual(len(requests_for_discovery), 1)
requests_for_token = self.mock_oauth_server.requests[token_request]
self.assertEqual(len(requests_for_token), 1)
self.assertEqual(
urllib.parse.parse_qs(requests_for_token[0].body),
{
"grant_type": ["authorization_code"],
"code": ["abc123"],
"client_id": [client_id],
"client_secret": [client_secret],
"redirect_uri": [f"{self.http_addr}/callback"],
},
)
identity = await self.con.query( | test_http_auth_ext_generic_oidc_callback_01 | python | geldata/gel | tests/test_http_ext_auth.py | https://github.com/geldata/gel/blob/master/tests/test_http_ext_auth.py | Apache-2.0 |
async def test_http_auth_ext_local_password_register_form_01(self):
base_url = self.mock_net_server.get_base_url().rstrip("/")
url = f"{base_url}/webhook-01"
alt_url = f"{base_url}/webhook-03"
await self.con.query(
"""
CONFIGURE CURRENT DATABASE
INSERT ext::auth::WebhookConfig {
url := <str>$url,
events := {
ext::auth::WebhookEvent.IdentityCreated,
ext::auth::WebhookEvent.EmailFactorCreated,
ext::auth::WebhookEvent.EmailVerificationRequested,
},
};
""",
url=url,
)
await self.con.query(
"""
CONFIGURE CURRENT DATABASE
INSERT ext::auth::WebhookConfig {
url := <str>$alt_url,
events := {
ext::auth::WebhookEvent.IdentityCreated,
},
};
""",
alt_url=alt_url,
)
webhook_request = (
"POST",
base_url,
"/webhook-01",
)
alt_webhook_request = (
"POST",
base_url,
"/webhook-03",
)
await self._wait_for_db_config("ext::auth::AuthConfig::webhooks")
try:
with self.http_con() as http_con:
self.mock_net_server.register_route_handler(*webhook_request)(
(
"",
204,
)
)
self.mock_net_server.register_route_handler(
*alt_webhook_request
)(
(
"",
204,
)
)
provider_config = (
await self.get_builtin_provider_config_by_name(
"local_emailpassword"
)
)
provider_name = provider_config.name
email = f"{uuid.uuid4()}@example.com"
form_data = {
"provider": provider_name,
"email": email,
"password": "test_password",
"redirect_to": "https://oauth.example.com/app/path",
"challenge": str(uuid.uuid4()),
}
form_data_encoded = urllib.parse.urlencode(form_data).encode()
_, headers, status = self.http_con_request(
http_con,
None,
path="register",
method="POST",
body=form_data_encoded,
headers={
"Content-Type": "application/x-www-form-urlencoded"
},
)
identity = await self.con.query(
"""
SELECT ext::auth::LocalIdentity
FILTER .<identity[is ext::auth::EmailPasswordFactor]
.email = <str>$email;
""",
email=email,
)
self.assertEqual(len(identity), 1)
pkce_challenge = await self.con.query_required_single(
"""
SELECT ext::auth::PKCEChallenge { * }
FILTER .challenge = <str>$challenge
AND .identity.id = <uuid>$identity_id;
""",
challenge=form_data["challenge"],
identity_id=identity[0].id,
)
self.assertEqual(status, 302)
location = headers.get("location")
assert location is not None
parsed_location = urllib.parse.urlparse(location)
parsed_query = urllib.parse.parse_qs(parsed_location.query)
self.assertEqual(parsed_location.scheme, "https")
self.assertEqual(parsed_location.netloc, "oauth.example.com")
self.assertEqual(parsed_location.path, "/app/path")
self.assertEqual(
parsed_query,
{
"code": [str(pkce_challenge.id)],
"provider": ["builtin::local_emailpassword"],
},
)
password_credential = await self.con.query(
"""
SELECT ext::auth::EmailPasswordFactor { password_hash }
FILTER .identity.id = <uuid>$identity
""",
identity=identity[0].id,
)
self.assertTrue(
ph.verify(
password_credential[0].password_hash, "test_password"
)
)
# Test Webhook side effect
async for tr in self.try_until_succeeds(
delay=2, timeout=120, ignore=(KeyError, AssertionError)
):
async with tr:
requests_for_webhook = self.mock_net_server.requests[
webhook_request
]
self.assertEqual(len(requests_for_webhook), 3)
event_types: dict[str, dict | None] = {
"IdentityCreated": None,
"EmailFactorCreated": None,
"EmailVerificationRequested": None,
}
for request in requests_for_webhook:
assert request.body is not None
event_data = json.loads(request.body)
event_type = event_data["event_type"]
self.assertIn(event_type, event_types)
self.assertEqual(
event_data["identity_id"], str(identity[0].id)
)
event_types[event_type] = event_data
self.assertTrue(
all(value is not None for value in event_types.values())
)
self.assertIn(
"verification_token",
cast(dict, event_types["EmailVerificationRequested"]),
)
# Test for alt_url webhook
async for tr in self.try_until_succeeds(
delay=2, timeout=120, ignore=(KeyError, AssertionError)
):
async with tr:
requests_for_alt_webhook = (
self.mock_net_server.requests[alt_webhook_request]
)
self.assertEqual(len(requests_for_alt_webhook), 1)
# Try to register the same user again (no redirect_to)
_, _, conflict_status = self.http_con_request(
http_con,
None,
path="register",
method="POST",
body=urllib.parse.urlencode(
{
**{
k: v
for k, v in form_data.items()
if k != 'redirect_to'
},
"challenge": str(uuid.uuid4()),
}
).encode(),
headers={
"Content-Type": "application/x-www-form-urlencoded"
},
)
self.assertEqual(conflict_status, 409)
# Try to register the same user again (no redirect_on_failure)
_, redirect_to_headers, redirect_to_status = (
self.http_con_request(
http_con,
None,
path="register",
method="POST",
body=urllib.parse.urlencode(
{
**form_data,
"challenge": str(uuid.uuid4()),
}
).encode(),
headers={
"Content-Type": "application/x-www-form-urlencoded"
},
)
)
self.assertEqual(redirect_to_status, 302)
location = redirect_to_headers.get("location")
assert location is not None
parsed_location = urllib.parse.urlparse(location)
parsed_query = urllib.parse.parse_qs(parsed_location.query)
self.assertEqual(
urllib.parse.urlunparse(
(
parsed_location.scheme,
parsed_location.netloc,
parsed_location.path,
'',
'',
'',
)
),
form_data["redirect_to"],
)
self.assertEqual(
parsed_query.get("error"),
["This user has already been registered"],
)
# Try to register the same user again (with redirect_on_failure)
redirect_on_failure_url = (
"https://example.com/app/path/different"
)
(
_,
redirect_on_failure_headers,
redirect_on_failure_status,
) = self.http_con_request(
http_con,
None,
path="register",
method="POST",
body=urllib.parse.urlencode(
{
**form_data,
"redirect_on_failure": redirect_on_failure_url,
"challenge": str(uuid.uuid4()),
}
).encode(),
headers={
"Content-Type": "application/x-www-form-urlencoded"
},
)
self.assertEqual(redirect_on_failure_status, 302)
location = redirect_on_failure_headers.get("location")
assert location is not None
parsed_location = urllib.parse.urlparse(location)
parsed_query = urllib.parse.parse_qs(parsed_location.query)
self.assertEqual(
urllib.parse.urlunparse(
(
parsed_location.scheme,
parsed_location.netloc,
parsed_location.path,
'',
'',
'',
)
),
redirect_on_failure_url,
)
self.assertEqual(
parsed_query.get("error"),
["This user has already been registered"],
)
finally:
await self.con.query(
"""
CONFIGURE CURRENT DATABASE
RESET ext::auth::WebhookConfig
filter .url in {<str>$url, <str>$alt_url};
""",
url=url,
alt_url=alt_url,
) | CONFIGURE CURRENT DATABASE
INSERT ext::auth::WebhookConfig {
url := <str>$url,
events := {
ext::auth::WebhookEvent.IdentityCreated,
ext::auth::WebhookEvent.EmailFactorCreated,
ext::auth::WebhookEvent.EmailVerificationRequested,
},
};
""",
url=url,
)
await self.con.query( | test_http_auth_ext_local_password_register_form_01 | python | geldata/gel | tests/test_http_ext_auth.py | https://github.com/geldata/gel/blob/master/tests/test_http_ext_auth.py | Apache-2.0 |
async def test_http_auth_ext_local_password_register_form_no_smtp(self):
await self.con.query(
"""
CONFIGURE CURRENT DATABASE RESET
current_email_provider_name;
""",
)
await self._wait_for_db_config(
"cfg::current_email_provider_name", is_reset=True
)
try:
with self.http_con() as http_con:
email = f"{uuid.uuid4()}@example.com"
form_data = {
"provider": "builtin::local_emailpassword",
"email": email,
"password": "test_password",
"challenge": str(uuid.uuid4()),
}
form_data_encoded = urllib.parse.urlencode(form_data).encode()
_, _, status = self.http_con_request(
http_con,
None,
path="register",
method="POST",
body=form_data_encoded,
headers={
"Content-Type": "application/x-www-form-urlencoded"
},
)
self.assertEqual(status, 201)
finally:
await self.con.query(
"""
CONFIGURE CURRENT DATABASE SET
current_email_provider_name := "email_hosting_is_easy";
""",
) | CONFIGURE CURRENT DATABASE RESET
current_email_provider_name;
""",
)
await self._wait_for_db_config(
"cfg::current_email_provider_name", is_reset=True
)
try:
with self.http_con() as http_con:
email = f"{uuid.uuid4()}@example.com"
form_data = {
"provider": "builtin::local_emailpassword",
"email": email,
"password": "test_password",
"challenge": str(uuid.uuid4()),
}
form_data_encoded = urllib.parse.urlencode(form_data).encode()
_, _, status = self.http_con_request(
http_con,
None,
path="register",
method="POST",
body=form_data_encoded,
headers={
"Content-Type": "application/x-www-form-urlencoded"
},
)
self.assertEqual(status, 201)
finally:
await self.con.query( | test_http_auth_ext_local_password_register_form_no_smtp | python | geldata/gel | tests/test_http_ext_auth.py | https://github.com/geldata/gel/blob/master/tests/test_http_ext_auth.py | Apache-2.0 |
async def test_http_auth_ext_local_password_register_json_02(self):
with self.http_con() as http_con:
provider_name = "builtin::local_emailpassword"
email = f"{uuid.uuid4()}@example.com"
json_data = {
"provider": provider_name,
"email": email,
"password": "test_password2",
"challenge": str(uuid.uuid4()),
}
json_data_encoded = json.dumps(json_data).encode()
body, _headers, status = self.http_con_request(
http_con,
None,
path="register",
method="POST",
body=json_data_encoded,
headers={"Content-Type": "application/json"},
)
self.assertEqual(status, 201, body)
identity = await self.con.query_single(
"""
with module ext::auth
select assert_single((
select LocalIdentity
filter .<identity[is EmailPasswordFactor]
.email = <str>$email
))
""",
email=email,
)
pkce_challenge = await self.con.query_single(
"""
SELECT ext::auth::PKCEChallenge { * }
FILTER .challenge = <str>$challenge
AND .identity.id = <uuid>$identity_id
""",
challenge=json_data["challenge"],
identity_id=identity.id,
)
self.assertEqual(
json.loads(body),
{
"code": str(pkce_challenge.id),
"provider": "builtin::local_emailpassword",
},
)
password_credential = await self.con.query(
"""
SELECT ext::auth::EmailPasswordFactor { password_hash }
FILTER .identity.id = <uuid>$identity
""",
identity=identity.id,
)
self.assertTrue(
ph.verify(
password_credential[0].password_hash, "test_password2"
)
) | with module ext::auth
select assert_single((
select LocalIdentity
filter .<identity[is EmailPasswordFactor]
.email = <str>$email
))
""",
email=email,
)
pkce_challenge = await self.con.query_single( | test_http_auth_ext_local_password_register_json_02 | python | geldata/gel | tests/test_http_ext_auth.py | https://github.com/geldata/gel/blob/master/tests/test_http_ext_auth.py | Apache-2.0 |
async def test_http_auth_ext_local_password_authenticate_01(self):
with self.http_con() as http_con:
provider_config = await self.get_builtin_provider_config_by_name(
"local_emailpassword"
)
provider_name = provider_config.name
email = f"{uuid.uuid4()}@example.com"
# Register a new user
form_data = {
"provider": provider_name,
"email": email,
"password": "test_auth_password",
"challenge": str(uuid.uuid4()),
}
form_data_encoded = urllib.parse.urlencode(form_data).encode()
self.http_con_request(
http_con,
None,
path="register",
method="POST",
body=form_data_encoded,
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
auth_data = {
"provider": form_data["provider"],
"email": form_data["email"],
"password": form_data["password"],
"challenge": str(uuid.uuid4()),
}
auth_data_encoded = urllib.parse.urlencode(auth_data).encode()
body, _headers, status = self.http_con_request(
http_con,
None,
path="authenticate",
method="POST",
body=auth_data_encoded,
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
self.assertEqual(status, 200)
identity = await self.con.query(
"""
SELECT ext::auth::LocalIdentity
FILTER .<identity[is ext::auth::EmailPasswordFactor]
.email = <str>$email;
""",
email=email,
)
self.assertEqual(len(identity), 1)
pkce_challenge = await self.con.query_single(
"""
SELECT ext::auth::PKCEChallenge { * }
FILTER .challenge = <str>$challenge
AND .identity.id = <uuid>$identity_id
""",
challenge=auth_data["challenge"],
identity_id=identity[0].id,
)
self.assertEqual(
json.loads(body),
{
"code": str(pkce_challenge.id),
},
)
# Attempt to authenticate with wrong password
auth_data_wrong_password = {
"provider": form_data["provider"],
"email": form_data["email"],
"password": "wrong_password",
"challenge": str(uuid.uuid4()),
}
auth_data_encoded_wrong_password = urllib.parse.urlencode(
auth_data_wrong_password
).encode()
_, _, wrong_password_status = self.http_con_request(
http_con,
None,
path="authenticate",
method="POST",
body=auth_data_encoded_wrong_password,
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
self.assertEqual(wrong_password_status, 403)
# Attempt to authenticate with a random email
random_email = f"{uuid.uuid4()}@example.com"
auth_data_random_handle = {
"provider": form_data["provider"],
"email": random_email,
"password": form_data["password"],
"challenge": str(uuid.uuid4()),
}
auth_data_encoded_random_handle = urllib.parse.urlencode(
auth_data_random_handle
).encode()
_, _, wrong_handle_status = self.http_con_request(
http_con,
None,
path="authenticate",
method="POST",
body=auth_data_encoded_random_handle,
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
self.assertEqual(wrong_handle_status, 403)
# Attempt to authenticate with a random email (redirect flow)
auth_data_redirect_to = {
"provider": form_data["provider"],
"email": random_email,
"password": form_data["password"],
"redirect_to": "https://example.com/app/some/path",
"challenge": str(uuid.uuid4()),
}
auth_data_encoded_redirect_to = urllib.parse.urlencode(
auth_data_redirect_to
).encode()
_, redirect_to_headers, redirect_to_status = self.http_con_request(
http_con,
None,
path="authenticate",
method="POST",
body=auth_data_encoded_redirect_to,
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
self.assertEqual(redirect_to_status, 302)
location = redirect_to_headers.get("location")
assert location is not None
parsed_location = urllib.parse.urlparse(location)
parsed_query = urllib.parse.parse_qs(parsed_location.query)
self.assertEqual(
urllib.parse.urlunparse(
(
parsed_location.scheme,
parsed_location.netloc,
parsed_location.path,
'',
'',
'',
)
),
auth_data_redirect_to["redirect_to"],
)
self.assertEqual(
parsed_query.get("error"),
[
(
"Could not find an Identity matching the provided "
"credentials"
)
],
)
# Attempt to authenticate with a random email
# (redirect flow with redirect_on_failure)
auth_data_redirect_on_failure = {
"provider": form_data["provider"],
"email": random_email,
"password": form_data["password"],
"redirect_to": "https://example.com/app/some/path",
"redirect_on_failure": "https://example.com/app/failure/path",
"challenge": str(uuid.uuid4()),
}
auth_data_encoded_redirect_on_failure = urllib.parse.urlencode(
auth_data_redirect_on_failure
).encode()
(
_,
redirect_on_failure_headers,
redirect_on_failure_status,
) = self.http_con_request(
http_con,
None,
path="authenticate",
method="POST",
body=auth_data_encoded_redirect_on_failure,
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
self.assertEqual(redirect_on_failure_status, 302)
location = redirect_on_failure_headers.get("location")
assert location is not None
parsed_location = urllib.parse.urlparse(location)
self.assertEqual(
urllib.parse.urlunparse(
(
parsed_location.scheme,
parsed_location.netloc,
parsed_location.path,
'',
'',
'',
)
),
auth_data_redirect_on_failure["redirect_on_failure"],
) | SELECT ext::auth::LocalIdentity
FILTER .<identity[is ext::auth::EmailPasswordFactor]
.email = <str>$email;
""",
email=email,
)
self.assertEqual(len(identity), 1)
pkce_challenge = await self.con.query_single( | test_http_auth_ext_local_password_authenticate_01 | python | geldata/gel | tests/test_http_ext_auth.py | https://github.com/geldata/gel/blob/master/tests/test_http_ext_auth.py | Apache-2.0 |
async def test_http_auth_ext_token_01(self):
base_url = self.mock_net_server.get_base_url().rstrip("/")
webhook_request = (
"POST",
base_url,
"/webhook-02",
)
url = f"{webhook_request[1]}/{webhook_request[2]}"
signing_secret_key = str(uuid.uuid4())
await self.con.query(
f"""
CONFIGURE CURRENT DATABASE
INSERT ext::auth::WebhookConfig {{
url := <str>$url,
events := {{
ext::auth::WebhookEvent.IdentityAuthenticated,
}},
signing_secret_key := <str>$signing_secret_key,
}};
""",
url=url,
signing_secret_key=signing_secret_key,
)
await self._wait_for_db_config("ext::auth::AuthConfig::webhooks")
try:
with self.http_con() as http_con:
self.mock_net_server.register_route_handler(*webhook_request)(
(
"",
204,
)
)
# Create a PKCE challenge and verifier
verifier = base64.urlsafe_b64encode(os.urandom(43)).rstrip(b'=')
challenge = base64.urlsafe_b64encode(
hashlib.sha256(verifier).digest()
).rstrip(b'=')
pkce = await self.con.query_single(
"""
select (
insert ext::auth::PKCEChallenge {
challenge := <str>$challenge,
auth_token := <str>$auth_token,
refresh_token := <str>$refresh_token,
id_token := <str>$id_token,
identity := (
insert ext::auth::Identity {
issuer := "https://example.com",
subject := "abcdefg",
}
),
}
) {
id,
challenge,
auth_token,
refresh_token,
id_token,
identity_id := .identity.id
}
""",
challenge=challenge.decode(),
auth_token="a_provider_token",
refresh_token="a_refresh_token",
id_token="an_id_token",
)
# Correct code, random verifier
(_, _, wrong_verifier_status) = self.http_con_request(
http_con,
{
"code": pkce.id,
"code_verifier": base64.urlsafe_b64encode(
os.urandom(43)
)
.rstrip(b"=")
.decode(),
},
path="token",
)
self.assertEqual(wrong_verifier_status, 403)
# Correct code, correct verifier
(
body,
_,
status,
) = self.http_con_request(
http_con,
{"code": pkce.id, "verifier": verifier.decode()},
path="token",
)
self.assertEqual(status, 200, body)
body_json = json.loads(body)
self.assertEqual(
body_json,
{
"auth_token": body_json["auth_token"],
"identity_id": str(pkce.identity_id),
"provider_token": "a_provider_token",
"provider_refresh_token": "a_refresh_token",
"provider_id_token": "an_id_token",
},
)
async for tr in self.try_until_succeeds(
delay=2, timeout=120, ignore=(KeyError, AssertionError)
):
async with tr:
requests_for_webhook = self.mock_net_server.requests[
webhook_request
]
self.assertEqual(len(requests_for_webhook), 1)
webhook_request = requests_for_webhook[0]
maybe_json_body = webhook_request.body
self.assertIsNotNone(maybe_json_body)
assert maybe_json_body is not None
event_data = json.loads(maybe_json_body)
self.assertEqual(
event_data["event_type"],
"IdentityAuthenticated",
)
self.assertEqual(
event_data["identity_id"], str(pkce.identity_id)
)
signature = requests_for_webhook[0].headers[
"x-ext-auth-signature-sha256"
]
self.assertEqual(
signature,
hmac.new(
signing_secret_key.encode(),
requests_for_webhook[0].body.encode(),
hashlib.sha256,
).hexdigest(),
)
# Correct code, correct verifier, already used PKCE
(_, _, replay_attack_status) = self.http_con_request(
http_con,
{"code": pkce.id, "verifier": verifier.decode()},
path="token",
)
self.assertEqual(replay_attack_status, 403)
finally:
await self.con.query(
f"""
CONFIGURE CURRENT DATABASE
RESET ext::auth::WebhookConfig filter .url = <str>$url;
""",
url=url,
) | ,
url=url,
signing_secret_key=signing_secret_key,
)
await self._wait_for_db_config("ext::auth::AuthConfig::webhooks")
try:
with self.http_con() as http_con:
self.mock_net_server.register_route_handler(*webhook_request)(
(
"",
204,
)
)
# Create a PKCE challenge and verifier
verifier = base64.urlsafe_b64encode(os.urandom(43)).rstrip(b'=')
challenge = base64.urlsafe_b64encode(
hashlib.sha256(verifier).digest()
).rstrip(b'=')
pkce = await self.con.query_single( | test_http_auth_ext_token_01 | python | geldata/gel | tests/test_http_ext_auth.py | https://github.com/geldata/gel/blob/master/tests/test_http_ext_auth.py | Apache-2.0 |
async def test_http_auth_ext_local_password_forgot_form_01(self):
with self.http_con() as http_con:
provider_name = "builtin::local_emailpassword"
email = f"{uuid.uuid4()}@example.com"
# Register a new user
form_data = {
"provider": provider_name,
"email": email,
"password": uuid.uuid4(),
"challenge": uuid.uuid4(),
}
form_data_encoded = urllib.parse.urlencode(form_data).encode()
self.http_con_request(
http_con,
None,
path="register",
method="POST",
body=form_data_encoded,
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
# Send reset
form_data = {
"provider": provider_name,
"reset_url": "https://example.com/app/reset-password",
"email": email,
"challenge": uuid.uuid4(),
}
form_data_encoded = urllib.parse.urlencode(form_data).encode()
body, _, status = self.http_con_request(
http_con,
None,
path="send-reset-email",
method="POST",
body=form_data_encoded,
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
self.assertEqual(status, 200)
identity = await self.con.query(
"""
with module ext::auth
SELECT LocalIdentity
FILTER .<identity[is EmailPasswordFactor].email = <str>$email
""",
email=email,
)
self.assertEqual(len(identity), 1)
data = json.loads(body)
assert_data_shape.assert_data_shape(
data,
{
"email_sent": email,
},
self.fail,
)
file_name_hash = hashlib.sha256(
f"{SENDER}{email}".encode()
).hexdigest()
test_file = os.environ.get(
"EDGEDB_TEST_EMAIL_FILE",
f"/tmp/edb-test-email-{file_name_hash}.pickle",
)
with open(test_file, "rb") as f:
email_args = pickle.load(f)
self.assertEqual(email_args["sender"], SENDER)
self.assertEqual(email_args["recipients"], email)
msg = cast(EmailMessage, email_args["message"]).get_body(
("html",)
)
assert msg is not None
html_email = msg.get_payload(decode=True).decode("utf-8")
match = re.search(
r'<p style="word-break: break-all">([^<]+)', html_email
)
assert match is not None
reset_url = match.group(1)
self.assertTrue(
reset_url.startswith(form_data['reset_url'] + '?reset_token=')
)
claims = auth_jwt.ResetToken.verify(
reset_url.split('=', maxsplit=1)[1], self.signing_key()
)
# Expiry checked as part of the validation
self.assertEqual(claims.subject, str(identity[0].id))
password_credential = await self.con.query(
"""
SELECT ext::auth::EmailPasswordFactor { password_hash }
FILTER .identity.id = <uuid>$identity
""",
identity=identity[0].id,
)
self.assertTrue(
base64.b64encode(
hashlib.sha256(
password_credential[0].password_hash.encode()
).digest()
).decode()
== claims.secret
)
# Send reset with redirect_to
_, redirect_headers, redirect_status = self.http_con_request(
http_con,
None,
path="send-reset-email",
method="POST",
body=urllib.parse.urlencode(
{
**form_data,
"redirect_to": "https://example.com/app/forgot-password",
}
).encode(),
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
self.assertEqual(redirect_status, 302)
location = redirect_headers.get("location")
assert location is not None
parsed_location = urllib.parse.urlparse(location)
parsed_query = urllib.parse.parse_qs(parsed_location.query)
self.assertEqual(
urllib.parse.urlunparse(
(
parsed_location.scheme,
parsed_location.netloc,
parsed_location.path,
'',
'',
'',
)
),
"https://example.com/app/forgot-password",
)
assert_data_shape.assert_data_shape(
parsed_query,
{
"email_sent": [email],
},
self.fail,
)
# Try sending reset for non existent user
_, _, error_status = self.http_con_request(
http_con,
None,
path="send-reset-email",
method="POST",
body=urllib.parse.urlencode(
{
**form_data,
"email": "[email protected]",
}
).encode(),
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
self.assertEqual(error_status, 200) | with module ext::auth
SELECT LocalIdentity
FILTER .<identity[is EmailPasswordFactor].email = <str>$email
""",
email=email,
)
self.assertEqual(len(identity), 1)
data = json.loads(body)
assert_data_shape.assert_data_shape(
data,
{
"email_sent": email,
},
self.fail,
)
file_name_hash = hashlib.sha256(
f"{SENDER}{email}".encode()
).hexdigest()
test_file = os.environ.get(
"EDGEDB_TEST_EMAIL_FILE",
f"/tmp/edb-test-email-{file_name_hash}.pickle",
)
with open(test_file, "rb") as f:
email_args = pickle.load(f)
self.assertEqual(email_args["sender"], SENDER)
self.assertEqual(email_args["recipients"], email)
msg = cast(EmailMessage, email_args["message"]).get_body(
("html",)
)
assert msg is not None
html_email = msg.get_payload(decode=True).decode("utf-8")
match = re.search(
r'<p style="word-break: break-all">([^<]+)', html_email
)
assert match is not None
reset_url = match.group(1)
self.assertTrue(
reset_url.startswith(form_data['reset_url'] + '?reset_token=')
)
claims = auth_jwt.ResetToken.verify(
reset_url.split('=', maxsplit=1)[1], self.signing_key()
)
# Expiry checked as part of the validation
self.assertEqual(claims.subject, str(identity[0].id))
password_credential = await self.con.query( | test_http_auth_ext_local_password_forgot_form_01 | python | geldata/gel | tests/test_http_ext_auth.py | https://github.com/geldata/gel/blob/master/tests/test_http_ext_auth.py | Apache-2.0 |
async def test_http_auth_ext_local_password_reset_form_01(self):
with self.http_con() as http_con:
provider_name = 'builtin::local_emailpassword'
email = f"{uuid.uuid4()}@example.com"
# Register a new user
form_data = {
"provider": provider_name,
"email": email,
"password": "test_auth_password",
"challenge": uuid.uuid4(),
}
form_data_encoded = urllib.parse.urlencode(form_data).encode()
self.http_con_request(
http_con,
None,
path="register",
method="POST",
body=form_data_encoded,
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
email_password_factor = await self.con.query_single(
"""
with module ext::auth
select assert_single((
select EmailPasswordFactor { verified_at }
filter .email = <str>$email
))
""",
email=email,
)
self.assertIsNone(email_password_factor.verified_at)
# Send reset
verifier = base64.urlsafe_b64encode(os.urandom(32)).rstrip(b'=')
challenge = (
base64.urlsafe_b64encode(hashlib.sha256(verifier).digest())
.rstrip(b'=')
.decode()
)
form_data = {
"provider": provider_name,
"reset_url": "https://example.com/app/reset-password",
"email": email,
"challenge": challenge,
}
form_data_encoded = urllib.parse.urlencode(form_data).encode()
body, _, status = self.http_con_request(
http_con,
None,
path="send-reset-email",
method="POST",
body=form_data_encoded,
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
self.assertEqual(status, 200, body)
file_name_hash = hashlib.sha256(
f"{SENDER}{email}".encode()
).hexdigest()
test_file = os.environ.get(
"EDGEDB_TEST_EMAIL_FILE",
f"/tmp/edb-test-email-{file_name_hash}.pickle",
)
with open(test_file, "rb") as f:
email_args = pickle.load(f)
self.assertEqual(email_args["sender"], SENDER)
self.assertEqual(email_args["recipients"], email)
msg = cast(EmailMessage, email_args["message"]).get_body(
("html",)
)
assert msg is not None
html_email = msg.get_payload(decode=True).decode("utf-8")
match = re.search(
r'<p style="word-break: break-all">([^<]+)', html_email
)
assert match is not None
reset_url = match.group(1)
self.assertTrue(
reset_url.startswith(form_data['reset_url'] + '?reset_token=')
)
reset_token = reset_url.split('=', maxsplit=1)[1]
# Update password
auth_data = {
"provider": provider_name,
"reset_token": reset_token,
"password": "new password",
}
auth_data_encoded = urllib.parse.urlencode(auth_data).encode()
body, _, status = self.http_con_request(
http_con,
None,
path="reset-password",
method="POST",
body=auth_data_encoded,
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
self.assertEqual(status, 200)
identity = await self.con.query(
"""
with module ext::auth
SELECT LocalIdentity
FILTER .<identity[is EmailPasswordFactor].email
= <str>$email
""",
email=email,
)
self.assertEqual(len(identity), 1)
email_password_factor = await self.con.query_single(
"""
with module ext::auth
SELECT EmailPasswordFactor { verified_at }
FILTER .identity.id = <uuid>$identity_id
""",
identity_id=identity[0].id,
)
self.assertIsNotNone(email_password_factor.verified_at)
pkce_challenge = await self.con.query_single(
"""
with module ext::auth
select PKCEChallenge { id }
filter .identity.id = <uuid>$identity_id
and .challenge = <str>$challenge
""",
identity_id=identity[0].id,
challenge=challenge,
)
self.assertEqual(
json.loads(body),
{"code": str(pkce_challenge.id)},
)
# Try to re-use the reset token
_, _, error_status = self.http_con_request(
http_con,
None,
path="reset-password",
method="POST",
body=auth_data_encoded,
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
self.assertEqual(error_status, 400)
# Try to re-use the reset token (with redirect_on_failure)
_, error_headers, error_status = self.http_con_request(
http_con,
None,
path="reset-password",
method="POST",
body=urllib.parse.urlencode(
{
**auth_data,
"redirect_to": "https://example.com/app/",
"redirect_on_failure": (
"https://example.com/app/reset-password"
),
}
).encode(),
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
self.assertEqual(error_status, 302)
location = error_headers.get("location")
assert location is not None
parsed_location = urllib.parse.urlparse(location)
parsed_query = urllib.parse.parse_qs(parsed_location.query)
self.assertEqual(
urllib.parse.urlunparse(
(
parsed_location.scheme,
parsed_location.netloc,
parsed_location.path,
'',
'',
'',
)
),
"https://example.com/app/reset-password",
)
self.assertEqual(
parsed_query.get("error"),
["Invalid 'reset_token'"],
) | with module ext::auth
select assert_single((
select EmailPasswordFactor { verified_at }
filter .email = <str>$email
))
""",
email=email,
)
self.assertIsNone(email_password_factor.verified_at)
# Send reset
verifier = base64.urlsafe_b64encode(os.urandom(32)).rstrip(b'=')
challenge = (
base64.urlsafe_b64encode(hashlib.sha256(verifier).digest())
.rstrip(b'=')
.decode()
)
form_data = {
"provider": provider_name,
"reset_url": "https://example.com/app/reset-password",
"email": email,
"challenge": challenge,
}
form_data_encoded = urllib.parse.urlencode(form_data).encode()
body, _, status = self.http_con_request(
http_con,
None,
path="send-reset-email",
method="POST",
body=form_data_encoded,
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
self.assertEqual(status, 200, body)
file_name_hash = hashlib.sha256(
f"{SENDER}{email}".encode()
).hexdigest()
test_file = os.environ.get(
"EDGEDB_TEST_EMAIL_FILE",
f"/tmp/edb-test-email-{file_name_hash}.pickle",
)
with open(test_file, "rb") as f:
email_args = pickle.load(f)
self.assertEqual(email_args["sender"], SENDER)
self.assertEqual(email_args["recipients"], email)
msg = cast(EmailMessage, email_args["message"]).get_body(
("html",)
)
assert msg is not None
html_email = msg.get_payload(decode=True).decode("utf-8")
match = re.search(
r'<p style="word-break: break-all">([^<]+)', html_email
)
assert match is not None
reset_url = match.group(1)
self.assertTrue(
reset_url.startswith(form_data['reset_url'] + '?reset_token=')
)
reset_token = reset_url.split('=', maxsplit=1)[1]
# Update password
auth_data = {
"provider": provider_name,
"reset_token": reset_token,
"password": "new password",
}
auth_data_encoded = urllib.parse.urlencode(auth_data).encode()
body, _, status = self.http_con_request(
http_con,
None,
path="reset-password",
method="POST",
body=auth_data_encoded,
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
self.assertEqual(status, 200)
identity = await self.con.query( | test_http_auth_ext_local_password_reset_form_01 | python | geldata/gel | tests/test_http_ext_auth.py | https://github.com/geldata/gel/blob/master/tests/test_http_ext_auth.py | Apache-2.0 |
async def test_http_auth_ext_webauthn_authenticate_options(self):
with self.http_con() as http_con:
email = f"{uuid.uuid4()}@example.com"
user_handle = uuid.uuid4().bytes
credential_id = uuid.uuid4().bytes
public_key = uuid.uuid4().bytes
await self.con.query_single(
"""
with identity := (insert ext::auth::LocalIdentity {
issuer := "local",
subject := "",
})
INSERT ext::auth::WebAuthnFactor {
email := <str>$email,
user_handle := <bytes>$user_handle,
credential_id := <bytes>$credential_id,
public_key := <bytes>$public_key,
identity := identity,
};
""",
email=email,
user_handle=user_handle,
credential_id=credential_id,
public_key=public_key,
)
body, _headers, status = self.http_con_request(
http_con,
path=f"webauthn/authenticate/options?email={email}",
)
self.assertEqual(status, 200)
body_json = json.loads(body)
self.assertIn("challenge", body_json)
self.assertIsInstance(body_json["challenge"], str)
self.assertIn("rpId", body_json)
self.assertIsInstance(body_json["rpId"], str)
self.assertIn("timeout", body_json)
self.assertIsInstance(body_json["timeout"], int)
self.assertIn("allowCredentials", body_json)
self.assertIsInstance(body_json["allowCredentials"], list)
allow_credentials = body_json["allowCredentials"]
self.assertTrue(
all(
"type" in cred and "id" in cred
for cred in allow_credentials
),
"Each credential should have 'type' and 'id' keys",
)
self.assertIn(
base64.urlsafe_b64encode(credential_id).rstrip(b"=").decode(),
[cred["id"] for cred in allow_credentials],
(
"The generated credential_id should be in the "
"'allowCredentials' list"
),
)
challenge_bytes = base64.urlsafe_b64decode(
f'{body_json["challenge"]}==='
)
self.assertTrue(
await self.con.query_single(
'''
SELECT EXISTS (
SELECT ext::auth::WebAuthnAuthenticationChallenge
filter .challenge = <bytes>$challenge
AND any(
.factors.email = <str>$email
AND .factors.user_handle = <bytes>$user_handle
)
)
''',
challenge=challenge_bytes,
email=email,
user_handle=user_handle,
)
) | with identity := (insert ext::auth::LocalIdentity {
issuer := "local",
subject := "",
})
INSERT ext::auth::WebAuthnFactor {
email := <str>$email,
user_handle := <bytes>$user_handle,
credential_id := <bytes>$credential_id,
public_key := <bytes>$public_key,
identity := identity,
};
""",
email=email,
user_handle=user_handle,
credential_id=credential_id,
public_key=public_key,
)
body, _headers, status = self.http_con_request(
http_con,
path=f"webauthn/authenticate/options?email={email}",
)
self.assertEqual(status, 200)
body_json = json.loads(body)
self.assertIn("challenge", body_json)
self.assertIsInstance(body_json["challenge"], str)
self.assertIn("rpId", body_json)
self.assertIsInstance(body_json["rpId"], str)
self.assertIn("timeout", body_json)
self.assertIsInstance(body_json["timeout"], int)
self.assertIn("allowCredentials", body_json)
self.assertIsInstance(body_json["allowCredentials"], list)
allow_credentials = body_json["allowCredentials"]
self.assertTrue(
all(
"type" in cred and "id" in cred
for cred in allow_credentials
),
"Each credential should have 'type' and 'id' keys",
)
self.assertIn(
base64.urlsafe_b64encode(credential_id).rstrip(b"=").decode(),
[cred["id"] for cred in allow_credentials],
(
"The generated credential_id should be in the "
"'allowCredentials' list"
),
)
challenge_bytes = base64.urlsafe_b64decode(
f'{body_json["challenge"]}==='
)
self.assertTrue(
await self.con.query_single( | test_http_auth_ext_webauthn_authenticate_options | python | geldata/gel | tests/test_http_ext_auth.py | https://github.com/geldata/gel/blob/master/tests/test_http_ext_auth.py | Apache-2.0 |
async def test_http_auth_ext_identity_delete_cascade_01(self):
"""
Test deleting a LocalIdentity deletes the associated Factors and
PKCEChallenge objects as well
"""
result = await self.con.query_single(
"""
with
identity := (insert ext::auth::LocalIdentity {
issuer := "local",
subject := "",
}),
factor := (insert ext::auth::EmailPasswordFactor {
identity := identity,
email := "[email protected]",
password_hash := "abc123",
}),
pkce_challenge := (insert ext::auth::PKCEChallenge {
identity := identity,
challenge := "abc123",
}),
select identity;
""",
)
await self.con.query(
"delete <ext::auth::Identity><uuid>$identity_id;",
identity_id=result.id,
) | Test deleting a LocalIdentity deletes the associated Factors and
PKCEChallenge objects as well | test_http_auth_ext_identity_delete_cascade_01 | python | geldata/gel | tests/test_http_ext_auth.py | https://github.com/geldata/gel/blob/master/tests/test_http_ext_auth.py | Apache-2.0 |
async def test_http_auth_ext_identity_delete_cascade_02(self):
"""
Test deleting an Identity deletes the associated objects as well
"""
result = await self.con.query_single(
"""
with
identity := (insert ext::auth::Identity {
issuer := "https://example.com",
subject := "abc123",
}),
pkce_challenge := (insert ext::auth::PKCEChallenge {
identity := identity,
challenge := "123abc",
}),
select identity;
""",
)
await self.con.query(
"delete <ext::auth::Identity><uuid>$identity_id;",
identity_id=result.id,
) | Test deleting an Identity deletes the associated objects as well | test_http_auth_ext_identity_delete_cascade_02 | python | geldata/gel | tests/test_http_ext_auth.py | https://github.com/geldata/gel/blob/master/tests/test_http_ext_auth.py | Apache-2.0 |
async def test_http_auth_ext_identity_delete_cascade_03(self):
"""
Test deleting a WebAuthn LocalIdentity deletes the associated
WebAuthnFactor and WebAuthnRegistrationChallenge
"""
challenge = uuid.uuid4().bytes
user_handle = uuid.uuid4().bytes
credential_id = uuid.uuid4().bytes
public_key = uuid.uuid4().bytes
result = await self.con.query_single(
"""
with
user_handle := <bytes>$user_handle,
credential_id := <bytes>$credential_id,
public_key := <bytes>$public_key,
challenge := <bytes>$challenge,
identity := (insert ext::auth::LocalIdentity {
issuer := "local",
subject := "",
}),
factor := (insert ext::auth::WebAuthnFactor {
identity := identity,
user_handle := user_handle,
email := "[email protected]",
credential_id := credential_id,
public_key := public_key,
}),
challenge := (insert ext::auth::WebAuthnRegistrationChallenge {
challenge := challenge,
email := "[email protected]",
user_handle := user_handle,
}),
pkce_challenge := (insert ext::auth::PKCEChallenge {
identity := identity,
challenge := "abc123",
}),
select identity;
""",
user_handle=user_handle,
credential_id=credential_id,
public_key=public_key,
challenge=challenge,
)
await self.con.query(
"delete <ext::auth::LocalIdentity><uuid>$identity_id;",
identity_id=result.id,
) | Test deleting a WebAuthn LocalIdentity deletes the associated
WebAuthnFactor and WebAuthnRegistrationChallenge | test_http_auth_ext_identity_delete_cascade_03 | python | geldata/gel | tests/test_http_ext_auth.py | https://github.com/geldata/gel/blob/master/tests/test_http_ext_auth.py | Apache-2.0 |
async def test_client_token_identity_card(self):
await self.con.query_single(
'''
select global ext::auth::ClientTokenIdentity
'''
) | select global ext::auth::ClientTokenIdentity | test_client_token_identity_card | python | geldata/gel | tests/test_http_ext_auth.py | https://github.com/geldata/gel/blob/master/tests/test_http_ext_auth.py | Apache-2.0 |
async def test_sql_dml_insert_01(self):
# base case
await self.scon.execute(
'''
INSERT INTO "Document" (title) VALUES ('Meeting report')
'''
)
res = await self.squery_values('SELECT title FROM "Document"')
self.assertEqual(res, [['Meeting report (new)']]) | INSERT INTO "Document" (title) VALUES ('Meeting report') | test_sql_dml_insert_01 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_02(self):
# when columns are not specified, all columns are expected,
# in alphabetical order:
# id, __type__, owner, title
await self.scon.execute("SET LOCAL allow_user_specified_id TO TRUE")
with self.assertRaisesRegex(
asyncpg.DataError,
"cannot assign to link '__type__': it is protected",
# TODO: positions are hard to recover since we don't even know which
# DML stmt this error is originating from
# position="30",
):
await self.scon.execute(
'''
INSERT INTO "Document" VALUES (NULL, NULL, NULL, 'Report')
'''
)
res = await self.squery_values('SELECT title FROM "Document"')
self.assertEqual(res, [['Report (new)']]) | INSERT INTO "Document" VALUES (NULL, NULL, NULL, 'Report') | test_sql_dml_insert_02 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_03(self):
# multiple rows at once
await self.scon.execute(
'''
INSERT INTO "Document" (title) VALUES ('Report'), ('Briefing')
'''
)
res = await self.squery_values('SELECT title FROM "Document"')
self.assert_data_shape(
res, tb.bag([['Report (new)'], ['Briefing (new)']])
) | INSERT INTO "Document" (title) VALUES ('Report'), ('Briefing') | test_sql_dml_insert_03 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_04(self):
# using arbitrary query instead of VALUES
await self.scon.execute(
'''
INSERT INTO "Document" (title)
SELECT c FROM (
SELECT 'Report', 1 UNION ALL SELECT 'Briefing', 2
) t(c, x)
WHERE x >= 2
'''
)
res = await self.squery_values('SELECT title FROM "Document"')
self.assert_data_shape(res, tb.bag([['Briefing (new)']])) | INSERT INTO "Document" (title)
SELECT c FROM (
SELECT 'Report', 1 UNION ALL SELECT 'Briefing', 2
) t(c, x)
WHERE x >= 2 | test_sql_dml_insert_04 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_05(self):
# insert link
await self.scon.execute('INSERT INTO "User" DEFAULT VALUES;')
await self.scon.execute(
'INSERT INTO "Document" (owner_id) SELECT id FROM "User" LIMIT 1'
)
res = await self.squery_values('SELECT owner_id FROM "Document"')
self.assert_shape(res, rows=1, columns=1)
# insert multiple
await self.scon.execute('INSERT INTO "User" DEFAULT VALUES;')
await self.scon.execute(
'INSERT INTO "Document" (owner_id) SELECT id FROM "User"'
)
res = await self.squery_values('SELECT owner_id FROM "Document"')
self.assert_shape(res, rows=3, columns=1)
# insert a null link
await self.scon.execute(
'INSERT INTO "Document" (owner_id) VALUES (NULL)'
)
# insert multiple, with nulls
await self.scon.execute(
'''
INSERT INTO "Document" (owner_id) VALUES
((SELECT id from "User" LIMIT 1)),
(NULL)
'''
) | INSERT INTO "Document" (owner_id) VALUES
((SELECT id from "User" LIMIT 1)),
(NULL) | test_sql_dml_insert_05 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_06(self):
# insert in a subquery: syntax error
with self.assertRaisesRegex(
asyncpg.PostgresSyntaxError,
'syntax error at or near "INTO"',
position="61",
):
await self.scon.execute(
'''
SELECT * FROM (
INSERT INTO "Document" (title) VALUES ('Meeting report')
)
'''
) | SELECT * FROM (
INSERT INTO "Document" (title) VALUES ('Meeting report')
) | test_sql_dml_insert_06 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_07(self):
# insert in a CTE
await self.scon.execute(
'''
WITH a AS (
INSERT INTO "Document" (title) VALUES ('Meeting report')
)
SELECT * FROM a
'''
) | WITH a AS (
INSERT INTO "Document" (title) VALUES ('Meeting report')
)
SELECT * FROM a | test_sql_dml_insert_07 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_08(self):
# insert in a CTE: invalid PostgreSQL
with self.assertRaisesRegex(
asyncpg.FeatureNotSupportedError,
'WITH clause containing a data-modifying statement must be at '
'the top level',
position="98",
):
await self.scon.execute(
'''
WITH a AS (
WITH b AS (
INSERT INTO "Document" (title) VALUES ('Meeting report')
)
SELECT * FROM b
)
SELECT * FROM a
'''
) | WITH a AS (
WITH b AS (
INSERT INTO "Document" (title) VALUES ('Meeting report')
)
SELECT * FROM b
)
SELECT * FROM a | test_sql_dml_insert_08 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_09(self):
# insert with a CTE
await self.scon.execute(
'''
WITH a AS (
SELECT 'Report' as t UNION ALL SELECT 'Briefing'
)
INSERT INTO "Document" (title) SELECT * FROM a
'''
)
res = await self.squery_values('SELECT title FROM "Document"')
self.assertEqual(res, tb.bag([['Report (new)'], ['Briefing (new)']])) | WITH a AS (
SELECT 'Report' as t UNION ALL SELECT 'Briefing'
)
INSERT INTO "Document" (title) SELECT * FROM a | test_sql_dml_insert_09 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_10(self):
# two inserts
await self.scon.execute(
'''
WITH a AS (
INSERT INTO "Document" (title) VALUES ('Report')
RETURNING title as t
)
INSERT INTO "Document" (title) SELECT t || ' - copy' FROM a
'''
)
res = await self.squery_values('SELECT title FROM "Document"')
self.assert_data_shape(
res, tb.bag([['Report (new)'], ['Report (new) - copy (new)']])
) | WITH a AS (
INSERT INTO "Document" (title) VALUES ('Report')
RETURNING title as t
)
INSERT INTO "Document" (title) SELECT t || ' - copy' FROM a | test_sql_dml_insert_10 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_11(self):
await self.scon.execute(
'''
WITH a AS (
INSERT INTO "Document" (title) VALUES ('Report')
)
INSERT INTO "Document" (title) VALUES ('Briefing')
'''
)
res = await self.squery_values('SELECT title FROM "Document"')
self.assert_data_shape(
res, tb.bag([['Report (new)'], ['Briefing (new)']])
) | WITH a AS (
INSERT INTO "Document" (title) VALUES ('Report')
)
INSERT INTO "Document" (title) VALUES ('Briefing') | test_sql_dml_insert_11 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_12(self):
# returning
await self.scon.execute('INSERT INTO "User" DEFAULT VALUES;')
res = await self.scon.fetch(
'''
INSERT INTO "Document" (title, owner_id)
SELECT 'Meeting Report', id FROM "User" LIMIT 1
RETURNING id, owner_id, LOWER(title) as my_title
'''
)
self.assert_shape(res, rows=1, columns=["id", "owner_id", "my_title"])
first = res[0]
self.assertEqual(first[2], 'meeting report (new)') | INSERT INTO "Document" (title, owner_id)
SELECT 'Meeting Report', id FROM "User" LIMIT 1
RETURNING id, owner_id, LOWER(title) as my_title | test_sql_dml_insert_12 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_13(self):
# returning sublink
await self.scon.execute('INSERT INTO "User" DEFAULT VALUES;')
await self.scon.execute(
'''
INSERT INTO "Document" (title, owner_id)
SELECT 'Report', id FROM "User" LIMIT 1
'''
)
res = await self.squery_values(
'''
INSERT INTO "Document" as subject (title, owner_id)
VALUES ('Report', NULL), ('Briefing', (SELECT id FROM "User"))
RETURNING (
SELECT COUNT(*) FROM "User" WHERE "User".id = owner_id
),
(
SELECT COUNT(*) FROM "User"
),
(
SELECT COUNT(*) FROM "Document" AS d
WHERE subject.title = d.title
)
'''
)
self.assertEqual(
res,
tb.bag(
[
[0, 1, 1],
[1, 1, 0],
]
),
) | INSERT INTO "Document" (title, owner_id)
SELECT 'Report', id FROM "User" LIMIT 1 | test_sql_dml_insert_13 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_14(self):
with self.assertRaisesRegex(
asyncpg.InvalidTextRepresentationError,
'invalid input syntax for type uuid',
):
await self.scon.execute(
'''
INSERT INTO "Document" (title, owner_id)
VALUES
('Briefing', 'bad uuid')
'''
) | INSERT INTO "Document" (title, owner_id)
VALUES
('Briefing', 'bad uuid') | test_sql_dml_insert_14 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_15(self):
with self.assertRaisesRegex(
asyncpg.exceptions.CardinalityViolationError,
"object type default::User with id '[0-9a-f-]+' does not exist",
):
await self.scon.execute(
'''
INSERT INTO "Document" (title, owner_id)
VALUES
('Report', '343a6c20-2e3b-11ef-8798-ebce402e7d3f')
'''
) | INSERT INTO "Document" (title, owner_id)
VALUES
('Report', '343a6c20-2e3b-11ef-8798-ebce402e7d3f') | test_sql_dml_insert_15 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_16(self):
with self.assertRaisesRegex(
asyncpg.exceptions.CannotCoerceError,
'cannot cast type boolean to uuid',
):
await self.scon.execute(
'''
INSERT INTO "Document" (title, owner_id)
VALUES ('Briefing', FALSE)
'''
) | INSERT INTO "Document" (title, owner_id)
VALUES ('Briefing', FALSE) | test_sql_dml_insert_16 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_17a(self):
# default values
await self.scon.execute(
'''
INSERT INTO "Document" DEFAULT VALUES;
'''
)
await self.scon.execute(
'''
INSERT INTO "Document" (id, title) VALUES (DEFAULT, 'Report');
'''
)
res = await self.squery_values('SELECT title FROM "Document"')
self.assert_data_shape(res, tb.bag([[None], ['Report (new)']]))
await self.scon.execute(
'''
INSERT INTO "Document" (title) VALUES ('Report2'), (DEFAULT);
'''
)
res = await self.squery_values('SELECT title FROM "Document"')
self.assert_data_shape(
res,
tb.bag([
[None],
[None],
['Report (new)'],
['Report2 (new)'],
]),
)
await self.scon.execute(
'''
INSERT INTO "Post" (title) VALUES ('post'), (DEFAULT);
'''
)
res = await self.squery_values('SELECT title FROM "Post"')
self.assert_data_shape(
res,
tb.bag([
['post'],
['untitled'],
]),
) | INSERT INTO "Document" DEFAULT VALUES; | test_sql_dml_insert_17a | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_17b(self):
# more default values
await self.scon.execute(
'''
INSERT INTO "Post" (id, title, content) VALUES
(DEFAULT, 'foo', 'bar'),
(DEFAULT, 'post', DEFAULT),
(DEFAULT, DEFAULT, 'content'),
(DEFAULT, DEFAULT, DEFAULT);
'''
)
res = await self.squery_values('SELECT title, content FROM "Post"')
self.assert_data_shape(
res,
tb.bag([
['foo', 'bar'],
['post', 'This page intentionally left blank'],
['untitled', 'content'],
['untitled', 'This page intentionally left blank'],
]),
) | INSERT INTO "Post" (id, title, content) VALUES
(DEFAULT, 'foo', 'bar'),
(DEFAULT, 'post', DEFAULT),
(DEFAULT, DEFAULT, 'content'),
(DEFAULT, DEFAULT, DEFAULT); | test_sql_dml_insert_17b | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_18(self):
res = await self.scon.fetch(
'''
WITH
a as (INSERT INTO "Child" (prop) VALUES ('a')),
b as (INSERT INTO "Child" (prop) VALUES ('b_0'), ('b_1'))
SELECT line FROM "Log" ORDER BY line;
'''
)
# changes to the database are not visible in the same query
self.assert_shape(res, 0, 0)
# so we need to re-select
res = await self.squery_values('SELECT line FROM "Log" ORDER BY line;')
self.assertEqual(
res,
[
["inserted all"],
["inserted each a"],
["inserted each b_0"],
["inserted each b_1"],
],
) | WITH
a as (INSERT INTO "Child" (prop) VALUES ('a')),
b as (INSERT INTO "Child" (prop) VALUES ('b_0'), ('b_1'))
SELECT line FROM "Log" ORDER BY line; | test_sql_dml_insert_18 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_19(self):
# exclusive on base, then insert into base and child
with self.assertRaisesRegex(
asyncpg.ExclusionViolationError,
'duplicate key value violates unique constraint '
'"[0-9a-f-]+;schemaconstr"',
):
await self.scon.execute(
'''
WITH
a as (INSERT INTO "Base" (prop) VALUES ('a')),
b as (INSERT INTO "Child" (prop) VALUES ('a'))
SELECT 1
'''
) | WITH
a as (INSERT INTO "Base" (prop) VALUES ('a')),
b as (INSERT INTO "Child" (prop) VALUES ('a'))
SELECT 1 | test_sql_dml_insert_19 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_20(self):
# CommandComplete tag (inserted rows) with no RETURNING
query = '''
INSERT INTO "Document" (title) VALUES ('Report'), ('Briefing');
'''
# extended (binary) protocol, because fetch
res = await self.scon.fetch(query)
# actually, no DataRows are returned, but asyncpg returns [] anyway
self.assert_shape(res, 0, 0)
# simple (text) protocol
res = await self.scon.execute(query)
self.assertEqual(res, 'INSERT 0 2')
# extended (binary) protocol because we used args
query = '''
INSERT INTO "Document" (title) VALUES ($1), ($2);
'''
res = await self.scon.execute(query, 'Report', 'Briefing')
self.assertEqual(res, 'INSERT 0 2') | # extended (binary) protocol, because fetch
res = await self.scon.fetch(query)
# actually, no DataRows are returned, but asyncpg returns [] anyway
self.assert_shape(res, 0, 0)
# simple (text) protocol
res = await self.scon.execute(query)
self.assertEqual(res, 'INSERT 0 2')
# extended (binary) protocol because we used args
query = | test_sql_dml_insert_20 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_21(self):
# CommandComplete tag (inserted rows) with RETURNING
query = '''
INSERT INTO "Document" (title) VALUES ('Report'), ('Briefing')
RETURNING id as my_id;
'''
res = await self.scon.fetch(query)
self.assert_shape(res, rows=2, columns=["my_id"])
# simple (text) protocol
res = await self.scon.execute(query)
self.assertEqual(res, 'INSERT 0 2')
# extended (binary) protocol because we used args
query = '''
INSERT INTO "Document" (title) VALUES ($1), ($2)
RETURNING id as my_id;
'''
res = await self.scon.execute(query, 'Report', 'Briefing')
self.assertEqual(res, 'INSERT 0 2') | res = await self.scon.fetch(query)
self.assert_shape(res, rows=2, columns=["my_id"])
# simple (text) protocol
res = await self.scon.execute(query)
self.assertEqual(res, 'INSERT 0 2')
# extended (binary) protocol because we used args
query = | test_sql_dml_insert_21 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_22(self):
# insert into link table
query = '''
INSERT INTO "Document" (title) VALUES ('Report'), ('Briefing')
RETURNING id;
'''
documents = await self.squery_values(query)
query = '''
WITH
u1 AS (INSERT INTO "User" DEFAULT VALUES RETURNING id),
u2 AS (INSERT INTO "User" DEFAULT VALUES RETURNING id)
SELECT id from u1 UNION ALL SELECT id from u2
'''
users = await self.squery_values(query)
res = await self.scon.execute(
'''
INSERT INTO "Document.shared_with" (source, target)
VALUES ($1, $2)
''',
documents[0][0],
users[0][0],
)
self.assertEqual(res, 'INSERT 0 1')
res = await self.scon.execute(
'''
INSERT INTO "Document.shared_with" (source, target)
VALUES ($1, $2), ($1, $3)
''',
documents[1][0],
users[0][0],
users[1][0],
)
self.assertEqual(res, 'INSERT 0 2') | documents = await self.squery_values(query)
query = | test_sql_dml_insert_22 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_24(self):
# insert into link table, link properties
documents = await self.squery_values(
'''
INSERT INTO "Document" (title) VALUES ('Report') RETURNING id
'''
)
users = await self.squery_values(
'''
INSERT INTO "User" DEFAULT VALUES RETURNING id
'''
)
res = await self.scon.execute(
'''
WITH t(doc, usr) as (VALUES ($1::uuid, $2::uuid))
INSERT INTO "Document.shared_with" (source, target, can_edit)
SELECT doc, usr, TRUE FROM t
''',
documents[0][0],
users[0][0],
)
self.assertEqual(res, 'INSERT 0 1')
res = await self.squery_values(
'SELECT can_edit FROM "Document.shared_with"'
)
self.assertEqual(res, [[True]]) | INSERT INTO "Document" (title) VALUES ('Report') RETURNING id | test_sql_dml_insert_24 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_25(self):
# insert into link table, returning
documents = await self.squery_values(
'''
INSERT INTO "Document" (title) VALUES ('Report') RETURNING id
'''
)
users = await self.squery_values(
'''
INSERT INTO "User" DEFAULT VALUES RETURNING id
'''
)
res = await self.squery_values(
'''
INSERT INTO "Document.shared_with"
VALUES ($1, $2, FALSE)
RETURNING source, target, not can_edit
''',
documents[0][0],
users[0][0],
)
self.assertEqual(len(res), 1)
self.assertEqual(res[0][0], documents[0][0])
self.assertEqual(res[0][1], users[0][0])
self.assertEqual(res[0][2], True) | INSERT INTO "Document" (title) VALUES ('Report') RETURNING id | test_sql_dml_insert_25 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_26(self):
# insert into single link table
documents = await self.squery_values(
'''
INSERT INTO "Document" (title) VALUES ('Report') RETURNING id
'''
)
users = await self.squery_values(
'''
INSERT INTO "User" DEFAULT VALUES RETURNING id
'''
)
res = await self.squery_values(
'''
INSERT INTO "Document.owner"
VALUES ($1, $2, FALSE)
RETURNING source, target, not is_author
''',
documents[0][0],
users[0][0],
)
self.assertEqual(len(res), 1)
self.assertEqual(res[0][0], documents[0][0])
self.assertEqual(res[0][1], users[0][0])
self.assertEqual(res[0][2], True) | INSERT INTO "Document" (title) VALUES ('Report') RETURNING id | test_sql_dml_insert_26 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_27(self):
with self.assertRaisesRegex(
asyncpg.PostgresError,
'column source is required when inserting into link tables',
):
await self.squery_values(
'''
INSERT INTO "Document.shared_with" (target, can_edit)
VALUES ('uuid 1'::uuid, FALSE)
''',
)
with self.assertRaisesRegex(
asyncpg.PostgresError,
'column target is required when inserting into link tables',
):
await self.squery_values(
'''
INSERT INTO "Document.shared_with" (source, can_edit)
VALUES ('uuid 1'::uuid, FALSE)
''',
) | INSERT INTO "Document.shared_with" (target, can_edit)
VALUES ('uuid 1'::uuid, FALSE)
''',
)
with self.assertRaisesRegex(
asyncpg.PostgresError,
'column target is required when inserting into link tables',
):
await self.squery_values( | test_sql_dml_insert_27 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_28(self):
documents = await self.squery_values(
'''
INSERT INTO "Document" (title) VALUES ('Report') RETURNING id
'''
)
res = await self.squery_values(
'''
INSERT INTO "Document.keywords"
VALUES ($1, 'notes')
RETURNING source, target
''',
documents[0][0],
)
self.assertEqual(len(res), 1)
self.assertEqual(res[0][0], documents[0][0])
self.assertEqual(res[0][1], 'notes')
res = await self.scon.execute(
'''
INSERT INTO "Document.keywords" (source, target)
VALUES ($1, 'priority'), ($1, 'recent')
''',
documents[0][0],
)
self.assertEqual(res, 'INSERT 0 2') | INSERT INTO "Document" (title) VALUES ('Report') RETURNING id | test_sql_dml_insert_28 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_29(self):
res = await self.scon.execute(
'''
INSERT INTO "User" (id) VALUES (DEFAULT), (DEFAULT)
'''
)
self.assertEqual(res, 'INSERT 0 2') | INSERT INTO "User" (id) VALUES (DEFAULT), (DEFAULT) | test_sql_dml_insert_29 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_31(self):
res = await self.squery_values(
'''
WITH u as (
INSERT INTO "User" (id) VALUES (DEFAULT), (DEFAULT) RETURNING id
)
INSERT INTO "Document" (title, owner_id)
SELECT 'Report', u.id FROM u
RETURNING title, owner_id
'''
)
self.assertEqual(
res, [['Report (new)', res[0][1]], ['Report (new)', res[1][1]]]
) | WITH u as (
INSERT INTO "User" (id) VALUES (DEFAULT), (DEFAULT) RETURNING id
)
INSERT INTO "Document" (title, owner_id)
SELECT 'Report', u.id FROM u
RETURNING title, owner_id | test_sql_dml_insert_31 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_32(self):
with self.assertRaisesRegex(
asyncpg.PostgresError,
'cannot write into table "columns"',
):
await self.squery_values(
'''
INSERT INTO information_schema.columns DEFAULT VALUES
'''
) | INSERT INTO information_schema.columns DEFAULT VALUES | test_sql_dml_insert_32 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_33(self):
# TODO: error message should say `owner_id` not `owner`
with self.assertRaisesRegex(
asyncpg.PostgresError,
'Expected 2 columns \\(title, owner\\), but got 1',
):
await self.squery_values(
'''
INSERT INTO "Document" (title, owner_id)
VALUES ('Report'), ('Report'), ('Briefing')
'''
) | INSERT INTO "Document" (title, owner_id)
VALUES ('Report'), ('Report'), ('Briefing') | test_sql_dml_insert_33 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_34(self):
id1 = uuid.uuid4()
id2 = uuid.uuid4()
id3 = uuid.uuid4()
id4 = uuid.uuid4()
id5 = uuid.uuid4()
await self.scon.execute("SET LOCAL allow_user_specified_id TO TRUE")
res = await self.squery_values(
f'''
INSERT INTO "Document" (id)
VALUES ($1), ('{id2}')
RETURNING id
''',
id1,
)
self.assertEqual(res, [[id1], [id2]])
res = await self.squery_values(
f'''
INSERT INTO "Document" (id)
SELECT id FROM (VALUES ($1::uuid), ('{id4}')) t(id)
RETURNING id
''',
id3,
)
self.assertEqual(res, [[id3], [id4]])
res = await self.squery_values(
f'''
INSERT INTO "Document" (id)
VALUES ($1)
RETURNING id
''',
id5,
)
self.assertEqual(res, [[id5]]) | ,
id1,
)
self.assertEqual(res, [[id1], [id2]])
res = await self.squery_values(
f | test_sql_dml_insert_34 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_35(self):
with self.assertRaisesRegex(
asyncpg.exceptions.DataError,
"cannot assign to property 'id'",
):
res = await self.squery_values(
f'''
INSERT INTO "Document" (id) VALUES ($1) RETURNING id
''',
uuid.uuid4(),
)
await self.scon.execute('SET LOCAL allow_user_specified_id TO TRUE')
id = uuid.uuid4()
res = await self.squery_values(
f'''
INSERT INTO "Document" (id) VALUES ($1) RETURNING id
''',
id,
)
self.assertEqual(res, [[id]]) | ,
uuid.uuid4(),
)
await self.scon.execute('SET LOCAL allow_user_specified_id TO TRUE')
id = uuid.uuid4()
res = await self.squery_values(
f | test_sql_dml_insert_35 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_37(self):
[doc] = await self.squery_values(
'''
INSERT INTO "Document" (title) VALUES ('Report') RETURNING id
'''
)
res = await self.scon.execute(
'''
WITH u AS (
INSERT INTO "User" DEFAULT VALUES RETURNING id
)
INSERT INTO "Document.shared_with" (source, target, can_edit)
SELECT $1, u.id, TRUE FROM u
''',
doc[0],
)
self.assertEqual(res, 'INSERT 0 1')
res = await self.squery_values(
'SELECT can_edit FROM "Document.shared_with"'
)
self.assertEqual(res, [[True]]) | INSERT INTO "Document" (title) VALUES ('Report') RETURNING id | test_sql_dml_insert_37 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_38(self):
res = await self.scon.execute(
'''
WITH
d AS (
INSERT INTO "Document" (title) VALUES ('Report') RETURNING id
),
u AS (
INSERT INTO "User" DEFAULT VALUES RETURNING id
)
INSERT INTO "Document.shared_with" (source, target, can_edit)
SELECT d.id, u.id, TRUE FROM d, u
'''
)
self.assertEqual(res, 'INSERT 0 1')
res = await self.squery_values(
'SELECT can_edit FROM "Document.shared_with"'
)
self.assertEqual(res, [[True]]) | WITH
d AS (
INSERT INTO "Document" (title) VALUES ('Report') RETURNING id
),
u AS (
INSERT INTO "User" DEFAULT VALUES RETURNING id
)
INSERT INTO "Document.shared_with" (source, target, can_edit)
SELECT d.id, u.id, TRUE FROM d, u | test_sql_dml_insert_38 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_40(self):
await self.squery_values(
f'''
INSERT INTO "User" DEFAULT VALUES
'''
)
res = await self.scon.execute(
f'''
INSERT INTO "Document2" (title, owner_id)
VALUES ('Raven', (select id FROM "User" LIMIT 1))
'''
)
self.assertEqual(res, 'INSERT 0 1')
res = await self.squery_values(
'''
SELECT title FROM "Document2"
'''
)
self.assertEqual(res, [['Raven']]) | )
res = await self.scon.execute(
f | test_sql_dml_insert_40 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_42(self):
await self.scon.execute("SET LOCAL allow_user_specified_id TO TRUE")
uuid1 = uuid.uuid4()
uuid2 = uuid.uuid4()
res = await self.scon.execute(
f'''
WITH
u1 as (
INSERT INTO "User" DEFAULT VALUES RETURNING id, 'hello' as x
),
u2 as (
INSERT INTO "User" (id) VALUES ($1), ($2)
RETURNING id, 'world' as y
)
INSERT INTO "Document" (owner_id, title)
VALUES
((SELECT id FROM u1), (SELECT x FROM u1)),
((SELECT id FROM u2 LIMIT 1), (SELECT y FROM u2 LIMIT 1)),
(
(SELECT id FROM u2 OFFSET 1 LIMIT 1),
(SELECT y FROM u2 OFFSET 1 LIMIT 1)
)
''',
uuid1,
uuid2,
)
self.assertEqual(res, 'INSERT 0 3')
res = await self.squery_values(
'''
SELECT title, owner_id FROM "Document"
'''
)
res[0][1] = None # first uuid is generated and unknown at this stage
self.assertEqual(
res,
[
['hello (new)', None],
['world (new)', uuid1],
['world (new)', uuid2],
],
) | ,
uuid1,
uuid2,
)
self.assertEqual(res, 'INSERT 0 3')
res = await self.squery_values( | test_sql_dml_insert_42 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_43(self):
await self.scon.execute("SET LOCAL allow_user_specified_id TO TRUE")
doc_id = uuid.uuid4()
user_id = uuid.uuid4()
res = await self.scon.execute(
'''
WITH
d AS (INSERT INTO "Document" (id) VALUES ($1)),
u AS (INSERT INTO "User" (id) VALUES ($2)),
dsw AS (
INSERT INTO "Document.shared_with" (source, target)
VALUES ($1, $2)
)
INSERT INTO "Document.keywords" VALUES ($1, 'top-priority')
''',
doc_id,
user_id,
)
self.assertEqual(res, 'INSERT 0 1')
res = await self.squery_values(
'''
SELECT source, target FROM "Document.shared_with"
'''
)
self.assertEqual(res, [[doc_id, user_id]]) | WITH
d AS (INSERT INTO "Document" (id) VALUES ($1)),
u AS (INSERT INTO "User" (id) VALUES ($2)),
dsw AS (
INSERT INTO "Document.shared_with" (source, target)
VALUES ($1, $2)
)
INSERT INTO "Document.keywords" VALUES ($1, 'top-priority')
''',
doc_id,
user_id,
)
self.assertEqual(res, 'INSERT 0 1')
res = await self.squery_values( | test_sql_dml_insert_43 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_44(self):
# Test that RETURNING supports "Table".col format
res = await self.squery_values(
'''
INSERT INTO "Document" (title) VALUES ('Test returning')
RETURNING "Document".id
'''
)
docid = res[0][0]
res = await self.squery_values('SELECT id, title FROM "Document"')
self.assertEqual(res, [[docid, 'Test returning (new)']]) | INSERT INTO "Document" (title) VALUES ('Test returning')
RETURNING "Document".id | test_sql_dml_insert_44 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_insert_45(self):
# Test that properties ending in _id work.
res = await self.scon.execute(
'''
INSERT INTO "Numbered" (num_id) VALUES (10)
'''
)
res = await self.squery_values('SELECT num_id FROM "Numbered"')
self.assertEqual(res, [[10]]) | INSERT INTO "Numbered" (num_id) VALUES (10) | test_sql_dml_insert_45 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_delete_01(self):
# delete, inspect CommandComplete tag
await self.scon.execute(
'''
INSERT INTO "Document" (title)
VALUES ('Report'), ('Report'), ('Briefing')
'''
)
res = await self.scon.execute(
'''
DELETE FROM "Document"
WHERE title = 'Report (new)'
''',
)
self.assertEqual(res, 'DELETE 2') | INSERT INTO "Document" (title)
VALUES ('Report'), ('Report'), ('Briefing') | test_sql_dml_delete_01 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_delete_02(self):
# delete with returning clause, inspect CommandComplete tag
await self.scon.execute(
'''
INSERT INTO "Document" (title)
VALUES ('Report'), ('Report'), ('Briefing')
'''
)
res = await self.scon.execute(
'''
DELETE FROM "Document"
WHERE title = 'Report (new)'
RETURNING title
''',
)
self.assertEqual(res, 'DELETE 2') | INSERT INTO "Document" (title)
VALUES ('Report'), ('Report'), ('Briefing') | test_sql_dml_delete_02 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_delete_03(self):
# delete with returning clause
await self.scon.execute(
'''
INSERT INTO "Document" (title) VALUES ('Report'), ('Briefing')
'''
)
res = await self.squery_values(
'''
DELETE FROM "Document"
RETURNING title
''',
)
self.assertEqual(res, [['Report (new)'], ['Briefing (new)']]) | INSERT INTO "Document" (title) VALUES ('Report'), ('Briefing') | test_sql_dml_delete_03 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_delete_04(self):
# delete with using clause
users = await self.squery_values(
'''
INSERT INTO "User" (id) VALUES (DEFAULT), (DEFAULT) RETURNING id
'''
)
await self.squery_values(
'''
WITH u(id) as (VALUES ($1), ($2))
INSERT INTO "Document" (title, owner_id)
SELECT 'Report', u.id FROM u
RETURNING title, owner_id
''',
str(users[0][0]),
str(users[1][0]),
)
res = await self.squery_values(
'''
DELETE FROM "Document"
USING "User" u
WHERE "Document".owner_id = u.id AND title = 'Report (new)'
RETURNING title, owner_id
''',
)
self.assertEqual(
res,
[
['Report (new)', res[0][1]],
['Report (new)', res[1][1]],
],
) | INSERT INTO "User" (id) VALUES (DEFAULT), (DEFAULT) RETURNING id | test_sql_dml_delete_04 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_delete_06(self):
# delete returning *
await self.scon.execute(
'''
INSERT INTO "Document" (title) VALUES ('Report')
'''
)
res = await self.squery_values(
'''
DELETE FROM "Document" RETURNING *
''',
)
self.assertEqual(res, [[res[0][0], res[0][1], None, 'Report (new)']])
self.assertIsInstance(res[0][0], uuid.UUID)
self.assertIsInstance(res[0][1], uuid.UUID) | INSERT INTO "Document" (title) VALUES ('Report') | test_sql_dml_delete_06 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
async def test_sql_dml_delete_07(self):
# delete with CTEs
await self.scon.execute(
'''
INSERT INTO "User" DEFAULT VALUES
'''
)
await self.scon.execute(
'''
INSERT INTO "Document" (title, owner_id)
VALUES
('Report', NULL),
('Briefing', (SELECT id FROM "User" LIMIT 1))
'''
)
res = await self.squery_values(
'''
WITH
users as (SELECT id FROM "User"),
not_owned as (
SELECT d.id
FROM "Document" d
LEFT JOIN users u ON d.owner_id = u.id
WHERE u.id IS NULL
)
DELETE FROM "Document"
USING not_owned
WHERE not_owned.id = "Document".id
RETURNING title
''',
)
self.assertEqual(res, [['Report (new)']]) | INSERT INTO "User" DEFAULT VALUES | test_sql_dml_delete_07 | python | geldata/gel | tests/test_sql_dml.py | https://github.com/geldata/gel/blob/master/tests/test_sql_dml.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.