This commit is contained in:
Yurii Motov 2026-01-05 18:53:58 +01:00
parent 44f25ad0ac
commit c70d79afe9
5 changed files with 554 additions and 0 deletions

View File

@ -0,0 +1,32 @@
import shutil
from pathlib import Path
import pytest
from typer.testing import CliRunner
@pytest.fixture(name="runner")
def get_runner():
runner = CliRunner()
with runner.isolated_filesystem():
yield runner
@pytest.fixture(name="root_dir")
def prepare_paths(runner):
docs_dir = Path("docs")
en_docs_dir = docs_dir / "en" / "docs"
lang_docs_dir = docs_dir / "lang" / "docs"
en_docs_dir.mkdir(parents=True, exist_ok=True)
lang_docs_dir.mkdir(parents=True, exist_ok=True)
yield Path.cwd()
@pytest.fixture
def copy_test_files(root_dir: Path, request: pytest.FixtureRequest):
en_file_path = Path(request.param[0])
translation_file_path = Path(request.param[1])
shutil.copy(str(en_file_path), str(root_dir / "docs" / "en" / "docs" / "doc.md"))
shutil.copy(
str(translation_file_path), str(root_dir / "docs" / "lang" / "docs" / "doc.md")
)

View File

@ -0,0 +1,166 @@
# Test translation fixer tool { #test-translation-fixer }
## Code blocks with and without comments { #code-blocks-with-and-without-comments }
This is a test page for the translation fixer tool.
### Code blocks with comments { #code-blocks-with-comments }
The following code blocks include comments in different styles.
Fixer tool should fix content, but preserve comments correctly.
```python
# This is a sample Python code block
def hello_world():
# Comment with indentation
print("Hello, world!") # Print greeting
```
```toml
# This is a sample TOML code block
title = "TOML Example" # Title of the document
```
```console
// Use the command "live" and pass the language code as a CLI argument
$ python ./scripts/docs.py live es
<span style="color: green;">[INFO]</span> Serving on http://127.0.0.1:8008
<span style="color: green;">[INFO]</span> Start watching changes
<span style="color: green;">[INFO]</span> Start detecting changes
```
```json
{
// This is a sample JSON code block
"greeting": "Hello, world!" // Greeting
}
```
### Code blocks with comments where language uses different comment styles { #code-blocks-with-different-comment-styles }
The following code blocks include comments in different styles based on the language.
Fixer tool will not preserve comments in these blocks.
```json
{
# This is a sample JSON code block
"greeting": "Hello, world!" # Print greeting
}
```
```console
# This is a sample console code block
$ echo "Hello, world!" # Print greeting
```
```toml
// This is a sample TOML code block
title = "TOML Example" // Title of the document
```
### Code blocks with comments with unsupported languages or without language specified { #code-blocks-with-unsupported-languages }
The following code blocks use unsupported languages for comment preservation.
Fixer tool will not preserve comments in these blocks.
```javascript
// This is a sample JavaScript code block
console.log("Hello, world!"); // Print greeting
```
```
# This is a sample console code block
$ echo "Hello, world!" # Print greeting
```
```
// This is a sample console code block
$ echo "Hello, world!" // Print greeting
```
### Code blocks with comments that don't follow pattern { #code-blocks-with-comments-without-pattern }
Fixer tool expects comments that follow specific pattern:
- For hash-style comments: comment starts with `# ` (hash following by whitespace) in the beginning of the string or after a whitespace.
- For slash-style comments: comment starts with `// ` (two slashes following by whitespace) in the beginning of the string or after a whitespace.
If comment doesn't follow this pattern, fixer tool will not preserve it.
```python
#Function declaration
def hello_world():# Print greeting
print("Hello, world!") #Print greeting without space after hash
```
```console
//Function declaration
def hello_world():// Print greeting
print("Hello, world!") //Print greeting without space after slashes
```
# Code includes { #code-includes }
## Simple code includes { #simple-code-includes }
{* ../../docs_src/python_types/tutorial001_py39.py *}
{* ../../docs_src/python_types/tutorial002_py39.py *}
## Code includes with highlighting { #code-includes-with-highlighting }
{* ../../docs_src/python_types/tutorial002_py39.py hl[1] *}
{* ../../docs_src/python_types/tutorial006_py39.py hl[10] *}
## Code includes with line ranges { #code-includes-with-line-ranges }
{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}
{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] *}
## Code includes with line ranges and highlighting { #code-includes-with-line-ranges-and-highlighting }
{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}
{* ../../docs_src/dependencies/tutorial015_an_py310.py ln[10:15] hl[12:14] *}
## Code includes qith title { #code-includes-with-title }
{* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[1,3] title["app/routers/users.py"] *}
{* ../../docs_src/bigger_applications/app_an_py39/internal/admin.py hl[3] title["app/internal/admin.py"] *}
# Code includes with unknown attributes { #code-includes-with-unknown-attributes }
{* ../../docs_src/python_types/tutorial001_py39.py unknown[123] *}
# Links { #links }
## Markdown-style links { #markdown-style-links }
This is a [Markdown link](https://example.com) to an external site.
This is a link with attributes: [**FastAPI** Project Generators](project-generation.md){.internal-link target=_blank}
This is a link to the main FastAPI site: [FastAPI](https://fastapi.tiangolo.com) - tool should add language code to the URL.
This is a link to one of the pages on FastAPI site: [How to](https://fastapi.tiangolo.com/how-to/) - tool should add language code to the URL.
## HTML-style links { #html-style-links }
This is an <a href="https://example.com" target="_blank" class="external-link">HTML link</a> to an external site.
This is an <a href="https://fastapi.tiangolo.com">link to the main FastAPI site</a> - tool should add language code to the URL.
This is an <a href="https://fastapi.tiangolo.com/how-to/">link to one of the pages on FastAPI site</a> - tool should add language code to the URL.

View File

@ -0,0 +1,163 @@
# Тестовый инструмент исправления переводов { #test-translation-fixer }
## Блоки кода с комментариями и без комментариев { #code-blocks-with-and-without-comments }
Это тестовая страница для инструмента исправления переводов.
### Блоки кода с комментариями { #code-blocks-with-comments }
Следующие блоки кода содержат комментарии в разных стилях.
Инструмент исправления должен исправлять содержимое, но корректно сохранять комментарии.
```python
# Это пример блока кода на Python
def hello_world():
# Комментарий с отступом
print("Hello, world!") # Печать приветствия
```
```toml
# Это пример блока кода на TOML
title = "TOML Example" # Заголовок документа
```
```console
// Используйте команду "live" и передайте код языка в качестве аргумента CLI
$ python ./scripts/docs.py live es
<span style="color: green;">[INFO]</span> Serving on http://127.0.0.1:8008
<span style="color: green;">[INFO]</span> Start watching changes
<span style="color: green;">[INFO]</span> Start detecting changes
```
```json
{
// Это пример блока кода на JSON
"greeting": "Hello, world!" // Печать приветствия
}
```
### Блоки кода с комментариями, где язык использует другие стили комментариев { #code-blocks-with-different-comment-styles }
Следующие блоки кода содержат комментарии в разных стилях в зависимости от языка.
Инструмент исправления не будет сохранять комментарии в этих блоках.
```json
{
# Это пример блока кода на JSON
"greeting": "Hello, world!" # Печать приветствия
}
```
```console
# Это пример блока кода консоли
$ echo "Hello, world!" # Печать приветствия
```
```toml
// Это пример блока кода на TOML
title = "TOML Example" // Заголовок документа
```
### Блоки кода с комментариями на неподдерживаемых языках или без указания языка { #code-blocks-with-unsupported-languages }
Следующие блоки кода используют неподдерживаемые языки для сохранения комментариев.
Инструмент исправления не будет сохранять комментарии в этих блоках.
```javascript
// Это пример блока кода на JavaScript
console.log("Hello, world!"); // Печать приветствия
```
```
# Это пример блока кода консоли
$ echo "Hello, world!" # Печать приветствия
```
```
// Это пример блока кода консоли
$ echo "Hello, world!" // Печать приветствия
```
### Блоки кода с комментариями, которые не соответствуют шаблону { #code-blocks-with-comments-without-pattern }
Инструмент исправления ожидает комментарии, которые соответствуют определённому шаблону:
- Для комментариев в стиле с решёткой: комментарий начинается с `# ` (решётка, затем пробел) в начале строки или после пробела.
- Для комментариев в стиле со слешами: комментарий начинается с `// ` (два слеша, затем пробел) в начале строки или после пробела.
Если комментарий не соответствует этому шаблону, инструмент исправления не будет его сохранять.
```python
#Объявление функции
def hello_world():# Печать приветствия
print("Hello, world!") #Печать приветствия без пробела после решётки
```
```console
//Объявление функции
def hello_world():// Печать приветствия
print("Hello, world!") //Печать приветствия без пробела после слешей
```
# Включения кода { #code-includes }
## Простые включения кода { #simple-code-includes }
{* ../../docs_src/python_types/tutorial001_py39.py *}
{* ../../docs_src/python_types/tutorial002_py39.py *}
## Включения кода с подсветкой { #code-includes-with-highlighting }
{* ../../docs_src/python_types/tutorial002_py39.py hl[1] *}
{* ../../docs_src/python_types/tutorial006_py39.py hl[10] *}
## Включения кода с диапазонами строк { #code-includes-with-line-ranges }
{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}
{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] *}
## Включения кода с диапазонами строк и подсветкой { #code-includes-with-line-ranges-and-highlighting }
{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}
{* ../../docs_src/dependencies/tutorial015_an_py310.py ln[10:15] hl[12:14] *}
## Включения кода с заголовком { #code-includes-with-title }
{* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[1,3] title["app/routers/users.py"] *}
{* ../../docs_src/bigger_applications/app_an_py39/internal/admin.py hl[3] title["app/internal/admin.py"] *}
# Включения кода с неизвестными атрибутами { #code-includes-with-unknown-attributes }
{* ../../docs_src/python_types/tutorial001_py39.py unknown[123] *}
# Ссылки { #links }
## Ссылки в стиле Markdown { #markdown-style-links }
Это [Markdown-ссылка](https://example.com) на внешний сайт.
Это ссылка с атрибутами: [**FastAPI** генераторы проектов](project-generation.md){.internal-link target=_blank}
Это ссылка на основной сайт FastAPI: [FastAPI](https://fastapi.tiangolo.com) — инструмент должен добавить код языка в URL.
Это ссылка на одну из страниц на сайте FastAPI: [How to](https://fastapi.tiangolo.com/how-to) — инструмент должен добавить код языка в URL.
## Ссылки в стиле HTML { #html-style-links }
Это <a href="https://example.com" target="_blank" class="external-link">HTML-ссылка</a> на внешний сайт.
Это <a href="https://fastapi.tiangolo.com">ссылка на основной сайт FastAPI</a> — инструмент должен добавить код языка в URL.
Это <a href="https://fastapi.tiangolo.com/how-to/">ссылка на одну из страниц на сайте FastAPI</a> — инструмент должен добавить код языка в URL.

View File

@ -0,0 +1,163 @@
# Тестовый инструмент исправления переводов { #test-translation-fixer }
## Блоки кода с комментариями и без комментариев { #code-blocks-with-and-without-comments }
Это тестовая страница для инструмента исправления переводов.
### Блоки кода с комментариями { #code-blocks-with-comments }
Следующие блоки кода содержат комментарии в разных стилях.
Инструмент исправления должен исправлять содержимое, но корректно сохранять комментарии.
```python
# Это пример блока кода на Python
def hello_world():
# Комментарий с отступом
print("Hello, world!") # Печать приветствия
```
```toml
# Это пример блока кода на TOML
title = "TOML Example" # Заголовок документа
```
```console
// Используйте команду "live" и передайте код языка в качестве аргумента CLI
$ python ./scripts/docs.py live es
<span style="color: green;">[INFO]</span> Serving on http://127.0.0.1:8008
<span style="color: green;">[INFO]</span> Start watching changes
<span style="color: green;">[INFO]</span> Start detecting changes
```
```json
{
// Это пример блока кода на JSON
"greeting": "Hello, world!" // Печать приветствия
}
```
### Блоки кода с комментариями, где язык использует другие стили комментариев { #code-blocks-with-different-comment-styles }
Следующие блоки кода содержат комментарии в разных стилях в зависимости от языка.
Инструмент исправления не будет сохранять комментарии в этих блоках.
```json
{
# This is a sample JSON code block
"greeting": "Hello, world!" # Print greeting
}
```
```console
# This is a sample console code block
$ echo "Hello, world!" # Print greeting
```
```toml
// This is a sample TOML code block
title = "TOML Example" // Title of the document
```
### Блоки кода с комментариями на неподдерживаемых языках или без указания языка { #code-blocks-with-unsupported-languages }
Следующие блоки кода используют неподдерживаемые языки для сохранения комментариев.
Инструмент исправления не будет сохранять комментарии в этих блоках.
```javascript
// This is a sample JavaScript code block
console.log("Hello, world!"); // Print greeting
```
```
# This is a sample console code block
$ echo "Hello, world!" # Print greeting
```
```
// This is a sample console code block
$ echo "Hello, world!" // Print greeting
```
### Блоки кода с комментариями, которые не соответствуют шаблону { #code-blocks-with-comments-without-pattern }
Инструмент исправления ожидает комментарии, которые соответствуют определённому шаблону:
- Для комментариев в стиле с решёткой: комментарий начинается с `# ` (решётка, затем пробел) в начале строки или после пробела.
- Для комментариев в стиле со слешами: комментарий начинается с `// ` (два слеша, затем пробел) в начале строки или после пробела.
Если комментарий не соответствует этому шаблону, инструмент исправления не будет его сохранять.
```python
#Function declaration
def hello_world():# Print greeting
print("Hello, world!") #Print greeting without space after hash
```
```console
//Function declaration
def hello_world():// Print greeting
print("Hello, world!") //Print greeting without space after slashes
```
# Включения кода { #code-includes }
## Простые включения кода { #simple-code-includes }
{* ../../docs_src/python_types/tutorial001_py39.py *}
{* ../../docs_src/python_types/tutorial002_py39.py *}
## Включения кода с подсветкой { #code-includes-with-highlighting }
{* ../../docs_src/python_types/tutorial002_py39.py hl[1] *}
{* ../../docs_src/python_types/tutorial006_py39.py hl[10] *}
## Включения кода с диапазонами строк { #code-includes-with-line-ranges }
{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[19:21] *}
{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] *}
## Включения кода с диапазонами строк и подсветкой { #code-includes-with-line-ranges-and-highlighting }
{* ../../docs_src/dependencies/tutorial013_an_py310.py ln[30:38] hl[31:33] *}
{* ../../docs_src/dependencies/tutorial015_an_py310.py ln[10:15] hl[12:14] *}
## Включения кода с заголовком { #code-includes-with-title }
{* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[1,3] title["app/routers/users.py"] *}
{* ../../docs_src/bigger_applications/app_an_py39/internal/admin.py hl[3] title["app/internal/admin.py"] *}
# Включения кода с неизвестными атрибутами { #code-includes-with-unknown-attributes }
{* ../../docs_src/python_types/tutorial001_py39.py unknown[123] *}
# Ссылки { #links }
## Ссылки в стиле Markdown { #markdown-style-links }
Это [Markdown-ссылка](https://example.com) на внешний сайт.
Это ссылка с атрибутами: [**FastAPI** генераторы проектов](project-generation.md){.internal-link target=_blank}
Это ссылка на основной сайт FastAPI: [FastAPI](https://fastapi.tiangolo.com/lang) — инструмент должен добавить код языка в URL.
Это ссылка на одну из страниц на сайте FastAPI: [How to](https://fastapi.tiangolo.com/lang/how-to/) — инструмент должен добавить код языка в URL.
## Ссылки в стиле HTML { #html-style-links }
Это <a href="https://example.com" target="_blank" class="external-link">HTML-ссылка</a> на внешний сайт.
Это <a href="https://fastapi.tiangolo.com/lang">ссылка на основной сайт FastAPI</a> — инструмент должен добавить код языка в URL.
Это <a href="https://fastapi.tiangolo.com/lang/how-to/">ссылка на одну из страниц на сайте FastAPI</a> — инструмент должен добавить код языка в URL.

View File

@ -0,0 +1,30 @@
from pathlib import Path
import pytest
from typer.testing import CliRunner
from scripts.translation_fixer import cli
data_path = Path(
"scripts/tests/test_translation_fixer/test_complex_doc/data"
).absolute()
@pytest.mark.parametrize(
"copy_test_files",
[(f"{data_path}/en_doc.md", f"{data_path}/translated_doc.md")],
indirect=True,
)
def test_fix(runner: CliRunner, root_dir: Path, copy_test_files):
result = runner.invoke(
cli,
["fix-pages", "docs/lang/docs/doc.md"],
)
assert result.exit_code == 0, result.output
fixed_content = (root_dir / "docs" / "lang" / "docs" / "doc.md").read_text()
expected_content = (data_path / "translated_doc_expected.md").read_text()
assert fixed_content == expected_content
assert "Fixing multiline code blocks in" in result.output
assert "Fixing markdown links in" in result.output