Contents
Expected result
OK
Explanation
We have more chances of testing API through network, so this code is getting the result through network and checking the output.
Programming Codes
JavaScript
const request = require('request'); const cheerio = require('cheerio'); const target_url = "https://www.yahoo.com/"; request( { method: 'GET', uri: target_url, gzip: true}, function(err, res, content) { const $ = cheerio.load(content); console.assert($('title').text().toLowerCase().match("yahoo"), "yahoo is not included in title"); console.log("OK"); } );
PHP
<?php $target_url = "https://www.yahoo.com/"; $context = stream_context_create(array('http' => array( 'method' => "GET", 'header' => implode("\r\n", array('Accept-Encoding: gzip,deflate')) ))); $content = file_get_contents($target_url, false, $context); if (isGzipResponse($http_response_header)) { $content = gzdecode($content); } $matches = []; if( preg_match('!<title>(.*?)</title>!is', $content, $matches) ) { assert(preg_match('!yahoo!is', $matches[1]) ,"yahoo is not included in title"); print("OK\n"); } else{ die("Failed to get content"); } function isGzipResponse($headers) { foreach($headers as $header) { if (stristr($header, 'content-encoding') and stristr($header, 'gzip')) { return true; } } }
Perl
use Carp::Assert; use HTML::TagParser; use LWP::UserAgent; my $ua = new LWP::UserAgent; my $target_url = "https://www.yahoo.com/"; my $resp = $ua->get($target_url); if($resp->is_success) { my $html = HTML::TagParser->new($resp->content); my $title = $html->getElementsByTagName( "title" ); if(ref $title){ assert($title->innerText()=~ m!yahoo!i, "yahoo is not included in title"); print("OK\n"); } else{ die("title tag is missing"); } } else{ die("Failed to crawl ".$target_url."\n".$resp->status_line); }
Python
from pyquery import PyQuery import re target_url = "https://www.yahoo.com/" pq = PyQuery(url=target_url) assert re.search(r"Yahoo", pq('title').text(), re.IGNORECASE), "yahoo is not included in title" print("OK")
Ruby
require 'open-uri' require 'nokogiri' target_url = "https://www.yahoo.com/" doc = Nokogiri.HTML(open(target_url)) doc.search('title').each do |elm| raise "yahoo is not included in title" unless elm.content.match(/yahoo/i) puts("OK") break end