Genius DM

Swagger CodeGen 을 이용한 JMeter Project 만들기 본문

Dev Tool

Swagger CodeGen 을 이용한 JMeter Project 만들기

Damon Jung 2018. 5. 8. 09:43

Swagger CodeGen 을 이용하여 JMeter 테스트 플랜 추출하기.


잘 알려졌다시피, JMeter 는 테스트 플랜을 작성하여 대량 HTTP Request 를 발생시켜 스트레스 테스트는 물론 유닛테스트까지 진행할 수 있는 매우 유용한 툴이다. RESTful API 프로젝트를 경험했다면, 한 번 이상은 써보는 툴이 아닌가 생각한다. 


하지만 JMeter Thread Group 을 생성하고, Loop Count, Number Of Threads, HTTP Url, Port, API path, Parameters, Request Body 만들기 등, 테스트 준비를 위해 API 스펙을 일일히 체크하며 만드는 것은 상당한 단순 반복 작업을 요구한다. 현재 내가 개발 중인 API 는 300 여개에 달하는데, 1:1 로 테스트 플랜 작성하면... 어마어마한 시간이 걸릴 것이다. 


그래서 자동으로 변환해주는 툴이 필요했는데, 마침 Swagger-Ui 도 사용하고 있어서, Swagger 에 Extension 같은 것이 없나 하고 찾아보다가 Swagger CodeGen ( https://swagger.io/swagger-codegen/ ) 을 발견하게 되었다. JSON 이나 YAML 으로 Formatting 된 API Description 을 지정한 언어 및 클라이언트 형태로 자동 변환해주는 툴이다.


실제로 Demo 로, https://editor.swagger.io//?_ga=2.265510287.1018892707.1525671527-715046869.1523851982#/ 에서 Swagger Editor 를 이용해서 JSON 을 작성한 후 Generate Server / Generate Client 를 통해 다양한 플렛폼 코드로 변환시킬 수 있다. 이 포스트에서는 외부망에 접근 불가능한 로컬 환경에서 사용할 수 있도록, CodeGen 직접 설치 및 사용 방법을 다뤄보도록 하겠다.



STEP 1. Java 설치

http://www.oracle.com/technetwork/java/javase/downloads/index.html 에서 JDK 를 다운로드 받아 설치한다.


STEP 2. 환경변수 설정

JDK 설치 폴더 ( 보통 x64 Machine 에서 C:\Program Files\Java\jdk{your-download-version} ) Path 를 복사한 후,

1. sysdm.cpl 실행
2. 시스템 속성의 고급 탭 클릭
3. 우측 하단 환경 변수 버튼 클릭
4. 시스템 변수 항목에 JAVA_HOME 을 추가하고, 설치 Path 를 입력한다.
5. 시스템 변수에 이미 만들어져 있는 Path 항목을 편집하여, %JAVA_HOME%\bin; 을 추가해준다.


STEP 3. CodeGen 다운로드

https://github.com/swagger-api/swagger-codegen Git Hub 에서 DownloadZip 하거나, Git 클라이언트를 이용해 Repository 에서 Pull 한다.


STEP 4. CodeGen Build

1. 명령 프롬프트 실행.
2. Git 압축 푼 폴더 Path 로 이동 cd {your-swagger-codegen-path}
3. ./mvnw clean package 실행

Maven Build 에 약 20분이 소요되었으니, 끈기를 가지고 기다린다. 최초에 명령어 입력 후 아무 반응이 없으면, Enter 키 한번 눌러주면 Maven Dependency Downloading 메시지를 끊임없이 볼 수 있을 것이다. 정말 오래 기다려야 한다, 기다려라.


STEP 5. Generate Codes

1. JSON 이나 YAML 로 작성한 Swagger Format 의 API 명세서를 준비한다. ( Sample 링크에서 좌측에 보이는 JSON 을 참고하자 )
2. 해당 JSON 을 적당한 Path 에 옮겨둔다.
3. 아래 명령어 실행.

java -jar modules\swagger-codegen-cli\target\swagger-codegen-cli.jar generate -i C:\Users\YourName\YourDownloadedJSON.json -l jmeter -o C:\MyTestPlans\JMeter


이후 C:\MyTestPlans\JMeter 폴더에 가보면, API 명세서에 적은 모든 API 에 별로 Thread Group 을 생성한 jmx JMeter 테스트 플랜 파일을 볼 수 있다. 특이하게도 csv 도 같이 추출되는데, 해당 테스트 플렌에 포함된 API 에서 선언해야 할 Query 타입 Parameter 들이 모두 포함되어 있다. 기본 값은 보통 0 이다. 이게 사용하기 싫으면,  Thread Group 내부에 API 더블 클릭 후, csv 옵션 내역을 삭제해버리면 된다.


JMeter 뿐만 아니라...

CodeGen 을 이용해서 C#, PHP, Java 등의 언어로 API 를 호출할 수 있는 HTTP Request Client 코드를 자동으로 생성할 수 있다. 방법은? -l 옵션만 변경해주면 된다.

java -jar modules\swagger-codegen-cli\target\swagger-codegen-cli.jar generate -i C:\Users\YourName\YourDownloadedJSON.json -l php -o C:\MyTestClient\PHP


java -jar modules\swagger-codegen-cli\target\swagger-codegen-cli.jar generate -i C:\Users\YourName\YourDownloadedJSON.json -l sharp -o C:\MyTestClient\CSharp


java -jar modules\swagger-codegen-cli\target\swagger-codegen-cli.jar generate -i C:\Users\YourName\YourDownloadedJSON.json -l java -o C:\MyTestClient\Java


Parameter Type 자동 생성, Parameter 가 모델 ( Class ) 인 경우 클래스 자동 생성, HTTP Request 코드 자동 생성, 프로젝트 자동 생성, 필요한 패키지 자동 생성 등... API 를 호출하기 위해 필요한 모든 것을 알아서 만들어 준다. 


정말 편리하다.












Extract JMeter test plans with Swagger CodeGen


JMeter is a great tool. It generates HTTP request for you once properly set up with a test plan and you can assert the response by adding an assertion step in your plan. You can easily perform stress test with this tool. If you've ever worked on a RESTful API project, you may have already heard of it or used it.


But making a test plan is not an easy task. You have to fill in those forms like HTTP URL, port, protocol, parameters, loop count, and number of threads, and add summary report and etc. I'm working on a project that has more than 130 APIs. Making all of them one by one will take like forever.


So I came up with a tool that does the heavy lifting for me. I'm already using Swagger UI on the project, so I started out with searching an extension in the swagger and fortunately, it has Swagger CodeGen. It just automatically converts OPEN API formatted JSON or YAML API description into miscellaneous clients and platforms.


You can actually see the live demo in here https://editor.swagger.io//?_ga=2.265510287.1018892707.1525671527-715046869.1523851982#/ . Just type in a proper JSON and select the one you want to get among the list of " Generate Client " or " Generate Server ". 


I'm going to deal with the private network circumstance where you can have no access to the external Internet. Here goes the installation of CodeGen in your local environment.



STEP 1. Install Java



STEP 2. Set up an environment variable

Copy the path for your JDK installation folder ( typically, it's located in C:\Program Files\Java\jdk{your-download-version} )

1. Execute sysdm.cpl on the command prompt
2. Click the advanced tab in the system property popup.
3. Click the environment variables on the bottom right.
4. Add JAVA_HOME in the system variable section, and paste the JDK installation path.
5. Edit Path item that already exists in the same section, and add  %JAVA_HOME%\bin; there.


STEP 3. Download Swagger CodeGen

Click the Download Zip button directly or use Git client to pull the resources from https://github.com/swagger-api/swagger-codegen 


STEP 4. Build CodeGen

1. Execute command prompt.
2. Go to the unzip folder of the codegen sources. type cd {your-swagger-codegen-path} in the prompt window.
3. Execute ./mvnw clean package

It took 20 minutes to complete the build job in my case. You have to be patient. If you see nothing happen in the prompt window, just type Enter then you will see the endless Maven Dependency Download messages rolling down on the console. It takes a long time, you just have to wait !!


STEP 5. Generate Codes

1. Prepare a OPEN API formatted JSON or YAML. ( Take this one as an example, the one that you can see on the left in this link Sample )
2. Put your JSON in somewhere.
3. Run the command below.

java -jar modules\swagger-codegen-cli\target\swagger-codegen-cli.jar generate -i C:\Users\YourName\YourDownloadedJSON.json -l jmeter -o C:\MyTestPlans\JMeter

After running this command, you're going to see that there're a bunch of jmx files and CSV pairs, each of them just matches the APIs that you've specified on your API description ( JSON / YAML ). Those CSVs are the list of parameters  that the API requires to pass in. Usually, the default value is 0. So, you have to put a proper test value in the file. If you want to use User Defined Variables in JMeter, you have to go to the Thread Group and see the nested menu in the API, and delete the CSV option there. Unless your User Defined Variables will be overridden by the CSV values.


You can extract not only JMeter...

but also you can generate C#, PHP, or JAVA HTTP Request clients by just switching the -l value like below.

java -jar modules\swagger-codegen-cli\target\swagger-codegen-cli.jar generate -i C:\Users\YourName\YourDownloadedJSON.json -l php -o C:\MyTestClient\PHP


java -jar modules\swagger-codegen-cli\target\swagger-codegen-cli.jar generate -i C:\Users\YourName\YourDownloadedJSON.json -l sharp -o C:\MyTestClient\CSharp


java -jar modules\swagger-codegen-cli\target\swagger-codegen-cli.jar generate -i C:\Users\YourName\YourDownloadedJSON.json -l java -o C:\MyTestClient\Java


CodeGen just automatically generates parameter type, parameter model ( class ), HTTP Request codes, project structures, necessary packages or third party resources, and all of the prerequisites to call the APIs in a specific platform or language.


Truly saved ton of times with this tool !




'Dev Tool' 카테고리의 다른 글

Quick Diagram Tool for C#  (2) 2018.07.28
Comments