해야 할 일
1. ruff를 python linter로 적용하기
2. 테스트 코드 관리 (카테고라이징 + 하드코딩부분 수정 + 코드부분 짧게 여러 파일로)
1. ruff 적용
https://docs.astral.sh/ruff/tutorial/
Tutorial - Ruff
Tutorial This tutorial will walk you through the process of integrating Ruff's linter and formatter into your project. For a more detailed overview, see Configuring Ruff. Getting Started To start, we'll install Ruff through PyPI (or with your preferred pac
docs.astral.sh
따라해본다.
일단 목표는 front의 linter 처럼 cmd s 누르면 적용이 되는 방식이던지 알려주는 방식인데 일단 해본다.
https://docs.astral.sh/ruff/editors/setup/
Setup - Ruff
Overview Editors Setup We have specific setup instructions depending on your editor of choice. If you don't see your editor on this list and would like a setup guide, please open an issue. If you're transferring your configuration from ruff-lsp, regardless
docs.astral.sh
vscode 확장 프로그램에 ruff 가 있어서 다운로드받았다.
일단 일차적으로 settings.json 을 cmd shift p 를 눌러서 연 후에 아래의 코드를 작성해봤다.
"[python]": {
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll": true
},
"editor.defaultFormatter": "ms-python.black-formatter"
}
안되서 지피티에게 물어보니까 위에 따로 더 뭔가 enable 을 해야하는 것 같았다. -> 아니였다.
그래서 깃헙 오픈소스 코드들을 뒤적거렸다.
계속 뭔가 toml 파일을 찾길래 찾다보니 toml 파일을 생성하고 안에 내용을 적어야 해당 내용을 바탕으로 포맷팅이 되는 것 같았다.
프로젝트 내에 pyproject.toml 파일을 생성하고 아래의 코드를 넣었다.
[project]
# Support Python 3.10+.
requires-python = ">=3.10"
[tool.ruff]
# Set the maximum line length to 79.
line-length = 79
[tool.ruff.lint]
# Add the `line-too-long` rule to the enforced rule set.
extend-select = ["E501"]
잘 적용되는 모습을 확인할 수 있었다.
다음에 포맷팅 관련으로 더 찾아보든 해야겠다...
그리고 하는 김에 pre commit 관련으로도 하는 편이 나을 것 같아 훅을 한번 만들어볼 생각이다.
Python Linter로 Ruff를 사용해보기(feat. pre-commit)
최신 Python Linter인 Ruff를 알아보자
velog.io
일단 pre commit config 를 사용하는 방법을 모르니 pre commit config 관련 블로그를 찾아봤다
https://jongseoung.tistory.com/250
[GIT] Pre-commit 사용법 및 설정 가이드
장고 프로젝트에서 코드의 품질을 유지하고 코드 검사를 자동화하여 실수를 줄 일 수 있는 방법 중 하나인 Pre-commit에 PEP8 스타일 가이드를 검사하는 pre-commit의 설정과 pre-commit의 사용법에 대
jongseoung.tistory.com
이블로그를 참고해서 일단 pip install pre-commit 으로 다운로드를 받았다.
그리고 루트 디렉토리에 .pre-commit-config.yaml 파일을 생성해서 안에 내용을 넣어주었다.
안에 넣어준 내용은 아래를 참고했다.
https://docs.astral.sh/ruff/integrations/#pre-commit
Integrations - Ruff
Integrations GitHub Actions GitHub Actions has everything you need to run Ruff out-of-the-box: name: CI on: push jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Install Python uses: actions/setup-python@v5 with: python-versio
docs.astral.sh
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.5.7
hooks:
# Run the linter.
- id: ruff
types_or: [ python, pyi, jupyter ]
args: [ --fix ]
# Run the formatter.
- id: ruff-format
types_or: [ python, pyi, jupyter ]
위의 코드에서 repo 도 그대로 넣는 것 같아서 일단 그대로 넣어봤다. (주석으로 바꾸라는 말이 안보였고,, 블로그에서도 딱히 안보였다..)
pre-commit install 을 해줬다.
일단 뭐가 만들어졌으니 실행해본다.
오류발생
지피티의 답변으로는 파일을 잘못작성한것같다고 말했다.
다른 깃 레포들을 확인해보니 repos 를 따로 안붙여서 나는 버그인 것 같다.
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.5.7
hooks:
- id: ruff
args: [--fix]
- id: ruff-format
이런식으로 바꿔서 작성해보았고
결과는
완성!
일단 지금까지만든 app 들에 전부 cmd s를 해주는데 문제가 발생했다.
이렇게 작성하니 기본 주석이나 prompting 관련 코드들이 전부 79자를 넘어간다고 오류가떠서 커밋이 안된다..
그래서 문자열 및 주석은 길이 관련에서 제외시켜보려고 한다.
첫번째 시도
toml 파일에 조건 추가하기
[tool.ruff.lint.pycodestyle]
ignore-overlong-task-comments = true
실패 => E501 에러가 사라지지 않는다
두번째 시도
https://github.com/astral-sh/ruff/issues/4484
Expected for noqa to be ignored for multi-line string variable? · Issue #4484 · astral-sh/ruff
(ruff=v0.0.267). Based on the docs we can add a noqa annotation to a multi-line string as follows: """ Some long string. """ # noqa I would assume this should also be true if the string is a variab...
github.com
위의 방법에서 힌트를 얻고 아래의 자료를 참고해서 # noqa : E501 로 일단 막아놨다.
string 의 경우에는 \ 문자를 이용해서 문자열을 여러 열로 이루어지도록 바꾸고
앞에 있는 api 설명 쪽은 그냥 저 주석을 통해서 해결했다.
https://docs.astral.sh/ruff/rules/line-too-long/
line-too-long (E501) - Ruff
line-too-long (E501) Derived from the pycodestyle linter. What it does Checks for lines that exceed the specified maximum character length. Why is this bad? Overlong lines can hurt readability. PEP 8, for example, recommends limiting lines to 79 characters
docs.astral.sh
2. 테스트 코드 하드 코딩 삭제 및 카테고라이징
일단 origin develop 을 머지하고서 문제를 해결하려고 했는데
isauthenticated 옵션이 켜져있어서 test 를 약간 수정해야한다.
force_authenticate를 통해서 할 수 있다고 하는데
지금 당장 수많은 테스트 함수들에 모두 일일이 넣어주는 건 너무 슬프기 때문에
최대한 create_user 함수 안에서 해결해서 다른 함수를 고치지 않고서도 로그인이 완료될 수 있도록 할 예정이다.
일단 create_user fixture 에 force_authenticate를 넣어서 가능한가 확인해봤는데
무서운 일이 발생했다.
에러를 살펴보니 어째서인지 모든 obejct.create 부분에서 오류가 나서, 이렇게 처리하는게 아니구나를 알았다.
그래서 force_authenticate 를 공식문서에서 어떻게 사용하는 건지 찾으려했으나 아직 찾지 못했다.
force_user 까지는 확인했는데 authenticate 문서가 보이지 않는다.
일단 시간이 늦었으니 내일 계속 해봐야할 것 같다.
ruff 적용하고 모든 파일에 적용하고 이것 저것 하는 데 시간이 꽤 들었다..
'소프트웨어 마에스트로 > BackEnd(Django)' 카테고리의 다른 글
[백엔드] pytest testcode 개편 (0) | 2024.08.16 |
---|---|
[백엔드] pytest 관련 서치 및 nested_serializer 손보기 (0) | 2024.08.16 |
[백엔드] serializer validation 추가하기 ( Fat model) (1) | 2024.08.14 |
[백엔드] sentry django 적용기 (0) | 2024.08.12 |
[백엔드] Django logfire -> sentry logging (0) | 2024.08.08 |