Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[로또] 김성규 미션 제출합니다. #4

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

kimseonggyu03
Copy link

@kimseonggyu03 kimseonggyu03 commented Feb 13, 2025

Summary by CodeRabbit

  • New Features
    • 로또 애플리케이션의 티켓 생성 및 번호 검증 프로세스가 개선되어, 구매 금액 입력, 당첨 번호와 보너스 번호 처리 과정이 보다 간편하고 정확해졌습니다.
    • 당첨 결과 계산과 티켓 정보 출력이 직관적으로 향상되어 사용자 경험이 개선되었습니다.
  • Documentation
    • 로또 시스템의 기능과 사용법에 대한 안내가 보완되어, 최신 기능에 대한 이해와 활용이 용이해졌습니다.

Copy link

coderabbitai bot commented Feb 13, 2025

Walkthrough

이 변경 사항은 외부 라이브러리 임포트 검사를 위한 새 함수 추가, 복권 시스템 관련 기능의 확장 및 개선, 그리고 테스트 설정 보완을 포함합니다. GitHub 워크플로우에 check_imports 함수가 도입되어 AST를 기반으로 외부 임포트를 감지하며, README 문서에는 복권 기능(입력 처리, 번호 생성, 결과 계산, 출력, 에러 처리)에 대한 상세한 설명이 추가되었습니다. 또한, pytest.ini에 커스텀 마커가 추가되었으며, src/lotto 내의 모듈에서 Lotto 클래스 개선과 함께 여러 신규 기능이 구현되었습니다.

Changes

변경된 파일 변경 요약
.github/workflows/check-no-external-libs.yml 외부 라이브러리 임포트 검사를 위한 check_imports 함수 추가 및 AST 기반 검사 로직 구현
docs/README.md 복권 시스템 기능에 대한 상세 설명 추가 (입력 처리, 번호 생성, 결과 계산, 출력, 에러 처리)
pytest.ini 테스트 설명용 custom_name 커스텀 마커 추가 (한국어 설명 포함)
src/lotto/lotto.py, src/lotto/main.py Lotto 클래스 개선 (정렬, 중복 및 범위 체크 강화), 번호 생성, 출력 메서드 추가 및 Rank 열거형 도입, 복권 구매-평가 관련 신규 함수 추가

Sequence Diagram(s)

sequenceDiagram
    participant U as 사용자
    participant M as 메인 함수
    participant L as Lotto 클래스
    U->>M: 구매 금액 입력
    M->>M: check_amount & prompt_purchase_amount 처리
    M->>L: 티켓 생성 (generate_num 호출)
    U->>M: 당첨 번호 입력
    M->>M: prompt_winning_numbers 처리
    U->>M: 보너스 번호 입력
    M->>M: prompt_bonus_number 처리
    M->>M: evaluate_tickets 호출하여 결과 계산
    M->>U: print_results로 결과 출력
Loading
sequenceDiagram
    participant W as 워크플로우
    participant F as 파일 (src)
    W->>F: 각 파일 읽기
    W->>W: AST 파싱 후 import 문 검사
    alt 외부 라이브러리 감지됨
        W->>W: SystemExit 발생하여 중단
    else
        W->>W: 다음 파일로 계속 진행
    end
Loading

Poem

당근 든 토끼, 코드를 노래해
외부 임포트 감지, 오! 날카로운 눈빛!
복권 기능 춤추며, 번호는 반짝,
입력부터 결과까지, 모든 게 반짝반짝!
테스트 마커와 문서, 행복한 변화의 발자취 🐰✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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. (Beta)
  • @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

codecov bot commented Feb 13, 2025

Codecov Report

Attention: Patch coverage is 85.04673% with 16 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/lotto/main.py 80.82% 9 Missing and 5 partials ⚠️
src/lotto/lotto.py 94.11% 1 Missing and 1 partial ⚠️
Files with missing lines Coverage Δ
src/lotto/lotto.py 94.59% <94.11%> (ø)
src/lotto/main.py 78.94% <80.82%> (ø)

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

🔭 Outside diff range comments (1)
.github/workflows/check-no-external-libs.yml (1)

25-30: 🛠️ Refactor suggestion

불필요한 공백 제거 및 함수 개선

  1. 30번 줄의 불필요한 공백을 제거해야 합니다.
  2. 모듈 경로 검사 로직을 개선할 수 있습니다.
          def is_internal_module(module_name):
              """ 내부 모듈(`src/` 폴더 내 Python 파일)인지 확인 """
              module_path = os.path.join('src', module_name.replace('.', '/') + '.py')
              module_dir = os.path.join('src', module_name.replace('.', '/'))
              return os.path.exists(module_path) or os.path.isdir(module_dir)
-              

추가로 다음과 같은 개선사항을 제안드립니다:

def is_internal_module(module_name):
    """ 내부 모듈(`src/` 폴더 내 Python 파일)인지 확인 """
    paths = [
        os.path.join('src', module_name.replace('.', '/') + '.py'),
        os.path.join('src', module_name.replace('.', '/'), '__init__.py')
    ]
    return any(os.path.exists(path) for path in paths)
🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 30-30: trailing spaces

(trailing-spaces)

🧹 Nitpick comments (9)
src/lotto/lotto.py (4)

6-8: [초기화 메서드에 대한 간단한 문서화 추가를 제안합니다]
__init__ 메서드의 파라미터 numbers: list[int]는 Python 3.9 이상 버전에서 유효합니다. 이 요구사항을 사용 설명서 혹은 docstring에 명시해 주시면 좋을 것 같습니다.


10-16: [예외 메시지 내용과 조건의 불일치를 수정해 주세요]
아래 조건에서는 6개가 “아닐” 때 예외를 발생시키지만, 메시지에는 6개가 “넘어가면”이라고 쓰여 있습니다. 실제 의도에 맞게 메시지를 수정해 주세요.

예시 수정안:

-raise ValueError("로또 번호의 개수가 6개가 넘어가면 예외가 발생한다.")
+raise ValueError("로또 번호는 정확히 6개여야 합니다.")
🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 16-16: src/lotto/lotto.py#L16
Added line #L16 was not covered by tests


18-20: [클래스 메서드 인자명 개선을 권장합니다]
메서드 정의 시 clss 대신 cls라는 관용적인 이름을 사용해 주시면 가독성이 조금 더 좋아질 수 있습니다.


25-26: [문자열 표현을 명확하게 할 수도 있습니다]
__str__에 대한 문자열 형태를 좀 더 사용자 친화적으로 구성할 수 있습니다. 예: "Lotto numbers: [1, 2, 3, 4, 5, 6]".

src/lotto/main.py (2)

36-44: [보너스 번호 검증 로직 리뷰]
중복 및 범위 감지 로직이 적절하고 메시지도 사용자 친화적입니다. 추가로 보너스 번호가 0 또는 음수일 때 등 다른 극단 사례도 테스트에 반영해 보시면 좋겠습니다.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 38-38: src/lotto/main.py#L38
Added line #L38 was not covered by tests


[warning] 40-40: src/lotto/main.py#L40
Added line #L40 was not covered by tests


[warning] 42-42: src/lotto/main.py#L42
Added line #L42 was not covered by tests

🪛 GitHub Actions: Check PEP8 Style

[error] 36-36: Expected 2 blank lines, found 1


68-83: [출력 형식 및 PEP8]
print_results 내에서 수익률 계산을 반올림하여 출력하는 로직이 유용합니다. 한편, PEP8 검사에서 줄 길이와 빈 줄 관련 지적이 다수 확인되었으므로, 코드 포맷팅을 수정해 주세요.

🧰 Tools
🪛 GitHub Actions: Check PEP8 Style

[error] 68-68: Expected 2 blank lines, found 1

docs/README.md (1)

1-24: [문서 업데이트가 명확하고 일관성 있습니다]
각 단계를 구체적으로 설명하고 있어 사용자 입장에서 기능을 파악하기 좋습니다. 5번 항목 ‘예외 처리’ 중에 다른 항목들과 맞춰 개조식 표현(“5. 예외 처리” 뒤에 한 칸 띄우기 등)을 좀 더 맞추면 형식적으로 통일감이 있을 것 같습니다.

.github/workflows/check-no-external-libs.yml (2)

23-23: 표준 라이브러리 허용 목록 확장 검토

현재 허용된 모듈 목록이 기본적인 작업을 위해 충분하지만, 다음과 같은 유용한 표준 라이브러리 모듈들도 고려해 보시는 것을 추천드립니다:

  • json: JSON 데이터 처리
  • collections: 특수 컨테이너 타입
  • typing: 타입 힌트
-          allowed_modules = {'sys', 'os', 'math', 'random', 'datetime', 're', 'enum'}
+          allowed_modules = {'sys', 'os', 'math', 'random', 'datetime', 're', 'enum', 'json', 'collections', 'typing'}

31-41: import 검사 로직 개선 제안

현재 구현은 기본적인 기능은 잘 수행하고 있지만, 다음과 같은 개선사항들을 고려해보시기 바랍니다:

  1. 파일 읽기 오류 처리
  2. 모든 위반 사항을 수집하여 한 번에 보고
  3. 더 자세한 오류 메시지 제공
def check_imports(file_path):
    violations = []
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            tree = ast.parse(f.read(), filename=file_path)
            for node in ast.walk(tree):
                if isinstance(node, ast.Import):
                    for alias in node.names:
                        if alias.name not in allowed_modules and not is_internal_module(alias.name):
                            violations.append(f'직접 import: {alias.name} (라인: {node.lineno})')
                elif isinstance(node, ast.ImportFrom):
                    if node.module and node.module not in allowed_modules and not is_internal_module(node.module):
                        violations.append(f'from import: {node.module} (라인: {node.lineno})')
        
        if violations:
            raise SystemExit(
                f'❌ {file_path}에서 외부 라이브러리 사용이 감지되었습니다:\n' +
                '\n'.join(f'  - {v}' for v in violations)
            )
    except Exception as e:
        raise SystemExit(f'❌ {file_path} 파일 처리 중 오류 발생: {str(e)}')
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ceaaaa6 and 40c8ca6.

📒 Files selected for processing (5)
  • .github/workflows/check-no-external-libs.yml (1 hunks)
  • docs/README.md (1 hunks)
  • pytest.ini (0 hunks)
  • src/lotto/lotto.py (1 hunks)
  • src/lotto/main.py (1 hunks)
💤 Files with no reviewable changes (1)
  • pytest.ini
🧰 Additional context used
🪛 YAMLlint (1.35.1)
.github/workflows/check-no-external-libs.yml

[error] 30-30: trailing spaces

(trailing-spaces)

🪛 GitHub Check: codecov/patch
src/lotto/lotto.py

[warning] 16-16: src/lotto/lotto.py#L16
Added line #L16 was not covered by tests

src/lotto/main.py

[warning] 7-7: src/lotto/main.py#L7
Added line #L7 was not covered by tests


[warning] 9-9: src/lotto/main.py#L9
Added line #L9 was not covered by tests


[warning] 33-34: src/lotto/main.py#L33-L34
Added lines #L33 - L34 were not covered by tests


[warning] 38-38: src/lotto/main.py#L38
Added line #L38 was not covered by tests


[warning] 40-40: src/lotto/main.py#L40
Added line #L40 was not covered by tests


[warning] 42-42: src/lotto/main.py#L42
Added line #L42 was not covered by tests


[warning] 50-51: src/lotto/main.py#L50-L51
Added lines #L50 - L51 were not covered by tests

🪛 GitHub Actions: Check PEP8 Style
src/lotto/main.py

[error] 3-3: Expected 2 blank lines, found 1


[error] 12-12: Expected 2 blank lines, found 1


[error] 22-22: Expected 2 blank lines, found 1


[error] 27-27: Expected 2 blank lines, found 1


[error] 36-36: Expected 2 blank lines, found 1


[error] 45-45: Expected 2 blank lines, found 1


[error] 53-53: Expected 2 blank lines, found 1


[error] 68-68: Expected 2 blank lines, found 1


[error] 84-84: Expected 2 blank lines, found 1


[error] 92-92: Line too long (80 > 79 characters)


[error] 95-95: Expected 2 blank lines after class or function definition, found 1

🔇 Additional comments (8)
src/lotto/lotto.py (2)

22-23: [정상 동작 확인]
get_numbers 메서드는 변환 로직 없이 내부 자료만 반환하므로, 현재 로직상 문제없이 동작해 보입니다.


29-47: [추가 테스트를 권장합니다]
Rank.get_rank는 정상적으로 순회 후 매칭되는 열거형을 반환해 주지만, 6개가 모두 일치하면서 보너스도 일치하는 특이 케이스(이론상 실제 1등보다 더 높은 케이스)를 다루지 않으니, 해당 상황에 대한 테스트도 한 번 고려해 보세요.

src/lotto/main.py (6)

3-11: [입력 검증 로직에 대한 테스트 보강을 권장합니다]
check_amount 함수에서 문자열이 숫자인지 검사하고, 1000원 단위인지 확인하는 로직은 적절합니다. 다만, int(input_amount)가 정확히 0인 경우나 예상치 못한 입력 형태에 대해 커버리지가 부족할 수 있으니 추가 테스트를 고려해 주세요.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 7-7: src/lotto/main.py#L7
Added line #L7 was not covered by tests


[warning] 9-9: src/lotto/main.py#L9
Added line #L9 was not covered by tests

🪛 GitHub Actions: Check PEP8 Style

[error] 3-3: Expected 2 blank lines, found 1


22-26: [티켓 출력 기능]
print_lotto_tickets는 단순 반복 출력이므로 특별한 문제가 없어 보입니다.

🧰 Tools
🪛 GitHub Actions: Check PEP8 Style

[error] 22-22: Expected 2 blank lines, found 1


27-35: [당첨 번호 입력 예외 상황 테스트 보강 제안]
당첨 번호 입력에서 ValueError가 발생할 수 있는 시나리오(예: 7개 이상 입력, 중복, 범위 벗어남 등)에 대한 테스트를 더 늘려서 커버리지를 높여 보시면 좋겠습니다.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 33-34: src/lotto/main.py#L33-L34
Added lines #L33 - L34 were not covered by tests

🪛 GitHub Actions: Check PEP8 Style

[error] 27-27: Expected 2 blank lines, found 1


45-52: [보너스 번호 재입력 흐름 검토]
prompt_bonus_number 함수는 예외 발생 시 계속 입력을 받도록 while True 루프를 유지하므로, check_bonus_number에서 예외 발생 시 로직 흐름이 적절히 이어집니다. 현재 구조는 좋아 보입니다.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 50-51: src/lotto/main.py#L50-L51
Added lines #L50 - L51 were not covered by tests

🪛 GitHub Actions: Check PEP8 Style

[error] 45-45: Expected 2 blank lines, found 1


53-67: [당첨 티켓 평가 로직 확인]
evaluate_tickets 함수는 교집합을 통한 매칭 계산과 보너스 확인이 깔끔히 구성되어 있습니다. 추가로, 전체 로직에 예외 상황(티켓이 비어있는 경우 등)을 테스트해 보면 안정성을 더 높일 수 있습니다.

🧰 Tools
🪛 GitHub Actions: Check PEP8 Style

[error] 53-53: Expected 2 blank lines, found 1


85-93: [메인 함수 로직이 간결합니다]
메인 흐름이 함수들을 순차적으로 호출하여 로또 게임을 실행하는 구조가 적절합니다.

🧰 Tools
🪛 GitHub Actions: Check PEP8 Style

[error] 92-92: Line too long (80 > 79 characters)

Comment on lines +12 to +21
def prompt_purchase_amount():
while True:
try:
print("구입금액을 입력해 주세요.")
amount = input()
return check_amount(amount)
except ValueError as error:
print(f"[ERROR] {error}")
raise

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

[입력이 유효하지 않을 때 반복 구조가 중단됩니다]
이 부분에서 ValueError가 발생하면 raise로 인해 while True 루프를 빠져나갑니다. 계속 입력을 받으려면 raise 대신 사용자에게 재입력을 유도하는 방식(continue)을 고려해 보세요.

-except ValueError as error:
-    print(f"[ERROR] {error}")
-    raise
+except ValueError as error:
+    print(f"[ERROR] {error}")
+    continue
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def prompt_purchase_amount():
while True:
try:
print("구입금액을 입력해 주세요.")
amount = input()
return check_amount(amount)
except ValueError as error:
print(f"[ERROR] {error}")
raise
def prompt_purchase_amount():
while True:
try:
print("구입금액을 입력해 주세요.")
amount = input()
return check_amount(amount)
except ValueError as error:
print(f"[ERROR] {error}")
continue
🧰 Tools
🪛 GitHub Actions: Check PEP8 Style

[error] 12-12: Expected 2 blank lines, found 1

@swthewhite swthewhite changed the title [로또] 김성규 제출합니다. [로또] 김성규 미션 제출합니다. Feb 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants