Browse Source

Add integration test for the CaseExpression

Walther Lalk 11 years ago
parent
commit
820f52289b
1 changed files with 71 additions and 0 deletions
  1. 71 0
      tests/TestCase/Database/QueryTest.php

+ 71 - 0
tests/TestCase/Database/QueryTest.php

@@ -2717,6 +2717,77 @@ class QueryTest extends TestCase {
 	}
 
 /**
+ * Tests that case statements work correctly for various use-cases.
+ *
+ * @return void
+ */
+	public function testSqlCaseStatement() {
+		$query = new Query($this->connection);
+		$publishedCase = $query
+			->newExpr()
+			->addCase($query
+				->newExpr()
+				->add(['published' => 'Y'])
+			);
+		$notPublishedCase = $query
+			->newExpr()
+			->addCase($query
+					->newExpr()
+					->add(['published' => 'N'])
+			);
+		$results = $query
+			->select([
+				'published' => $query->func()->sum($publishedCase),
+				'not_published' => $query->func()->sum($notPublishedCase)
+			])
+			->from(['comments'])
+			->execute()
+			->fetchAll('assoc');
+
+		$this->assertEquals(5, $results[0]['published']);
+		$this->assertEquals(1, $results[0]['not_published']);
+
+		$query = new Query($this->connection);
+		$query
+			->insert(['article_id', 'user_id', 'comment', 'published'])
+			->into('comments')
+			->values([
+				'article_id' => 2,
+				'user_id' => 1,
+				'comment' => 'In limbo',
+				'published' => 'L'
+			])
+			->execute();
+
+		$query = new Query($this->connection);
+		$conditions = [
+			$query
+				->newExpr()
+				->add(['published' => 'Y']),
+			$query
+				->newExpr()
+				->add(['published' => 'N'])
+		];
+		$trueValues = [
+			'Published',
+			'Not published'
+		];
+		$results = $query
+			->select([
+				'id',
+				'comment',
+				'status' => $query->newExpr()->addCase($conditions, $trueValues, 'None')
+			])
+			->from(['comments'])
+			->execute()
+			->fetchAll('assoc');
+
+		$this->assertEquals('Published', $results[2]['status']);
+		$this->assertEquals('Not published', $results[3]['status']);
+		$this->assertEquals('None', $results[6]['status']);
+	}
+
+/**
  * Assertion for comparing a table's contents with what is in it.
  *
  * @param string $table