<?php

/**
 * Implements hook_permission().
 */
function qunit_permission() {
  if (module_exists('simpletest')) {
    return array();
  }
  else {
    return array(
      'administer unit tests' => array(
        'title' => t('Administer unit tests'),
        'description' => t('Manage and run automated testing. %warning', array('%warning' => t('Warning: Give to trusted roles only; this permission has security implications.'))),
      ),
    );
  }
}

/**
 * Implements hook_menu().
 */
function qunit_menu() {
  $items['admin/config/development/qunit'] = array(
    'title' => 'JavaScript testing',
    'description' => "Run the tests for Drupal's JavaScript code, which will make sure that the JavaScript works properly your browser.",
    'page callback' => 'qunit_run_tests',
    'access arguments' => array('administer unit tests'),
  );
  return $items;
}

/**
 * Implements hook_library().
 */
function qunit_library() {
  $libraries['qunit'] = array(
    'title' => 'QUnit',
    'website' => 'http://docs.jquery.com/QUnit',
    'version' => '20110420',
    'js' => array(
      // The QUnit JavaScript library.
      drupal_get_path('module', 'qunit') . '/qunit/qunit/qunit.js' => array('weight' => JS_LIBRARY),
      // The QUnit Drupal behavior.
      drupal_get_path('module', 'qunit') . '/qunit.admin.js' => array(),
    ),
    'css' => array(
      // The QUnit library CSS framework.
      drupal_get_path('module', 'qunit') . '/qunit/qunit/qunit.css' => array(),
      // CSS fixes to make QUnit look nicer when in Drupal.
      drupal_get_path('module', 'qunit') . '/qunit.admin.css' => array(),
    ),
  );
  return $libraries;
}

/**
 * Implements hook_library_alter().
 */
function qunit_library_alter(&$libraries, $module) {
  // Add available JavaScript tests and dependencies.
  if ($module == 'qunit') {
    $libraries['qunit']['js'][drupal_get_path('module', 'qunit') . '/tests/drupal.test.js'] = array();
    $libraries['qunit']['js'][drupal_get_path('module', 'qunit') . '/tests/jquery.once.test.js'] = array();
  }
}

/**
 * Menu callback; Page to run all the JavaScript tests.
 */
function qunit_run_tests() {
  drupal_add_library('qunit', 'qunit');
  $output = '<div id="qunit-wrapper"><h1 id="qunit-header">QUnit Test Suite</h1><h2 id="qunit-banner"></h2><div id="qunit-testrunner-toolbar"></div><h2 id="qunit-userAgent"></h2><ol id="qunit-tests"></ol><div id="qunit-fixture">test markup</div></div>';
  return $output;
}

