Skip to content

Commit

Permalink
Added unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
pookmish committed May 28, 2024
1 parent b263111 commit 304a8d8
Show file tree
Hide file tree
Showing 4 changed files with 160 additions and 61 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ public function loadOverrides($names) {
$overrides['migrate_plus.migration.su_stanford_person']['source']['plugin'] = 'cap_url';
$overrides['migrate_plus.migration.su_stanford_person']['source']['authentication']['client_id'] = $this->getCapClientId();
$overrides['migrate_plus.migration.su_stanford_person']['source']['authentication']['client_secret'] = $this->getCapClientSecret();

$overrides['migrate_plus.migration.su_stanford_person']['status'] = $this->getCapClientId() && $this->getCapClientSecret();
}
return $overrides;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,15 @@

namespace Drupal\stanford_person_importer\Plugin\migrate\source;

use Drupal\config_pages\ConfigPagesLoaderServiceInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Url;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate_plus\Plugin\migrate\source\Url as UrlPlugin;
use Drupal\stanford_person_importer\CapInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
* Source plugin for retrieving data via CAP URLs.
Expand All @@ -13,38 +19,42 @@
* id = "cap_url"
* )
*/
class CapUrl extends UrlPlugin {
class CapUrl extends UrlPlugin implements ContainerFactoryPluginInterface {

const URL_CHUNKS = 15;

/**
* Cap service.
*
* @var \Drupal\stanford_person_importer\CapInterface
* {@inheritDoc}
*/
protected $cap;

protected $configPages;

public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $migration);

$this->cap = \Drupal::service('stanford_person_importer.cap');
$this->configPages = \Drupal::service('@config_pages.loader');
$this->configFactory = \Drupal::configFactory();
$this->entityTypeManager = \Drupal::entityTypeManager();
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$migration,
$container->get('stanford_person_importer.cap'),
$container->get('config_pages.loader'),
$container->get('config.factory'),
$container->get('entity_type.manager')
);
}

/**
* {@inheritDoc}
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration, protected CapInterface $cap, protected ConfigPagesLoaderServiceInterface $configPages, protected ConfigFactoryInterface $configFactory, protected EntityTypeManagerInterface $entityTypeManager) {
$this->sourceUrls = $this->getImporterUrls();
$configuration['urls'] = $this->sourceUrls;
parent::__construct($configuration, $plugin_id, $plugin_definition, $migration);
}


/**
* Get a list of urls for the importer.
*
* @return array|null
* Array of urls or NULL if any errors occur.
*/
protected function getImporterUrls(): ?array {
protected function getImporterUrls(): array {
$urls = &drupal_static('cap_source_urls');
if ($urls !== NULL) {
return $urls;
Expand All @@ -58,7 +68,7 @@ protected function getImporterUrls(): ?array {
$urls = array_merge($urls, $this->getSunetUrls());
}
catch (\Exception $e) {
return NULL;
return [];
}

$allowed_fields = $this->getAllowedFields();
Expand All @@ -77,8 +87,8 @@ protected function getImporterUrls(): ?array {
* Array of CAP selectors.
*/
protected function getAllowedFields() {
$allowed_fields = $this->configFactory->getEditable('migrate_plus.migration.su_stanford_person')
->getOriginal('source.fields') ?: [];
$allowed_fields = $this->configFactory->get('migrate_plus.migration.su_stanford_person')
->get('source.fields') ?: [];
foreach ($allowed_fields as &$field) {
$field = $field['selector'];
if ($slash_position = strpos($field, '/')) {
Expand Down Expand Up @@ -128,11 +138,7 @@ protected function getOrgsUrls() {
*/
protected function getWorkgroupUrls(): array {
$workgroups = array_filter($this->configPages->getValue('stanford_person_importer', 'su_person_workgroup', [], 'value') ?? []);

if ($workgroups) {
return $this->getUrlChunks($this->cap->getWorkgroupUrl($workgroups));
}
return [];
return $workgroups ? $this->getUrlChunks($this->cap->getWorkgroupUrl($workgroups)) : [];
}

/**
Expand All @@ -146,7 +152,9 @@ protected function getSunetUrls(): array {

$urls = [];
foreach (array_chunk($sunets, self::URL_CHUNKS) as $chunk) {
$urls[] = $this->cap->getSunetUrl($chunk)->toString(TRUE)->getGeneratedUrl();
$urls[] = $this->cap->getSunetUrl($chunk)
->toString(TRUE)
->getGeneratedUrl();
}
return $urls;
}
Expand Down Expand Up @@ -195,4 +203,5 @@ protected function getCapClientId(): string {
protected function getCapClientSecret(): string {
return $this->configPages->getValue('stanford_person_importer', 'su_person_cap_password', 0, 'value') ?? '';
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,6 @@ protected function getCapService() {
->willReturn(Url::fromUri('http://localhost.orgs'));
$cap->method('getWorkgroupUrl')
->willReturn(Url::fromUri('http://localhost.workgroup'));
$cap->method('getSunetUrl')
->will($this->returnCallback([$this, 'getSunetUrlCallback']));

return $cap;
}
Expand All @@ -127,13 +125,12 @@ public function testBasicMethods() {
}

/**
* Test the config overrides when theres no urls.
* Test the config overrides when there's no urls.
*/
public function testEmptyConfigOverrides() {
$overrides = $this->configOverrides->loadOverrides(['migrate_plus.migration.su_stanford_person']);
$this->assertEmpty($overrides['migrate_plus.migration.su_stanford_person']['source']['authentication']['client_id']);
$this->assertEmpty($overrides['migrate_plus.migration.su_stanford_person']['source']['authentication']['client_secret']);
$this->assertEmpty($overrides['migrate_plus.migration.su_stanford_person']['source']['urls']);
}

/**
Expand All @@ -156,38 +153,10 @@ public function testConfigOverrides() {
}
});

$this->configOverrides->loadOverrides(['migrate_plus.migration.su_stanford_person']);

drupal_static_reset('cap_source_urls');
$overrides = $this->configOverrides->loadOverrides(['migrate_plus.migration.su_stanford_person']);

$expected_urls = [
'http://localhost.orgs?ps=15&whitelist=fooBar,barFoo',
'http://localhost.workgroup?p=1&ps=15&whitelist=fooBar,barFoo',
'http://localhost.workgroup?p=2&ps=15&whitelist=fooBar,barFoo',
'http://localhost.sunet?whitelist=fooBar,barFoo',
];
asort($expected_urls);
asort($overrides['migrate_plus.migration.su_stanford_person']['source']['urls']);
foreach ($overrides['migrate_plus.migration.su_stanford_person']['source']['urls'] as &$url) {
$url = urldecode($url);
}
$this->assertEquals(array_values($expected_urls), array_values($overrides['migrate_plus.migration.su_stanford_person']['source']['urls']));

$this->sunetUrlError = TRUE;
drupal_static_reset('cap_source_urls');
$overrides = $this->configOverrides->loadOverrides(['migrate_plus.migration.su_stanford_person']);
$this->assertFalse($overrides['migrate_plus.migration.su_stanford_person']['status']);
}

/**
* Cap mock service callback.
*/
public function getSunetUrlCallback() {
if ($this->sunetUrlError) {
throw new \Exception('Error getting sunet url');
}
return Url::fromUri('http://localhost.sunet');
$this->assertEquals('foo', $overrides['migrate_plus.migration.su_stanford_person']['source']['authentication']['client_id']);
$this->assertEquals('bar', $overrides['migrate_plus.migration.su_stanford_person']['source']['authentication']['client_secret']);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
<?php

namespace Drupal\Tests\stanford_person_importer\Unit\Plugin\migrate\source;

use Drupal\config_pages\ConfigPagesLoaderServiceInterface;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
use Drupal\Core\Url;
use Drupal\Core\Utility\UnroutedUrlAssembler;
use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\stanford_person_importer\CapInterface;
use Drupal\stanford_person_importer\Plugin\migrate\source\CapUrl;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;

class CapUrlTest extends UnitTestCase {

protected $plugin;

protected $profileCount = 10;

public function testUrls() {
$config_pages = $this->createMock(ConfigPagesLoaderServiceInterface::class);

$config_pages->method('getValue')
->will($this->returnCallback([$this, 'getConfigPageValue']));
$entity = $this->createMock(ContentEntityInterface::class);
$field_list = $this->createMock(FieldItemListInterface::class);
$field_list->method('getString')->willReturn('org:code');
$entity->method('get')->willReturn($field_list);
$entity_storage = $this->createMock(EntityStorageInterface::class);
$entity_storage->method('load')->willReturn($entity);
$entity_type_manager = $this->createMock(EntityTypeManagerInterface::class);
$entity_type_manager->method('getStorage')->willReturn($entity_storage);
$migration = $this->createMock(MigrationInterface::class);

$container = new ContainerBuilder();

$container->set('config_pages.loader', $config_pages);
$container->set('config.factory', $this->getConfigFactoryStub([
'migrate_plus.migration.su_stanford_person' => [
'source' => [
'fields' => [
['selector' => 'foo'],
['selector' => 'bar/bin/foo'],
['selector' => 'baz'],
],
],
],
]));
$container->set('entity_type.manager', $entity_type_manager);
$container->set('unrouted_url_assembler', $this->getUrlAssembler());

$cap = $this->createMock(CapInterface::class);
$cap->method('getTotalProfileCount')
->will($this->returnCallback([$this, 'getCapProfileCount']));
$cap->method('getOrganizationUrl')
->willReturn(Url::fromUri('http://orgurl'));
$cap->method('getWorkgroupUrl')
->willReturn(Url::fromUri('http://workgroupurl'));
$cap->method('getSunetUrl')
->willReturn(Url::fromUri('http://suneturl'));

$container->set('stanford_person_importer.cap', $cap);
\Drupal::setContainer($container);

$plugin = TestCapUrl::create($container, [
'fields' => [],
'ids' => [],
], 'cap_url', [], $migration);

$this->assertEquals([
'http://orgurl?ps=15&whitelist=foo%2Cbar%2Cbaz',
'http://workgroupurl?p=1&ps=15&whitelist=foo%2Cbar%2Cbaz',
'http://workgroupurl?p=2&ps=15&whitelist=foo%2Cbar%2Cbaz',
'http://suneturl?whitelist=foo%2Cbar%2Cbaz',
], $plugin->getSourceUrls());
}

public function getConfigPageValue($bundle, $field, $delta, $key) {
switch ($field) {
case 'su_person_orgs':
return [1, 2, 3];
case 'su_person_child_orgs':
return FALSE;
case 'su_person_workgroup':
return ['bar:foo', 'bin:foo'];
case 'su_person_sunetid':
return ['foofoofoo'];
}
}

protected function getUrlAssembler() {
$request_stack = new RequestStack();
$request_stack->push(new Request());
$path_processor = $this->createMock(OutboundPathProcessorInterface::class);
return new UnroutedUrlAssembler($request_stack, $path_processor);
}

public function getCapProfileCount() {
$count = $this->profileCount;
$this->profileCount += 10;
return $count;
}

}

class TestCapUrl extends CapUrl {

public function getSourceUrls() {
return $this->sourceUrls;
}

}

0 comments on commit 304a8d8

Please sign in to comment.