BDD Random Sentence Generator with Behave

  • Share this:

Code introduction


This function is a Behavior-Driven Development (BDD) function based on the Behave library, which is used to generate a random sentence. It includes three steps: Given a user, When the user generates a random sentence, and Then check if the sentence contains at least three words.


Technology Stack : Behave

Code Type : Behavior-Driven Testing (BDD) function

Code Difficulty : Intermediate


                
                    
def generate_random_sentence():
    import random
    from behave import Given, When, Then

    @Given('a user')
    def a_user(context):
        context.user = "Alice"

    @When('the user generates a random sentence')
    def the_user_generates_a_random_sentence(context):
        words = ["the", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]
        context.sentence = " ".join(random.sample(words, random.randint(3, 7)))

    @Then('the sentence should contain at least three words')
    def the_sentence_should_contain_at_least_three_words(context):
        assert len(context.sentence.split()) >= 3                
              
Tags: