Skip to content

Conversation

@move-hoon
Copy link
Member

@move-hoon move-hoon commented Apr 21, 2025

Related issue 🛠

Work Description ✏️

JAR 파일에서 .env의 위치 확인 후 해당 경로(루트)에서 읽도록 수정

  • JAR 빌드 시 src/main/resources/.env 파일은 Gradle 리소스 처리 방식에 따라 JAR 루트 디렉토리로 복사되는 것을 알게되었습니다.
  • 이로 인해 JAR 내부 구조에서는 .env가 classpath:/에 위치하게 되며, directory("src/main/resources")로 설정 시 해당 파일을 찾지 못했습니다.
  • 따라서 Dotenv.configure().load()로 수정하여 루트 디렉토리에서 .env 파일을 읽도록 수정했습니다.

Trouble Shooting ⚽️

테스트에서 getWebhookUrl 메서드를 호출하며 발생한 문제

  • 테스트 코드에서는 .env 파일의 위치를 src/test/resources로 지정하였습니다.
  • 그러나 테스트 코드에서 EnvUtil.getWebhookUrl을 호출할 경우, 해당 메서드 내부의 dotenv.get(envKey) 로직은 기본적으로 루트 디렉토리의 .env 파일을 참조하게 되어, 테스트가 실패하는 문제가 발생했습니다.
  • 이를 해결하기 위해, EnvUtil과 동일한 로직을 가진 테스트 전용 유틸리티 클래스인 TestEnvUtil을 새로 작성하였고, 해당 클래스에서는 .env 파일의 경로를 src/test/resources로 명시하여 테스트 환경에서도 정상적으로 .env 파일을 읽어올 수 있도록 설정하였습니다.

@move-hoon move-hoon self-assigned this Apr 21, 2025
@move-hoon move-hoon linked an issue Apr 21, 2025 that may be closed by this pull request
1 task
@height
Copy link

height bot commented Apr 21, 2025

Link Height tasks by mentioning a task ID in the pull request title or commit messages, or description and comments with the keyword link (e.g. "Link T-123").

💡Tip: You can also use "Close T-X" to automatically close a task when the pull request is merged.

@coderabbitai
Copy link

coderabbitai bot commented Apr 21, 2025

Summary by CodeRabbit

  • 신규 기능

    • 테스트 환경에서 다양한 서비스(Slack, Discord 등)의 Webhook URL을 손쉽게 조회할 수 있는 유틸리티가 추가되었습니다.
  • 테스트

    • 테스트에서 사용하는 .env 파일 경로가 변경되었으며, Webhook URL 조회 로직이 새로운 유틸리티 클래스를 사용하도록 개선되었습니다.
      """

Summary by CodeRabbit

  • Chores
    • 환경 변수 파일의 기본 경로 로딩 방식이 단순화되었습니다.
    • 테스트 환경 파일 위치가 변경되어 테스트 리소스 디렉토리를 사용하도록 수정되었습니다.
    • 테스트용 환경 변수 유틸리티 클래스 TestEnvUtil이 추가되어, 서비스별 웹훅 URL을 환경 변수에서 안전하게 조회할 수 있도록 구현되었습니다.

Walkthrough

이번 변경에서는 환경 변수 유틸리티 클래스에서 Dotenv 인스턴스의 초기화 방식을 단순화하여, .env 파일을 classpath에서 자동으로 로드하도록 수정했습니다. 테스트 코드에서는 테스트용 .env 파일 위치를 src/test/resources로 변경하고, 기존 EnvUtil.getWebhookUrl 호출을 새로 추가된 TestEnvUtil.getWebhookUrl로 대체했습니다. TestEnvUtil 클래스는 서비스 타입, 팀, 스테이지, 서버 타입을 받아 환경 변수 키를 생성하고, 유효성 검사 및 예외 처리를 포함하여 웹훅 URL을 반환하는 기능을 제공합니다.

Changes

파일/경로 그룹 변경 요약
src/main/java/org/sopt/makers/global/util/EnvUtil.java Dotenv 초기화 시 디렉토리 지정(.directory("src/main/resources"))을 제거하고, 기본 .load()만 사용하도록 변경
src/test/java/org/sopt/makers/global/util/EnvUtilTest.java 테스트용 .env 파일 경로를 src/test/resources로 변경 및 관련 디렉토리 생성 로직 수정, EnvUtil.getWebhookUrl 호출을 TestEnvUtil.getWebhookUrl로 변경
src/test/java/org/sopt/makers/global/util/TestEnvUtil.java 새로운 테스트용 환경 변수 유틸리티 클래스 추가: 서비스별 웹훅 URL 조회 기능, 파라미터 유효성 검사 및 예외 처리 구현

Assessment against linked issues

Objective Addressed Explanation
Dotenv.configure().directory("src/main/resources") → Dotenv.configure().load()로 수정하여 classpath 상의 .env를 로드하도록 변경 (#7)

Poem

🐰
환경 변수 hop! hop!
디렉토리 지정은 이제 stop!
classpath 따라 깡총깡총,
JAR 속에서도 문제 없쥐롱.
테스트도 자리에 착,
.env 파일도 딱!
오늘도 코드는 깔끔하게 hop!
"""

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ed577ee and 6e2f493.

📒 Files selected for processing (2)
  • src/main/java/org/sopt/makers/global/util/EnvUtil.java (1 hunks)
  • src/test/java/org/sopt/makers/global/util/EnvUtilTest.java (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: sentry-notifier-lambda-ci
src/test/java/org/sopt/makers/global/util/EnvUtilTest.java

[error] 54-54: Test failure: Exception thrown when querying Webhook URL with a non-existent key (org.opentest4j.AssertionFailedError).


[error] 48-48: Test failure: Failed to retrieve Webhook URL from a valid key (org.opentest4j.AssertionFailedError).


[error] 96-96: Test failure: Case-insensitive key recognition failed (org.opentest4j.AssertionFailedError).


[error] 96-96: Test failure: Case-insensitive key recognition failed (org.opentest4j.AssertionFailedError).


[error] 96-96: Test failure: Case-insensitive key recognition failed (org.opentest4j.AssertionFailedError).


[error] 90-90: Test failure: WebhookUrlNotFoundException thrown for case-insensitive key recognition (org.sopt.makers.global.exception.unchecked.WebhookUrlNotFoundException).


[error] 90-90: Test failure: WebhookUrlNotFoundException thrown for case-insensitive key recognition (org.sopt.makers.global.exception.unchecked.WebhookUrlNotFoundException).


[error] 90-90: Test failure: WebhookUrlNotFoundException thrown for case-insensitive key recognition (org.sopt.makers.global.exception.unchecked.WebhookUrlNotFoundException).

🔇 Additional comments (2)
src/main/java/org/sopt/makers/global/util/EnvUtil.java (1)

18-18:

Details

❓ Verification inconclusive

Dotenv 구성이 단순화되었습니다.

Dotenv의 초기화 방식이 단순화되어 명시적인 디렉토리 설정 없이 기본 로드 메커니즘을 사용하도록 변경되었습니다. 이 변경으로 .env 파일은 클래스패스에서 자동으로 로드될 것입니다.

변경된 코드가 제대로 동작하는지 확인하기 위해 다음 스크립트를 실행해보세요:


🏁 Script executed:

#!/bin/bash
# .env 파일의 실제 위치 확인
find . -name ".env" -type f | sort

Length of output: 34


Dotenv 기본 로드 검증이 필요합니다

현재 find . -name ".env" -type f 명령으로 .env 파일을 찾을 수 없어, 기본 로드 메커니즘이 제대로 동작하는지 확인이 불가능한 상태입니다.
다음 중 하나를 수행해 주세요:

  • 실제 .env 파일이 저장된 경로를 다시 확인하고 그 위치를 기반으로 테스트
  • 애플리케이션을 실행해 환경 변수가 정상적으로 로드되는지 직접 검증
src/test/java/org/sopt/makers/global/util/EnvUtilTest.java (1)

25-25: 환경 변수 파일 경로가 테스트 리소스 디렉토리로 변경되었습니다.

환경 변수 파일의 경로가 src/main/resources/.env에서 src/test/resources/.env로 변경되었습니다. 이는 EnvUtil 클래스의 Dotenv 로드 방식 변경과 일치하도록 조정한 것입니다.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (3)
src/test/java/org/sopt/makers/global/util/TestEnvUtil.java (3)

10-15: 클래스 가시성과 Dotenv 구성에 대한 검토

이 클래스는 패키지 프라이빗(default visibility)으로 선언되어 있습니다. 이는 의도적인 설계일 수 있지만, 다른 패키지의 테스트에서 재사용하기 어려울 수 있습니다. 또한 Dotenv의 경로가 하드코딩되어 있어 테스트 리소스 구조가 변경될 경우 수정이 필요합니다.

-class TestEnvUtil {
+public class TestEnvUtil {

또한 Dotenv 경로를 상수로 추출하거나 설정 가능하게 만드는 것을 고려해보세요:

+private static final String TEST_RESOURCES_PATH = "src/test/resources";
 private static final Dotenv dotenv = Dotenv.configure()
-	.directory("src/test/resources")
+	.directory(TEST_RESOURCES_PATH)
 	.load();

28-47: getWebhookUrl 메서드 관련 제안

메서드 구현은 전반적으로 견고하나, 몇 가지 개선 사항이 있습니다:

  1. 매개변수 검증 로직을 별도의 메서드로 추출하면 코드 가독성이 향상될 것입니다.
  2. 예외 메시지에 어떤 매개변수가 잘못되었는지 구체적인 정보를 포함하면 디버깅에 도움이 됩니다.
  3. 환경 변수 키 구성 로직도 별도 메서드로 추출하면 더 명확해질 것입니다.
 public static String getWebhookUrl(String service, String team, String stage, String type) {
-	if (service == null || team == null || stage == null || type == null) {
-		throw InvalidEnvParameterException.from(ErrorMessage.INVALID_ENV_PARAMETER);
-	}
+	validateParameters(service, team, stage, type);
 
 	String prefix = resolvePrefix(service.toLowerCase());
-	String envKey = String.format("%s%s_%s_%s",
-		prefix,
-		team.toUpperCase(),
-		stage.toUpperCase(),
-		type.toUpperCase());
+	String envKey = buildEnvKey(prefix, team, stage, type);
 
 	String webhookUrl = dotenv.get(envKey);
 
 	if (webhookUrl == null || webhookUrl.isBlank()) {
-		throw new WebhookUrlNotFoundException(ErrorMessage.WEBHOOK_URL_NOT_FOUND);
+		throw new WebhookUrlNotFoundException(
+			ErrorMessage.WEBHOOK_URL_NOT_FOUND.withArgs(envKey));
 	}
 
 	return webhookUrl;
 }
+
+private static void validateParameters(String service, String team, String stage, String type) {
+	if (service == null || team == null || stage == null || type == null) {
+		throw InvalidEnvParameterException.from(ErrorMessage.INVALID_ENV_PARAMETER);
+	}
+}
+
+private static String buildEnvKey(String prefix, String team, String stage, String type) {
+	return String.format("%s%s_%s_%s",
+		prefix,
+		team.toUpperCase(),
+		stage.toUpperCase(),
+		type.toUpperCase());
+}

49-55: resolvePrefix 메서드에 대한 피드백

switch 표현식을 사용한 구현은 깔끔하지만, 새로운 서비스 타입을 추가할 때마다 코드를 수정해야 합니다. 더 확장 가능한 접근 방식을 고려해볼 수 있습니다.

다음과 같이 Map을 사용하여 구현할 수 있습니다:

+private static final Map<String, String> SERVICE_PREFIXES = Map.of(
+	"slack", SLACK_WEBHOOK_PREFIX,
+	"discord", DISCORD_WEBHOOK_PREFIX
+);

 private static String resolvePrefix(String service) {
-	return switch (service) {
-		case "slack" -> SLACK_WEBHOOK_PREFIX;
-		case "discord" -> DISCORD_WEBHOOK_PREFIX;
-		default -> throw new UnsupportedServiceTypeException(ErrorMessage.UNSUPPORTED_SERVICE_TYPE);
-	};
+	String prefix = SERVICE_PREFIXES.get(service);
+	if (prefix == null) {
+		throw new UnsupportedServiceTypeException(
+			ErrorMessage.UNSUPPORTED_SERVICE_TYPE.withArgs(service));
+	}
+	return prefix;
 }

이렇게 하면 지원되는 서비스 목록을 한 곳에서 관리할 수 있고, 새 서비스 추가 시 코드 변경 없이 Map에만 추가하면 됩니다.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6e2f493 and 17ea94d.

📒 Files selected for processing (2)
  • src/test/java/org/sopt/makers/global/util/EnvUtilTest.java (6 hunks)
  • src/test/java/org/sopt/makers/global/util/TestEnvUtil.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/test/java/org/sopt/makers/global/util/EnvUtilTest.java
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/test/java/org/sopt/makers/global/util/TestEnvUtil.java (3)
src/main/java/org/sopt/makers/global/exception/unchecked/InvalidEnvParameterException.java (1)
  • InvalidEnvParameterException (5-14)
src/main/java/org/sopt/makers/global/exception/unchecked/UnsupportedServiceTypeException.java (1)
  • UnsupportedServiceTypeException (5-13)
src/main/java/org/sopt/makers/global/exception/unchecked/WebhookUrlNotFoundException.java (1)
  • WebhookUrlNotFoundException (5-13)

@move-hoon move-hoon changed the title Bug/#7 fix: .env 파일을 로드하도록 수정 완료 Apr 21, 2025
@move-hoon move-hoon merged commit dc7fc2a into main Apr 21, 2025
2 checks passed
@move-hoon move-hoon deleted the bug/#7 branch May 12, 2025 07:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug: JAR 빌드 환경에서 .env 로드 실패 이슈

2 participants