public function SensorDataApiTest::testApiPost in farmOS 2.x
Test API POST requests.
File
- modules/
asset/ sensor/ tests/ src/ Functional/ SensorDataApiTest.php, line 85
Class
- SensorDataApiTest
- Test the Sensor data API.
Namespace
Drupal\Tests\farm_sensor\FunctionalCode
public function testApiPost() {
// Build the path.
$uri = $this
->buildPath($this->asset);
$url = Url::fromUri($uri);
// Build a private_key query param.
$private_key = [
RequestOptions::QUERY => [
'private_key' => $this->asset
->get('private_key')->value,
],
];
// Make the asset public. This should not matter for posting data.
$this->asset
->set('public', TRUE)
->save();
// Test data.
$test_data = [
'test_1' => 100,
'test_2' => 200,
];
// Make a request without a private key.
$payload = [
RequestOptions::BODY => Json::encode($test_data),
];
$response = $this
->processRequest('POST', $url, $payload);
// Assert that access is denied.
$this
->assertEquals(403, $response
->getStatusCode());
// Post data with a private key.
$response = $this
->processRequest('POST', $url, $private_key + $payload);
$this
->assertEquals(201, $response
->getStatusCode());
// Assert that new data streams were created.
$this->asset = Asset::load($this->asset
->id());
$data_streams = $this->asset
->get('data_stream')
->referencedEntities();
$this
->assertEquals(2, count($data_streams));
// Assert that new data was saved in DB.
$response = $this
->processRequest('GET', $url);
$data = Json::decode($response
->getBody());
$this
->assertEquals(2, count($data));
// More test data.
$test_data = [
'test_1' => 101,
'test_2' => 201,
];
// Post data with a private key.
$payload = [
RequestOptions::BODY => Json::encode($test_data),
];
$response = $this
->processRequest('POST', $url, $private_key + $payload);
$this
->assertEquals(201, $response
->getStatusCode());
// Assert that no new data streams were created.
$this->asset = Asset::load($this->asset
->id());
$data_streams = $this->asset
->get('data_stream')
->referencedEntities();
$this
->assertEquals(2, count($data_streams));
// Assert that new data was saved in DB.
$response = $this
->processRequest('GET', $url);
$data = Json::decode($response
->getBody());
$this
->assertEquals(4, count($data));
}