Skip to content

Commit

Permalink
Added unit tests for unlink() on HasMany association
Browse files Browse the repository at this point in the history
  • Loading branch information
Benjamin Tamási committed Aug 22, 2016
1 parent ac06672 commit 67eddd5
Showing 1 changed file with 80 additions and 0 deletions.
80 changes: 80 additions & 0 deletions tests/TestCase/ORM/Association/HasManyTest.php
Expand Up @@ -643,4 +643,84 @@ protected function assertSelectClause($expected, $query)
}
$this->assertEquals($expected, $query->clause('select'));
}

/**
* Tests that unlinking calls the right methods
*
* @return void
*/
public function testUnlinkSuccess()
{
$articles = TableRegistry::get('Articles');
$authors = TableRegistry::get('Authors');

$assoc = $authors->hasMany('Articles', [
'sourceTable' => $authors,
'targetTable' => $articles
]);

$entity = $authors->get(1, ['contain' => 'Articles']);
$initial = $entity->articles;
$this->assertCount(2, $initial);

$assoc->unlink($entity, $entity->tags);
$this->assertEmpty($entity->get('articles'), 'Property should be empty');

$new = $articles->get(2, ['contain' => 'Articles']);
$this->assertCount(0, $new->articles, 'DB should be clean');
$this->assertSame(4, $authors->find()->count(), 'Authors should still exist');
$this->assertSame(3, $articles->find()->count(), 'Articles should still exist');
}

/**
* Tests that unlink will work without contain() being called
*/
public function testUnlinkWithoutContain()
{
$articles = TableRegistry::get('Articles');
$authors = TableRegistry::get('Authors');

$assoc = $authors->hasMany('Articles', [
'sourceTable' => $authors,
'targetTable' => $articles
]);

$entity = $authors->get(1);
$entities = $articles->find()->where(['Articles.author_id' => $entity->id])->all();
$this->assertCount(2, $entities);

$assoc->unlink($entity, $entities);

$new = $articles->get(2, ['contain' => 'Articles']);
$this->assertCount(0, $new->articles, 'DB should be clean');
$this->assertSame(4, $authors->find()->count(), 'Authors should still exist');
$this->assertSame(3, $articles->find()->count(), 'Articles should still exist');
}

/**
* Tests that unlink with an empty array does nothing
*
* @return void
*/
public function testUnlinkWithEmptyArray()
{
$articles = TableRegistry::get('Articles');
$authors = TableRegistry::get('Authors');

$assoc = $authors->hasMany('Articles', [
'sourceTable' => $authors,
'targetTable' => $articles
]);

$entity = $authors->get(1, ['contain' => 'Articles']);
$initial = $entity->articles;
$this->assertCount(2, $initial);

$assoc->unlink($entity, []); // Unlink with empty array

$new = $articles->get(2, ['contain' => 'Articles']);
$this->assertCount(2, $new->articles, 'Articles should remain linked');
$this->assertSame(4, $authors->find()->count(), 'Authors should still exist');
$this->assertSame(3, $articles->find()->count(), 'Articles should still exist');
}
}

0 comments on commit 67eddd5

Please sign in to comment.