티스토리 뷰

Programing/Python

Python + Jenkins 연동

Tomining 2016. 8. 26. 21:42
Python 프로젝트를 Jenkins 에 연동하는 방법에 대해서 정리해 보았습니다.
Jenkins 설치는 어렵지 않으며, 구글링을 통해서 쉽게 설치할 수 있으니, 여기서는 생략하도록 하겠습니다.

환경은 CentOS 에서 진행했습니다.

준비작업

Python 프로젝트를 Jenkins 연동을 하려면 몇가지 사전 설치 작업이 필요합니다.
일단 Python 이 설치가 되어 있어야 합니다.(이건 당연한 이야기), 그리고 virtualenv 또한 설치되어 있어야 합니다.

# 1. Python download
$ wget https://www.python.org/ftp/python/3.5.2/Python-3.5.2.tgz
tar xvf Python-3.5.2.tgz
cd Python-3.5.2

# 2. Compile
$ ./configure CFLAGS=-fPIC --enable-shared --prefix={파이썬 설치 경로}
make install

# 3. PATH
vi~/.bashrc
.bashrc-------------------------------
export PYTHON_HOME=${APP_HOME}/apps/python
export PATH=${PYTHON_HOME}/bin/:$PATH
--------------------------------------
source~/.bashrc

# 4. ldconfig - root permission required
$vi /etc/ld.so.conf.d/python.conf
python.conf---------------------------
{파이썬 설치 경로}/lib
--------------------------------------
$/sbin/ldconfig -v

# 5. Check
$ {파이썬 설치 경로}/bin/python3 -V
# 1. pip update
$ pip3 install --upgrade pip

# 2. virtualenv install
$ pip3 install virtualenv

# 3. check
$ virtualenv

python 3.X 를 설치하는 경우 pip 등 몇가지 python tool 이 포함되지만 설치시에 open-ssl 이 설치되어 있지 않는 경우 pip 등 몇가지가 설치되지 않을 수 있습니다.
설치(make install) 시에 로그로 확인할 수 있습니다. 만약 pip 가 파이선 설치경로/bin 디렉토리에 보이지 않는다면 open-ssl 설치 후 재설치 하시면 됩니다.
(수동으로 pip 설치하셔도 무방합니다.)

Jenkins Plugin 도 설치가 필요합니다.(아래 목록참고)
  • git
  • Cobertura
  • HTML Publisher
  • Violation - pep8 이난 pyflakes 등 reporting 설정을 도와주는 플러그인

  • Shiningpanda - Jenkins 에서 virtualenv 를 사용할 수 있도록 해 주는 플러그인


이 외에도 몇가지 Python 패키지도 필요합니다.
  • xmlrunner
  • pylint
  • pep8
  • pyflakes
  • coverage

모두 pip install command 를 통해서 쉽게 설치할 수 있습니다.
또는 requirements.txt 파일(아래참고)을 생성 후 아래와 같이 작성한 뒤 pip install -r requirements.txt 를 하면 쉽게 여러 패키지들을 설치할 수 있습니다.

xmlrunner==1.7.7
pylint==1.6.4
pep8==1.7.0
pyflakes==1.2.3
coverage==4.2


프로젝트 설정 및  Jenkins 설정


1. TestCase 수행 결과

Python 프로젝트에서 TestCase 를 모두 수행할 수 있도록 test.py 를 하나 생성해 둡니다.

import unittest
import xmlrunner


def runner(output='test_result'):
    return xmlrunner.XMLTestRunner(
        output=output
    )


def find_tests():
    return unittest.TestLoader().discover(’test_project.tests')


if __name__ == '__main__':
    runner().run(find_tests())

여기에서는 testcase 를 {프로젝트ROOT}/test_project/tests 하위에 생성했다고 가정하고 있습니다.
아래처럼 command 를 수행하면 test_result 디렉토리 하위에 Test결과들이 xml 로 남겨집니다.
pip install -r requirements.txt

python -m test.py

이를 Jenkins 빌드 환경설정에서 “빌드 후 조치” > “Publish JUnit test result report” 설정을 하면 됩니다.


빌드를 수행해 보면 빌드 결과에 “Test Result” 메뉴가 노출되며, 클릭해서 보시면 아래처럼 결과를 확인 할 수 있습니다.



2. Violation

Violation Plugin 을 이용하여 pep8 이나 pyflakes 를 적용할 수 있습니다.
pylint, pep8, pyflakes 를 사전에 설치하거나 requirements.txt 를 이용하여 설치 후 사용할 수 있습니다.

Jenkins 설정에서 Build > Virtualenv Builder 항목에 아래와 같이 command 를 등록합니다.

pip install -r requirements.txt

rm -f pep8.log pyflakes.log

python -m test.py

pep8 --config=pep8.cfg uit > pep8.log || true
pyflakes test_project > pyflakes.log || true
[pep8]
max-line-length = 120

특정 pep8 의 rule 을 무시하고 싶다면 ignore = {rule1 번호},{rule2 번호},… 순으로 작성하면 됩니다.
pep8 에 대한 자세한 설정은 https://pep8.readthedocs.io/en/1.7.0/intro.html#configuration 에서 확인 할 수 있습니다.

그리고 아래와 같이 설정할 수 있습니다.


설정 후 빌드를 하면 아래처럼 결과를 확인 할 수 있습니다.



3. Coverage

Jenkins 설정에서 Build > Virtualenv Builder 항목에 아래와 같이 command 를 등록합니다.

pip install -r requirements.txt

rm -f pep8.log pyflakes.log

python -m coverage run --rcfile=coverage.cfg test.py

python -m coverage xml -o coverage.xml
python -m coverage html -d coverage

pep8 --config=pep8.cfg uit > pep8.log || true
pyflakes test_project > pyflakes.log || true
[report]
omit =
    test_project/tests/*

coverage.cfg 파일에 report > omit 설정을 추가 한 것은 test case 코드가 coverage 로 분석되는 것을 막기 위함입니다.
coverage 에 대한 자세한 설정은 https://coverage.readthedocs.io/en/coverage-4.2/config.html# 에서 확인 할 수 있습니다.


위처럼 설정 후 빌드를 수행하면 아래처럼 Coverage 정보를 확인 할 수 있습니다.



4. LOC

python project 에서 LOC를 확인하기 위해서는 보통 cloc 를 사용합니다.
cloc란 Python코드 뿐만아니라 다양한 언어를 지원하며 빈줄/주석/코드 등의 라인 수를 계산해 줍니다.

cloc 를 사용해야 하는 이유를 공식페이지에서는 아래와 같이 소개하고 있습니다.

cloc has many features that make it easy to use, thorough, extensible, and portable:

  1. Exists as a single, self-contained file that requires minimal installation effort---just download the file and run it.
  2. Can read language comment definitions from a file and thus potentially work with computer languages that do not yet exist.
  3. Allows results from multiple runs to be summed together by language and by project.
  4. Can produce results in a variety of formats: plain text, SQL, XML, YAML, comma separated values.
  5. Can count code within compressed archives (tar balls, Zip files, Java .ear files).
  6. Has numerous troubleshooting options.
  7. Handles file and directory names with spaces and other unusual characters.
  8. Has no dependencies outside the standard Perl distribution.
  9. Runs on Linux, FreeBSD, NetBSD, OpenBSD, Mac OS X, AIX, HP-UX, Solaris, IRIX, and z/OS systems that have Perl 5.6 or higher. The source version runs on Windows with either ActiveState Perl, Strawberry Perl, Cygwin, or MobaXTerm+Perl plugin. Alternatively on Windows one can run the Windows binary which has no dependencies.

한줄로 요약해 보면 "사용이 쉽고, 다양한 언어를 지원하고 output 또한 다양한 포멧으로 지원하는 등 많은 기능을 제공하고 있다”라고 할 수 있습니다.

설치는 간단합니다.
https://sourceforge.net/projects/cloc/files/cloc/v1.64/ 에서 플랫폼에 맞는 파일을 받아서 압축을 풀거나 실행파일을 실행하면 됩니다.
CentOS 환경에서는 압축해제 후 PATH를 설정해 주면 됩니다.

Jenkins 설정에서 Build > Virtualenv Builder 항목에 아래와 같이 command 를 등록합니다.

pip install -r requirements.txt

rm -f pep8.log pyflakes.log

cloc —by-file —xml —out=cloc.xml
python -m coverage run --rcfile=coverage.cfg test.py

python -m coverage xml -o coverage.xml
python -m coverage html -d coverage

pep8 --config=pep8.cfg uit > pep8.log || true
pyflakes test_project > pyflakes.log || true


결과는 아래와 같이 언어별로 구분하여 확인 할 수 있습니다.


언어별 트렌드 정보도 차트로 확인할 수 있습니다.



여기까지 잘 진행했다면 기본적인 기능은 연동했다고 할 수 있습니다.
  • TestCase 수행 결과
  • pep8(코드 스타일), pyflakes(코드 정적분석)
  • coverage(테스트 커버리지)
  • loc(코드 라인수)



참고


'Programing > Python' 카테고리의 다른 글

sqlparse 사용기  (0) 2016.08.18
PyJNIus 사용기  (0) 2016.07.28
PEP8 이란?  (0) 2016.07.27
APScheduler 사용기  (0) 2016.07.26
JPype 사용기  (0) 2016.07.19
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
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 27
28 29 30
글 보관함