pytest-dev / pytest-bdd

BDD library for the py.test runner
https://pytest-bdd.readthedocs.io/en/latest/
MIT License
1.27k stars 215 forks source link

Gherkin Localization Issue ? #397

Open arqeco opened 3 years ago

arqeco commented 3 years ago

Hello,

I've tried the following:

login.feature

#language: pt
#encoding: UTF-8
Funcionalidade: Login no Programa
    Cenário: O usuário ainda não é cadastrado
        Dado que o usuário esteja na tela de login
        Quando ele clicar no botão de Criar Conta
        Então ele deve ser levado para a tela de criação de conta

test_login.py

import pytest

from pytest_bdd import scenarios, given, when, then, parsers

scenarios("../features/login.feature")

@given("que o usuário esteja na tela de login")
def tela_login():
    assert True

@when("ele clicar no botão de Criar Conta")
def evento_criar_conta():
    assert True

@then("ele deve ser levado para a tela de criação de conta")
def tela_criacao_conta():
    assert True

This is the result:

ERROR step_defs/test_login.py - pytest_bdd.exceptions.NoScenariosFound

Is there support for Gherkin localization in pytest-bdd ?

https://cucumber.io/docs/gherkin/languages/

Thanks in advance, Márcio

youtux commented 3 years ago

Currently pytest-bdd is not localized, sorry for that.

arqeco commented 3 years ago

Where in the pytest-bdd code someone must look for to try to implement localization ?

youtux commented 3 years ago

The parsing logic is not completely straight forward. I started reimplementing the parser with the idea to make many things (including localization) easier, but I didn't manage to complete it. I will probably start working on that again in the next month.

arqeco commented 3 years ago

I began studying BDD a few days and the code above is my first try.

Gherkin natural language is great!

So I believe I'll be writing my feature files mixing the prefixes of each line in English and the rest of the line in Portuguese. Not pretty, but it will be simple to use the text editor to replace the prefixes with Portuguese equivalents when pytest-bdd is ready for localization.

Thank you for your work @youtux

arqeco commented 3 years ago

Well, mixing languages in a feature file was not a good idea.

So now I am using this hook to create copies of the feature files, but with translated keywords, before the start of the tests.

tests/conftest.py

import pytest
import pathlib

def pytest_sessionstart(session):
    keywords = {
        "Feature": ["Funcionalidade", "Característica", "Caracteristica"],
        "Background": ["Contexto", "Cenário de Fundo", "Cenario de Fundo", "Fundo"],
        "Scenario": ["Cenário", "Cenario"],
        "ScenarioOutline": ["Esquema do Cenário", "Esquema do Cenario", "Delineação do Cenário", "Delineacao do Cenario"],
        "Examples": ["Exemplos", "Cenários", "Cenarios"],
        "Given": ["Dado", "Dada", "Dados", "Dadas"],
        "When": ["Quando"],
        "Then": ["Então", "Entao"],
        "And": ["E"],
        "But": ["Mas"]
    }
    path = pathlib.Path(__file__).parent.absolute()
    path_in = path / "features"
    path_out = path / "translated_features"
    if not path_out.exists():
        path_out.mkdir()
    feature_files = list(path_in.glob("*.feature"))
    for file in feature_files:
        output = path_out / file.name
        print(f"> Traduzindo {output}")
        f1 = open(file, "r", encoding="utf-8")
        lines = f1.readlines()
        for n in range(len(lines)):
            for key in keywords:
                for word in keywords[key]:
                    if lines[n].strip().startswith(word):
                        lines[n] = lines[n].replace(word, key)
        lines.insert(0, "# File automatically generated by pytest_sessionstart() in tests/conftest.py\n")
        with open(output, 'w', encoding="utf-8") as f2:
            f2.writelines(lines)

tests/step_defs/test_login.py

import pytest
from pytest_bdd import scenarios, given, when, then, parsers

# Scenarios
# scenarios("../features/login.feature")
scenarios("../translated_features/login.feature")

...
metallkopf commented 3 years ago

@youtux how about this? you wouldn't need to refactor the parser, just to add locales. it worked against @arqeco sample.

https://github.com/metallkopf/pytest-bdd/commit/608da77fa709dc84b2d4342b00d7ec1466a724b9

TheoAndersen commented 2 years ago

Hi @youtux or @graingert

I'm currently needing localization as well.

Would it be helpful to work more on this following @metallkopf's start?

elchupanebrej commented 1 year ago

Could you please check https://github.com/elchupanebrej/pytest-bdd-ng -it supports localization out the box