<?php

/**
 * @file
 * Tests for amp.module.
 */

class AmpTestCase extends DrupalWebTestCase {
  protected $admin_user;

  public static function getInfo() {
    return array(
      'name' => 'AMP display modes',
      'description' => 'Tests for the AMP module.',
      'group' => 'AMP',
    );
  }

  protected function setUp() {
    // Enable AMP module.
    parent::setUp('field_ui', 'amp_test');

    // Create Admin user.
    $this->admin_user = $this->drupalCreateUser(array(
        'administer content types',
        'administer fields',
      )
    );
    $this->drupalLogin($this->admin_user);

    // Install the AMP theme.
    theme_enable(array('amptheme', 'ampsubtheme_example'));
  }

  /**
   * Test the AMP view mode.
   */
  public function testAmpViewMode() {
    // Login as an admin user.
    $this->drupalLogin($this->admin_user);

    // Create a node to test AMP metadata.
    $node = $this->drupalCreateNode(array('type' => 'article'));

    // Enable AMP display on article content.
    $this->drupalGet("admin/structure/types/manage/article/display");
    $this->assertResponse(200);
    $edit = ["view_modes_custom[amp]" => '1'];
    $this->drupalPost(NULL, $edit, t('Save'));

    // Check the full display.
    $this->drupalGet('node/' . $node->nid);
    $this->assertResponse(200);
    $this->assertText($node->body[LANGUAGE_NONE][0]['value']);
    // This will match http/https on any domain + subfolder, using clean urls or without.
    $pattern = '|<link rel="amphtml" href="http(.*):\/\/(.*)node\/1[&\?]amp(.*)"\s\/>|';
    $this->assertPattern($pattern, 'Check that link rel="amphtml" is present on the page.');

    // Check the AMP display.
    $this->drupalGet('node/' . $node->nid, array('query' => array('amp' => TRUE)));
    $this->assertResponse(200);
    $this->assertText($node->body[LANGUAGE_NONE][0]['value']);
    $pattern = '|<link rel="canonical" href="http(.*):\/\/(.*)node\/1"\s\/>|';
    $this->assertPattern($pattern, 'Check that link rel="canonical" is present on the page.');

    // Configure AMP field formatters.
    $this->drupalGet('admin/structure/types/manage/article/display/amp');
    $this->assertResponse(200);
    $edit = [
      "fields[field_image][type]" => 'amp_image',
      "fields[body][type]" => 'amp_text',
    ];
    $this->drupalPost(NULL, $edit, t('Save'));

    // Check the warnfix messages.
    $this->drupalGet('node/' . $node->nid, array('query' => array('amp' => NULL, 'warnfix' => NULL)));
    $this->assertResponse(200);
    $this->assertRaw('AMP-HTML Validation Issues and Fixes');
    $this->assertRaw('-------------------------------------');
    $this->assertRaw('PASS');
  }
}
