IntelliJ IDEA에서 EvoSuite 실행(JUnit Test Generator)

Developer Tools|2017. 6. 28. 20:10

JUnit 테스트를 자동 생성해야 할 일이 생겼다. 이런건 뭔가 큰 잘못을 저지르는 기분이긴 하지만 어쩔 수 없는 상황이다.
구글링 하니 JUnit-Tools와 EvoSuite가 상단에 나왔다. JUnit-Tools는 훑어 봐도 명확히 어떤걸 어떻게 만들어 준다는 건지 감이 안와서 일단 EvoSuite를 선택했다.

http://www.evosuite.org/evosuite/

나는 IDEA를 사용하니 IDEA 플러그인(http://www.evosuite.org/documentation/intellij-idea-plugin/)을 Settings > Plugins에서 "EvoSuite Plugin"으로 검색해서 설치하고 재시작한다.

패키지 하나를 우클릭하고 Run EvoSuite를 선택하니 Maven과 Java 설치 경로를 지정하는 창이 나온다. OK 버튼을 눌러서 실행하면 된다(만약 OK 버튼이 안보이면 창 크기를 조정한다).

Going to execute command:
D:\dev\tool\apache-maven-3.3.9\bin\mvn.cmd  compile  evosuite:generate  -Dcores=1  -DmemoryInMB=2000  -DtimeInMinutesPerClass=3  -DspawnManagerPort=5617  -Dcuts=com.acme.spring.security.CustomAuthenticationFailureHandler,com.acme.spring.security.AuthJdbcDaoImpl,com.acme.spring.security.AuthManager,com.acme.spring.security.AuthUser  evosuite:export  -DtargetFolder=src/evo
in folder: G:\repos\my-project
Going to execute command:
D:\dev\tool\apache-maven-3.3.9\bin\mvn.cmd  compile  evosuite:generate  -Dcores=1  -DmemoryInMB=2000  -DtimeInMinutesPerClass=3  -DspawnManagerPort=5617  -Dcuts=com.acme.spring.security.CustomAuthenticationFailureHandler,com.acme.spring.security.AuthJdbcDaoImpl,com.acme.spring.security.AuthManager,com.acme.spring.security.AuthUser  evosuite:export  -DtargetFolder=src/evo
in folder: G:\repos\my-project
[INFO] Scanning for projects...
[WARNING]
[WARNING] Some problems were encountered while building the effective model for console:console:war:0.0.1-SNAPSHOT
[WARNING] 'build.plugins.plugin.version' for org.apache.maven.plugins:maven-compiler-plugin is missing. @ line 488, column 21
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
Downloading: http://192.168.0.123:8081/artifactory/plugins-release/org/codehaus/mojo/maven-metadata.xml
Downloading: http://192.168.0.123:8081/artifactory/plugins-snapshot/org/codehaus/mojo/maven-metadata.xml
Downloading: http://192.168.0.123:8081/artifactory/plugins-snapshot/org/apache/maven/plugins/maven-metadata.xml
Downloading: http://192.168.0.123:8081/artifactory/plugins-release/org/apache/maven/plugins/maven-metadata.xml
Downloaded: http://192.168.0.123:8081/artifactory/plugins-snapshot/org/apache/maven/plugins/maven-metadata.xml (18 KB at 20.4 KB/sec)
Downloaded: http://192.168.0.123:8081/artifactory/plugins-snapshot/org/codehaus/mojo/maven-metadata.xml (27 KB at 29.4 KB/sec)
Downloaded: http://192.168.0.123:8081/artifactory/plugins-release/org/apache/maven/plugins/maven-metadata.xml (18 KB at 15.2 KB/sec)
Downloaded: http://192.168.0.123:8081/artifactory/plugins-release/org/codehaus/mojo/maven-metadata.xml (27 KB at 22.4 KB/sec)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.317 s
[INFO] Finished at: 2016-05-25T16:47:01+09:00
[INFO] Final Memory: 10M/123M
[INFO] ------------------------------------------------------------------------
[ERROR] No plugin found for prefix 'evosuite' in the current project and in the plugin groups [org.apache.maven.plugins, org.codehaus.mojo] available from the repositories [local (C:\Users\daniel\.m2\repository), central (http://192.168.0.123:8081/artifactory/plugins-release), snapshots (http://192.168.0.123:8081/artifactory/plugins-snapshot)] -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/NoPluginFoundForPrefixException

실행 결과 콘솔에 빌드 실패가 뜬다. IDEA 플러그인은 Maven에 의존하기 때문에, 결국 아래 페이지에 있는 모든 내용을 pom.xml에 적용한 후에야 오류 없이 테스트 코드 생성을 시작한다.

http://www.evosuite.org/documentation/maven-plugin/

기존 pom.xml과 diff 해보니 아래와 같은 코드를 추가했다.

    <properties>
        <evosuiteVersion>1.0.3</evosuiteVersion>
    </properties>

    <dependencies>
        <!-- Testing -->
        <dependency>
            <groupId>org.evosuite</groupId>
            <artifactId>evosuite-standalone-runtime</artifactId>
            <version>${evosuiteVersion}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.evosuite.plugins</groupId>
                <artifactId>evosuite-maven-plugin</artifactId>
                <version>${evosuiteVersion}</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>prepare</goal>
                        </goals>
                        <phase>process-test-classes</phase>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.17</version>
                <configuration>
                    <properties>
                        <property>
                            <name>listener</name>
                            <value>org.evosuite.runtime.InitializingListener</value>
                        </property>
                    </properties>
                </configuration>
            </plugin>
        </plugins>
    </build>

// ... 중략

    <repositories>
        <repository>
            <id>EvoSuite</id>
            <name>EvoSuite Repository</name>
            <url>http://www.evosuite.org/m2</url>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>EvoSuite</id>
            <name>EvoSuite Repository</name>
            <url>http://www.evosuite.org/m2</url>
        </pluginRepository>
    </pluginRepositories>

Core 2개에 Core 당 2,000MB의 메모리를 부여하고, 클래스당 3분의 시간을 할당하도록 조건을 설정했다. 퇴근 전에 총 713개의 클래스에 대해서 테스트 케이스를 생성하도록 실행했는데 다음날 아침에 오니 생성이 끝나 있었다(로그에는 6시간 48분이 걸렸다고 찍혀있다).

전체 컴파일을 하니 없는 객체에 대해서 assertSame을 수행하는 오류와 테스트 코드에서 인수에 null을 넘기기 때문에 발생하는 메소드 ambiguous 문제가 여러 개 발생한다. 오류는 그냥 에러가 발생하는 코드를 삭제해서 해결했다.

전체 테스트를 Coverage 측정과 함께 실행하니 총 6150개의 테스트 중 23개가 실패한다. 실패한 테스트를 삭제하고 다시 실행하니 테스트 커버리지(라인)는 39.5%가 나온다.

단위 테스트가 전혀 작성되지 않은 소스 코드를 받아서 무조건 커버리지가 나오게 테스트를 만들어야 하는 상황이라서 EvoSuite를 사용했지만 기분은 별로다. 그냥 시간과 전기 낭비인 것 같아서 ...


EOF

댓글()

IntelliJ IDEA에서 GitLab 저장소 접근 오류가 발생하는 경우의 조치 방법(Could not read from remote repository)

Developer Tools|2017. 6. 27. 19:03

오늘(2016-06-03) GitLab 저장소에 pull을 실행했더니 오류가 발생한다.

10:24:31.442: [my-repo] git -c core.quotepath=false pull --progress --no-stat -v --progress origin develop
java.io.IOException: Illegal char in base64 code.
    at com.trilead.ssh2.crypto.Base64.decode(Base64.java:107)
    at com.trilead.ssh2.KnownHosts.initialize(KnownHosts.java:412)
    at com.trilead.ssh2.KnownHosts.initialize(KnownHosts.java:440)
    at com.trilead.ssh2.KnownHosts.addHostkeys(KnownHosts.java:137)
    at org.jetbrains.git4idea.ssh.SSHMain.configureKnownHosts(SSHMain.java:462)
    at org.jetbrains.git4idea.ssh.SSHMain.start(SSHMain.java:155)
    at org.jetbrains.git4idea.ssh.SSHMain.main(SSHMain.java:137)
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.

Git Bash에서 fetch 명령을 실행하니 아래와 같이 ECDSA key를 ~/known_hosts에 추가 할거냐고 묻는다.

$ git -c core.quotepath=false fetch origin --progress --prune
The authenticity of host 'gitlab.com (104.210.2.228)' can't be established.
ECDSA key fingerprint is SHA256:HbW3g8zUjNSksFbqTiUWPWg2Bq1x8xdGUrliXFzSnUw.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'gitlab.com,104.210.2.228' (ECDSA) to the list of known hosts.
From gitlab.com:my-account/my-repo

추가하면 Git Bash에서는 문제가 해결되지만 IDEA에서는 여전히 오류가 발생한다.

~/known_hosts 파일을 열어서 예전 gitlab.com 정보(gitlab.com,62.204.93.103 ...)를 삭제하면 문제가 해결된다.


EOF

댓글()

Eclipse 설치 후 처음 할 일

Developer Tools|2017. 6. 20. 19:09

아래는 모두 eclipse.ini 파일의 수정 작업

VM 경로 추가

-vm
/dev/sdk/jdk1.6.0_26/bin/javaw.exe

UTF-8로 인코딩 변경

-Dfile.encoding=UTF-8


EOF

댓글()

Vagrant - 기본+

DevOps|2017. 6. 8. 19:12

Vagrant - 기본의 내용을 보충한다.

포트 포워딩(PORT FORWARDING)

호스트 머신의 포트를 통해서 게스트 머신의 특정 포트에 접속, 네트워크 트래픽을 게스트 머신으로 보내는 방법.

게스트 머신의 아파치에 접근하기 위해서는 아래와 같이 Vagrantfile을 편집한다. guest 속성의 80이 가상머신의 포트, host속성의 4567이 호스트의 포트다.
즉 아래와 같이 설정하면 호스트에서 http://localhost:4567로 접속하면 가상머신의 80 포트에 접속해서 아파치 화면을 볼 수 있다.

Vagrant.configure("2") do |config|
  config.vm.box = "hashicorp/precise64"
  config.vm.network :forwarded_port, guest: 80, host: 4567
end

포트를 변경한 후에는 vagrant reload 명령으로 가상머신을 재시작 한다.

가상머신의 포트 포워딩 설정이 기억나지 않을 때는 VirtualBox를 실행하고 해당 가상머신의 설정 → 네트워크 → 어댑터 1 → 포트 포워딩을 클릭하여 확인할 수 있다.

MEMORY, CPU 크기 설정

가상머신의 memory나 cpu의 크기를 변경하려면 아래와 같이 설정을 조정할 수 있다. 아래는 메모리를 2GB로, CPU를 2개로 조정한 예이다.

config.vm.provider :virtualbox do |vb|
    vb.memory = 2048
    vb.cpus = 2
end

스냅샷(SNAPSHOT) 생성/복구

가상머신의 스냅샷을 생성하려면 스냅샷 이름과 함께 vagrant snapshot save 명령을 사용한다. 아래의 예는 first_snapshot이라는 이름으로 스냅샷을 생성하고 있다.

vagrant snapshot save first_snapshot

가상머신의 상태를 복구하려면 restore 명령을 사용한다. 아래는 first_snapshot이라는 이름의 스냅샷을 이용해 가상머신의 상태를 되돌리고 있다.

vagrant snapshot restore first_snapshot

생성한 스냅샷을 이용해서 상태를 복구하려면 스냅샷의 이름을 알고 있어야 한다. 스냅샷 목록을 통해 지금까지 생성된 스냅샷의 이름을 확인할 수 있다.

$ vagrant snapshot list
first_snapshot

BOOT TIMEOUT 옵션

가상머신의 부트 시간이 너무 오래 걸려서 실패하는 경우, boot_timeout 옵션을 조정해서 시간을 늘릴 수 있다.

config.vm.boot_timeout = 600

초 단위로 지정하며 기본 값은 300이다(5분).


EOF

댓글()

Vagrant - 기본

DevOps|2017. 6. 2. 19:10

윈도(Windows)를 주로 사용하지만 리눅스 환경이 필요한 경우가 많아서 Vagrant를 그간 꾸준히 사용해 왔다. 정리를 위해 Vagrant에 대한 개요와 기본 사용법을 정리해 본다.

설치

우선 Vagrant와 VirtualBox의 설치가 필요하다. 아래 주소에서 내려받아서 설치한다.

Vagrantfile 생성

vagrant init 명령을 실행하면 현재 폴더에 Vagrantfile을 생성한다. 아래와 같이 Box의 이름을 추가하면 해당 박스를 사용하는 Vagrantfile을 생성한다.

vagrant init bento/centos-7.3

이렇게 생성한 Vagrantfile에는 다량의 주석이 포함되어 있어서 이 주석만 잘 읽어봐도 기본적인 설정 방법을 아는데 무리가 없다.

Box 검색

원하는 리눅스 배포본과 버전의 Box를 아래 주소에서 검색할 수 있다.

각 리눅스 배포본 제공자의 오피셜 박스를 사용하는게 안전하다. 다만 CentOS의 경우는 Bento 프로젝트에서 제공하는 박스도 많이 사용하는 것 같다.

Vagrant machine 생성

vagrant up

위 명령을 Vagrantfile이 있는 폴더에서 실행하면 가상 머신이 생성된다.

$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'bento/centos-7.3'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'bento/centos-7.3' is up to date...
==> default: Setting the name of the VM: Documents_default_1496384515554_86818
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
    default: Warning: Remote connection disconnect. Retrying...
    default:
    default: Vagrant insecure key detected. Vagrant will automatically replace
    default: this with a newly generated keypair for better security.
    default:
    default: Inserting generated public key within guest...
    default: Removing insecure key from the guest if it's present...
    default: Key inserted! Disconnecting and reconnecting using new SSH key...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
==> default: Mounting shared folders...
    default: /vagrant => C:/Users/daniel/vagrant-test

Vagrant machine에 SSH로 접속

vagrant ssh

위 명령을 Vagrantfile이 있는 폴더에서 실행하면 vagrant 사용자로 가상 머신에 SSH로 접속이 된다.
PuTTY 등의 SSH 클라이언트로 접속하려면 127.0.0.1:2222에 vagrant로 접속하면 된다. 암호 또한 vagrant다. 2222 포트로 접속하는 이유는 기본으로 가상 머신의 22 포트와 호스트 머신의 2222 포트가 port forwarding 방식으로 연결되어 있기 때문이다. 이미 다른 가상 머신이 2222 포트를 사용 중이면 다른 포트가 자동으로 할당되며, 이는 실행 로그를 통해 알아내면 된다.

Vagrant machine을 다루는 기본 명령

삭제(terminate)

vagrant destroy

정지(shutdown, poweroff)

vagrant halt

가상 머신을 끈다.

재시작(reboot, halt and up)

vagrant reload

가상 머신을 재시작한다. 정지 후 시작하는 것과 동일하다.

일시 중지(suspending)

vagrant suspend

현재의 동작 상태를 저장한 상태로 정지한다. 다시 시작하면 부팅 과정 없이 저장한 지점에서 바로 시작한다.

다시 시작(resume)

vagrant resume

일시 중지 상태의 가상 머신을 이전 지점에서 다시 시작한다.

상태 확인(status)

vagrant status

가상 머신의 상태를 확인한다. 정지 상태면 poweroff로 표시되고 정상 동작 중이면 running으로 표시된다.


EOF

댓글()