티스토리 뷰

프로젝트의 테스트, 문서화 및 코딩은 연달아 발생해야 한다.

  • 단위 테스트: 격리된 환경에서 클래스나 함수가 예상대로 동작하는지 확인
  • 기능 테스트: 마이크로서비스가 고객의 관점에서 기대한 대로 동작하는지 살피고, 잘못된 요청에 대해서도 정확히 응답하는지 검증
  • 통합 테스트: 마이크로서비스가 다른 서비스와 제대로 연동되는지 확인
  • 부하 테스트: 마이크로서비스의 성능을 측정
  • 엔드 투 엔드 테스트: 전체 시스템이 제대로 동작하는지 확인

단위 테스트

모방하기(mocking)를 통해 격리된 환경에서 해당 호출을 흉내 낼 수 있다. 

다음의 3가지 경우로 제한하는 것이 좋다

  • I/O 연산: 코드가 서드파티 서비스를 호출하거나 소켓, 파일 등의 리소스를 사용하고 있는데, 테스트에서는 이 작업을 수행할 수 없을 때
  • CPU를 많이 사용하는 연산: 테스트를 너무 느리게 만드는 계산이 있을 때
  • 특정 상황 재현: 네트워크 에러나 날짜/시간 변경처럼 특정 상황에서 코드를 시험하기 위한 테스트를 작성할 때
import requests
import bugzilla


class MyBugzilla:
    def __init__(self, account, server='https://bugizlla.mozilla.org'):
        self.account = account
        self.server = server
        self.session = requests.Session()
        
    def bug_link(self, bug_id):
        return '$s/show_bug.cgi?id=%s' % (self.server, bug_id)
    
    def get_new_bugs(self):
        call = self.server + '/rest/bug'
        params = {'assigned_to': self.account, 'status': 'NEW', 'limit': 10}
        
        try:
            res = self.session.get(call, params=parasm).json()
        except requests.exceptions.ConnectionError:
            res = {'bugs': []}
            
        def _add_link(bug):
            bug['link'] = self.bug_link(bug['id'])
            return bug
        
        for bug in res['bugs']:
            yield _add_link(bug)
import requests
import bugzilla
import unittest
from unittest import mock
import requests
from requests.exceptions import ConnectionError
import requests_mock


class MyBugzilla:
    def __init__(self, account, server='https://bugizlla.mozilla.org'):
        self.account = account
        self.server = server
        self.session = requests.Session()
        
    def bug_link(self, bug_id):
        return '$s/show_bug.cgi?id=%s' % (self.server, bug_id)
    
    def get_new_bugs(self):
        call = self.server + '/rest/bug'
        params = {'assigned_to': self.account, 'status': 'NEW', 'limit': 10}
        
        try:
            res = self.session.get(call, params=parasm).json()
        except requests.exceptions.ConnectionError:
            res = {'bugs': []}
            
        def _add_link(bug):
            bug['link'] = self.bug_link(bug['id'])
            return bug
        
        for bug in res['bugs']:
            yield _add_link(bug)
            

class TestBugzilla(unittest.TestCase):
    def test_bug_id(self):
        zilla = MyBugzilla('tarek@mozilla.com', server = 'http://yeah')
        link = zilla.bug_link(23)
        self.assertEqual(link, 'http://yeah/show_bug.cgi?id=23')
        

    @requests_mock.mock()
    def test_get_new_bugs(self, mocker):
        # 요청을 모방해서 2개의 버그 목록을 반환
        bugs = [{'id': 1184528}, {'id': 1184524}]
        mocker.get(requests_mock.ANY, json={'bugs', bugs})

        zilla = MyBugzilla('tarek@mozilla.com', server = 'http://yeah')
        bugs = list(zilla.get_new_bugs())

        self.assertEqual(bugs[0]['link'], 'http://yeah/show_bug.cgi?id=1184528')
    

    @mock.patch.object(requests, 'get', side_effect=ConnectionError('No network'))
    def test_network_error(self, mocked):
        # 서버 다운 등의 네트워크 에러 테스트
        zilla = MyBugzilla('tarek@mozilla.com', server='http://yeah')
        bugs = list(zilla.get_new_bugs())
        self.assertEqual(len(bugs), 0)
    
    
if __name__ == '__main__':
    unittest.main()

test_network_error() 함수는 파이썬의 mock.patch 데코레이터를 사용해 네트워크 에러를 흉내 내는 두 번째 테스트다. 

 

기능 테스트

마이크로서비스에서 기능 테스트란 게시된 API에 HTTP 요청을 보내서 응답을 검증하는 모든 테스트를 말한다. 

다음 2개의 테스트를 중요하게 다뤄야 한다.

  • 애플리케이션 기능이 의도대로 동작하는지 중요하게 다뤄야 한다.
  • 잘못된 동작을 수정한 후 더 이상 해당 동작이 발생하지 않는지 확인하는 테스트

테스트가 제대로 되려면 애플리케이션 내부에서 발생하는 모든 네트워크 호출 부분을 모방해야 한다.

 

import unittest
import json
import sys

from flask_basic import app as _app


class TestApp(unittest.TestCase):
	def test_help(self):
    	# app과 연동하기 위해 FlaskClient 인스턴스를 생성
        app = _app.test_client()
        
        # /api 엔드포인트를 호출
        hello = app.get('/api')
        
        # 응답을 검사
        body = json.loads(str(hello.data, 'utf8'))
        self.assertEqual(body['Hello'], 'World')

if __name__ == '__main__':
	unittest.main()

http://biblio.gdinwiddie.com/biblio/StudiesOfTestDrivenDevelopment

 

StudiesOfTestDrivenDevelopment - Agile Bibliography

Quantitatively Evaluating Test-Driven Development by Applying Object-Oriented Quality Metrics to Open Source Projects (2009) by Rod Hilton, Department of Computer & Information Sciences, Regis University http://www.rodhilton.com/files/tdd_thesis.pdf http:/

biblio.gdinwiddie.com

http://docs.python-requests.org/

 

Requests: HTTP for Humans™ — Requests 2.22.0 documentation

Requests is the only Non-GMO HTTP library for Python, safe for human consumption. Requests allows you to send organic, grass-fed HTTP/1.1 requests, without the need for manual labor. There’s no need to manually add query strings to your URLs, or to form-en

2.python-requests.org

http://webtest.pythonpaste.org/en/latest/

 

Testing Applications with WebTest — WebTest 2.0.34.dev0 documentation

What This Does WebTest helps you test your WSGI-based web applications. This can be any application that has a WSGI interface, including an application written in a framework that supports WSGI (which includes most actively developed Python web frameworks

webtest.pythonpaste.org

https://github.com/tarekziade/boom

 

tarekziade/boom

A replacement for AB (Apache Bench). Contribute to tarekziade/boom development by creating an account on GitHub.

github.com

https://github.com/muatik/flask-profiler

 

muatik/flask-profiler

a flask profiler which watches endpoint calls and tries to make some analysis. - muatik/flask-profiler

github.com

https://github.com/statsd/statsd

 

statsd/statsd

Daemon for easy but powerful stats aggregation. Contribute to statsd/statsd development by creating an account on GitHub.

github.com

https://graphite.readthedocs.io/en/latest/

 

Graphite Documentation — Graphite 1.1.5 documentation

© Copyright 2008-2012, Chris Davis; 2011-2017 The Graphite Project Revision c3b06cce.

graphite.readthedocs.io

https://docs.locust.io

 

Locust Documentation — Locust 0.9.0 documentation

© Copyright . Revision 4bde2ca9.

docs.locust.io

https://docs.seleniumhq.org/

 

Selenium - Web Browser Automation

What is Selenium? Selenium automates browsers. That's it! What you do with that power is entirely up to you. Primarily, it is for automating web applications for testing purposes, but is certainly not limited to just that. Boring web-based administration t

docs.seleniumhq.org

https://pytest.org/

불러오는 중입니다...

https://nose.readthedocs.io

 

Note to Users — nose 1.3.7 documentation

nose is nicer testing for python nose extends unittest to make testing easier. Note to Users Nose has been in maintenance mode for the past several years and will likely cease without a new person/team to take over maintainership. New projects should consi

nose.readthedocs.io

http://plugincompat.herokuapp.com/

 

pytest Plugin Compatibility

 

plugincompat.herokuapp.com

https://github.com/pytest-dev/pytest-cov

 

pytest-dev/pytest-cov

Coverage plugin for pytest. Contribute to pytest-dev/pytest-cov development by creating an account on GitHub.

github.com

https://github.com/tholo/pytest-flake8

 

tholo/pytest-flake8

pytest plugin to run flake8. Contribute to tholo/pytest-flake8 development by creating an account on GitHub.

github.com

https://tox.readthedocs.io

 

Welcome to the tox automation project — tox 3.13.3.dev5 documentation

1. environment creation: create a fresh environment, by default virtualenv is used. tox will automatically try to discover a valid Python interpreter version by using the environment name (e.g. py27 means Python 2.7 and the basepython configuration value)

tox.readthedocs.io

http://www.sphinx-doc.org/en/master/

 

Overview — Sphinx 3.0.0+/a498960de documentation

Welcome What users say: “Cheers for a great tool that actually makes programmers want to write documentation!“ Sphinx is a tool that makes it easy to create intelligent and beautiful documentation, written by Georg Brandl and licensed under the BSD license

www.sphinx-doc.org

https://recommonmark.readthedocs.io/en/stable/

 

recommonmark — Recommonmark 0.5.0 documentation

This allows you to write both .md and .rst files inside of the same project. Links For all links in commonmark that aren’t explicit URLs, they are treated as cross references with the :any: role. This allows referencing a lot of things including files, lab

recommonmark.readthedocs.io

http://pygments.org/

 

Welcome! — Pygments

Welcome! This is the home of Pygments. It is a generic syntax highlighter suitable for use in code hosting, forums, wikis or other applications that need to prettify source code. Highlights are: a wide range of over 300 languages and other text formats is

pygments.org

https://travis-ci.org/

 

Travis CI - Test and Deploy Your Code with Confidence

 

travis-ci.org

https://tox-travis.readthedocs.io/en/stable/

 

tox-travis: Integrate tox and Travis — Tox-Travis 0.12 documentation

© Copyright 2017, Ryan Hiebert Revision de62ecd5.

tox-travis.readthedocs.io

https://docs.readthedocs.io/en/stable/

 

Read the Docs: Documentation Simplified — Read the Docs 3.6.1 documentation

© Copyright 2010-2019, Read the Docs, Inc & contributors Revision 7be01d84.

docs.readthedocs.io

https://coveralls.io/

 

Coveralls.io - Test Coverage History and Statistics

The leading provider of test coverage analytics. Ensure that all your new code is fully covered, and see coverage trends emerge. Works with most CI services. Always free for open source.

coveralls.io

 

'Microservices' 카테고리의 다른 글

Microservice  (0) 2019.07.22
최근에 올라온 글
글 보관함