View source  
  <?php
namespace Drupal\Tests\lingotek\Functional;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\language\Entity\ContentLanguageSettings;
use Drupal\lingotek\Entity\LingotekProfile;
use Drupal\lingotek\Lingotek;
use Drupal\node\Entity\Node;
use GuzzleHttp\Exception\ServerException;
use Symfony\Component\HttpFoundation\Response;
class LingotekNodeNotificationCallbackQueueWorkerTest extends LingotekTestBase {
  
  public static $modules = [
    'block',
    'node',
  ];
  
  protected $node;
  protected function setUp() : void {
    parent::setUp();
    
    $this
      ->drupalPlaceBlock('page_title_block', [
      'region' => 'header',
      'weight' => -5,
    ]);
    $this
      ->drupalPlaceBlock('local_tasks_block', [
      'region' => 'header',
      'weight' => -10,
    ]);
    
    $this
      ->drupalCreateContentType([
      'type' => 'article',
      'name' => 'Article',
    ]);
    
    ConfigurableLanguage::createFromLangcode('es')
      ->save();
    
    ContentLanguageSettings::loadByEntityTypeBundle('node', 'article')
      ->setLanguageAlterable(TRUE)
      ->save();
    \Drupal::service('content_translation.manager')
      ->setEnabled('node', 'article', TRUE);
    drupal_static_reset();
    \Drupal::entityTypeManager()
      ->clearCachedDefinitions();
    $this
      ->applyEntityUpdates();
    
    $this
      ->rebuildContainer();
    $this
      ->saveLingotekContentTranslationSettingsForNodeTypes();
    $profile = LingotekProfile::create([
      'id' => 'automatic_worker',
      'label' => 'Custom profile',
      'auto_upload' => TRUE,
      'auto_request' => TRUE,
      'auto_download' => TRUE,
      'auto_download_worker' => TRUE,
    ]);
    $profile
      ->save();
  }
  
  public function testAutomatedNotificationNodeTranslation() {
    
    $this
      ->drupalLogin($this->rootUser);
    
    $edit = [];
    $edit['title[0][value]'] = 'Llamas are cool';
    $edit['body[0][value]'] = 'Llamas are very cool';
    $edit['langcode[0][value]'] = 'en';
    $edit['lingotek_translation_management[lingotek_translation_profile]'] = 'automatic_worker';
    $this
      ->saveAndPublishNodeForm($edit);
    
    $node = Node::load(1);
    
    $content_translation_service = \Drupal::service('lingotek.content_translation');
    
    $this
      ->assertIdentical(Lingotek::STATUS_IMPORTING, $content_translation_service
      ->getSourceStatus($node));
    $this
      ->goToContentBulkManagementForm();
    
    $url = Url::fromRoute('lingotek.notify', [], [
      'query' => [
        'project_id' => 'test_project',
        'document_id' => 'dummy-document-hash-id',
        'complete' => 'false',
        'type' => 'document_uploaded',
        'progress' => '0',
      ],
    ])
      ->setAbsolute()
      ->toString();
    $request = $this->client
      ->post($url, [
      'cookies' => $this->cookies,
      'headers' => [
        'Accept' => 'application/json',
        'Content-Type' => 'application/json',
      ],
      'http_errors' => FALSE,
    ]);
    $response = json_decode($request
      ->getBody(), TRUE);
    $this
      ->verbose($request);
    $this
      ->assertIdentical([
      'es',
    ], $response['result']['request_translations'], 'Spanish language has been requested after notification automatically.');
    $this
      ->goToContentBulkManagementForm();
    $node = $this
      ->resetStorageCachesAndReloadNode();
    
    $this
      ->assertIdentical(Lingotek::STATUS_CURRENT, $content_translation_service
      ->getSourceStatus($node));
    
    $this
      ->assertIdentical(Lingotek::STATUS_PENDING, $content_translation_service
      ->getTargetStatus($node, 'es'));
    $this
      ->goToContentBulkManagementForm();
    
    $url = Url::fromRoute('lingotek.notify', [], [
      'query' => [
        'project_id' => 'test_project',
        'document_id' => 'dummy-document-hash-id',
        'locale_code' => 'es-ES',
        'locale' => 'es_ES',
        'complete' => 'true',
        'type' => 'target',
        'progress' => '100',
      ],
    ])
      ->setAbsolute()
      ->toString();
    $request = $this->client
      ->post($url, [
      'cookies' => $this->cookies,
      'headers' => [
        'Accept' => 'application/json',
        'Content-Type' => 'application/json',
      ],
      'http_errors' => FALSE,
    ]);
    $response = json_decode($request
      ->getBody(), TRUE);
    $this
      ->verbose($request);
    $this
      ->assertTrue($response['result']['download_queued'], 'Spanish language has been queued after notification automatically.');
    $this
      ->goToContentBulkManagementForm();
    $node = $this
      ->resetStorageCachesAndReloadNode();
    
    $this
      ->assertIdentical(Lingotek::STATUS_READY, $content_translation_service
      ->getTargetStatus($node, 'es'));
    $this
      ->goToContentBulkManagementForm();
    $this
      ->assertTargetStatus('ES', Lingotek::STATUS_READY);
    
    $this->container
      ->get('cron')
      ->run();
    $this
      ->goToContentBulkManagementForm();
    $this
      ->assertTargetStatus('ES', Lingotek::STATUS_CURRENT);
  }
  
  public function testNotificationsInARow() {
    ConfigurableLanguage::createFromLangcode('it')
      ->save();
    ConfigurableLanguage::createFromLangcode('ca')
      ->save();
    ConfigurableLanguage::createFromLangcode('hu')
      ->save();
    ConfigurableLanguage::createFromLangcode('de')
      ->save();
    
    $edit = [];
    $edit['title[0][value]'] = 'Llamas are cool';
    $edit['body[0][value]'] = 'Llamas are very cool';
    $edit['langcode[0][value]'] = 'en';
    $edit['lingotek_translation_management[lingotek_translation_profile]'] = 'automatic_worker';
    $this
      ->saveAndPublishNodeForm($edit);
    $this
      ->goToContentBulkManagementForm();
    
    $this
      ->clickLink('EN');
    $this
      ->assertText('The import for node Llamas are cool is complete.');
    
    $languages = [
      'DE' => 'de_DE',
      'ES' => 'es_ES',
      'HU' => 'hu_HU',
      'IT' => 'it_IT',
      'CA' => 'ca_ES',
    ];
    foreach ($languages as $langcode => $locale) {
      $this
        ->clickLink($langcode);
      $this
        ->assertText(new FormattableMarkup("Locale '@locale' was added as a translation target for node Llamas are cool.", [
        '@locale' => $locale,
      ]));
    }
    
    $requests = [];
    foreach ($languages as $langcode => $locale) {
      $url = Url::fromRoute('lingotek.notify', [], [
        'query' => [
          'project_id' => 'test_project',
          'document_id' => 'dummy-document-hash-id',
          'locale_code' => str_replace('_', '-', $locale),
          'locale' => $locale,
          'complete' => 'true',
          'type' => 'target',
          'progress' => '100',
        ],
      ])
        ->setAbsolute()
        ->toString();
      $requests[] = \Drupal::httpClient()
        ->postAsync($url);
    }
    $count = 0;
    
    foreach ($requests as $request) {
      try {
        $request
          ->then(function ($response) use ($request) {
          $message = new TranslatableMarkup('FULFILLED. Got a response with status %status and body: %body', [
            '%status' => $response
              ->getStatusCode(),
            '%body' => (string) $response
              ->getBody(TRUE),
          ]);
          $this
            ->verbose($message);
        }, function ($response) use ($request) {
          $message = new TranslatableMarkup('REJECTED. Got a response with status %status and body: %body', [
            '%status' => $response
              ->getStatusCode(),
            '%body' => (string) $response
              ->getBody(TRUE),
          ]);
          $this
            ->verbose($message);
        });
      } catch (\Exception $error) {
        $count++;
      }
    }
    foreach ($requests as $request) {
      $request
        ->wait(TRUE);
    }
    
    $this
      ->goToContentBulkManagementForm();
    
    $current_links = $this
      ->xpath("//a[contains(@class,'language-icon') and contains(@class, 'target-ready')]");
    $this
      ->assertEqual(count($current_links), count($languages) - $count, new FormattableMarkup('Various languages (@var) are ready.', [
      '@var' => count($languages) - $count,
    ]));
    $this
      ->assertTrue(TRUE, new FormattableMarkup('@count target languages failed, but error where given back so the TMS can retry.', [
      '@count' => $count,
    ]));
    $this
      ->assertEqual(5, count($current_links), new FormattableMarkup('All languages (@var) are ready.', [
      '@var' => count($current_links),
    ]));
    
    $this->container
      ->get('cron')
      ->run();
    $this
      ->goToContentBulkManagementForm();
    $current_links = $this
      ->xpath("//a[contains(@class,'language-icon') and contains(@class, 'target-current')]");
    $this
      ->assertEqual(count($current_links), count($languages) - $count, new FormattableMarkup('Various languages (@var) are current.', [
      '@var' => count($languages) - $count,
    ]));
    $this
      ->assertTrue(TRUE, new FormattableMarkup('@count target languages failed, but error where given back so the TMS can retry.', [
      '@count' => $count,
    ]));
    $this
      ->assertEqual(5, count($current_links), new FormattableMarkup('All languages (@var) are current.', [
      '@var' => count($current_links),
    ]));
  }
  
  public function testAutomatedNotificationNodeTranslationWithError() {
    
    ConfigurableLanguage::createFromLangcode('it')
      ->save();
    
    $edit = [];
    $edit['title[0][value]'] = 'Llamas are cool';
    $edit['body[0][value]'] = 'Llamas are very cool';
    $edit['langcode[0][value]'] = 'en';
    $edit['lingotek_translation_management[lingotek_translation_profile]'] = 'automatic_worker';
    $this
      ->saveAndPublishNodeForm($edit);
    
    $url = Url::fromRoute('lingotek.notify', [], [
      'query' => [
        'project_id' => 'test_project',
        'document_id' => 'dummy-document-hash-id',
        'complete' => 'false',
        'type' => 'document_uploaded',
        'progress' => '0',
      ],
    ])
      ->setAbsolute()
      ->toString();
    $request = $this->client
      ->post($url, [
      'cookies' => $this->cookies,
      'headers' => [
        'Accept' => 'application/json',
        'Content-Type' => 'application/json',
      ],
      'http_errors' => FALSE,
    ]);
    
    $url = Url::fromRoute('lingotek.notify', [], [
      'query' => [
        'project_id' => 'test_project',
        'document_id' => 'dummy-document-hash-id',
        'locale_code' => 'es-ES',
        'locale' => 'es_ES',
        'complete' => 'true',
        'type' => 'target',
        'progress' => '100',
      ],
    ])
      ->setAbsolute()
      ->toString();
    $request = $this->client
      ->post($url, [
      'cookies' => $this->cookies,
      'headers' => [
        'Accept' => 'application/json',
        'Content-Type' => 'application/json',
      ],
      'http_errors' => FALSE,
    ]);
    $response = json_decode($request
      ->getBody(), TRUE);
    $this
      ->verbose($request);
    $this
      ->assertTrue($response['result']['download_queued'], 'Spanish language has been queued after notification automatically.');
    $this
      ->assertEqual('Download for target es_ES in document dummy-document-hash-id has been queued.', $response['messages'][0]);
    
    $this
      ->goToContentBulkManagementForm();
    
    $this
      ->assertTargetStatus('ES', Lingotek::STATUS_READY);
    
    $this->container
      ->get('cron')
      ->run();
    $this
      ->goToContentBulkManagementForm();
    $this
      ->assertTargetStatus('ES', Lingotek::STATUS_CURRENT);
    
    \Drupal::state()
      ->set('lingotek.must_error_in_download', TRUE);
    
    $url = Url::fromRoute('lingotek.notify', [], [
      'query' => [
        'project_id' => 'test_project',
        'document_id' => 'dummy-document-hash-id',
        'locale_code' => 'it-IT',
        'locale' => 'it_IT',
        'complete' => 'true',
        'type' => 'target',
        'progress' => '100',
      ],
    ])
      ->setAbsolute()
      ->toString();
    $request = $this->client
      ->post($url, [
      'cookies' => $this->cookies,
      'headers' => [
        'Accept' => 'application/json',
        'Content-Type' => 'application/json',
      ],
      'http_errors' => FALSE,
    ]);
    $response = json_decode($request
      ->getBody(), TRUE);
    $this
      ->verbose($request);
    $this
      ->assertTrue($response['result']['download_queued'], 'Italian language has been queued after notification automatically.');
    $this
      ->assertEqual('Download for target it_IT in document dummy-document-hash-id has been queued.', $response['messages'][0]);
    $url = Url::fromRoute('lingotek.notify', [], [
      'query' => [
        'project_id' => 'test_project',
        'document_id' => 'dummy-document-hash-id',
        'locale_code' => 'it-IT',
        'locale' => 'it_IT',
        'complete' => 'true',
        'type' => 'target',
        'progress' => '100',
      ],
    ])
      ->setAbsolute()
      ->toString();
    $request = \Drupal::httpClient()
      ->postAsync($url);
    try {
      $response = $request
        ->wait();
    } catch (ServerException $exception) {
      if ($exception
        ->getCode() === Response::HTTP_SERVICE_UNAVAILABLE) {
        $this
          ->fail('The request returned a 503 status code.');
      }
      else {
        $this
          ->fail('The request fail with an unexpected status code.');
      }
    }
    $this
      ->verbose(var_export($response, TRUE));
    
    $this->container
      ->get('cron')
      ->run();
    $this
      ->goToContentBulkManagementForm();
    
    $this
      ->assertTargetStatus('IT', Lingotek::STATUS_ERROR);
    
    $this
      ->clickLink('IT');
    $this
      ->assertText('The download for node Llamas are cool failed. Please try again.');
    
    $node = Node::load(1);
    $content_translation_service = \Drupal::service('lingotek.content_translation');
    $this
      ->assertIdentical(Lingotek::STATUS_ERROR, $content_translation_service
      ->getTargetStatus($node, 'it'));
  }
  
  protected function resetStorageCachesAndReloadNode() {
    
    $node_storage = $this->container
      ->get('entity_type.manager')
      ->getStorage('node');
    
    $metadata_storage = $this->container
      ->get('entity_type.manager')
      ->getStorage('lingotek_content_metadata');
    
    $metadata_storage
      ->resetCache([
      1,
    ]);
    $node_storage
      ->resetCache([
      1,
    ]);
    
    $node = $node_storage
      ->load(1);
    return $node;
  }
}