Skip to content

Commit

Permalink
Merge pull request #339 from SWM-NM/dev
Browse files Browse the repository at this point in the history
TestDuringController 테스트 코드 일부 추가
  • Loading branch information
aj4941 authored Sep 22, 2023
2 parents a64dbf6 + a14a785 commit 1f512ed
Show file tree
Hide file tree
Showing 14 changed files with 226 additions and 19 deletions.
10 changes: 9 additions & 1 deletion Main.java
Original file line number Diff line number Diff line change
@@ -1 +1,9 @@

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int A = input.nextInt();
int B = input.nextInt();
System.out.println(A+B);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@ public void saveTempCode(@RequestBody TempCodeDto tempCodeDto) {
@Operation(summary = "저장된 코드를 확인합니다", description = "테스트 중일 때, 문제 번호를 바꿀 때 코드 정보를\n" +
"testId와 attemptProblemId를 이용하여 가져온다. \n")
public ResponseEntity<TempCode> getTempCode(@RequestParam String testId,
@RequestParam String problemNumber){
@RequestParam String problemNumber) {

String key =String.format("testId:%s:problemNumber:%s",testId, problemNumber);
String key = String.format("testId:%s:problemNumber:%s", testId, problemNumber);

return new ResponseEntity<>(tempCodeService.getTempCode(key), HttpStatus.OK);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public class RunCodeService {
public OutputDto runCode(TestInputData testInputData) throws Exception {

CloseableHttpClient httpClient = HttpClients.createDefault();
String url = "http://10.0.102.184:8080";
String url = "http://localhost:8001";

ObjectMapper objectMapper = new ObjectMapper();
String inputDataJson = objectMapper.writeValueAsString(testInputData);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public class SolvedCheckService {

private final ObjectMapper objectMapper;

@Transactional
public List<AttemptProblemDto> isSolvedCheck(TestCheckDto testCheckDto) {
Long testId = testCheckDto.getTestId();
String bojId = testCheckDto.getBojId();
Expand Down Expand Up @@ -65,6 +66,7 @@ public void checkAttemptedProblemResult(Tests test, String bojId) {
if (minutes <= test.getTestTime()) {
attemptProblem.setIsSolved(true);
attemptProblem.setExecutionTime(minutes);
attemptProblemRepository.save(attemptProblem);
}
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,11 @@ public class TempCodeService {

private final RedisTemplate<String, Object> redisTemplate;

private final AttemptProblemRepository attemptProblemRepository;

public void saveTempCode(TempCodeDto tempCodeDto) {
String key = generateKey(tempCodeDto);
Long remainingTTL = redisTemplate.getExpire(key);

if (!(remainingTTL == null || remainingTTL <= 0)) {
if (remainingTTL != null && remainingTTL > 0) {
TempCode tempCode = Optional.ofNullable((TempCode) redisTemplate.opsForValue().get(key))
.orElseThrow(() -> new MorandiException(TestErrorCode.KEY_NOT_FOUND));

Expand All @@ -43,8 +41,7 @@ public void saveTempCode(TempCodeDto tempCodeDto) {
// 테스트 남은 시간만큼 TTL을 설정한다
redisTemplate.expire(key, expireTime, TimeUnit.MINUTES);
}
else
{
else {
throw new MorandiException(TestErrorCode.TTL_EXPIRED);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
package swm_nm.morandi.domain.testInfo.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
Expand All @@ -9,7 +8,6 @@
import swm_nm.morandi.domain.testRecord.dto.TestRecordDto;
import swm_nm.morandi.domain.testInfo.dto.TestTypeDto;
import swm_nm.morandi.domain.testInfo.service.*;
import swm_nm.morandi.domain.testRecord.service.TestDetailsService;

import java.util.List;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,22 +24,23 @@ public class TempCodeInitializer {
private final AttemptProblemRepository attemptProblemRepository;

public String generateKey(Tests test, int problemNumber) {
return String.format("testId:%s:problemNumber:%s",test.getTestId(), problemNumber);
return String.format("testId:%s:problemNumber:%s", test.getTestId(), problemNumber);
}
public void initTempCodeCacheWhenTestStart(Tests test){
public void initTempCodeCacheWhenTestStart(Tests test) {
List<AttemptProblem> attemptProblems = attemptProblemRepository.findAllByTestOrderByAttemptProblemIdAsc(test);
LocalDateTime now = LocalDateTime.now();
AtomicInteger i = new AtomicInteger(1);

attemptProblems.forEach(attemptProblem-> {
attemptProblems.forEach(attemptProblem -> {
String key = generateKey(test, i.getAndIncrement());
//끝나는 시간
// 끝나는 시간
LocalDateTime endTime = now.plusMinutes(test.getTestTime());
Duration duration = Duration.between(now, endTime);
long expireTime = duration.toMinutes();

// tempCode를 저장
redisTemplate.opsForValue().set(key, new TempCode("initialized", endTime));

// 테스트 남은 시간만큼 TTL을 설정한다
redisTemplate.expire(key, expireTime, TimeUnit.MINUTES);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,9 @@ public TestStartResponseDto getTestStartsData(Long testTypeId) {
//현재 테스트가 진행중인지 확인하도록
//이미 테스트 중인지 확인
Tests test = testProgressCheckService.isTestinProgress(member);
if(test!=null)
{
if (test != null) {
return getTestStartResponseDto(member.getCurrentTestId(), test);
}


TestType testType = testTypeRepository.findById(testTypeId).orElseThrow(() -> new MorandiException(TestTypeErrorCode.TEST_TYPE_NOT_FOUND));
// 현재 진행중인 테스트가 없을 경우 테스트 타입에 맞는 테스트 시작
test = addTestService.startTestByTestTypeId(testType, member);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package swm_nm.morandi.domain.testDuring.controller;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;
import swm_nm.morandi.domain.testDuring.dto.OutputDto;
import swm_nm.morandi.domain.testDuring.dto.TestInputData;
import swm_nm.morandi.domain.testDuring.service.RunCodeService;
import static org.assertj.core.api.Assertions.assertThat;

@SpringBootTest
class TestDuringControllerTest {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package swm_nm.morandi.domain.testDuring.service;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;
import swm_nm.morandi.domain.testDuring.dto.OutputDto;
import swm_nm.morandi.domain.testDuring.dto.TestInputData;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest
class RunCodeServiceTest {

@Autowired
private RunCodeService runCodeService;
@Test
@Transactional
void pythonRunCodeTest() throws Exception {
// given
TestInputData testInputData = new TestInputData();
testInputData.setCode(readFileContent("temp.py"));
testInputData.setInput(null);
testInputData.setLanguage("Python");

// when
OutputDto outputDto = runCodeService.runCode(testInputData);

// then
assertThat(outputDto.getOutput()).isEqualTo("168\n");
}

@Test
@Transactional
void cppRunCodeTest() throws Exception {
// given
TestInputData testInputData = new TestInputData();
testInputData.setCode(readFileContent("temp.cpp"));
testInputData.setInput("1 2");
testInputData.setLanguage("Cpp");

// when
OutputDto outputDto = runCodeService.runCode(testInputData);

// then
assertThat(outputDto.getOutput()).isEqualTo("3\n");
}

@Test
@Transactional
void javaRunCodeTest() throws Exception {
// given
TestInputData testInputData = new TestInputData();
testInputData.setCode(readFileContent("Main.java"));
testInputData.setInput("1 2");
testInputData.setLanguage("Java");

// when
OutputDto outputDto = runCodeService.runCode(testInputData);

// then
assertThat(outputDto.getOutput()).isEqualTo("3\n");
}

private String readFileContent(String filePath) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
StringBuilder content = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
content.append(line).append("\n");
}
return content.toString();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package swm_nm.morandi.domain.testDuring.service;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestReporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.test.context.support.WithMockUser;
import swm_nm.morandi.domain.member.entity.Member;
import swm_nm.morandi.domain.member.repository.MemberRepository;
import swm_nm.morandi.domain.problem.entity.Problem;
import swm_nm.morandi.domain.problem.repository.ProblemRepository;
import swm_nm.morandi.domain.testDuring.dto.TestCheckDto;
import swm_nm.morandi.domain.testExit.dto.AttemptProblemDto;
import swm_nm.morandi.domain.testExit.entity.AttemptProblem;
import swm_nm.morandi.domain.testExit.entity.Tests;
import swm_nm.morandi.domain.testInfo.repository.TestRepository;
import swm_nm.morandi.domain.testRecord.repository.AttemptProblemRepository;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.IntStream;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;

@SpringBootTest
@WithMockUser(username = "1", roles = "USER")
class SolvedCheckServiceTest {

@Autowired
private TestRepository testRepository;

@Autowired
private MemberRepository memberRepository;

@Autowired
private AttemptProblemRepository attemptProblemRepository;

@Autowired
private ProblemRepository problemRepository;

@Autowired
private SolvedCheckService solvedCheckService;
@Test
void isSolvedCheck() {
// given
Optional<Member> result = memberRepository.findById(1L);
Member member = result.get();
Tests test = Tests.builder()
.member(member)
.testDate(LocalDateTime.now())
.testTime(120L)
.build();
Tests savedTest = testRepository.save(test);
// 백준 문제 : 1002, 1003, 1004
List<Problem> problems = problemRepository.findAllById(Arrays.asList(1L, 2L, 3L));

IntStream.range(0, 3).mapToObj(i -> AttemptProblem.builder()
.member(member)
.test(savedTest)
.isSolved(false)
.problem(problems.get(i))
.build()).forEachOrdered(attemptProblem -> attemptProblemRepository.save(attemptProblem));

TestCheckDto testCheckDto = new TestCheckDto();
testCheckDto.setTestId(savedTest.getTestId());
testCheckDto.setBojId("aj4941");
testCheckDto.setTestTypeId(1L);

// when
List<AttemptProblemDto> attemptProblemDtos = solvedCheckService.isSolvedCheck(testCheckDto);

// aj4941 유저는 백준 문제 1002, 1003, 1004번 모두 정답이므로 3문제가 모두 정답처리 되어야 한다.
int count = (int) attemptProblemDtos.stream().filter(AttemptProblemDto::getIsSolved).count();

// then
assertThat(count).isEqualTo(3);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package swm_nm.morandi.domain.testDuring.service;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class TempCodeServiceTest {
@Test
void saveTempCodeTest() {

}
}
14 changes: 14 additions & 0 deletions temp.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> pll;
int dx[4] = { -1, 1, 0, 0 };
int dy[4] = { 0, 0, -1, 1 };

int main(void)
{
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int a, b; cin >> a >> b;
cout << a + b;
}
1 change: 1 addition & 0 deletions temp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
print(123 + 45)

0 comments on commit 1f512ed

Please sign in to comment.