Converted all unittest asserts to plain, pytest-powered asserts.

This commit is contained in:
Jakub Roztocil 2014-04-24 14:58:15 +02:00
parent 6071fff4af
commit b880e996d0
14 changed files with 313 additions and 360 deletions

View File

@ -4,7 +4,6 @@ import time
import json import json
import shutil import shutil
import tempfile import tempfile
import unittest
try: try:
from unittest import skipIf, skip from unittest import skipIf, skip
except ImportError: except ImportError:
@ -26,7 +25,7 @@ sys.path.insert(0, os.path.realpath(os.path.join(TESTS_ROOT, '..')))
from httpie import ExitStatus from httpie import ExitStatus
from httpie.models import Environment from httpie.models import Environment
from httpie.core import main from httpie.core import main
from httpie.compat import is_py26, bytes, str from httpie.compat import bytes, str
def patharg(path): def patharg(path):
@ -39,7 +38,7 @@ HTTPBIN_URL = os.environ.get('HTTPBIN_URL',
CRLF = '\r\n' CRLF = '\r\n'
OK = 'HTTP/1.1 200' HTTP_OK = 'HTTP/1.1 200'
OK_COLOR = ( OK_COLOR = (
'HTTP\x1b[39m\x1b[38;5;245m/\x1b[39m\x1b' 'HTTP\x1b[39m\x1b[38;5;245m/\x1b[39m\x1b'
'[38;5;37m1.1\x1b[39m\x1b[38;5;245m \x1b[39m\x1b[38;5;37m200' '[38;5;37m1.1\x1b[39m\x1b[38;5;245m \x1b[39m\x1b[38;5;37m200'
@ -189,22 +188,3 @@ def http(*args, **kwargs):
finally: finally:
stdout.close() stdout.close()
stderr.close() stderr.close()
class BaseTestCase(unittest.TestCase):
maxDiff = 100000
if is_py26:
def assertIn(self, member, container, msg=None):
self.assertTrue(member in container, msg)
def assertNotIn(self, member, container, msg=None):
self.assertTrue(member not in container, msg)
def assertDictEqual(self, d1, d2, msg=None):
self.assertEqual(set(d1.keys()), set(d2.keys()), msg)
self.assertEqual(sorted(d1.values()), sorted(d2.values()), msg)
def assertIsNone(self, obj, msg=None):
self.assertEqual(obj, None, msg=msg)

View File

@ -1,11 +1,13 @@
"""HTTP authentication-related tests.""" """HTTP authentication-related tests."""
from unittest import TestCase
import requests import requests
from tests import BaseTestCase, http, httpbin, OK, skipIf from tests import http, httpbin, HTTP_OK, skipIf
import httpie.input import httpie.input
class AuthTest(BaseTestCase): class AuthTest(TestCase):
def test_basic_auth(self): def test_basic_auth(self):
r = http( r = http(
@ -13,9 +15,9 @@ class AuthTest(BaseTestCase):
'GET', 'GET',
httpbin('/basic-auth/user/password') httpbin('/basic-auth/user/password')
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn('"authenticated": true', r) assert '"authenticated": true' in r
self.assertIn('"user": "user"', r) assert '"user": "user"' in r
@skipIf(requests.__version__ == '0.13.6', @skipIf(requests.__version__ == '0.13.6',
'Redirects with prefetch=False are broken in Requests 0.13.6') 'Redirects with prefetch=False are broken in Requests 0.13.6')
@ -26,9 +28,9 @@ class AuthTest(BaseTestCase):
'GET', 'GET',
httpbin('/digest-auth/auth/user/password') httpbin('/digest-auth/auth/user/password')
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn(r'"authenticated": true', r) assert r'"authenticated": true' in r
self.assertIn(r'"user": "user"', r) assert r'"user": "user"', r
def test_password_prompt(self): def test_password_prompt(self):
@ -41,9 +43,9 @@ class AuthTest(BaseTestCase):
httpbin('/basic-auth/user/password') httpbin('/basic-auth/user/password')
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn('"authenticated": true', r) assert '"authenticated": true' in r
self.assertIn('"user": "user"', r) assert '"user": "user"' in r
def test_credentials_in_url(self): def test_credentials_in_url(self):
url = httpbin('/basic-auth/user/password') url = httpbin('/basic-auth/user/password')
@ -52,9 +54,9 @@ class AuthTest(BaseTestCase):
'GET', 'GET',
url url
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn('"authenticated": true', r) assert '"authenticated": true'in r
self.assertIn('"user": "user"', r) assert '"user": "user"' in r
def test_credentials_in_url_auth_flag_has_priority(self): def test_credentials_in_url_auth_flag_has_priority(self):
"""When credentials are passed in URL and via -a at the same time, """When credentials are passed in URL and via -a at the same time,
@ -66,6 +68,6 @@ class AuthTest(BaseTestCase):
'GET', 'GET',
url url
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn('"authenticated": true', r) assert '"authenticated": true' in r
self.assertIn('"user": "user"', r) assert '"user": "user"' in r

View File

@ -1,14 +1,16 @@
"""Tests for dealing with binary request and response data.""" """Tests for dealing with binary request and response data."""
from unittest import TestCase
from httpie.compat import urlopen from httpie.compat import urlopen
from httpie.output import BINARY_SUPPRESSED_NOTICE from httpie.output import BINARY_SUPPRESSED_NOTICE
from tests import ( from tests import (
BaseTestCase, TestEnvironment, http, httpbin, TestEnvironment, http, httpbin,
BIN_FILE_PATH, BIN_FILE_CONTENT, BIN_FILE_PATH_ARG, BIN_FILE_PATH, BIN_FILE_CONTENT, BIN_FILE_PATH_ARG,
) )
class BinaryRequestDataTest(BaseTestCase): class BinaryRequestDataTest(TestCase):
def test_binary_stdin(self): def test_binary_stdin(self):
with open(BIN_FILE_PATH, 'rb') as stdin: with open(BIN_FILE_PATH, 'rb') as stdin:
@ -23,7 +25,7 @@ class BinaryRequestDataTest(BaseTestCase):
httpbin('/post'), httpbin('/post'),
env=env, env=env,
) )
self.assertEqual(r, BIN_FILE_CONTENT) assert r == BIN_FILE_CONTENT
def test_binary_file_path(self): def test_binary_file_path(self):
env = TestEnvironment( env = TestEnvironment(
@ -38,7 +40,7 @@ class BinaryRequestDataTest(BaseTestCase):
env=env, env=env,
) )
self.assertEqual(r, BIN_FILE_CONTENT) assert r == BIN_FILE_CONTENT
def test_binary_file_form(self): def test_binary_file_form(self):
env = TestEnvironment( env = TestEnvironment(
@ -53,10 +55,10 @@ class BinaryRequestDataTest(BaseTestCase):
'test@' + BIN_FILE_PATH_ARG, 'test@' + BIN_FILE_PATH_ARG,
env=env, env=env,
) )
self.assertIn(bytes(BIN_FILE_CONTENT), bytes(r)) assert bytes(BIN_FILE_CONTENT) in bytes(r)
class BinaryResponseDataTest(BaseTestCase): class BinaryResponseDataTest(TestCase):
url = 'http://www.google.com/favicon.ico' url = 'http://www.google.com/favicon.ico'
@ -71,7 +73,7 @@ class BinaryResponseDataTest(BaseTestCase):
'GET', 'GET',
self.url self.url
) )
self.assertIn(BINARY_SUPPRESSED_NOTICE.decode(), r) assert BINARY_SUPPRESSED_NOTICE.decode() in r
def test_binary_suppresses_when_not_terminal_but_pretty(self): def test_binary_suppresses_when_not_terminal_but_pretty(self):
r = http( r = http(
@ -81,7 +83,7 @@ class BinaryResponseDataTest(BaseTestCase):
env=TestEnvironment(stdin_isatty=True, env=TestEnvironment(stdin_isatty=True,
stdout_isatty=False) stdout_isatty=False)
) )
self.assertIn(BINARY_SUPPRESSED_NOTICE.decode(), r) assert BINARY_SUPPRESSED_NOTICE.decode() in r
def test_binary_included_and_correct_when_suitable(self): def test_binary_included_and_correct_when_suitable(self):
r = http( r = http(
@ -90,4 +92,4 @@ class BinaryResponseDataTest(BaseTestCase):
env=TestEnvironment(stdin_isatty=True, env=TestEnvironment(stdin_isatty=True,
stdout_isatty=False) stdout_isatty=False)
) )
self.assertEqual(r, self.bindata) assert r == self.bindata

View File

@ -1,23 +1,25 @@
"""CLI argument parsing related tests.""" """CLI argument parsing related tests."""
import json import json
from unittest import TestCase
# noinspection PyCompatibility # noinspection PyCompatibility
import argparse import argparse
from tests import ( from tests import (
BaseTestCase, TestEnvironment, http, httpbin, TestEnvironment, http, httpbin,
FILE_PATH_ARG, JSON_FILE_PATH_ARG, FILE_PATH_ARG, JSON_FILE_PATH_ARG,
JSON_FILE_CONTENT, FILE_CONTENT, OK, FILE_PATH JSON_FILE_CONTENT, FILE_CONTENT, HTTP_OK, FILE_PATH
) )
from httpie import input from httpie import input
from httpie.input import KeyValue, KeyValueArgType
from httpie import ExitStatus from httpie import ExitStatus
from httpie.cli import parser from httpie.cli import parser
class ItemParsingTest(BaseTestCase): class ItemParsingTest(TestCase):
def setUp(self): def setUp(self):
self.key_value_type = input.KeyValueArgType( self.key_value_type = KeyValueArgType(
*input.SEP_GROUP_ALL_ITEMS *input.SEP_GROUP_ALL_ITEMS
) )
@ -39,22 +41,18 @@ class ItemParsingTest(BaseTestCase):
]) ])
# `requests.structures.CaseInsensitiveDict` => `dict` # `requests.structures.CaseInsensitiveDict` => `dict`
headers = dict(headers._store.values()) headers = dict(headers._store.values())
self.assertDictEqual(headers, { assert headers == {
'foo:bar': 'baz', 'foo:bar': 'baz',
'jack@jill': 'hill', 'jack@jill': 'hill',
}) }
self.assertDictEqual(data, { assert data == {'baz=bar': 'foo'}
'baz=bar': 'foo', assert 'bar@baz' in files
})
self.assertIn('bar@baz', files)
def test_escape_longsep(self): def test_escape_longsep(self):
headers, data, files, params = input.parse_items([ headers, data, files, params = input.parse_items([
self.key_value_type('bob\\:==foo'), self.key_value_type('bob\\:==foo'),
]) ])
self.assertDictEqual(params, { assert params == {'bob:': 'foo'}
'bob:': 'foo',
})
def test_valid_items(self): def test_valid_items(self):
headers, data, files, params = input.parse_items([ headers, data, files, params = input.parse_items([
@ -74,37 +72,31 @@ class ItemParsingTest(BaseTestCase):
# Parsed headers # Parsed headers
# `requests.structures.CaseInsensitiveDict` => `dict` # `requests.structures.CaseInsensitiveDict` => `dict`
headers = dict(headers._store.values()) headers = dict(headers._store.values())
self.assertDictEqual(headers, { assert headers == {'header': 'value', 'eh': ''}
'header': 'value',
'eh': ''
})
# Parsed data # Parsed data
raw_json_embed = data.pop('raw-json-embed') raw_json_embed = data.pop('raw-json-embed')
self.assertDictEqual(raw_json_embed, json.loads( assert raw_json_embed == json.loads(
JSON_FILE_CONTENT.decode('utf8'))) JSON_FILE_CONTENT.decode('utf8'))
data['string-embed'] = data['string-embed'].strip() data['string-embed'] = data['string-embed'].strip()
self.assertDictEqual(dict(data), { assert dict(data) == {
"ed": "", "ed": "",
"string": "value", "string": "value",
"bool": True, "bool": True,
"list": ["a", 1, {}, False], "list": ["a", 1, {}, False],
"obj": {"a": "b"}, "obj": {"a": "b"},
"string-embed": FILE_CONTENT, "string-embed": FILE_CONTENT,
}) }
# Parsed query string parameters # Parsed query string parameters
self.assertDictEqual(params, { assert params == {'query': 'value'}
'query': 'value',
})
# Parsed file fields # Parsed file fields
self.assertIn('file', files) assert 'file' in files
self.assertEqual(files['file'][1].read().strip().decode('utf8'), assert files['file'][1].read().strip().decode('utf8') == FILE_CONTENT
FILE_CONTENT)
class QuerystringTest(BaseTestCase): class QuerystringTest(TestCase):
def test_query_string_params_in_url(self): def test_query_string_params_in_url(self):
r = http( r = http(
@ -116,9 +108,9 @@ class QuerystringTest(BaseTestCase):
path = '/get?a=1&b=2' path = '/get?a=1&b=2'
url = httpbin(path) url = httpbin(path)
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn('GET %s HTTP/1.1' % path, r) assert 'GET %s HTTP/1.1' % path in r
self.assertIn('"url": "%s"' % url, r) assert '"url": "%s"' % url in r
def test_query_string_params_items(self): def test_query_string_params_items(self):
r = http( r = http(
@ -132,9 +124,9 @@ class QuerystringTest(BaseTestCase):
path = '/get?a=1&b=2' path = '/get?a=1&b=2'
url = httpbin(path) url = httpbin(path)
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn('GET %s HTTP/1.1' % path, r) assert 'GET %s HTTP/1.1' % path in r
self.assertIn('"url": "%s"' % url, r) assert '"url": "%s"' % url in r
def test_query_string_params_in_url_and_items_with_duplicates(self): def test_query_string_params_in_url_and_items_with_duplicates(self):
r = http( r = http(
@ -149,68 +141,57 @@ class QuerystringTest(BaseTestCase):
path = '/get?a=1&a=1&a=1&a=1&b=2' path = '/get?a=1&a=1&a=1&a=1&b=2'
url = httpbin(path) url = httpbin(path)
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn('GET %s HTTP/1.1' % path, r) assert 'GET %s HTTP/1.1' % path in r
self.assertIn('"url": "%s"' % url, r) assert '"url": "%s"' % url in r
class CLIParserTestCase(BaseTestCase): class CLIParserTestCase(TestCase):
def test_expand_localhost_shorthand(self): def test_expand_localhost_shorthand(self):
args = parser.parse_args(args=[':'], env=TestEnvironment()) args = parser.parse_args(args=[':'], env=TestEnvironment())
assert args.url == 'http://localhost'
self.assertEqual(args.url, 'http://localhost')
def test_expand_localhost_shorthand_with_slash(self): def test_expand_localhost_shorthand_with_slash(self):
args = parser.parse_args(args=[':/'], env=TestEnvironment()) args = parser.parse_args(args=[':/'], env=TestEnvironment())
assert args.url == 'http://localhost/'
self.assertEqual(args.url, 'http://localhost/')
def test_expand_localhost_shorthand_with_port(self): def test_expand_localhost_shorthand_with_port(self):
args = parser.parse_args(args=[':3000'], env=TestEnvironment()) args = parser.parse_args(args=[':3000'], env=TestEnvironment())
assert args.url == 'http://localhost:3000'
self.assertEqual(args.url, 'http://localhost:3000')
def test_expand_localhost_shorthand_with_path(self): def test_expand_localhost_shorthand_with_path(self):
args = parser.parse_args(args=[':/path'], env=TestEnvironment()) args = parser.parse_args(args=[':/path'], env=TestEnvironment())
assert args.url == 'http://localhost/path'
self.assertEqual(args.url, 'http://localhost/path')
def test_expand_localhost_shorthand_with_port_and_slash(self): def test_expand_localhost_shorthand_with_port_and_slash(self):
args = parser.parse_args(args=[':3000/'], env=TestEnvironment()) args = parser.parse_args(args=[':3000/'], env=TestEnvironment())
assert args.url == 'http://localhost:3000/'
self.assertEqual(args.url, 'http://localhost:3000/')
def test_expand_localhost_shorthand_with_port_and_path(self): def test_expand_localhost_shorthand_with_port_and_path(self):
args = parser.parse_args(args=[':3000/path'], env=TestEnvironment()) args = parser.parse_args(args=[':3000/path'], env=TestEnvironment())
assert args.url == 'http://localhost:3000/path'
self.assertEqual(args.url, 'http://localhost:3000/path')
def test_dont_expand_shorthand_ipv6_as_shorthand(self): def test_dont_expand_shorthand_ipv6_as_shorthand(self):
args = parser.parse_args(args=['::1'], env=TestEnvironment()) args = parser.parse_args(args=['::1'], env=TestEnvironment())
assert args.url == 'http://::1'
self.assertEqual(args.url, 'http://::1')
def test_dont_expand_longer_ipv6_as_shorthand(self): def test_dont_expand_longer_ipv6_as_shorthand(self):
args = parser.parse_args( args = parser.parse_args(
args=['::ffff:c000:0280'], args=['::ffff:c000:0280'],
env=TestEnvironment() env=TestEnvironment()
) )
self.assertEqual(args.url, 'http://::ffff:c000:0280') assert args.url == 'http://::ffff:c000:0280'
def test_dont_expand_full_ipv6_as_shorthand(self): def test_dont_expand_full_ipv6_as_shorthand(self):
args = parser.parse_args( args = parser.parse_args(
args=['0000:0000:0000:0000:0000:0000:0000:0001'], args=['0000:0000:0000:0000:0000:0000:0000:0001'],
env=TestEnvironment() env=TestEnvironment()
) )
assert args.url == 'http://0000:0000:0000:0000:0000:0000:0000:0001'
self.assertEqual(
args.url,
'http://0000:0000:0000:0000:0000:0000:0000:0001'
)
class ArgumentParserTestCase(BaseTestCase): class ArgumentParserTestCase(TestCase):
def setUp(self): def setUp(self):
self.parser = input.Parser() self.parser = input.Parser()
@ -226,9 +207,9 @@ class ArgumentParserTestCase(BaseTestCase):
self.parser._guess_method() self.parser._guess_method()
self.assertEqual(self.parser.args.method, 'GET') assert self.parser.args.method == 'GET'
self.assertEqual(self.parser.args.url, 'http://example.com/') assert self.parser.args.url == 'http://example.com/'
self.assertEqual(self.parser.args.items, []) assert self.parser.args.items == []
def test_guess_when_method_not_set(self): def test_guess_when_method_not_set(self):
@ -241,9 +222,9 @@ class ArgumentParserTestCase(BaseTestCase):
self.parser._guess_method() self.parser._guess_method()
self.assertEqual(self.parser.args.method, 'GET') assert self.parser.args.method == 'GET'
self.assertEqual(self.parser.args.url, 'http://example.com/') assert self.parser.args.url == 'http://example.com/'
self.assertEqual(self.parser.args.items, []) assert self.parser.args.items == []
def test_guess_when_method_set_but_invalid_and_data_field(self): def test_guess_when_method_set_but_invalid_and_data_field(self):
self.parser.args = argparse.Namespace() self.parser.args = argparse.Namespace()
@ -254,12 +235,14 @@ class ArgumentParserTestCase(BaseTestCase):
self.parser.env = TestEnvironment() self.parser.env = TestEnvironment()
self.parser._guess_method() self.parser._guess_method()
self.assertEqual(self.parser.args.method, 'POST') assert self.parser.args.method == 'POST'
self.assertEqual(self.parser.args.url, 'http://example.com/') assert self.parser.args.url == 'http://example.com/'
self.assertEqual( assert self.parser.args.items == [
self.parser.args.items, KeyValue(key='data',
[input.KeyValue( value='field',
key='data', value='field', sep='=', orig='data=field')]) sep='=',
orig='data=field')
]
def test_guess_when_method_set_but_invalid_and_header_field(self): def test_guess_when_method_set_but_invalid_and_header_field(self):
self.parser.args = argparse.Namespace() self.parser.args = argparse.Namespace()
@ -272,19 +255,21 @@ class ArgumentParserTestCase(BaseTestCase):
self.parser._guess_method() self.parser._guess_method()
self.assertEqual(self.parser.args.method, 'GET') assert self.parser.args.method == 'GET'
self.assertEqual(self.parser.args.url, 'http://example.com/') assert self.parser.args.url == 'http://example.com/'
self.assertEqual( assert self.parser.args.items, [
self.parser.args.items, KeyValue(key='test',
[input.KeyValue( value='header',
key='test', value='header', sep=':', orig='test:header')]) sep=':',
orig='test:header')
]
def test_guess_when_method_set_but_invalid_and_item_exists(self): def test_guess_when_method_set_but_invalid_and_item_exists(self):
self.parser.args = argparse.Namespace() self.parser.args = argparse.Namespace()
self.parser.args.method = 'http://example.com/' self.parser.args.method = 'http://example.com/'
self.parser.args.url = 'new_item=a' self.parser.args.url = 'new_item=a'
self.parser.args.items = [ self.parser.args.items = [
input.KeyValue( KeyValue(
key='old_item', value='b', sep='=', orig='old_item=b') key='old_item', value='b', sep='=', orig='old_item=b')
] ]
self.parser.args.ignore_stdin = False self.parser.args.ignore_stdin = False
@ -293,15 +278,14 @@ class ArgumentParserTestCase(BaseTestCase):
self.parser._guess_method() self.parser._guess_method()
self.assertEqual(self.parser.args.items, [ assert self.parser.args.items, [
input.KeyValue( KeyValue(key='new_item', value='a', sep='=', orig='new_item=a'),
key='new_item', value='a', sep='=', orig='new_item=a'), KeyValue(
input.KeyValue(
key='old_item', value='b', sep='=', orig='old_item=b'), key='old_item', value='b', sep='=', orig='old_item=b'),
]) ]
class TestNoOptions(BaseTestCase): class TestNoOptions(TestCase):
def test_valid_no_options(self): def test_valid_no_options(self):
r = http( r = http(
@ -310,7 +294,7 @@ class TestNoOptions(BaseTestCase):
'GET', 'GET',
httpbin('/get') httpbin('/get')
) )
self.assertNotIn('GET /get HTTP/1.1', r) assert 'GET /get HTTP/1.1' not in r
def test_invalid_no_options(self): def test_invalid_no_options(self):
r = http( r = http(
@ -318,12 +302,12 @@ class TestNoOptions(BaseTestCase):
'GET', 'GET',
httpbin('/get') httpbin('/get')
) )
self.assertEqual(r.exit_status, 1) assert r.exit_status == 1
self.assertIn('unrecognized arguments: --no-war', r.stderr) assert 'unrecognized arguments: --no-war' in r.stderr
self.assertNotIn('GET /get HTTP/1.1', r) assert 'GET /get HTTP/1.1' not in r
class IgnoreStdinTest(BaseTestCase): class IgnoreStdinTest(TestCase):
def test_ignore_stdin(self): def test_ignore_stdin(self):
with open(FILE_PATH) as f: with open(FILE_PATH) as f:
@ -333,9 +317,9 @@ class IgnoreStdinTest(BaseTestCase):
httpbin('/get'), httpbin('/get'),
env=TestEnvironment(stdin=f, stdin_isatty=False) env=TestEnvironment(stdin=f, stdin_isatty=False)
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn('GET /get HTTP', r) # Don't default to POST. assert 'GET /get HTTP' in r, "Don't default to POST."
self.assertNotIn(FILE_CONTENT, r) # Don't send stdin data. assert FILE_CONTENT not in r, "Don't send stdin data."
def test_ignore_stdin_cannot_prompt_password(self): def test_ignore_stdin_cannot_prompt_password(self):
r = http( r = http(
@ -343,5 +327,5 @@ class IgnoreStdinTest(BaseTestCase):
'--auth=username-without-password', '--auth=username-without-password',
httpbin('/get'), httpbin('/get'),
) )
self.assertEqual(r.exit_status, ExitStatus.ERROR) assert r.exit_status == ExitStatus.ERROR
self.assertIn('because --ignore-stdin', r.stderr) assert 'because --ignore-stdin' in r.stderr

View File

@ -2,34 +2,36 @@
Tests for the provided defaults regarding HTTP method, and --json vs. --form. Tests for the provided defaults regarding HTTP method, and --json vs. --form.
""" """
from unittest import TestCase
from tests import ( from tests import (
BaseTestCase, TestEnvironment, TestEnvironment,
http, httpbin, http, httpbin,
OK, FILE_PATH, HTTP_OK, FILE_PATH,
) )
class ImplicitHTTPMethodTest(BaseTestCase): class ImplicitHTTPMethodTest(TestCase):
def test_implicit_GET(self): def test_implicit_GET(self):
r = http(httpbin('/get')) r = http(httpbin('/get'))
self.assertIn(OK, r) assert HTTP_OK in r
def test_implicit_GET_with_headers(self): def test_implicit_GET_with_headers(self):
r = http( r = http(
httpbin('/headers'), httpbin('/headers'),
'Foo:bar' 'Foo:bar'
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn('"Foo": "bar"', r) assert '"Foo": "bar"' in r
def test_implicit_POST_json(self): def test_implicit_POST_json(self):
r = http( r = http(
httpbin('/post'), httpbin('/post'),
'hello=world' 'hello=world'
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn(r'\"hello\": \"world\"', r) assert r'\"hello\": \"world\"' in r
def test_implicit_POST_form(self): def test_implicit_POST_form(self):
r = http( r = http(
@ -37,8 +39,8 @@ class ImplicitHTTPMethodTest(BaseTestCase):
httpbin('/post'), httpbin('/post'),
'foo=bar' 'foo=bar'
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn('"foo": "bar"', r) assert '"foo": "bar"' in r
def test_implicit_POST_stdin(self): def test_implicit_POST_stdin(self):
with open(FILE_PATH) as f: with open(FILE_PATH) as f:
@ -51,10 +53,10 @@ class ImplicitHTTPMethodTest(BaseTestCase):
httpbin('/post'), httpbin('/post'),
env=env env=env
) )
self.assertIn(OK, r) assert HTTP_OK in r
class AutoContentTypeAndAcceptHeadersTest(BaseTestCase): class AutoContentTypeAndAcceptHeadersTest(TestCase):
""" """
Test that Accept and Content-Type correctly defaults to JSON, Test that Accept and Content-Type correctly defaults to JSON,
but can still be overridden. The same with Content-Type when --form but can still be overridden. The same with Content-Type when --form
@ -67,9 +69,9 @@ class AutoContentTypeAndAcceptHeadersTest(BaseTestCase):
'GET', 'GET',
httpbin('/headers') httpbin('/headers')
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn('"Accept": "*/*"', r) assert '"Accept": "*/*"' in r
self.assertNotIn('"Content-Type": "application/json', r) assert '"Content-Type": "application/json' not in r
def test_POST_no_data_no_auto_headers(self): def test_POST_no_data_no_auto_headers(self):
# JSON headers shouldn't be automatically set for POST with no data. # JSON headers shouldn't be automatically set for POST with no data.
@ -77,9 +79,9 @@ class AutoContentTypeAndAcceptHeadersTest(BaseTestCase):
'POST', 'POST',
httpbin('/post') httpbin('/post')
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn('"Accept": "*/*"', r) assert '"Accept": "*/*"' in r
self.assertNotIn('"Content-Type": "application/json', r) assert '"Content-Type": "application/json' not in r
def test_POST_with_data_auto_JSON_headers(self): def test_POST_with_data_auto_JSON_headers(self):
r = http( r = http(
@ -87,9 +89,9 @@ class AutoContentTypeAndAcceptHeadersTest(BaseTestCase):
httpbin('/post'), httpbin('/post'),
'a=b' 'a=b'
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn('"Accept": "application/json"', r) assert '"Accept": "application/json"' in r
self.assertIn('"Content-Type": "application/json; charset=utf-8', r) assert '"Content-Type": "application/json; charset=utf-8' in r
def test_GET_with_data_auto_JSON_headers(self): def test_GET_with_data_auto_JSON_headers(self):
# JSON headers should automatically be set also for GET with data. # JSON headers should automatically be set also for GET with data.
@ -98,9 +100,9 @@ class AutoContentTypeAndAcceptHeadersTest(BaseTestCase):
httpbin('/post'), httpbin('/post'),
'a=b' 'a=b'
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn('"Accept": "application/json"', r) assert '"Accept": "application/json"' in r
self.assertIn('"Content-Type": "application/json; charset=utf-8', r) assert '"Content-Type": "application/json; charset=utf-8' in r
def test_POST_explicit_JSON_auto_JSON_accept(self): def test_POST_explicit_JSON_auto_JSON_accept(self):
r = http( r = http(
@ -108,11 +110,11 @@ class AutoContentTypeAndAcceptHeadersTest(BaseTestCase):
'POST', 'POST',
httpbin('/post') httpbin('/post')
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertEqual(r.json['headers']['Accept'], 'application/json') assert r.json['headers']['Accept'] == 'application/json'
# Make sure Content-Type gets set even with no data. # Make sure Content-Type gets set even with no data.
# https://github.com/jkbr/httpie/issues/137 # https://github.com/jkbr/httpie/issues/137
self.assertIn('application/json', r.json['headers']['Content-Type']) assert 'application/json' in r.json['headers']['Content-Type']
def test_GET_explicit_JSON_explicit_headers(self): def test_GET_explicit_JSON_explicit_headers(self):
r = http( r = http(
@ -122,9 +124,9 @@ class AutoContentTypeAndAcceptHeadersTest(BaseTestCase):
'Accept:application/xml', 'Accept:application/xml',
'Content-Type:application/xml' 'Content-Type:application/xml'
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn('"Accept": "application/xml"', r) assert '"Accept": "application/xml"' in r
self.assertIn('"Content-Type": "application/xml"', r) assert '"Content-Type": "application/xml"' in r
def test_POST_form_auto_Content_Type(self): def test_POST_form_auto_Content_Type(self):
r = http( r = http(
@ -132,12 +134,8 @@ class AutoContentTypeAndAcceptHeadersTest(BaseTestCase):
'POST', 'POST',
httpbin('/post') httpbin('/post')
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn( assert '"Content-Type": "application/x-www-form-urlencoded' in r
'"Content-Type":'
' "application/x-www-form-urlencoded; charset=utf-8"',
r
)
def test_POST_form_Content_Type_override(self): def test_POST_form_Content_Type_override(self):
r = http( r = http(
@ -146,8 +144,8 @@ class AutoContentTypeAndAcceptHeadersTest(BaseTestCase):
httpbin('/post'), httpbin('/post'),
'Content-Type:application/xml' 'Content-Type:application/xml'
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn('"Content-Type": "application/xml"', r) assert '"Content-Type": "application/xml"' in r
def test_print_only_body_when_stdout_redirected_by_default(self): def test_print_only_body_when_stdout_redirected_by_default(self):
@ -159,7 +157,7 @@ class AutoContentTypeAndAcceptHeadersTest(BaseTestCase):
stdout_isatty=False stdout_isatty=False
) )
) )
self.assertNotIn('HTTP/', r) assert 'HTTP/' not in r
def test_print_overridable_when_stdout_redirected(self): def test_print_overridable_when_stdout_redirected(self):
@ -172,4 +170,4 @@ class AutoContentTypeAndAcceptHeadersTest(BaseTestCase):
stdout_isatty=False stdout_isatty=False
) )
) )
self.assertIn(OK, r) assert HTTP_OK in r

View File

@ -1,7 +1,8 @@
import os import os
import subprocess import subprocess
from unittest import TestCase
from tests import TESTS_ROOT, BaseTestCase, skipIf from tests import TESTS_ROOT, skipIf
def has_docutils(): def has_docutils():
@ -25,9 +26,9 @@ def get_readme_errors():
return err return err
class READMETest(BaseTestCase): class READMETest(TestCase):
@skipIf(not has_docutils(), 'docutils not installed') @skipIf(not has_docutils(), 'docutils not installed')
def test_README_reStructuredText_valid(self): def test_README_reStructuredText_valid(self):
errors = get_readme_errors() errors = get_readme_errors()
self.assertFalse(errors, msg=errors) assert not errors, errors

View File

@ -1,5 +1,6 @@
import os import os
import time import time
from unittest import TestCase
from httpie.compat import urlopen from httpie.compat import urlopen
from httpie.downloads import ( from httpie.downloads import (
@ -10,19 +11,17 @@ from httpie.downloads import (
ContentRangeError, ContentRangeError,
Download, Download,
) )
from tests import ( from tests import httpbin, http, TestEnvironment, Response
BaseTestCase, httpbin, http, TestEnvironment, Response
)
class DownloadUtilsTest(BaseTestCase): class DownloadUtilsTest(TestCase):
def test_Content_Range_parsing(self): def test_Content_Range_parsing(self):
parse = parse_content_range parse = parse_content_range
self.assertEqual(parse('bytes 100-199/200', 100), 200) assert parse('bytes 100-199/200', 100) == 200
self.assertEqual(parse('bytes 100-199/*', 100), 200) assert parse('bytes 100-199/*', 100) == 200
# missing # missing
self.assertRaises(ContentRangeError, parse, None, 100) self.assertRaises(ContentRangeError, parse, None, 100)
@ -44,42 +43,34 @@ class DownloadUtilsTest(BaseTestCase):
def test_Content_Disposition_parsing(self): def test_Content_Disposition_parsing(self):
parse = filename_from_content_disposition parse = filename_from_content_disposition
self.assertEqual( assert 'hello-WORLD_123.txt' == parse(
parse('attachment; filename=hello-WORLD_123.txt'), 'attachment; filename=hello-WORLD_123.txt')
'hello-WORLD_123.txt' assert 'hello-WORLD_123.txt' == parse(
) 'attachment; filename=".hello-WORLD_123.txt"')
self.assertEqual( assert 'white space.txt' == parse(
parse('attachment; filename=".hello-WORLD_123.txt"'), 'attachment; filename="white space.txt"')
'hello-WORLD_123.txt' assert '"quotes".txt' == parse(
) r'attachment; filename="\"quotes\".txt"')
self.assertEqual( assert parse('attachment; filename=/etc/hosts') == 'hosts'
parse('attachment; filename="white space.txt"'), assert parse('attachment; filename=') is None
'white space.txt'
)
self.assertEqual(
parse(r'attachment; filename="\"quotes\".txt"'),
'"quotes".txt'
)
self.assertEqual(parse('attachment; filename=/etc/hosts'), 'hosts')
self.assertIsNone(parse('attachment; filename='))
def test_filename_from_url(self): def test_filename_from_url(self):
self.assertEqual(filename_from_url( assert 'foo.txt' == filename_from_url(
url='http://example.org/foo', url='http://example.org/foo',
content_type='text/plain' content_type='text/plain'
), 'foo.txt') )
self.assertEqual(filename_from_url( assert 'foo.html' == filename_from_url(
url='http://example.org/foo', url='http://example.org/foo',
content_type='text/html; charset=utf8' content_type='text/html; charset=utf8'
), 'foo.html') )
self.assertEqual(filename_from_url( assert 'foo' == filename_from_url(
url='http://example.org/foo', url='http://example.org/foo',
content_type=None content_type=None
), 'foo') )
self.assertEqual(filename_from_url( assert 'foo' == filename_from_url(
url='http://example.org/foo', url='http://example.org/foo',
content_type='x-foo/bar' content_type='x-foo/bar'
), 'foo') )
def test_unique_filename(self): def test_unique_filename(self):
@ -93,21 +84,12 @@ class DownloadUtilsTest(BaseTestCase):
exists.attempt = 0 exists.attempt = 0
return exists return exists
self.assertEqual( assert 'foo.bar' == get_unique_filename('foo.bar', make_exists())
get_unique_filename('foo.bar', exists=make_exists()), assert 'foo.bar-1' == get_unique_filename('foo.bar', make_exists(1))
'foo.bar' assert 'foo.bar-10' == get_unique_filename('foo.bar', make_exists(10))
)
self.assertEqual(
get_unique_filename('foo.bar', exists=make_exists(1)),
'foo.bar-1'
)
self.assertEqual(
get_unique_filename('foo.bar', exists=make_exists(10)),
'foo.bar-10'
)
class DownloadsTest(BaseTestCase): class DownloadsTest(TestCase):
# TODO: more tests # TODO: more tests
def test_actual_download(self): def test_actual_download(self):
@ -121,10 +103,10 @@ class DownloadsTest(BaseTestCase):
stdout_isatty=False stdout_isatty=False
) )
) )
self.assertIn('Downloading', r.stderr) assert 'Downloading' in r.stderr
self.assertIn('[K', r.stderr) assert '[K' in r.stderr
self.assertIn('Done', r.stderr) assert 'Done' in r.stderr
self.assertEqual(body, r) assert body == r
def test_download_with_Content_Length(self): def test_download_with_Content_Length(self):
download = Download(output_file=open(os.devnull, 'w')) download = Download(output_file=open(os.devnull, 'w'))
@ -137,7 +119,7 @@ class DownloadsTest(BaseTestCase):
time.sleep(1.1) time.sleep(1.1)
download.chunk_downloaded(b'12345') download.chunk_downloaded(b'12345')
download.finish() download.finish()
self.assertFalse(download.interrupted) assert not download.interrupted
def test_download_no_Content_Length(self): def test_download_no_Content_Length(self):
download = Download(output_file=open(os.devnull, 'w')) download = Download(output_file=open(os.devnull, 'w'))
@ -145,7 +127,7 @@ class DownloadsTest(BaseTestCase):
time.sleep(1.1) time.sleep(1.1)
download.chunk_downloaded(b'12345') download.chunk_downloaded(b'12345')
download.finish() download.finish()
self.assertFalse(download.interrupted) assert not download.interrupted
def test_download_interrupted(self): def test_download_interrupted(self):
download = Download(output_file=open(os.devnull, 'w')) download = Download(output_file=open(os.devnull, 'w'))
@ -155,4 +137,4 @@ class DownloadsTest(BaseTestCase):
)) ))
download.chunk_downloaded(b'1234') download.chunk_downloaded(b'1234')
download.finish() download.finish()
self.assertTrue(download.interrupted) assert download.interrupted

View File

@ -1,30 +1,32 @@
from unittest import TestCase
import requests import requests
from httpie import ExitStatus from httpie import ExitStatus
from tests import ( from tests import (
BaseTestCase, TestEnvironment, TestEnvironment,
http, httpbin, OK, skip, skipIf http, httpbin, HTTP_OK, skip, skipIf
) )
class ExitStatusTest(BaseTestCase): class ExitStatusTest(TestCase):
def test_ok_response_exits_0(self): def test_ok_response_exits_0(self):
r = http( r = http(
'GET', 'GET',
httpbin('/status/200') httpbin('/status/200')
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertEqual(r.exit_status, ExitStatus.OK) assert r.exit_status == ExitStatus.OK
def test_error_response_exits_0_without_check_status(self): def test_error_response_exits_0_without_check_status(self):
r = http( r = http(
'GET', 'GET',
httpbin('/status/500') httpbin('/status/500')
) )
self.assertIn('HTTP/1.1 500', r) assert 'HTTP/1.1 500' in r
self.assertEqual(r.exit_status, ExitStatus.OK) assert r.exit_status == ExitStatus.OK
self.assertTrue(not r.stderr) assert not r.stderr
@skip('timeout broken in requests' @skip('timeout broken in requests'
' (https://github.com/jkbr/httpie/issues/185)') ' (https://github.com/jkbr/httpie/issues/185)')
@ -34,7 +36,7 @@ class ExitStatusTest(BaseTestCase):
'GET', 'GET',
httpbin('/delay/1') httpbin('/delay/1')
) )
self.assertEqual(r.exit_status, ExitStatus.ERROR_TIMEOUT) assert r.exit_status == ExitStatus.ERROR_TIMEOUT
def test_3xx_check_status_exits_3_and_stderr_when_stdout_redirected(self): def test_3xx_check_status_exits_3_and_stderr_when_stdout_redirected(self):
r = http( r = http(
@ -44,9 +46,9 @@ class ExitStatusTest(BaseTestCase):
httpbin('/status/301'), httpbin('/status/301'),
env=TestEnvironment(stdout_isatty=False,) env=TestEnvironment(stdout_isatty=False,)
) )
self.assertIn('HTTP/1.1 301', r) assert 'HTTP/1.1 301' in r
self.assertEqual(r.exit_status, ExitStatus.ERROR_HTTP_3XX) assert r.exit_status == ExitStatus.ERROR_HTTP_3XX
self.assertIn('301 moved permanently', r.stderr.lower()) assert '301 moved permanently' in r.stderr.lower()
@skipIf(requests.__version__ == '0.13.6', @skipIf(requests.__version__ == '0.13.6',
'Redirects with prefetch=False are broken in Requests 0.13.6') 'Redirects with prefetch=False are broken in Requests 0.13.6')
@ -58,8 +60,8 @@ class ExitStatusTest(BaseTestCase):
httpbin('/status/301') httpbin('/status/301')
) )
# The redirect will be followed so 200 is expected. # The redirect will be followed so 200 is expected.
self.assertIn('HTTP/1.1 200 OK', r) assert 'HTTP/1.1 200 OK' in r
self.assertEqual(r.exit_status, ExitStatus.OK) assert r.exit_status == ExitStatus.OK
def test_4xx_check_status_exits_4(self): def test_4xx_check_status_exits_4(self):
r = http( r = http(
@ -67,10 +69,10 @@ class ExitStatusTest(BaseTestCase):
'GET', 'GET',
httpbin('/status/401') httpbin('/status/401')
) )
self.assertIn('HTTP/1.1 401', r) assert 'HTTP/1.1 401' in r
self.assertEqual(r.exit_status, ExitStatus.ERROR_HTTP_4XX) assert r.exit_status == ExitStatus.ERROR_HTTP_4XX
# Also stderr should be empty since stdout isn't redirected. # Also stderr should be empty since stdout isn't redirected.
self.assertTrue(not r.stderr) assert not r.stderr
def test_5xx_check_status_exits_5(self): def test_5xx_check_status_exits_5(self):
r = http( r = http(
@ -78,5 +80,5 @@ class ExitStatusTest(BaseTestCase):
'GET', 'GET',
httpbin('/status/500') httpbin('/status/500')
) )
self.assertIn('HTTP/1.1 500', r) assert 'HTTP/1.1 500' in r
self.assertEqual(r.exit_status, ExitStatus.ERROR_HTTP_5XX) assert r.exit_status == ExitStatus.ERROR_HTTP_5XX

View File

@ -1,26 +1,28 @@
"""High-level tests.""" """High-level tests."""
from unittest import TestCase
from tests import ( from tests import (
BaseTestCase, TestEnvironment, TestEnvironment,
http, httpbin, OK, http, httpbin, HTTP_OK,
FILE_PATH, FILE_CONTENT FILE_PATH, FILE_CONTENT
) )
class HTTPieTest(BaseTestCase): class HTTPieTest(TestCase):
def test_GET(self): def test_GET(self):
r = http( r = http(
'GET', 'GET',
httpbin('/get') httpbin('/get')
) )
self.assertIn(OK, r) assert HTTP_OK in r
def test_DELETE(self): def test_DELETE(self):
r = http( r = http(
'DELETE', 'DELETE',
httpbin('/delete') httpbin('/delete')
) )
self.assertIn(OK, r) assert HTTP_OK in r
def test_PUT(self): def test_PUT(self):
r = http( r = http(
@ -28,8 +30,8 @@ class HTTPieTest(BaseTestCase):
httpbin('/put'), httpbin('/put'),
'foo=bar' 'foo=bar'
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn(r'\"foo\": \"bar\"', r) assert r'\"foo\": \"bar\"' in r
def test_POST_JSON_data(self): def test_POST_JSON_data(self):
r = http( r = http(
@ -37,8 +39,8 @@ class HTTPieTest(BaseTestCase):
httpbin('/post'), httpbin('/post'),
'foo=bar' 'foo=bar'
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn(r'\"foo\": \"bar\"', r) assert r'\"foo\": \"bar\"' in r
def test_POST_form(self): def test_POST_form(self):
r = http( r = http(
@ -47,8 +49,8 @@ class HTTPieTest(BaseTestCase):
httpbin('/post'), httpbin('/post'),
'foo=bar' 'foo=bar'
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn('"foo": "bar"', r) assert '"foo": "bar"' in r
def test_POST_form_multiple_values(self): def test_POST_form_multiple_values(self):
r = http( r = http(
@ -58,10 +60,8 @@ class HTTPieTest(BaseTestCase):
'foo=bar', 'foo=bar',
'foo=baz', 'foo=baz',
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertDictEqual(r.json['form'], { assert r.json['form'] == {'foo': ['bar', 'baz']}
'foo': ['bar', 'baz']
})
def test_POST_stdin(self): def test_POST_stdin(self):
@ -77,8 +77,8 @@ class HTTPieTest(BaseTestCase):
httpbin('/post'), httpbin('/post'),
env=env env=env
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn(FILE_CONTENT, r) assert FILE_CONTENT in r
def test_headers(self): def test_headers(self):
r = http( r = http(
@ -86,6 +86,6 @@ class HTTPieTest(BaseTestCase):
httpbin('/headers'), httpbin('/headers'),
'Foo:bar' 'Foo:bar'
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn('"User-Agent": "HTTPie', r) assert '"User-Agent": "HTTPie' in r
self.assertIn('"Foo": "bar"', r) assert '"Foo": "bar"' in r

View File

@ -1,11 +1,14 @@
from unittest import TestCase
from httpie import ExitStatus
from tests import ( from tests import (
BaseTestCase, TestEnvironment, TestEnvironment,
http, httpbin, http, httpbin,
OK, COLOR, CRLF HTTP_OK, COLOR, CRLF
) )
class VerboseFlagTest(BaseTestCase): class VerboseFlagTest(TestCase):
def test_verbose(self): def test_verbose(self):
r = http( r = http(
@ -14,9 +17,8 @@ class VerboseFlagTest(BaseTestCase):
httpbin('/get'), httpbin('/get'),
'test-header:__test__' 'test-header:__test__'
) )
self.assertIn(OK, r) assert HTTP_OK in r
#noinspection PyUnresolvedReferences assert r.count('__test__') == 2
self.assertEqual(r.count('__test__'), 2)
def test_verbose_form(self): def test_verbose_form(self):
# https://github.com/jkbr/httpie/issues/53 # https://github.com/jkbr/httpie/issues/53
@ -28,8 +30,8 @@ class VerboseFlagTest(BaseTestCase):
'foo=bar', 'foo=bar',
'baz=bar' 'baz=bar'
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn('foo=bar&baz=bar', r) assert 'foo=bar&baz=bar' in r
def test_verbose_json(self): def test_verbose_json(self):
r = http( r = http(
@ -39,12 +41,12 @@ class VerboseFlagTest(BaseTestCase):
'foo=bar', 'foo=bar',
'baz=bar' 'baz=bar'
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn('"baz": "bar"', r) # request assert '"baz": "bar"' in r # request
self.assertIn(r'\"baz\": \"bar\"', r) # response assert r'\"baz\": \"bar\"' in r # response
class PrettyOptionsTest(BaseTestCase): class PrettyOptionsTest(TestCase):
"""Test the --pretty flag handling.""" """Test the --pretty flag handling."""
def test_pretty_enabled_by_default(self): def test_pretty_enabled_by_default(self):
@ -53,14 +55,14 @@ class PrettyOptionsTest(BaseTestCase):
httpbin('/get'), httpbin('/get'),
env=TestEnvironment(colors=256), env=TestEnvironment(colors=256),
) )
self.assertIn(COLOR, r) assert COLOR in r
def test_pretty_enabled_by_default_unless_stdout_redirected(self): def test_pretty_enabled_by_default_unless_stdout_redirected(self):
r = http( r = http(
'GET', 'GET',
httpbin('/get') httpbin('/get')
) )
self.assertNotIn(COLOR, r) assert COLOR not in r
def test_force_pretty(self): def test_force_pretty(self):
r = http( r = http(
@ -69,7 +71,7 @@ class PrettyOptionsTest(BaseTestCase):
httpbin('/get'), httpbin('/get'),
env=TestEnvironment(stdout_isatty=False, colors=256), env=TestEnvironment(stdout_isatty=False, colors=256),
) )
self.assertIn(COLOR, r) assert COLOR in r
def test_force_ugly(self): def test_force_ugly(self):
r = http( r = http(
@ -77,7 +79,7 @@ class PrettyOptionsTest(BaseTestCase):
'GET', 'GET',
httpbin('/get'), httpbin('/get'),
) )
self.assertNotIn(COLOR, r) assert COLOR not in r
def test_subtype_based_pygments_lexer_match(self): def test_subtype_based_pygments_lexer_match(self):
"""Test that media subtype is used if type/subtype doesn't """Test that media subtype is used if type/subtype doesn't
@ -92,7 +94,7 @@ class PrettyOptionsTest(BaseTestCase):
'a=b', 'a=b',
env=TestEnvironment(colors=256) env=TestEnvironment(colors=256)
) )
self.assertIn(COLOR, r) assert COLOR in r
def test_colors_option(self): def test_colors_option(self):
r = http( r = http(
@ -105,8 +107,8 @@ class PrettyOptionsTest(BaseTestCase):
) )
#noinspection PyUnresolvedReferences #noinspection PyUnresolvedReferences
# Tests that the JSON data isn't formatted. # Tests that the JSON data isn't formatted.
self.assertEqual(r.strip().count('\n'), 0) assert not r.strip().count('\n')
self.assertIn(COLOR, r) assert COLOR in r
def test_format_option(self): def test_format_option(self):
r = http( r = http(
@ -119,11 +121,11 @@ class PrettyOptionsTest(BaseTestCase):
) )
#noinspection PyUnresolvedReferences #noinspection PyUnresolvedReferences
# Tests that the JSON data is formatted. # Tests that the JSON data is formatted.
self.assertEqual(r.strip().count('\n'), 2) assert r.strip().count('\n') == 2
self.assertNotIn(COLOR, r) assert COLOR not in r
class LineEndingsTest(BaseTestCase): class LineEndingsTest(TestCase):
"""Test that CRLF is properly used in headers and """Test that CRLF is properly used in headers and
as the headers/body separator.""" as the headers/body separator."""
@ -132,11 +134,11 @@ class LineEndingsTest(BaseTestCase):
for header in lines: for header in lines:
if header == CRLF: if header == CRLF:
break break
self.assertTrue(header.endswith(CRLF), repr(header)) assert header.endswith(CRLF), repr(header)
else: else:
self.fail('CRLF between headers and body not found in %r' % msg) self.fail('CRLF between headers and body not found in %r' % msg)
body = ''.join(lines) body = ''.join(lines)
self.assertNotIn(CRLF, body) assert CRLF not in body
return body return body
def test_CRLF_headers_only(self): def test_CRLF_headers_only(self):
@ -146,7 +148,7 @@ class LineEndingsTest(BaseTestCase):
httpbin('/get') httpbin('/get')
) )
body = self._validate_crlf(r) body = self._validate_crlf(r)
self.assertFalse(body, 'Garbage after headers: %r' % r) assert not body, 'Garbage after headers: %r' % r
def test_CRLF_ugly_response(self): def test_CRLF_ugly_response(self):
r = http( r = http(
@ -162,7 +164,7 @@ class LineEndingsTest(BaseTestCase):
'GET', 'GET',
httpbin('/get') httpbin('/get')
) )
self.assertEqual(r.exit_status, 0) assert r.exit_status == ExitStatus.OK
self._validate_crlf(r) self._validate_crlf(r)
def test_CRLF_ugly_request(self): def test_CRLF_ugly_request(self):

View File

@ -1,14 +1,15 @@
import os import os
import shutil import shutil
from unittest import TestCase
from tests import ( from tests import (
BaseTestCase, TestEnvironment, TestEnvironment,
mk_config_dir, http, httpbin, mk_config_dir, http, httpbin,
OK, HTTP_OK,
) )
class SessionsTest(BaseTestCase): class SessionsTest(TestCase):
@property @property
def env(self): def env(self):
@ -27,7 +28,7 @@ class SessionsTest(BaseTestCase):
'Hello:World', 'Hello:World',
env=self.env env=self.env
) )
self.assertIn(OK, r) assert HTTP_OK in r
def tearDown(self): def tearDown(self):
shutil.rmtree(self.config_dir) shutil.rmtree(self.config_dir)
@ -40,11 +41,10 @@ class SessionsTest(BaseTestCase):
httpbin('/get'), httpbin('/get'),
env=self.env env=self.env
) )
self.assertIn(OK, r) assert HTTP_OK in r
assert r.json['headers']['Hello'] == 'World'
self.assertEqual(r.json['headers']['Hello'], 'World') assert r.json['headers']['Cookie'] == 'hello=world'
self.assertEqual(r.json['headers']['Cookie'], 'hello=world') assert 'Basic ' in r.json['headers']['Authorization']
self.assertIn('Basic ', r.json['headers']['Authorization'])
def test_session_ignored_header_prefixes(self): def test_session_ignored_header_prefixes(self):
r = http( r = http(
@ -55,16 +55,16 @@ class SessionsTest(BaseTestCase):
'If-Unmodified-Since: Sat, 29 Oct 1994 19:43:31 GMT', 'If-Unmodified-Since: Sat, 29 Oct 1994 19:43:31 GMT',
env=self.env env=self.env
) )
self.assertIn(OK, r) assert HTTP_OK in r
r2 = http( r2 = http(
'--session=test', '--session=test',
'GET', 'GET',
httpbin('/get') httpbin('/get')
) )
self.assertIn(OK, r2) assert HTTP_OK in r2
self.assertNotIn('Content-Type', r2.json['headers']) assert 'Content-Type' not in r2.json['headers']
self.assertNotIn('If-Unmodified-Since', r2.json['headers']) assert 'If-Unmodified-Since' not in r2.json['headers']
def test_session_update(self): def test_session_update(self):
# Get a response to a request from the original session. # Get a response to a request from the original session.
@ -74,7 +74,7 @@ class SessionsTest(BaseTestCase):
httpbin('/get'), httpbin('/get'),
env=self.env env=self.env
) )
self.assertIn(OK, r1) assert HTTP_OK in r1
# Make a request modifying the session data. # Make a request modifying the session data.
r2 = http( r2 = http(
@ -86,7 +86,7 @@ class SessionsTest(BaseTestCase):
'Hello:World2', 'Hello:World2',
env=self.env env=self.env
) )
self.assertIn(OK, r2) assert HTTP_OK in r2
# Get a response to a request from the updated session. # Get a response to a request from the updated session.
r3 = http( r3 = http(
@ -95,12 +95,11 @@ class SessionsTest(BaseTestCase):
httpbin('/get'), httpbin('/get'),
env=self.env env=self.env
) )
self.assertIn(OK, r3) assert HTTP_OK in r3
assert r3.json['headers']['Hello'] == 'World2'
self.assertEqual(r3.json['headers']['Hello'], 'World2') assert r3.json['headers']['Cookie'] == 'hello=world2'
self.assertEqual(r3.json['headers']['Cookie'], 'hello=world2') assert (r1.json['headers']['Authorization'] !=
self.assertNotEqual(r1.json['headers']['Authorization'], r3.json['headers']['Authorization'])
r3.json['headers']['Authorization'])
def test_session_read_only(self): def test_session_read_only(self):
# Get a response from the original session. # Get a response from the original session.
@ -110,7 +109,7 @@ class SessionsTest(BaseTestCase):
httpbin('/get'), httpbin('/get'),
env=self.env env=self.env
) )
self.assertIn(OK, r1) assert HTTP_OK in r1
# Make a request modifying the session data but # Make a request modifying the session data but
# with --session-read-only. # with --session-read-only.
@ -123,7 +122,7 @@ class SessionsTest(BaseTestCase):
'Hello:World2', 'Hello:World2',
env=self.env env=self.env
) )
self.assertIn(OK, r2) assert HTTP_OK in r2
# Get a response from the updated session. # Get a response from the updated session.
r3 = http( r3 = http(
@ -132,7 +131,7 @@ class SessionsTest(BaseTestCase):
httpbin('/get'), httpbin('/get'),
env=self.env env=self.env
) )
self.assertIn(OK, r3) assert HTTP_OK in r3
# Origin can differ on Travis. # Origin can differ on Travis.
del r1.json['origin'], r3.json['origin'] del r1.json['origin'], r3.json['origin']
@ -140,11 +139,10 @@ class SessionsTest(BaseTestCase):
del r1.json['headers']['X-Request-Id'], \ del r1.json['headers']['X-Request-Id'], \
r3.json['headers']['X-Request-Id'] r3.json['headers']['X-Request-Id']
# Should be the same as before r2. # Should be the same as before r2.
self.assertDictEqual(r1.json, r3.json) assert r1.json == r3.json
def test_session_by_path(self): def test_session_by_path(self):
session_path = os.path.join(self.config_dir, 'session-by-path.json') session_path = os.path.join(self.config_dir, 'session-by-path.json')
r1 = http( r1 = http(
'--session=' + session_path, '--session=' + session_path,
'GET', 'GET',
@ -152,7 +150,7 @@ class SessionsTest(BaseTestCase):
'Foo:Bar', 'Foo:Bar',
env=self.env env=self.env
) )
self.assertIn(OK, r1) assert HTTP_OK in r1
r2 = http( r2 = http(
'--session=' + session_path, '--session=' + session_path,
@ -160,6 +158,6 @@ class SessionsTest(BaseTestCase):
httpbin('/get'), httpbin('/get'),
env=self.env env=self.env
) )
self.assertIn(OK, r2) assert HTTP_OK in r2
self.assertEqual(r2.json['headers']['Foo'], 'Bar') assert r2.json['headers']['Foo'] in 'Bar'

View File

@ -1,13 +1,15 @@
from unittest import TestCase
from httpie.compat import is_windows from httpie.compat import is_windows
from httpie.output import BINARY_SUPPRESSED_NOTICE from httpie.output import BINARY_SUPPRESSED_NOTICE
from tests import ( from tests import (
http, httpbin, skipIf, http, httpbin, skipIf,
BaseTestCase, TestEnvironment, TestEnvironment,
BIN_FILE_CONTENT, BIN_FILE_PATH BIN_FILE_CONTENT, BIN_FILE_PATH
) )
class StreamTest(BaseTestCase): class StreamTest(TestCase):
# GET because httpbin 500s with binary POST body. # GET because httpbin 500s with binary POST body.
@skipIf(is_windows, 'Pretty redirect not supported under Windows') @skipIf(is_windows, 'Pretty redirect not supported under Windows')
@ -27,7 +29,7 @@ class StreamTest(BaseTestCase):
stdout_isatty=False, stdout_isatty=False,
) )
) )
self.assertIn(BINARY_SUPPRESSED_NOTICE.decode(), r) assert BINARY_SUPPRESSED_NOTICE.decode() in r
# We get 'Bad Request' but it's okay. # We get 'Bad Request' but it's okay.
#self.assertIn(OK_COLOR, r) #self.assertIn(OK_COLOR, r)
@ -46,7 +48,7 @@ class StreamTest(BaseTestCase):
stdin_isatty=False stdin_isatty=False
), ),
) )
self.assertIn(BINARY_SUPPRESSED_NOTICE.decode(), r) assert BINARY_SUPPRESSED_NOTICE.decode() in r
# We get 'Bad Request' but it's okay. # We get 'Bad Request' but it's okay.
#self.assertIn(OK, r) #self.assertIn(OK, r)
@ -68,4 +70,4 @@ class StreamTest(BaseTestCase):
) )
# We get 'Bad Request' but it's okay. # We get 'Bad Request' but it's okay.
#self.assertIn(OK.encode(), r) #self.assertIn(OK.encode(), r)
self.assertIn(BIN_FILE_CONTENT, r) assert BIN_FILE_CONTENT in r

View File

@ -1,13 +1,14 @@
import os import os
from unittest import TestCase
from httpie.input import ParseError from httpie.input import ParseError
from tests import ( from tests import (
BaseTestCase, TestEnvironment, http, httpbin, TestEnvironment, http, httpbin,
FILE_PATH_ARG, FILE_PATH, OK, FILE_CONTENT, FILE_PATH_ARG, FILE_PATH, HTTP_OK, FILE_CONTENT,
) )
class MultipartFormDataFileUploadTest(BaseTestCase): class MultipartFormDataFileUploadTest(TestCase):
def test_non_existent_file_raises_parse_error(self): def test_non_existent_file_raises_parse_error(self):
self.assertRaises(ParseError, http, self.assertRaises(ParseError, http,
@ -27,16 +28,15 @@ class MultipartFormDataFileUploadTest(BaseTestCase):
'foo=bar' 'foo=bar'
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn('Content-Disposition: form-data; name="foo"', r) assert 'Content-Disposition: form-data; name="foo"' in r
self.assertIn('Content-Disposition: form-data; name="test-file";' assert 'Content-Disposition: form-data; name="test-file";' \
' filename="%s"' % os.path.basename(FILE_PATH), r) ' filename="%s"' % os.path.basename(FILE_PATH) in r
#noinspection PyUnresolvedReferences assert r.count(FILE_CONTENT) == 2
self.assertEqual(r.count(FILE_CONTENT), 2) assert '"foo": "bar"' in r
self.assertIn('"foo": "bar"', r)
class RequestBodyFromFilePathTest(BaseTestCase): class RequestBodyFromFilePathTest(TestCase):
""" """
`http URL @file' `http URL @file'
@ -48,9 +48,9 @@ class RequestBodyFromFilePathTest(BaseTestCase):
httpbin('/post'), httpbin('/post'),
'@' + FILE_PATH_ARG '@' + FILE_PATH_ARG
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn(FILE_CONTENT, r) assert FILE_CONTENT in r
self.assertIn('"Content-Type": "text/plain"', r) assert '"Content-Type": "text/plain"' in r
def test_request_body_from_file_by_path_with_explicit_content_type(self): def test_request_body_from_file_by_path_with_explicit_content_type(self):
r = http( r = http(
@ -59,9 +59,9 @@ class RequestBodyFromFilePathTest(BaseTestCase):
'@' + FILE_PATH_ARG, '@' + FILE_PATH_ARG,
'Content-Type:x-foo/bar' 'Content-Type:x-foo/bar'
) )
self.assertIn(OK, r) assert HTTP_OK in r
self.assertIn(FILE_CONTENT, r) assert FILE_CONTENT in r
self.assertIn('"Content-Type": "x-foo/bar"', r) assert '"Content-Type": "x-foo/bar"' in r
def test_request_body_from_file_by_path_no_field_name_allowed(self): def test_request_body_from_file_by_path_no_field_name_allowed(self):
env = TestEnvironment(stdin_isatty=True) env = TestEnvironment(stdin_isatty=True)
@ -71,7 +71,7 @@ class RequestBodyFromFilePathTest(BaseTestCase):
'field-name@' + FILE_PATH_ARG, 'field-name@' + FILE_PATH_ARG,
env=env env=env
) )
self.assertIn('perhaps you meant --form?', r.stderr) assert 'perhaps you meant --form?' in r.stderr
def test_request_body_from_file_by_path_no_data_items_allowed(self): def test_request_body_from_file_by_path_no_data_items_allowed(self):
r = http( r = http(
@ -81,4 +81,4 @@ class RequestBodyFromFilePathTest(BaseTestCase):
'foo=bar', 'foo=bar',
env=TestEnvironment(stdin_isatty=False) env=TestEnvironment(stdin_isatty=False)
) )
self.assertIn('cannot be mixed', r.stderr) assert 'cannot be mixed' in r.stderr

View File

@ -1,13 +1,14 @@
import os import os
import tempfile import tempfile
from unittest import TestCase
from tests import ( from tests import (
BaseTestCase, TestEnvironment, TestEnvironment,
http, httpbin, Environment, skip http, httpbin, Environment, skip
) )
class WindowsOnlyTests(BaseTestCase): class WindowsOnlyTests(TestCase):
@skip('FIXME: kills the runner') @skip('FIXME: kills the runner')
#@skipIf(not is_windows, 'windows-only') #@skipIf(not is_windows, 'windows-only')
@ -16,7 +17,7 @@ class WindowsOnlyTests(BaseTestCase):
http(httpbin('/get'), env=Environment()) http(httpbin('/get'), env=Environment())
class FakeWindowsTest(BaseTestCase): class FakeWindowsTest(TestCase):
def test_output_file_pretty_not_allowed_on_windows(self): def test_output_file_pretty_not_allowed_on_windows(self):
@ -28,5 +29,4 @@ class FakeWindowsTest(BaseTestCase):
httpbin('/get'), httpbin('/get'),
env=TestEnvironment(is_windows=True) env=TestEnvironment(is_windows=True)
) )
self.assertIn( assert 'Only terminal output can be colorized on Windows' in r.stderr
'Only terminal output can be colorized on Windows', r.stderr)