Test::XPath(3pm)
π Test::XPath π
okay bestie, welcome to the Test::XPath(3pm) page β it lives in User Contributed Perl Documentation, and it's about testing your XML and HTML with XPath, which is genuinely one of the most underrated flexes in all of Perl. let's get into it π
β¨ NAME β¨
Test::XPath β test XML and HTML content and structure with XPath expressions. that's it, that's the whole vibe π¦
β¨ SYNOPSIS β¨
here's the whole thing in action, no cap:
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' );
like, look at that. recursive callbacks, method calls with blocks, CSS selectors instead of XPath β it's giving versatility π
β¨ DESCRIPTION β¨
Use the absolute power of XPath expressions to validate the structure of your XML and HTML documents. that's the whole point, and it slaps. π₯
π About XPath π
XPath is a powerful query language for XML documents. Test::XPath leans on the libxml2 implementation that XML::LibXML gives you. and libxml2? pretty much the canonical library for XML processing β it serves up an efficient and complete implementation of the XPath spec, periodt. π
XPath works by selecting nodes in an XML document. Nodes, generally speaking, line up with the elements (a.k.a. tags) defined in your XML, the text inside those elements, attribute values, and comments. the expressions you use to make those selections have this URI-like syntax, and the basics go like this:
$nodenameβ 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, because examples are the moment:
headβ selects all of the child nodes of theheadelement./htmlβ selects the roothtmlelement.body/pβ selects allpelements that are children of thebodyelement.//pβ selects allpelements no matter where they are in the document.body//pβ selects allpelements that are descendants of thebodyelement, no matter where they appear under thebodyelement.//@langβ selects all attributes namedlang.
There are also useful predicates to select certain nodes. some examples:
body//p[1]β select the first paragraph under the body element.body//p[last()]β select the last paragraph under the body element.//script[@src]β select allscriptnodes that have asrcattribute.//script[@src='foo.js']β select allscriptnodes that have asrcattribute set tofoo.js.//img[@height > 400]β select allimgnodes with a height attribute greater than 400.head/*β select all child nodes below theheadnode.p[@*]β select allpnodes that have any attribute.count(//p)β select a count of allpnodes in the document.contains(//title, "Welcome")β select true if the title node contains the stringWelcome, and false if it does not.
There are a bunch of core functions in XPath. on top of the last() and count() examples up there, there are functions for node sets, booleans, numbers, and strings. go read the XPath 1.0 W3C Recommendation at http://www.w3.org/TR/xpath for thorough (and honestly quite readable) documentation of XPath support, including syntax and the core functions. and the W3Schools tutorial at http://www.w3schools.com/Xpath/default.asp gives you a nice overview of XPath. iykyk πβ¨
πΈ Testing HTML πΈ
if you want to use XPath to test the content and structure of an HTML document, bestie, be sure to pass the is_html option to new(), like so:
my $tx = Test::XPath->new( xml => $html, is_html => 1 );
Test::XPath will then use XML::LibXML's HTML parser to parse the document, rather than its XML parser. the upshot? you won't have to worry about namespace prefixes, and XML::LibXML won't try to fetch any DTD specified in the DOCTYPE section of your HTML. two problems, gone, no cap. π
β¨ Class Interface β¨
π Constructor π
new
my $tx = Test::XPath->new( xml => $xml );
Creates and returns an XML::XPath object. this object is your little main character β you use it to run XPath tests on the XML you passed in. here are the supported parameters:
xmlβ the XML to be parsed and tested. Required unless thefileordocoption is passed.
xml => '<foo><bar>hey</bar></foo>',
fileβ name of a file containing the XML to be parsed and tested. Required unless thexmlordocoption is passed.
file => 'rss.xml',
docβ anXML::LibXMLdocument object. Required unless thexmlorfileoption is passed.
doc => XML::LibXML->new->parse_file($xml_file),
is_htmlβ if the XML you're testing is actually HTML, pass this option a true value andXML::LibXML's HTML parser will be used instead of the XML parser. this is especially useful if your HTML has a DOCTYPE declaration or an XML namespace (xmlnsattribute) and you don't want the parser grabbing the DTD over the Internet and you don't want to mess with a namespace prefix in your XPath expressions.
is_html => 1,
xmlnsβ set up prefixes for XML namespaces. Required if your XML uses namespaces and you want to write reasonable XPath expressions.
xmlns => {
x => 'http://www.w3.org/1999/xhtml',
a => 'http://www.w3.org/2007/app',
},
optionsβ optional hash reference ofXML::LibXML::Parseroptions, such asvalidation,recover,suppress_errors, andno_network. these can be useful for tweaking the behavior of the parser.
options => { recover_silently => 1, no_network => 1 },
filterβ pass a filter name or a code reference forTest::XPathto use to filter XPath expressions before passing them on toXML::LibXML. the code reference argument lets you transform XPath expressions if, for example, you use a custom XPath syntax that's more concise than XPath.
filter => 'css_selector',
filter => sub { my $xpath = shift; },
There is currently only one built-in filter, css_selector. so if you pass
filter => 'css_selector',
Then any paths passed to ok(), is(), etc., will be passed through HTML::Selector::XPath. this allows you to use CSS selector syntax, which can be more compact for simple expressions. for example, this CSS 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 β¨
ok β the moment of truth π
$tx->ok( $xpath, $description )
$tx->ok( $xpath, $coderef, $description )
Okay so this one tests that running an XPath expression against the XML document gives back a true value. If the XPath expression finds no nodes, the result is gonna be false, no cap. And if it does find a value, that value has to be true in the Perl sense. That's it, that's the vibe check. π
$tx->ok( '//foo/bar', 'Should have bar element under foo element' );
$tx->ok( 'contains(//title, "Welcome")', 'Title should "Welcome"' );
But wait β you can also run recursive tests against your document by passing a code reference as the second argument to ok(). Once that first selection is done, every selected node gets assigned to the node attribute, and the XML::XPath object gets passed to the code reference. So like, say you wanted to test for the presence of story elements in your doc and check that each one had an incremented id 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' );
And even better, use PerlX::MethodCallWithBlock to pass a block to the method instead of a code reference β it's giving main character energy fr:
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 whole duration of the call to the code reference. Either way, you can call ok() and pass code references anywhere in the hierarchy. For example, to make sure 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', 'f8dy@example.com', 'Email should be right' );
}, 'Should have author elements' );
}, 'Should have entry elments' );
not_ok β the reverse, iconic π
$tx->not_ok( $xpath, $description )
This is the reverse of the non-recursive ok(), bestie. The test succeeds if the XPath expression matches no part of the document at all. Zero. Nada. π
$tx->not_ok( '//foo/bar[@id=0]', 'Should have no bar elements with Id 0' );
is
isnt
$tx->is( $xpath, $want, $description );
$tx->isnt( $xpath, $dont_want, $description );
is() and isnt() compare the value returned by evaluation of the XPath expression against the document to a value, using eq and ne respectively. Classic. πΈ
$tx->is( '/html/head/title', 'Welcome', 'Title should be welcoming' );
$tx->isnt( '/html/head/link/@type', 'hello', 'Link type should not' );
As with Test::More::ok(), 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'
like
unlike
$tx->like( $xpath, qr/want/, $description );
$tx->unlike( $xpath, qr/dont_want/, $description );
Similar to is() and isnt(), but these methods match the value returned by the XPath expression against a regular expression instead. Regex girlies rise up π
$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 Test::More::like(), 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$)'
cmp_ok β bring your own operator π«Ά
$tx->cmp_ok( $xpath, $op, $want, $description );
Like Test::More::cmp_ok(), this method lets you compare the value returned by an XPath expression to a value using any binary Perl operator. Go off. β
$tx->cmp_ok( '/html/head/title', 'eq', 'Welcome' );
$tx->cmp_ok( '//story[1]/@id', '==', 1 );
As with Test::More::cmp_ok(), a failing test will yield a useful diagnostic message, something like:
# Failed test
# at t/foo.t line 104.
# '0'
# &&
# '1'
π Accessors π
node
my $node = $tx->node;
Returns the current context node. Usually this is the node for the entire document, but in recursive tests run in code references passed to ok(), the node will be one of the nodes selected for the test. iykyk π
xpc
Returns the XML::LibXML::XPathContext used to execute the XPath expressions. It can be super useful to grab this object so you can create new XPath functions to use in your tests. Like, say you wanted to define a grep() XPath function that returns true for a node value matching 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;
} );
Then you can use grep() like literally any other XPath function to select only those nodes whose content matches a regular expression. This example makes sure that there are email nodes under author nodes that end in @example.com or example.org:
$tx->ok(
'grep(//author/email, "@example[.](?:com|org)$")',
'Should have example email'
);
π§ Utilities π§
find_value
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 that gets compared by is, isnt, like, unlike, and cmp_ok. Simple lil example: β¨
my $val = $tx->find_value('/html/head/title');
π See Also π
- XML Path Language (XPath) Version 1.0 W3C Recommendation <http://www.w3.org/TR/xpath>.
- W3Schools XPath Tutorial <https://www.w3schools.com/xml/xpath_intro.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
xpath_ok()andno_xpath()test functions.
π Support π
This module is stored in an open GitHub repository <http://github.com/manwar/test-xpath/tree/>. Feel free to fork and contribute! Fr fr, the door is open π«Ά
Please file bug reports via GitHub Issues <http://github.com/manwar/test-xpath/issues/> or by sending mail to bug-Test-XPath@rt.cpan.org <mailto:bug-Test-XPath@rt.cpan.org>.
π Author π
David E. Wheeler <david@kineticode.com>
Currently maintained by Mohammad S Anwar <mohammad.anwar@yahoo.com>
β 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.
And that's a wrap, bestie!! π This was Test::XPath(3pm) as shipped with perl v5.34.0, dated 2022-08-19. Go write some slay XPath assertions, you absolute icon πβ¨π¦
π¦ where this page comes from
- debian bookworm: libtest-xpath-perl 0.20-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- debian trixie: libtest-xpath-perl 0.20-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libtest-xpath-perl 0.20-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libtest-xpath-perl 0.20-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libtest-xpath-perl 0.20-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms