DEV Community

Cover image for Developing a Program with Test Driven Development
Elias Elikem Ifeanyi Dzobo
Elias Elikem Ifeanyi Dzobo

Posted on

Developing a Program with Test Driven Development

Test-driven development (TDD) is a software development process that emphasizes writing automated tests before writing code. In this approach, the developer writes a failing test case that specifies the behavior they want to implement, and then writes the minimum amount of code needed to make the test pass. The process is then repeated, with new test cases being added and the code being updated to pass them.

One of the key benefits of TDD is that it helps ensure that code is reliable and meets the intended specifications. By writing tests first, the developer is forced to think carefully about the expected behavior of their code and to consider edge cases and potential errors. This can help catch bugs early in the development process, when they are easier and cheaper to fix.

Using a Test Driven Development approach, we would be implementing a program that collates news feeds on particular topics of interest. Considering the fast pace at which technology improves, staying up to date with the latest news and updates is a must, however it can be quite tasking to check for news articles daily. In this article, we’ll be exploring developing a program to collate news articles using newsapi and a test driven development approach.

Setting up an Environment

The first step is setting up a development environment. We’ll be using python to develop this program so we’ll be setting a virtual environment to develop in. Setting up a Python virtual environment is a best practice for developing Python applications. It helps to isolate dependencies, avoid conflicts between different versions of libraries, and keep the system Python environment clean. Here are the steps to set up a Python virtual environment:

  1. Open a terminal or command prompt on your computer.
  2. Install the virtualenv package by typing the following command and pressing Enter:
pip install virtualenv
Enter fullscreen mode Exit fullscreen mode
  1. Create a new folder where you want to keep your virtual environment, and navigate to that folder using the cd command.
  2. Create a virtual environment by typing the following command and pressing Enter:
virtualenv venv
Enter fullscreen mode Exit fullscreen mode

This will create a new folder called venv
in the current directory, containing a fresh Python installation and a pip
executable for installing packages.

  1. Activate the virtual environment by typing the following command and pressing Enter:
source venv/bin/activate
Enter fullscreen mode Exit fullscreen mode

On Windows, the command is slightly different:

venv\Scripts\activate
Enter fullscreen mode Exit fullscreen mode

Activating the virtual environment will modify your system's PATH environment variable to use the Python installation and packages in the virtual environment.

  1. You can now install packages using pip as usual, and they will be installed only in the virtual environment, not globally on your system. For example, to install the newsapi package, type the following command and press Enter:
pip install newsapi-python
Enter fullscreen mode Exit fullscreen mode

Writing our Test cases

The next step is to write the test cases that will define the functionality of our program. Test-driven development (TDD) is a software development approach that emphasizes writing tests before writing the actual code. This approach helps ensure that the code meets the intended specifications and catches any issues early in the development process.

For our program, we'll define a set of test cases that cover the following functionality:

  1. Retrieving news articles on a specific topic
  2. Sorting news articles by date
  3. Filtering news articles by source
  4. Limiting the number of articles returned

Here's an example of a test case that retrieves news articles on a specific topic:

import unittest
from newsapi import NewsApiClient

class NewsAPITestCase(unittest.TestCase):

    def setUp(self):
        self.api_key = 'your_api_key_here'
        self.newsapi = NewsApiClient(api_key=self.api_key)

    def test_retrieve_news_articles(self):
        topic = 'artificial intelligence'
        response = self.newsapi.get_everything(q=topic)
        articles = response['articles']
        self.assertTrue(len(articles) > 0, f"No news articles found on {topic}")
Enter fullscreen mode Exit fullscreen mode

This test case checks that the API returns at least one news article when searching for articles related to 'artificial intelligence'.

Writing the Code

With our test cases defined, we can now write the code to implement the desired functionality. For each test case, we'll write the minimum amount of code necessary to make the test pass. This iterative process of writing tests and then implementing the code is the foundation of TDD.

Here's an example implementation of the test case we defined earlier:

def get_news_articles(topic, sources=None, sort_by='publishedAt', limit=None):
    response = newsapi.get_everything(q=topic, sources=sources, sort_by=sort_by, page_size=limit)
    articles = response['articles']
    return articles
Enter fullscreen mode Exit fullscreen mode

This function takes a topic as input and returns a list of news articles that match the topic. If sources are specified, it filters the results to only include articles from those sources. The articles are sorted by the published date, with the most recent articles appearing first. Finally, if a limit is specified, it only returns that number of articles.

Running the Tests

With our code implemented, we can now run the test suite to ensure that everything is working correctly. To do this, we'll use a testing framework such as unittest to run our tests.

if __name__ == '__main__':
    unittest.main()
Enter fullscreen mode Exit fullscreen mode

Running the test suite should produce output similar to the following:

----------------------------------------------------------------------
Ran 1 test in 0.058s

OK
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this article, we explored using Test Driven Development to create a program that collates news articles about a particular topic.

Top comments (0)