Random String Generator Functionality Testing

  • Share this:

Code introduction


This code defines a custom function `random_string` that generates a random string of a specified length. It also includes a unittest-based test class `TestRandomString` that tests the functionality of this function. The test class contains two test methods, one to test the length of the generated string and another to ensure the string contains only letters.


Technology Stack : unittest, random

Code Type : unittest

Code Difficulty : Intermediate


                
                    
import unittest
import random

def random_string(length=10):
    letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    return ''.join(random.choice(letters) for i in range(length))

class TestRandomString(unittest.TestCase):

    def test_random_string_length(self):
        """Ensure the length of the generated string matches the expected length."""
        self.assertEqual(len(random_string(10)), 10)

    def test_random_string_characters(self):
        """Ensure the generated string contains only letters."""
        random_str = random_string(10)
        self.assertTrue(all(char.isalpha() for char in random_str))

# Test case execution
if __name__ == '__main__':
    unittest.main()