Skip to content

Commit

Permalink
Step3 PR request (#5539)
Browse files Browse the repository at this point in the history
* [step3] ready

* [step3] 자동차 대수와 시도할 회수가 정확하게 입력된다 - 테스트 성공

* [step3] 변수명 수정

* [step3] String.format대신 printf 사용

* [step3] OOP설계(Car)

- Car는 전진한 거리 distance를 가진다.
- Car는 random값이 4 이상이면 거리증가

* [step3] OOP설계(Race): Race에는 n대의 차가 참여

* [step3] OOP설계(Race): 개선

- 초기화 streawm 이용
- 0 이하시 에러
- runRound 추가

* [step3] 객체를 이용한 프로그램 실행

* [step3] 리팩토링 - car 처음 distance 초기값 0->1

- 아예 차가 나타나지 않는 현상 방지

* [step3] CarMoveTest 추가

* [step3] CarMoveTest 개선

* [step3] RaceRoundTest: race가 1번이라도 열리면 100대중 1개는 전진 한다

* [step3] MainOutputTest (미완성)

* [step3] 테스트 성공

* [test] 테스트 성공

* [test] 필요 없는 부분 정리

* [step3] 사용하지 않는provideOutput 메서드 삭제 -

* [step3] resultView 생성

* [step3] 워닝 수정

* [step3] runraces로 운영 분리

* [step3] InputView 추가

* [step3] InputView 반영

* [step3] 라이브러리 버전업+롬복 추가

* [step3] 정리및 빈 LINE CHECK 추가

* [step3] action 정리
  • Loading branch information
rkaehdaos authored Apr 16, 2024
1 parent 1bf1b76 commit 9fd75c9
Show file tree
Hide file tree
Showing 10 changed files with 296 additions and 5 deletions.
68 changes: 68 additions & 0 deletions .github/workflows/push-test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
name: Gradle test On GitHub Action
on:
push:
branches-ignore: [ 'main','master','rkaehdaos' ]

jobs:
onPushTest:
if: github.event.pull_request.opened == false
runs-on: ubuntu-latest
steps:
- name: Checkout source code
uses: actions/checkout@master

- name: setup-java-21
uses: actions/setup-java@v4
with:
distribution: 'zulu' # See 'Supported distributions' for available options
java-version: '11'
cache: 'gradle'

- name: test
run: |
echo "Available processors: $(nproc)"
gradle test jacocoTestCoverageVerification --no-daemon --parallel
- name: Extract coverage info and update step summary
run: |
echo 'CSV 파일에서 커버리지 정보 추출';
awk -F',' 'NR > 1 {instructions_covered += $5; instructions_missed += $4; branches_covered += $7; branches_missed += $6} END {print instructions_covered, instructions_missed, branches_covered, branches_missed}' build/reports/jacoco/test/jacocoTestReport.csv > coverage.txt
read instructions_covered instructions_missed branches_covered branches_missed < coverage.txt
echo '커버리지 계산';
total_instructions=$((instructions_covered + instructions_missed))
total_branches=$((branches_covered + branches_missed))
instruction_coverage=$(echo "scale=2; $instructions_covered / $total_instructions * 100" | bc)
echo '분모가 0일 경우, 커버리지를 'N/A'로 설정';
if [ "$total_instructions" -eq 0 ]; then
instruction_coverage="N/A"
else
instruction_coverage=$(echo "scale=2; $instructions_covered / $total_instructions * 100" | bc)%
fi
if [ "$total_branches" -eq 0 ]; then
branch_coverage="N/A"
else
branch_coverage=$(echo "scale=2; $branches_covered / $total_branches * 100" | bc)%
fi
echo 'GITHUB_STEP_SUMMARY에 커버리지 정보 추가';
echo "JaCoCo 커버리지 요약" >> $GITHUB_STEP_SUMMARY
echo "Instruction Coverage: $instruction_coverage" >> $GITHUB_STEP_SUMMARY
echo "Branch Coverage: $branch_coverage" >> $GITHUB_STEP_SUMMARY
- name: Upload JaCoCo coverage report
uses: actions/upload-artifact@v4
if: failure()
with:
name: jacoco-report
path: build/reports/jacoco/test/html

- name: Notification
uses: 8398a7/action-slack@v3
if: always()
with:
status: ${{ job.status }}
author_name: GeunChang Ahn
job_name: onPushTest
fields: repo,message,commit,author,eventName,ref,workflow,job,took,
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
17 changes: 16 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,19 @@
* 모든 피드백을 완료하면 다음 단계를 도전하고 앞의 과정을 반복한다.

## 온라인 코드 리뷰 과정
* [텍스트와 이미지로 살펴보는 온라인 코드 리뷰 과정](https://github.com/next-step/nextstep-docs/tree/master/codereview)
* [텍스트와 이미지로 살펴보는 온라인 코드 리뷰 과정](https://github.com/next-step/nextstep-docs/tree/master/codereview)

UI 로직을 InputView, ResultView와 같은 클래스를 추가해 분리한다.


## 기능 목록 및 commit 로그 요구사항
- commit message 종류 구분
```text
feat (feature)
fix (bug fix)
docs (documentation)
style (formatting, missing semi colons, …)
refactor
test (when adding missing tests)
chore (maintain)
```
22 changes: 18 additions & 4 deletions build.gradle
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
plugins {
id 'java'
id 'jacoco'
}

version '1.0'
Expand All @@ -9,8 +10,13 @@ repositories {
}

dependencies {
testImplementation 'org.assertj:assertj-core:3.22.0'
testImplementation 'org.junit.jupiter:junit-jupiter:5.8.2'
compileOnly 'org.projectlombok:lombok:1.18.32'
annotationProcessor 'org.projectlombok:lombok:1.18.32'
testCompileOnly 'org.projectlombok:lombok:1.18.32'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.32'

testImplementation 'org.assertj:assertj-core:3.25.3'
testImplementation 'org.junit.jupiter:junit-jupiter:5.10.2'
}

java {
Expand All @@ -19,6 +25,14 @@ java {
}
}

test {
useJUnitPlatform()
tasks.named('test') {
useJUnitPlatform() // Junit5 사용: 테스트 종속성에 JUnit Jupiter API와 JUnit Jupiter Engine을 포함해야 함.
maxParallelForks = Runtime.runtime.availableProcessors()
finalizedBy jacocoTestCoverageVerification
}
jacocoTestReport {
reports { csv.setRequired(true) }
}
jacocoTestCoverageVerification {
dependsOn jacocoTestReport
}
1 change: 1 addition & 0 deletions gradle.properties
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
org.gradle.jvmargs=-Dfile.encoding=UTF-8
org.gradle.console.encoding=UTF-8
org.gradle.console=plain
11 changes: 11 additions & 0 deletions src/main/java/step3_CarRacing/Car.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package step3_CarRacing;

public class Car {
private int distance = 1;
public void move(int randomValue) {
if (randomValue >= 4) distance++;
}
public int getDistance() {
return distance;
}
}
31 changes: 31 additions & 0 deletions src/main/java/step3_CarRacing/CarRacingGame.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package step3_CarRacing;

import step3_CarRacing.view.InputView;
import step3_CarRacing.view.ResultView;

import java.util.Scanner;

public class CarRacingGame {
public static void main(String[] args) {
//init
Scanner scanner = new Scanner(System.in);
InputView inputView = new InputView(scanner);
ResultView resultView = new ResultView();

//input
int numberOfCars = inputView.getNumberOfCars();
Race race = new Race(numberOfCars);
int numberOfRounds = inputView.getNumberOfRounds();

//result
runRaces(numberOfRounds, race, resultView);
}

private static void runRaces(int numberOfRounds, Race race, ResultView resultView) {
resultView.printResultHeader();
for (int i = 0; i < numberOfRounds; i++) {
race.runRound();
resultView.displayRaceResult(race.getCars());
}
}
}
27 changes: 27 additions & 0 deletions src/main/java/step3_CarRacing/Race.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package step3_CarRacing;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.IntStream;

public class Race {
private final Random random;
private final List<Car> cars;

public Race(int numberOfCars) {
if (numberOfCars < 0) throw new IllegalArgumentException("0이상이어야 함");
random = new Random();

cars = new ArrayList<>();
IntStream.range(0, numberOfCars).forEach(car -> cars.add(new Car()));
}

public List<Car> getCars() {
return cars;
}

public void runRound() {
cars.forEach(car -> car.move(random.nextInt(10)));
}
}
21 changes: 21 additions & 0 deletions src/main/java/step3_CarRacing/view/InputView.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package step3_CarRacing.view;

import java.util.Scanner;

public class InputView {
private final Scanner scanner;

public InputView(Scanner scanner) {
this.scanner = scanner;
}

public int getNumberOfCars() {
System.out.println("자동차 대수는 몇 대 인가요?");
return scanner.nextInt();
}

public int getNumberOfRounds() {
System.out.println("시도할 회수는 몇 회 인가요?");
return scanner.nextInt();
}
}
16 changes: 16 additions & 0 deletions src/main/java/step3_CarRacing/view/ResultView.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package step3_CarRacing.view;

import step3_CarRacing.Car;

import java.util.List;

public class ResultView {
public void displayRaceResult(List<Car> cars) {
cars.forEach(car -> System.out.println("-".repeat(car.getDistance())));
System.out.println();
}

public void printResultHeader() {
System.out.print("실행 결과\n");
}
}
87 changes: 87 additions & 0 deletions src/test/java/step3_CarRacing/CarRacingGameTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
package step3_CarRacing;

import org.junit.jupiter.api.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintStream;

import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.*;


class CarRacingGameTest {
private final InputStream stdIn = System.in;
private final PrintStream stdOut = System.out;
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();

@BeforeEach
void setUpPrintStream() {
System.setOut(new PrintStream(outContent));
}

@AfterEach
void restoreSystemIn() {
System.setIn(stdIn);
System.setOut(stdOut);
}

@ParameterizedTest
@CsvSource({
"2,3,9",
"2,4,12",
"3,1,4",
"3,2,8",
"12,1234,16042",
"100,1,101",
"100,2,202",
"100,50,5050",
"100,73,7373",
"8562,1,8563",
})
@DisplayName("csvSource로 부터 받은 데이터와 예상메시지가 일치해야 한다.")
public void MainOutputTest(String expectedCars, String expectedTries, long expectedLines) {
// GIVEN
provideInput(expectedCars, expectedTries);

// WHEN
CarRacingGame.main(new String[]{});

// THEN
String outputStreamCaptorString = outContent.toString();
String raceResult = outputStreamCaptorString.split("\n실행 결과\n", 2)[1];

long linesCount = raceResult.lines().count();
assertThat(linesCount).isEqualTo(expectedLines);

long emptyLinesCount = raceResult.lines().filter(String::isEmpty).count();
assertThat(emptyLinesCount).isEqualTo(Long.parseLong(expectedTries));
}

private void provideInput(String... strings) {
String inputStr = String.join("\n", strings);
System.setIn(new ByteArrayInputStream(inputStr.getBytes(UTF_8)));
}

@Test
@DisplayName("value4가 4이상이면 움직이고 그러지 않으면 움직이지 않는다.")
void CarMoveTest() {
Car car = new Car();
car.move(4); // 무조건 움직임
assertThat(car.getDistance()).isEqualTo(2);
car.move(3); // 무조건 안움직임
assertThat(car.getDistance()).isEqualTo(2);
}

@RepeatedTest(10000)
@DisplayName("100개의 차가 참가한 race가 일단 열리면, 100대중 1개는 전진 한다")
public void RaceRoundTest() {
Race race = new Race(100);
race.runRound();
boolean anyCarMoved = race.getCars().stream().anyMatch(car -> car.getDistance() > 1);
assertThat(anyCarMoved).isTrue();
}
}

0 comments on commit 9fd75c9

Please sign in to comment.