Integrated QUnit via django-qunit. Let the js testing begin! [bug 638856]

This commit is contained in:
Ricky Rosario 2011-02-11 17:19:46 -05:00
Родитель 9e063c132a
Коммит 1b03a4de54
11 изменённых файлов: 698 добавлений и 6 удалений

Просмотреть файл

@ -1,3 +1,4 @@
from django.conf import settings
from django.conf.urls.defaults import patterns, url, include
from sumo import views
@ -12,3 +13,10 @@ urlpatterns = patterns('',
url(r'^robots.txt$', views.robots, name='robots.txt'),
('^services', include(services_patterns)),
)
if 'django_qunit' in settings.INSTALLED_APPS:
urlpatterns += patterns('',
url(r'^qunit/(?P<path>.*)', views.kitsune_qunit),
url(r'^_qunit/', include('django_qunit.urls')),
)

Просмотреть файл

@ -2,15 +2,15 @@ import logging
import os
import socket
import StringIO
import time
from django.conf import settings
from django.core.cache import cache, parse_backend_uri
from django.core.cache import parse_backend_uri
from django.http import (HttpResponsePermanentRedirect, HttpResponseRedirect,
HttpResponse)
from django.views.decorators.cache import never_cache
import celery.task
from commonware.decorators import xframe_allow
import django_qunit.views
import jingo
from PIL import Image
@ -93,7 +93,6 @@ def monitor(request):
status_summary['memcache'] = False
log.warning('Memcache is not configured.')
# Check Libraries and versions
libraries_results = []
status_summary['libraries'] = True
@ -105,7 +104,6 @@ def monitor(request):
msg = "Failed to create a jpeg image: %s" % e
libraries_results.append(('PIL+JPEG', False, msg))
msg = 'We want read + write.'
filepaths = (
(settings.USER_AVATAR_PATH, os.R_OK | os.W_OK, msg),
@ -143,3 +141,12 @@ def monitor(request):
'filepath_results': filepath_results,
'status_summary': status_summary},
status=status)
# Allows another site to embed the QUnit suite
# in an iframe (for CI).
@xframe_allow
def kitsune_qunit(request, path):
"""View that hosts QUnit tests."""
ctx = django_qunit.views.get_suite_context(request, path)
return jingo.render(request, 'tests/qunit.html', ctx)

Просмотреть файл

@ -93,3 +93,48 @@ the tests for it, as well.
If we liberate some functionality into a new package, the tests for that
functionality should move to that package, too.
JavaScript Tests
================
Frontend JavaScript is currently tested with QUnit_, a simple set of
functions for test setup/teardown and assertions.
Running JavaScript Tests
------------------------
You can run the tests a few different ways but during development you
probably want to run them in a web browser by opening this page:
http://127.0.0.1:8000/en-US/qunit/
Before you can load that page, you'll need to adjust your settings_local.py
file so it includes django-qunit::
INSTALLED_APPS += (
# ...
'django_qunit',
)
Writing JavaScript Tests
------------------------
QUnit_ tests for the HTML page above are discovered automatically. Just add
some_test.js to ``media/js/tests/`` and it will run in the suite. If
you need to include a library file to test against, edit
``media/js/tests/suite.json``.
QUnit_ has some good examples for writing tests. Here are a few
additional tips:
* Any HTML required for your test should go in a sandbox using
``tests.createSandbox('#your-template')``.
See js/testutils.js for details.
* To make a useful test based on an actual production template, you can create
a snippet and include that in ``templates/tests/qunit.html`` assigned to its own
div. During test setup, reference the div in createSandbox()
* You can use `$.mockjax`_ to test how your code handles server responses,
errors, and timeouts.
.. _Qunit: http://docs.jquery.com/Qunit
.. _`$.mockjax`: http://enterprisejquery.com/2010/07/mock-your-ajax-requests-with-mockjax-for-rapid-development/

Просмотреть файл

@ -0,0 +1,324 @@
/*!
* MockJax - jQuery Plugin to Mock Ajax requests
*
* Version: 1.3.2
* Released: 2010-10-07
* Source: http://github.com/appendto/jquery-mockjax
* Docs: http://enterprisejquery.com/2010/07/mock-your-ajax-requests-with-mockjax-for-rapid-development
* Plugin: mockjax
* Author: Jonathan Sharp (http://jdsharp.com)
* License: MIT,GPL
*
* Copyright (c) 2010 appendTo LLC.
* Dual licensed under the MIT or GPL licenses.
* http://appendto.com/open-source-licenses
*/
(function($) {
var _ajax = $.ajax,
mockHandlers = [];
$.extend({
ajax: function(origSettings) {
var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings),
mock = false;
// Iterate over our mock handlers (in registration order) until we find
// one that is willing to intercept the request
$.each(mockHandlers, function(k, v) {
if ( !mockHandlers[k] ) {
return;
}
var m = null;
// If the mock was registered with a function, let the function decide if we
// want to mock this request
if ( $.isFunction(mockHandlers[k]) ) {
m = mockHandlers[k](s);
} else {
m = mockHandlers[k];
// Inspect the URL of the request and check if the mock handler's url
// matches the url for this ajax request
if ( $.isFunction(m.url.test) ) {
// The user provided a regex for the url, test it
if ( !m.url.test( s.url ) ) {
m = null;
}
} else {
// Look for a simple wildcard '*' or a direct URL match
var star = m.url.indexOf('*');
if ( ( m.url != '*' && m.url != s.url && star == -1 ) ||
( star > -1 && m.url.substr(0, star) != s.url.substr(0, star) ) ) {
// The url we tested did not match the wildcard *
m = null;
}
}
if ( m ) {
// Inspect the data submitted in the request (either POST body or GET query string)
if ( m.data && s.data ) {
var identical = false;
// Deep inspect the identity of the objects
(function ident(mock, live) {
// Test for situations where the data is a querystring (not an object)
if (typeof live === 'string') {
// Querystring may be a regex
identical = $.isFunction( mock.test ) ? mock.test(live) : mock == live;
return identical;
}
$.each(mock, function(k, v) {
if ( live[k] === undefined ) {
identical = false;
return false;
} else {
identical = true;
if ( typeof live[k] == 'object' ) {
return ident(mock[k], live[k]);
} else {
if ( $.isFunction( mock[k].test ) ) {
identical = mock[k].test(live[k]);
} else {
identical = ( mock[k] == live[k] );
}
return identical;
}
}
});
})(m.data, s.data);
// They're not identical, do not mock this request
if ( identical == false ) {
m = null;
}
}
// Inspect the request type
if ( m && m.type && m.type != s.type ) {
// The request type doesn't match (GET vs. POST)
m = null;
}
}
}
if ( m ) {
if ( typeof console !== 'undefined' && console.log ) {
console.log('MOCK GET: ' + s.url);
}
mock = true;
// Handle JSONP Parameter Callbacks, we need to replicate some of the jQuery core here
// because there isn't an easy hook for the cross domain script tag of jsonp
if ( s.dataType === "jsonp" ) {
if ( s.type.toUpperCase() === "GET" ) {
if ( !jsre.test( s.url ) ) {
s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
}
} else if ( !s.data || !jsre.test(s.data) ) {
s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
}
s.dataType = "json";
}
// Build temporary JSONP function
var jsre = /=\?(&|$)/;
if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
jsonp = s.jsonpCallback || ("jsonp" + jsc++);
// Replace the =? sequence both in the query string and the data
if ( s.data ) {
s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
}
s.url = s.url.replace(jsre, "=" + jsonp + "$1");
// We need to make sure
// that a JSONP style response is executed properly
s.dataType = "script";
// Handle JSONP-style loading
window[ jsonp ] = window[ jsonp ] || function( tmp ) {
data = tmp;
success();
complete();
// Garbage collect
window[ jsonp ] = undefined;
try {
delete window[ jsonp ];
} catch(e) {}
if ( head ) {
head.removeChild( script );
}
};
}
var rurl = /^(\w+:)?\/\/([^\/?#]+)/,
parts = rurl.exec( s.url ),
remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);
// Test if we are going to create a script tag (if so, intercept & mock)
if ( s.dataType === "script" && s.type.toUpperCase() === "GET" && remote ) {
// Synthesize the mock request for adding a script tag
var callbackContext = origSettings && origSettings.context || s;
function success() {
// If a local callback was specified, fire it and pass it the data
if ( s.success ) {
s.success.call( callbackContext, ( m.response ? m.response.toString() : m.responseText || ''), status, {} );
}
// Fire the global callback
if ( s.global ) {
trigger( "ajaxSuccess", [{}, s] );
}
}
function complete() {
// Process result
if ( s.complete ) {
s.complete.call( callbackContext, {} , status );
}
// The request was completed
if ( s.global ) {
trigger( "ajaxComplete", [{}, s] );
}
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active ) {
jQuery.event.trigger( "ajaxStop" );
}
}
function trigger(type, args) {
(s.context ? jQuery(s.context) : jQuery.event).trigger(type, args);
}
//if ( m.response && $.isFunction(m.response) ) {
// m.response();
//} else {
$.globalEval(m.responseText);
//}
success();
complete();
return false;
}
_ajax.call($, $.extend(true, {}, origSettings, {
// Mock the XHR object
xhr: function() {
// Extend with our default mockjax settings
m = $.extend({}, $.mockjaxSettings, m);
// Return our mock xhr object
return {
status: m.status,
readyState: 1,
open: function() { },
send: function() {
var process = $.proxy(function() {
// The request has returned
this.status = m.status;
this.readyState = 4;
// We have an executable function, call it to give
// the mock a chance to update it's data
if ( $.isFunction(m.response) ) {
m.response(origSettings);
}
// Copy over our mock to our xhr object before passing control back to
// jQuery's onreadystatechange callback
if ( s.dataType == 'json' && ( typeof m.responseText == 'object' ) ) {
this.responseText = JSON.stringify(m.responseText);
} else if ( s.dataType == 'xml' ) {
if ( $.xmlDOM && typeof m.responseXML == 'string' ) {
// Parse the XML from a string into a DOM
this.responseXML = $.xmlDOM( m.responseXML )[0];
} else {
this.responseXML = m.responseXML;
}
} else {
this.responseText = m.responseText;
}
this.onreadystatechange( m.isTimeout ? 'timeout' : undefined );
}, this);
if ( m.proxy ) {
// We're proxying this request and loading in an external file instead
_ajax({
global: false,
url: m.proxy,
type: m.type,
data: m.data,
dataType: s.dataType,
complete: function(xhr, txt) {
m.responseXML = xhr.responseXML;
m.responseText = xhr.responseText;
this.responseTimer = setTimeout(process, m.responseTime || 0);
}
});
} else {
// type == 'POST' || 'GET' || 'DELETE'
if ( s.async === false ) {
// TODO: Blocking delay
process();
} else {
this.responseTimer = setTimeout(process, m.responseTime || 50);
}
}
},
abort: function() {
clearTimeout(this.responseTimer);
},
setRequestHeader: function() { },
getResponseHeader: function(header) {
// 'Last-modified', 'Etag', 'content-type' are all checked by jQuery
if ( m.headers && m.headers[header] ) {
// Return arbitrary headers
return m.headers[header];
} else if ( header == 'Last-modified' ) {
return m.lastModified || (new Date()).toString();
} else if ( header == 'Etag' ) {
return m.etag || '';
} else if ( header == 'content-type' ) {
return m.contentType || 'text/plain';
}
}
};
}
}));
return false;
}
});
// We don't have a mock request, trigger a normal request
if ( !mock ) {
return _ajax.apply($, arguments);
}
}
});
$.mockjaxSettings = {
//url: null,
//type: 'GET',
status: 200,
responseTime: 500,
isTimeout: false,
contentType: 'text/plain',
response: '',
responseText: '',
responseXML: '',
proxy: '',
lastModified: null,
etag: '',
headers: {
etag: 'IJF@H#@923uf8023hFO@I#H#',
'content-type' : 'text/plain'
}
};
$.mockjax = function(settings) {
var i = mockHandlers.length;
mockHandlers[i] = settings;
return i;
};
$.mockjaxClear = function(i) {
if ( arguments.length == 1 ) {
mockHandlers[i] = null;
} else {
mockHandlers = [];
}
};
})(jQuery);

108
media/js/libs/jstestnet.js Normal file
Просмотреть файл

@ -0,0 +1,108 @@
//
// Adapter for JS TestNet
// https://github.com/kumar303/jstestnet
//
// Be sure this file is loaded *after* qunit/testrunner.js or whatever else
// you're using
(function() {
var canPost = false;
try {
canPost = !!window.top.postMessage;
} catch(e){}
if (!canPost) {
return;
}
function postMsg(data) {
var msg = '';
for (var k in data) {
if (msg.length > 0) {
msg += '&';
}
msg += k + '=' + encodeURI(data[k]);
}
window.top.postMessage(msg, '*');
}
// QUnit (jQuery)
// http://docs.jquery.com/QUnit
if ( typeof QUnit !== "undefined" ) {
QUnit.begin = function() {
postMsg({
action: 'hello',
user_agent: navigator.userAgent
});
};
QUnit.done = function(failures, total) {
// // Clean up the HTML (remove any un-needed test markup)
// $("nothiddendiv").remove();
// $("loadediframe").remove();
// $("dl").remove();
// $("main").remove();
//
// // Show any collapsed results
// $('ol').show();
postMsg({
action: 'done',
failures: failures,
total: total
});
};
QUnit.log = function(result, message, details) {
// Strip out html:
message = message.replace(/<(?:.|\s)*?>/g, '');
var msg = {
action: 'log',
result: result,
message: message,
stacktrace: null
};
if (details) {
if (typeof(details.source) !== 'undefined') {
msg.stacktrace = details.source;
}
}
postMsg(msg);
};
QUnit.moduleStart = function(name) {
postMsg({
action: 'set_module',
name: name
});
};
QUnit.testStart = function(name) {
postMsg({
action: 'set_test',
name: name
});
};
// window.TestSwarm.serialize = function(){
// // Clean up the HTML (remove any un-needed test markup)
// remove("nothiddendiv");
// remove("loadediframe");
// remove("dl");
// remove("main");
//
// // Show any collapsed results
// var ol = document.getElementsByTagName("ol");
// for ( var i = 0; i < ol.length; i++ ) {
// ol[i].style.display = "block";
// }
//
// return trimSerialize();
// };
} else {
throw new Error("Cannot adapt to jstestnet: Unknown test runner");
}
})();

Просмотреть файл

@ -0,0 +1,43 @@
$(document).ready(function(){
var kboxFixture = {
setup: function() {
this.sandbox = tests.createSandbox('#kbox');
},
teardown: function() {
this.sandbox.remove();
}
};
module('kbox', kboxFixture);
test('declarative', function() {
var $sandbox = this.sandbox;
$sandbox.find('.kbox').kbox().each(function() {
// kboxes shouldn't be visible initially
ok($(this).is(':hidden'), 'kbox starts hidden');
// If there is a target, click it. Otherwise, open programmatically.
var target = $(this).attr('data-target');
if (target) {
$(target).click();
} else {
$(this).data('kbox').open();
}
ok($(this).is(':visible'), 'kbox is now visible');
equals($(this).attr('title'), $sandbox.find('.kbox-title').text(),
'kbox title is correct');
if($(this).data('modal')) {
ok($('#kbox-overlay').length === 1 &&
$('#kbox-overlay').is(':visible'), 'overlay for modal kbox');
}
var kbox = $(this).data('kbox');
kbox.close();
ok($(this).is(':hidden'), 'kbox is not visible anymore');
kbox.destroy();
equals(0, $sandbox.find('.kbox-container').length,
'destroy cleans up kbox properly');
ok($('#kbox-overlay').length === 0, 'overlay cleaned up')
});
});
});

Просмотреть файл

@ -0,0 +1,7 @@
{
"name": "Main Test Suite",
"extra_media_urls": [
"js/libs/jstestnet.js",
"js/testutils.js"
]
}

90
media/js/testutils.js Normal file
Просмотреть файл

@ -0,0 +1,90 @@
/*
Functions that tests can use.
*/
tests = {};
tests.waitFor = function(checkCondition, config) {
/*
Wait for a condition before doing anything else.
Good for making async tests fast on fast machines.
Use it like this:
tests.waitFor(function() {
return (thing == 'done');
}).thenDo(function() {
equals(1,1);
ok(stuff());
});
You can pass in a config object as the second argument
with these possible attributed:
config.interval = milliseconds to wait between polling condition
config.timeout = milliseconds to wait before giving up on condition
*/
if (typeof(config) === 'undefined') {
config = {};
}
var interval = config.interval || 5,
timeout = config.timeout || 300,
run,
runWhenReady,
timeSpent = 0;
run = function() {
if (timeSpent > timeout) {
throw new Error("Spent too long waiting for condition");
}
timeSpent += interval;
var ready = checkCondition();
if (!ready) {
setTimeout(run, interval);
} else {
if (typeof runWhenReady === 'function') {
runWhenReady();
}
}
};
setTimeout(run, interval);
return {
thenDo: function(fn) {
runWhenReady = fn;
}
}
};
tests._sbCounter = 0;
tests.createSandbox = function(tmpl) {
/*
Returns a jQuery object for a temporary, unique div filled with html
from a template.
tmpl: an optional jQuery locator from which to copy html. This would
typically be the ID of a div in qunit.html
Example::
module('Group of tests', {
setup: function() {
this.sandbox = tests.createSandbox('#foobar-template');
},
teardown: function() {
this.sandbox.remove();
}
});
test('some test', function() {
this.sandbox.append('...');
});
*/
tests._sbCounter++;
var sb = $('<div id="sandbox-'+tests._sbCounter.toString()+'"></div>');
if (tmpl) {
sb.append($(tmpl).html());
}
$('#sandbox').append(sb);
return sb;
};

Просмотреть файл

@ -614,3 +614,6 @@ WEBTRENDS_EPOCH = date(2010, 8, 1) # When WebTrends started gathering stats on
WEBTRENDS_REALM = 'Webtrends Basic Authentication'
MOBILE_COOKIE = 'msumo'
# Directory of JavaScript test files for django_qunit to run
QUNIT_TEST_DIRECTORY = os.path.join(MEDIA_ROOT, 'js', 'tests')

Просмотреть файл

@ -0,0 +1,57 @@
<!DOCTYPE html>
<html>
<head>
<title>QUnit Test Suite</title>
<link rel="stylesheet" href="{{ url('qunit_css') }}" type="text/css" media="screen">
<link rel="stylesheet" href="{{ MEDIA_URL }}css/kbox.css" type="text/css" media="screen">
</head>
<body>
<h1 id="qunit-header">QUnit Test Suite ({{ suite.name }})</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
{% if in_directory or subsuites %}
<div id="navigation">
{% if in_subdirectory %}
<a href="{{ url('qunit_test_overview', previous_directory) }}">..</a>
{% endif %}
{% for suite in subsuites %}
<a href="{{ suite }}/">{{ suite }}</a>
{% endfor %}
</div>
{% endif %}
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
<div id="qunit-fixture">test markup, will be hidden</div>
<div id="sandbox"><!-- custom Kitsune sandbox area --></div>
{# Test Sandboxes: #}
<div style="display:none;">
<div id="kbox">
<div class="kbox" title="test kbox" data-target="#sandbox a.kbox-target">
<p>lorem ipsum dolor sit amet.</p>
</div>
<a href="#" class="kbox-target">click me</a>
<div class="kbox" title="modal kbox" data-modal="true">
<p>modal kbox</p>
</div>
</div>
</div>
<script src="{{ url('jsi18n') }}/build:{{ BUILD_ID_JS }}"></script>
{{ js('common') }}
<script type="text/javascript" src="{{ url('qunit_js') }}"></script>
<script type="text/javascript" src="{{ MEDIA_URL }}js/libs/jquery.mockjax.js"></script>
{% for url in suite.extra_urls %}
<script type="text/javascript" src="{{ url }}"></script>
{% endfor %}
{% for url in suite.extra_media_urls %}
<script type="text/javascript" src="{{ MEDIA_URL }}{{ url }}"></script>
{% endfor %}
{% for file in files %}
<script type="text/javascript" src="{{ url('qunit_test', file) }}"></script>
{% endfor %}
</body>
</html>

2
vendor

@ -1 +1 @@
Subproject commit 4dba3cc53067741faae499b791ea71f728c52287
Subproject commit c8a58dc23cefb33687c3533c72f574857b6a452d