Assertによるテスト結果の確認

Contents [hide]

出力

OK

説明

テストはローカルPC内だけでなくネットワークのAPIを叩いてそれを検証する事が増えています。
この例ではネットワークの出力結果をテストしています。

各プログラミング言語での書き方

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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

1
2
3
4
5
6
7
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

1
2
3
4
5
6
7
8
9
10
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

プログラミング言語比較サイトProgrammingLang.comでは、同じ問題を複数のプログラミング言語がそれぞれどのような記述で解決できるのかの例を提供。
複数の言語を比較し、貴方の問題を解決するのに最適な言語の選択と、その言語での解法を得る事を手助けします。
全問題カバー: JavaScript Perl PHP Python Ruby | 一部: C C# C++ Go Java Rust Shell
 
問題解法大分類(50音順)
Class | 時間 | 数値 | System | Database | Test | Network | 配列 | ファイルシステム | 変数 | 文字列
その他役立ちコンテンツ

※当サイトではアフィリエイトプログラムを利用して商品を紹介しています。