Name

Test::XPath - Test \s-1XML\s0 and \s-1HTML\s0 content and structure with XPath expressions

Synopsis

  use Test::More tests => 5;
  use Test::XPath;

  my $xml = <<'XML';
  <html>
    <head>
      <title>Hello</title>
      <style type="text/css" src="foo.css"></style>
      <style type="text/css" src="bar.css"></style>
    </head>
    <body>
      <h1>Welcome to my lair.</h1>
    </body>
  </html>
  XML

  my $tx = Test::XPath->new( xml => $xml );

  $tx->ok( '/html/head', 'There should be a head' );
  $tx->is( '/html/head/title', 'Hello', 'The title should be correct' );

  # Recursing into a document:
  my @css = qw(foo.css bar.css);
  $tx->ok( '/html/head/style[@type="text/css"]', sub {
      my $css = shift @css;
      shift->is( './@src', $css, "Style src should be $css");
  }, 'Should have style' );

  # Better yet, use PerlX::MethodCallWithBlock:
  use PerlX::MethodCallWithBlock;
  my @css = qw(foo.css bar.css);
  use PerlX::MethodCallWithBlock;
  $tx->ok( '/html/head/style[@type="text/css"]', 'Should have style' ) {
      my $css = shift @css;
      shift->is( './@src', $css, "Style src should be $css");
  };

  # Or use CSS Selectors:
  $tx = Test::XPath->new( xml => $xml, filter => 'css_selector' );
  $tx->ok( '> html > head', 'There should be a head' );

Description

Use the power of XPath expressions to validate the structure of your \s-1XML\s0 and \s-1HTML\s0 documents.

About XPath

XPath is a powerful query language for \s-1XML\s0 documents. Test::XPath relies on the libxml2 implementation provided by XML::LibXML. libxml2 \*(-- pretty much the canonical library for \s-1XML\s0 processing \*(-- provides an efficient and complete implementation of the XPath spec.

XPath works by selecting nodes in an \s-1XML\s0 document. Nodes, in general, correspond to the elements (a.k.a. tags) defined in the \s-1XML\s0, text within those elements, attribute values, and comments. The expressions for making such selections use a URI-like syntax, the basics of which are: Selects all child nodes with the name. Selects the root node. Selects nodes from the current node that match the selection, regardless of where they are in the node hierarchy. Selects the current node. Selects the parent of the current node. Selects attributes.

And some examples: Selects all of the child nodes of the \*(L"head\*(R" element. Selects the root \*(L"html\*(R" element. Selects all \*(L"p\*(R" elements that are children of the \*(L"body\*(R" element. Selects all \*(L"p\*(R" elements no matter where they are in the document. Selects all \*(L"p\*(R" elements that are descendants of the \*(L"body\*(R" element, no matter where they appear under the \*(L"body\*(R" element. Selects all attributes named \*(L"lang\*(R".

There are also useful predicates to select certain nodes. Some examples: Select the first paragraph under the body element. Select the last paragraph under the body element. Select all \*(L"script\*(R" nodes that have a \*(L"src\*(R" attribute. Select all \*(L"script\*(R" nodes that have a \*(L"src\*(R" attribute set to \*(L"foo.js\*(R". Select all \*(L"img\*(R" nodes with a height attribute greater than 400. Select all child nodes below the \*(L"head\*(R" node. Select all \*(L"p\*(R" nodes that have any attribute. Select a count of all \*(L"p\*(R" nodes in the document.

There are a bunch of core functions in XPath. In addition to the (\*(C`last()\*(C' and \*(C`count()\*(C') examples above, there are functions for node sets, booleans, numbers, and strings. See the XPath 1.0 W3C Recommendation <http://www.w3.org/TR/xpath>, for thorough (and quite readable) documentation of XPath support, including syntax and the core functions. The W3Schools tutorial <http://www.w3schools.com/Xpath/default.asp> provides a nice overview of XPath.

Testing \s-1HTML\s0

If you want to use XPath to test the content and structure of an \s-1HTML\s0 document, be sure to pass the \*(C`is_html\*(C' option to \*(C`new()\*(C', like so:

my $tx = Test::XPath->new( xml => $html, is_html => 1 );

Test::XPath will then use XML::LibXML's \s-1HTML\s0 parser to parse the document, rather than its \s-1XML\s0 parser. The upshot is that you won't have to worry about namespace prefixes, and XML::LibXML won't try to fetch any \s-1DTD\s0 specified in the \s-1DOCTYPE\s0 section of your \s-1HTML\s0.

Class Interface

Constructor

\*(C`new\*(C'

my $tx = Test::XPath->new( xml => $xml );

Creates and returns an XML::XPath object. This object can be used to run XPath tests on the \s-1XML\s0 passed to it. The supported parameters are: xml => '<foo><bar>hey</bar></foo>', The \s-1XML\s0 to be parsed and tested. Required unless the \*(C`file\*(C' or \*(C`doc\*(C' option is passed. file => 'rss.xml', Name of a file containing the \s-1XML\s0 to be parsed and tested. Required unless the \*(C`xml\*(C' or \*(C`doc\*(C' option is passed. doc => XML::LibXML->new->parse_file($xml_file), An XML::LibXML document object. Required unless the \*(C`xml\*(C' or \*(C`file\*(C' option is passed. is_html => 1, If the \s-1XML\s0 you're testing is actually \s-1HTML\s0, pass this option a true value and XML::LibXML's \s-1HTML\s0 parser will be used instead of the \s-1XML\s0 parser. This is especially useful if your \s-1HTML\s0 has a \s-1DOCTYPE\s0 declaration or an \s-1XML\s0 namespace (xmlns attribute) and you don't want the parser grabbing the \s-1DTD\s0 over the Internet and you don't want to mess with a namespace prefix in your XPath expressions. xmlns => { x => 'http://www.w3.org/1999/xhtml', a => 'http://www.w3.org/2007/app', }, Set up prefixes for \s-1XML\s0 namespaces. Required if your \s-1XML\s0 uses namespaces and you want to write reasonable XPath expressions. options => { recover_silently => 1, no_network => 1 }, Optional hash reference of XML::LibXML::Parser options, such as \*(L"validation\*(R", \*(L"recover\*(R", \*(L"suppress_errors\*(R", and \*(L"no_network\*(R". These can be useful for tweaking the behavior of the parser. filter => 'css_selector', filter => sub { my $xpath = shift; }, Pass a filter name or a code reference for Test::XPath to use to filter XPath expressions before passing them on to XML::LibXML. The code reference argument allows you to transform XPath expressions if, for example, you use a custom XPath syntax that's more concise than XPath. There is currently only one built-in filter, \*(C`css_selector\*(C'. So if you pass filter => 'css_selector', Then any paths passed to \*(C`ok()\*(C', \*(C`is()\*(C', etc., will be passed through HTML::Selector::XPath. This allows you to use \s-1CSS\s0 selector syntax, which can be more compact for simple expressions. For example, this \s-1CSS\s0 selector: $tx->is('div#content div.article h1', '...') Is equivalent to this XPath expression: $tx->is('//div[@id="content"]//div[@class="article"]//h1', '...')

Instance Interface

Assertions

\*(C`ok\*(C'

$tx->ok( $xpath, $description ) $tx->ok( $xpath, $coderef, $description )

Test that an XPath expression evaluated against the \s-1XML\s0 document returns a true value. If the XPath expression finds no nodes, the result will be false. If it finds a value, the value must be a true value (in the Perl sense).

$tx->ok( '//foo/bar', 'Should have bar element under foo element' ); $tx->ok( 'contains(//title, "Welcome")', 'Title should "Welcome"' );

You can also run recursive tests against your document by passing a code reference as the second argument to \*(C`ok()\*(C'. Once the initial selection has been completed, each selected node will be assigned to the \*(C`node\*(C' attribute and the XML::XPath object passed to the code reference. For example, if you wanted to test for the presence of \*(L"story\*(R" elements in your document, and to test that each such element had an incremented \*(L"id\*(R" attribute, you'd do something like this:

my $i = 0; $tx->ok( '//assets/story', sub { shift->is('./@id', ++$i, "ID should be $i in story $i"); }, 'Should have story elements' );

Even better, use PerlX::MethodCallWithBlock to pass a block to the method instead of a code reference:

use PerlX::MethodCallWithBlock; my $i = 0; $tx->ok( '//assets/story', 'Should have story elements' ) { shift->is('./@id', ++$i, "ID should be $i in story $i"); };

For convenience, the XML::XPath object is also assigned to $_ for the duration of the call to the code reference. Either way, you can call \*(C`ok()\*(C' and pass code references anywhere in the hierarchy. For example, to ensure that an Atom feed has entries and that each entry has a title, a link, and a very specific author element with name, uri, and email subnodes, you can do this:

$tx->ok( '/feed/entry', sub { $_->ok( './title', 'Should have a title' ); $_->ok( './author', sub { $_->is( './name', 'Mark Pilgrim', 'Mark should be author' ); $_->is( './uri', 'http://example.org/', 'URI should be correct' ); $_->is( './email', '[email protected]', 'Email should be right' ); }, 'Should have author elements' ); }, 'Should have entry elments' );

\*(C`not_ok\*(C'

$tx->not_ok( $xpath, $description )

The reverse of the non-recursive \*(C`ok()\*(C', the test succeeds if the XPath expression matches no part of the document.

$tx->not_ok( '//foo/bar[@id=0]', 'Should have no bar elements with Id 0' );

\*(C`is\*(C'

\*(C`isnt\*(C'

$tx->is( $xpath, $want, $description ); $tx->isnt( $xpath, $dont_want, $description );

\*(C`is()\*(C' and \*(C`isnt()\*(C' compare the value returned by evaluation of the XPath expression against the document to a value using \*(C`eq\*(C' and \*(C`ne\*(C', respectively.

$tx->is( '/html/head/title', 'Welcome', 'Title should be welcoming' ); $tx->isnt( '/html/head/link/@type', 'hello', 'Link type should not' );

As with \*(C`Test::More::ok()\*(C', a failing test will yield a useful diagnostic message, something like:

# Failed test 'Title should be welcoming' # at t/foo.t line 47. # got: 'Bienvenidos' # expected: 'Hello'

\*(C`like\*(C'

\*(C`unlike\*(C'

$tx->like( $xpath, qr/want/, $description ); $tx->unlike( $xpath, qr/dont_want/, $description );

Similar to \*(C`is()\*(C' and \*(C`isnt()\*(C', but these methods match the value returned by the XPath expression against a regular expression.

$tx->like( '/html/head/title', qr/^Foobar Inc.: .+/, 'Title context' ); $tx->unlike( '/html/head/title', qr/Error/, 'Should be no error in title' );

As with \*(C`Test::More::like()\*(C', a failing test will yield a useful diagnostic message, something like:

# Failed test 'Title should, like, welcome' # at t/foo.t line 62. # 'Bye' # doesn't match '(?-xism:^Howdy$)'

\*(C`cmp_ok\*(C'

$tx->cmp_ok( $xpath, $op, $want, $description );

Like \*(C`Test::More::cmp_ok()\*(C', this method allows you to compare the value returned by an XPath expression to a value using any binary Perl operator.

$tx->cmp_ok( '/html/head/title', 'eq', 'Welcome' ); $tx->cmp_ok( '//story[1]/@id', '==', 1 );

As with \*(C`Test::More::cmp_ok()\*(C', a failing test will yield a useful diagnostic message, something like:

# Failed test # at t/foo.t line 104. # '0' # && # '1'

Accessors

\*(C`node\*(C'

my $node = $tx->node;

Returns the current context node. This will usually be the node for the entire document, but in recursive tests run in code references passed to \*(C`ok()\*(C', the node will be one of the nodes selected for the test.

\*(C`xpc\*(C'

Returns the XML::LibXML::XPathContext used to execute the XPath expressions. It can be useful to access this object in order to create new XPath functions to use in your tests. For example, say that you wanted to define a \*(C`grep()\*(C' XPath function that returns true for a node value that matches a regular expression. You can define one like so:

$tx->xpc->registerFunction( grep => sub { my ($nodelist, $regex) = @_; my $result = XML::LibXML::NodeList->new; for my $node ($nodelist->get_nodelist) { $result->push($node) if $node->textContent =~ $regex; } return $result; } );

You can then use \*(C`grep()\*(C' like any other XPath function to select only those nodes with content matching a regular expression. This example makes sure that there are \*(L"email\*(R" nodes under \*(L"author\*(R" nodes that end in \*(L"@example.com\*(R" or \*(L"example.org\*(R":

$tx->ok( 'grep(//author/email, "@example[.](?:com|org)$")', 'Should have example email' );

Utilities

\*(C`find_value\*(C'

my $val = $tx->find_value($xpath);

Returns the value returned by evaluation of the XPath expression against the document relative to the current node. This is the method used internally to fetch the value to be compared by \*(C`is\*(C', \*(C`isnt\*(C', \*(C`like\*(C', \*(C`unlike\*(C', and \*(C`cmp_ok\*(C'. A simple example:

my $val = $tx->find_value('/html/head/title');

See Also

  • \s-1XML\s0 Path Language (XPath) Version 1.0 W3C Recommendation <http://www.w3.org/TR/xpath>.

  • W3Schools XPath Tutorial <http://www.w3schools.com/Xpath/default.asp>.

  • XML::LibXML::XPathContext - The XML::LibXML XPath evaluation library.

  • Test::XML::XPath - Another library for testing XPath assertions using a functional interface. Ships with Test::XML.

  • Test::HTML::Content - Another module that that offers \*(C`xpath_ok()\*(C' and \*(C`no_xpath()\*(C' test functions.

Support

This module is stored in an open GitHub repository <http://github.com/theory/test-xpath/tree/>. Feel free to fork and contribute!

Please file bug reports via GitHub Issues <http://github.com/theory/test-xpath/issues/> or by sending mail to [email protected] <mailto:[email protected]>.

Author

David E. Wheeler <[email protected]>

Copyright and License

Copyright (c) 2009-2010 David E. Wheeler. Some Rights Reserved.

This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.