I'm unit-testing my Symfony 2 application with Codeception.
For one test, I want to fetch the associated entity in a one-to-one relationship, but I can't for the life of me figure out how to do it, because codeception complains no matter how I do it.
My first try:
$log_id = $I->grabFromRepository('BM2SiteBundle:Realm', 'log', array('id' => $realm_id));
error:
1) Failed to test the realm details in RealmBasicsCest::testRealmView
(/Volumes/User
Data/Users/Tom/Sites/BM2/src/BM2/SiteBundle/Tests/functional/RealmBasicsCest.php)
Sorry, I couldn't grab from repository
"BM2SiteBundle:Realm","log",{"id":1}:
Doctrine\ORM\Query\QueryException: [Semantical Error] line 0, col 9
near 'log FROM BM2\SiteBundle\Entity\Realm': Error: Invalid
PathExpression. Must be a StateFieldPathExpression.
2nd try:
$log_id = $I->grabFromRepository('BM2SiteBundle:EventLog', 'id', array('realm' => $realm_id));
error:
1) Failed to test the realm details in RealmBasicsCest::testRealmView
(/Volumes/User
Data/Users/Tom/Sites/BM2/src/BM2/SiteBundle/Tests/functional/RealmBasicsCest.php)
Sorry, I couldn't grab from repository
"BM2SiteBundle:EventLog","id",{"realm":1}:
Doctrine\ORM\Query\QueryException: A single-valued association path
expression to an inverse side is not supported in DQL queries. Use an
explicit join instead.
definition of the one-to-one relationship:
one-to-one field="log" target-entity="EventLog" inversed-by="realm" fetch="EXTRA_LAZY"
For further testing I need the id of the log to construct a URL.
Related
I've been playing around with unit tests for a while but I've reached a point that I'm not sure how I can achieve what I want.
I've got a test that involves a JsonResource, and within this JsonResouce I have this sample.
'id' => $this->id,
'name' => $this->name,
'state' => $this->state->name,
'users' => UsersResource::collection($this->users()->limit($userLimit)->get()),
'clients' => ClientsResource::collection($this->clients()->limit($clientLimit)->get()),
My test involves calling this JsonResource, which is related to a model of Group, that contains users and clients alongisde some other attributes.
To mock the operation that is being done before calling this JsonResource, I've used a Mock on the repository that wraps my Group class, saying it should return an instance of Group:class. It then comes the time that the jsonresource is called with this Group instance, and I need to mock these attributes, but since clients() and users() are functions, I need to mock those since there is no database access. Here comes Mockery::mock(Group::Class)
$this->groupMock = Mockery::mock(Group::class);
$this->groupMock->shouldReceive('getAttribute')->with('id')->once()->andReturn(1);
$this->groupMock->shouldReceive('getAttribute')->with('state')->once()->(new GroupState(['name' => 'some group name']));
$this->groupMock->shouldReceive('getAttribute')->with('name')->once()->andReturn('something');
I'm wondering how I can make these lines below work. As far as I can tell, it doesn't recognise the order of the method calls or "concatenating" order. Is it achievable? How could I make this work?
$this->groupMock->shouldReceive('clients')->andReturn($this->groupMock)
->shouldReceive('limit')->with(6)->andReturn($this->groupMock)
->shouldReceive('get')->andReturn(collect(factory(User::class, 2)->make()));
$this->groupMock->shouldReceive('users')->andReturn($this->groupMock)
->shouldReceive('limit')->with(8)->andReturn($this->groupMock)
->shouldReceive('get')->andReturn(collect(factory(User::class, 6)->make()))
I am trying to get data from my data source using loopback 4. It is working fine if the table name is simple and does not contain any special character.
But if there is a table with some special character like Underscore it does not allow me to create a model for that and I am not able to access the data from that table.
I have a table named "my_data" that contains column:- id,first_name,last_name.
But when I use the command lb4 model and pass the model name as my_data it converts it to my-data. and later on, when I call the API it throws an error by saying that relation publi.mydata does not exist.
WARNING: relational database doesn't support {strict: false} mode. {strict: true} mode will be set for model MyData instead.
Unhandled error in GET /my_data?filter=%7B%0A%20%20%22fields%22%3A%20%7B%0A%20%20%20%20%22id%22%3A%20true%2C%0A%20%20%20%20%first_name%22%3A%20true%2C%0A%20%20%20%20%22additionalProp1%22%3A%20%7B%7D%0A%20%20%7D%0A%7D: 500 error: relation "public.mydata" does not exist
at Connection.parseE (/Users/apple/others/loopback4/hello/node_modules/pg/lib/connection.js:614:13)
at Connection.parseMessage (/Users/apple/others/loopback4/hello/node_modules/pg/lib/connection.js:413:19)
at Socket.<anonymous> (/Users/apple/others/loopback4/hello/node_modules/pg/lib/connection.js:129:22)
at Socket.emit (events.js:315:20)
at addChunk (_stream_readable.js:297:12)
at readableAddChunk (_stream_readable.js:273:9)
at Socket.Readable.push (_stream_readable.js:214:10)
at TCP.onStreamRead (internal/stream_base_commons.js:186:23)
Is ther any way to get data from table named like this? If anyone know how to do this please let me know.
Use settings.table in the #model decorator:
#model({
settings: {
table: 'my_data',
},
})
Further reading
https://loopback.io/doc/en/lb4/Model.html#data-mapping-properties
I have a Symfony 5 project which has default authentication and User entity. I was reading Doctrine documentation in order to use $em->createQueryBuilder() function but I got this error:
[Semantical Error] line 0, col 14 near 'User u WHERE': Error: Class 'User' is not defined.
I just need to query some users with an specific role so I wrote the following code in the controller:
$em = $this->getDoctrine()->getManager();
$qb = $em->createQueryBuilder();
$category_users = $qb->select(array('u'))
->from('User', 'u')
->where('u.category = ' . $category->getId())
->setParameter('roles', '%"ROLE_CUSTOM"%')
->orderBy('u.name', 'ASC')
->getQuery()
->getResult();
I know the error does not have to do with writing the query itself and I guess this could have two questions, but just in case...
Question 1: What am I forgetting to get this error? I have read in previous versions of Symfony I should add Bundle name to from('User', 'u') but I am not sure about this version.
Question 2: Is this code optimal for this kind of query? Or maybe I am overcomplicating stuff?
You must use a FqCN for the Entity.
e.g. from('App\Entity\User', 'u')
So, I am working on migrating this php site with an existing database which I cannot change over to Rails. There is a table: Quotes with a column named type. Whenever I try and create a model of this and set the type, it tells me the following error:
ActiveRecord::SubclassNotFound (Invalid single-table inheritance type: HOME is not a subclass of Quotes)
I don't understand why it thinks its inheriting because it's not supposed to. My create method looks like this:
quote = Quotes.create(
agent_id: agent.id,
client_id: client.id,
type: 'HOME',
status: 0,
date_created: DateTime.now
)
If I comment out the type, everything works fine. But with the Type it errors.
I resolved this by setting the models inheritance_column to nil. Active Record Models can inherit from a table through the attribute :type, setting the inheritance_column to nil removes that attribute allowing you to have a database column named type
class Quote < ActiveRecord::Base
self.inheritance_column = nil
end
I hate having potential gotchas deep in the code especially in the intial processes like generating a model. Better to just change the reserved word to something else and free yourself up to take advantage of inheritance column later if the need comes up. A cleaner solution is listed here -> rename a database column name using migration
It reads;
Execute $> rails generate migration ChangeColumnName
where, ChangeColumnName is the name of our migration. This can be any name.
Now, edit the generated migration file at db/migrate/_change_column_name.rb
class ChangeColumnName < ActiveRecord::Migration
def change
rename_column :table_name, :old_column, :new_column
end
end
$> rake db:migrate
You will have to edit controller and view files e.g. if the model name is Product then you will likely edit these files
/app/views/products/_form.html.erb
/app/views/products/show.html.erb
/app/controllers/products_controller.erb
/app/views/products/index.html.erb
Trying to make a simple application in rails 3.
If I create a team model with rails g scaffold team name:string && rake db:migrate, then run rake, I get success from the prebuilt tests.
If I simply add validates_uniqueness_of :name to the team model. The functional tests fail with
1) Failure:
test_should_create_team(TeamsControllerTest) [/test/functional/teams_controller_test.rb:20]:
"Team.count" didn't change by 1.
<3> expected but was
<2>.
I modified tests/fixtures/teams.yml to look like this:
one:
name: MyString
two:
name: MyString2
The test still fails.
It can't get much more basic than this; what have I missed?
Fixtures basically represent model instances that are in the database.
If you look at the top of test/functional/teams_controller_test.rb you'll see
setup do
#team = teams(:one)
end
and then in your failing functional test you'll have
post :create, :team => #team.attributes
This is what's happening: you're trying to create a new team with the same attributes as "the team fixture named :one". Since both would have the same name (since they have the exact same attributes), the uniqueness validation is failing.
Try replacing your setup block with this
setup do
#team = teams(:one)
#team.name = 'unique name'
end
Now you'll be creating a new team with the name 'unique name' (which isn't in the database according to the fixtures), and your test will pass.