def test_limit_offset_w_ambiguous_cols(self): t = table("t", column("x", Integer), column("y", Integer)) cols = [t.c.x, t.c.x.label("q"), t.c.x.label("p"), t.c.y] s = select(cols).where(t.c.x == 5).order_by(t.c.y).limit(10).offset(20) self.assert_compile( s, "SELECT anon_1.x, anon_1.q, anon_1.p, anon_1.y " "FROM (SELECT t.x AS x, t.x AS q, t.x AS p, t.y AS y, " "ROW_NUMBER() OVER (ORDER BY t.y) AS mssql_rn " "FROM t " "WHERE t.x = :x_1) AS anon_1 " "WHERE mssql_rn > :param_1 AND mssql_rn <= :param_2 + :param_1", checkparams={ "param_1": 20, "param_2": 10, "x_1": 5 }, ) c = s.compile(dialect=mssql.dialect()) eq_(len(c._result_columns), 4) result_map = c._create_result_map() for col in cols: is_(result_map[col.key][1][0], col)
def test_password_custom_obj(self): class SecurePassword(str): def __init__(self, value): self.value = value def __str__(self): return self.value sp = SecurePassword("secured_password") u = url.URL("dbtype", username="******", password=sp, host="localhost") eq_(u.password, "secured_password") eq_(str(u), "dbtype://*****:*****@localhost") # test in-place modification sp.value = "new_secured_password" eq_(u.password, "new_secured_password") eq_(str(u), "dbtype://*****:*****@localhost") u.password = "******" eq_(u.password, "hi") eq_(str(u), "dbtype://*****:*****@localhost") u.password = None is_(u.password, None) eq_(str(u), "dbtype://x@localhost")
def test_insp_column_prop(self): User = self.classes.User prop = inspect(User.name) is_(prop, User.name) is_(prop.parent, class_mapper(User)) assert not hasattr(prop, "mapper")
def test_info_from_hybrid(self): A = self._fixture() A._value.info["foo"] = "bar" A.value.info["bar"] = "hoho" insp = inspect(A) is_(insp.all_orm_descriptors["value"].info, A.value.info)
def test_cast_type(self): Json = self.classes.Json s = Session(testing.db) j = Json(json={"field": 10}) s.add(j) s.commit() jq = s.query(Json).filter(Json.int_field == 10).one() eq_(j.id, jq.id) jq = s.query(Json).filter(Json.text_field == "10").one() eq_(j.id, jq.id) jq = s.query(Json).filter(Json.json_field.astext == "10").one() eq_(j.id, jq.id) jq = s.query(Json).filter(Json.text_field == "wrong").first() is_(jq, None) j.json = {"field": True} s.commit() jq = s.query(Json).filter(Json.text_field == "true").one() eq_(j.id, jq.id)
def test_select(self): t = Table("t", MetaData(), Column("x", Integer)) s = t.select() is_(inspect(s), s) assert s.is_selectable is_(s.selectable, s)
def test_synonym_filter(self): User = self.classes.User syn = inspect(User).synonyms eq_(list(syn.keys()), ["name_syn"]) is_(syn.name_syn, User.name_syn.original_property) eq_(dict(syn), {"name_syn": User.name_syn.original_property})
def test_fixed_char(self, char_type): m = self.metadata t = Table( "t1", m, Column("id", Integer, primary_key=True), Column("data", char_type(30), nullable=False), ) if py2k and char_type is NCHAR: v1, v2, v3 = u"value 1", u"value 2", u"value 3" else: v1, v2, v3 = "value 1", "value 2", "value 3" with testing.db.begin() as conn: t.create(conn) conn.execute( t.insert(), dict(id=1, data=v1), dict(id=2, data=v2), dict(id=3, data=v3), ) eq_( conn.execute(t.select().where(t.c.data == v2)).fetchall(), [(2, "value 2 ")], ) m2 = MetaData() t2 = Table("t1", m2, autoload_with=conn) is_(type(t2.c.data.type), char_type) eq_( conn.execute(t2.select().where(t2.c.data == v2)).fetchall(), [(2, "value 2 ")], )
def test_mapper_selectable(self): User = self.classes.User user_table = self.tables.users insp = inspect(User) is_(insp.selectable, user_table) assert not insp.is_selectable assert not insp.is_aliased_class
def test_deprecated_dialect_name_still_loads(self): dialects.registry.clear() with expect_deprecated( "The 'postgres' dialect name " "has been renamed to 'postgresql'" ): dialect = url.URL("postgres").get_dialect() is_(dialect, postgresql.dialect)
def test_no_instance_level_collections(self): @event.listens_for(self.Target, "event_one") def listen_one(x, y): pass t1 = self.Target() t2 = self.Target() t1.dispatch.event_one(5, 6) t2.dispatch.event_one(5, 6) is_( self.Target.dispatch._empty_listener_reg[self.Target]["event_one"], t1.dispatch.event_one, ) @event.listens_for(t1, "event_one") def listen_two(x, y): pass is_not( self.Target.dispatch._empty_listener_reg[self.Target]["event_one"], t1.dispatch.event_one, ) is_( self.Target.dispatch._empty_listener_reg[self.Target]["event_one"], t2.dispatch.event_one, )
def test_name_normalize(self, original, normalized, is_quote): orig_norm = self.dialect.normalize_name(original) eq_(orig_norm, normalized) if is_quote: is_(orig_norm.quote, True) else: assert not isinstance(orig_norm, quoted_name)
def test_backref_events(self): User, Address = self._user_address_fixture( addresses_args={"backref": "user"}) u1 = User() a1 = Address() u1.addresses.append(a1) is_(a1.user, u1)
def test_reflection(self): Table("mysql_json", self.metadata, Column("foo", mysql.JSON)) self.metadata.create_all() reflected = Table("mysql_json", MetaData(), autoload_with=testing.db) is_(reflected.c.foo.type._type_affinity, sqltypes.JSON) assert isinstance(reflected.c.foo.type, mysql.JSON)
def test_aliased_class(self): Address = self.classes.Address ualias = aliased(Address) insp = inspect(ualias) is_(insp.mapper, inspect(Address)) is_(insp.selectable, ualias._aliased_insp.selectable) assert not insp.is_selectable assert insp.is_aliased_class
def test_subclass_getitem(self, get_dilbert): session = Session() dilbert = get_dilbert(session) is_( dilbert, session.query(Engineer).filter( Engineer.engineer_name == "engineer1")[0], )
def test_session_accessor(self): User = self.classes.User u1 = User(name="ed") insp = inspect(u1) is_(insp.session, None) s = Session() s.add(u1) is_(insp.session, s)
def test_instance_state_ident_persistent(self): User = self.classes.User u1 = User(name="ed") s = Session(testing.db) s.add(u1) s.flush() insp = inspect(u1) eq_(insp.identity, (u1.id, )) is_(s.query(User).get(insp.identity), u1)
def test_bind_joined_sub_class_joined_sub_class(self): base_class_bind = Mock(name="base") joined_class_bind = Mock(name="joined") session = self._fixture({ self.classes.BaseClass: base_class_bind, self.classes.JoinedSubClass: joined_class_bind, }) is_(session.get_bind(self.classes.BaseClass), base_class_bind) is_(session.get_bind(self.classes.JoinedSubClass), joined_class_bind)
def test_baseclass_sub_table_filter(self, get_dilbert): session = Session() dilbert = get_dilbert(session) is_( dilbert, session.query(Person).filter( (Engineer.engineer_name == "engineer1") & (engineers.c.person_id == people.c.person_id)).first(), )
def test_col_filter(self): User = self.classes.User insp = inspect(User) eq_( list(insp.column_attrs), [insp.get_property("id"), insp.get_property("name")], ) eq_(list(insp.column_attrs.keys()), ["id", "name"]) is_(insp.column_attrs.id, User.id.property)
def test_col_property(self): User = self.classes.User user_table = self.tables.users insp = inspect(User) id_prop = insp.attrs.id eq_(id_prop.columns, [user_table.c.id]) is_(id_prop.expression, user_table.c.id) assert not hasattr(id_prop, "mapper")
def test_executemany_correct_flag_options(self): for opt, expected in [ (None, EXECUTEMANY_DEFAULT), ("batch", EXECUTEMANY_BATCH), ("values", EXECUTEMANY_VALUES), ]: self.engine = engines.testing_engine( options={"executemany_mode": opt} ) is_(self.engine.dialect.executemany_mode, expected)
def test_array_agg_array_literal_explicit_type(self): from sqlalchemy_1_3.dialects.postgresql import array expr = array([column("data", Integer), column("d2", Integer)]) agg_expr = func.array_agg(expr, type_=ARRAY(Integer)) is_(agg_expr.type._type_affinity, ARRAY) is_(agg_expr.type.item_type._type_affinity, Integer) self.assert_compile( agg_expr, "array_agg(ARRAY[data, d2])", dialect="postgresql" )
def test_subclass_base_alias_filter(self, get_dilbert): session = Session() dilbert = get_dilbert(session) palias = people.alias("palias") is_( dilbert, session.query(Engineer).filter( (palias.c.name == "dilbert") & (palias.c.person_id == Person.person_id)).first(), )
def test_collection_assignment_mutates_previous_two(self): User, Address = self.classes.User, self.classes.Address u1 = User(name="jack") a1 = Address(email_address="a1") u1.addresses.append(a1) is_(a1.user, u1) u1.addresses = [] is_(a1.user, None)
def test_update_unordered_dict(self): User = self.classes.User session = Session() # Do an update using unordered dict and check that the parameters used # are ordered in table order q = session.query(User) with mock.patch.object(q, "_execute_crud") as exec_: q.filter(User.id == 15).update({"name": "foob", "id": 123}) # Confirm that parameters are a dict instead of tuple or list params_type = type(exec_.mock_calls[0][1][0].parameters) is_(params_type, dict)
def test_del_from_collection(self): User, Address = self.classes.User, self.classes.Address u1 = User(name="jack") a1 = Address(email_address="a1") u1.addresses.append(a1) is_(a1.user, u1) del u1.addresses[0] is_(a1.user, None)
def test_indexed_entity(self): umapper = inspect(self.classes.User) amapper = inspect(self.classes.Address) path = PathRegistry.coerce( ( umapper, umapper.attrs.addresses, amapper, amapper.attrs.email_address, ) ) is_(path[0], umapper) is_(path[2], amapper)
def test_del_from_scalar(self): User, Address = self.classes.User, self.classes.Address u1 = User(name="jack") a1 = Address(email_address="a1") u1.addresses.append(a1) is_(a1.user, u1) del a1.user assert a1 not in u1.addresses