A Python program for testing with Unittest, including input and output file capabilities

I have created a program that consists of one function. This function takes a file as input and writes the result to an output file. I now need to test whether the result matches the expected output. Below is the code for the program:

import os

def username(input):
    with open(input, 'r') as file:
        if os.stat(input).st_size == 0:
             print('File is empty')
        else:
             print('File is not empty')
             for line in file:
                 count = 1
                 id, first, middle, surname, department = line.split(":")  
                 first1 = first.lower()
                 middle1 = middle.lower()
                 surname1 = surname.lower()
                 username = first1[:1] + middle1[:1] + surname1
                 username1 = username[:8]

                 if username1 not in usernames:
                      usernames.append(username1)
                      data = id + ":" + username1 + ":" + first + ":" + middle + ":" + surname + ":" + department
                 else:
                      username2 = username1 + str(count)
                      usernames.append(username2)
                      data = id + ":" + username2 + ":" + first + ":" + middle + ":" + surname + ":" + department
                      count += 1


                 with open("output.txt", "a+") as username_file:
                      username_file.write(data)


usernames = []

if __name__ == '__main__':
     username("input_file1.txt")
     username("input_file2.txt")
     username("input_file3.txt")
     with open("output.txt", "a+") as username_file:
          username_file.write("\n")

I am trying to write unittests for this program but encountering an error "TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper". Below is the code for my test:

import unittest
import program.py

class TestProgram(unittest.TestCase):
    def test_username(self):
        i_f = open("input_file1.txt", 'r')
        result = program.username(i_f)
        o_f = open("expected_output.txt", 'r')
        self.assertEqual(result, o_f)

if __name__ == '__main__':
    unittest.main()

I would greatly appreciate any help you can provide on resolving this issue!!!

Answer №1

Just passing the IO object without reading the file won't work.

To fix this issue, make sure to edit TestProgram and include the .read() method.

class TestProgram(unittest.TestCase):
    def test_username(self):
        with open("input_file1.txt", 'r') as i_f:
            file_contents = i_f.read() # read the file
            result = program.username(file_contents)
        with open("expected_output.txt", 'r') as o_f:
            expected_result = o_f.read()
        self.assertEqual(result, expected_result)

An alternative solution is using the with-as syntax for automatic file closing.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When attempting to scrape a website, some content may not be visible within the page source

Currently, I am facing a challenge in extracting information from a specific website: . The data is structured in repeating cards, yet I cannot seem to find the details within the page source. Despite my efforts with tools like Selenium's web driver, ...

Utilizing Scikit-image for extracting features from images

I have been using scikit-image to successfully classify road features. Take a look at the results here: https://i.stack.imgur.com/zRJNh.jpg. However, I am facing challenges in the next step of classifying these features. Specifically, I need to classify fe ...

Seeking assistance with an assignment for school

My computer science class assigned me with creating a number guessing game. While I have successfully written the program, I am facing challenges in solving certain issues that arose during its development. Here is my code snippet: import random print( ...

Obtaining a series of coordinates from a Numpy array

I have a 100x100x100 numpy array that represents a 3D volume composed of 2D slices. My goal is to conduct cross correlation on the object in this volume across multiple volumes using a template derived from the volume with the best signal-to-noise ratio. ...

Tips for extracting HTML text with Python and Selenium

Utilizing Python's Selenium module, I am attempting to extract text and store it in a list or dataframe. Specifically, I am looking to retrieve the text "M" from a class named "flex". Once obtained, I want to input this along with another item into a ...

Wagtail user access control for various users granted

Within my wagtail app, I am working on a model that needs to be accessible only to specific types of users. In django, I would typically use the UserPassesTestMixin for this purpose. However, in wagtail, I plan to base access on session data instead. If th ...

Python script that automatically selects and downloads the right version of chromedriver for Selenium

Unfortunately, Chromedriver is always specific to the version of Chrome you have installed. This means that when you use PyInstaller to package your Python code and a chromedriver into a deployable .exe file for Windows, it may not work properly because yo ...

What is causing abandoned PhantomJS processes to be left behind by nose tests on Windows 8?

I'm currently running Python Selenium nose tests on Windows 8 with PhantomJS. To install Chutzpah (PhantomJS), I used Chocolatey. When executing the nose tests, a "ShimGen" process emerges along with numerous "PhantomJS is a headless WebKit with Java ...

Utilize a Python script to transmit data to JavaScript through JSON in order to dynamically alter the content of

Currently, I am developing an interactive display that utilizes sensors on a raspberry pi. The display is set to show a webpage and I have implemented a python script to handle sensor interaction. My goal is to change the displayed web page when a user p ...

Guide for testing URL connectivity using Python

My scenario is similar to the one described in this Stack Overflow post. However, I want to log an error message if the URL cannot be reached. Here's my attempt: # Defining the URL and checking the connection by printing the status url = 'https ...

Transferring hash functions from php's crypt() to Python

Is there a python equivalent to PHP's crypt() function that generates a random salt and embeds it within the saved string? I have a table of hashed passwords created with the $5$ string key for a SHA256 based salted cryptogram. These hashes include a ...

Tips for efficiently determining the position of an element within a strictly increasing list in Python

My initial thought is to iterate through the list, but with the possibility of it growing as large as 1000000, that could be highly inefficient. UPDATE: I am aware of binary search as well. I'm curious if there exists a built-in Python function that ...

Ways to achieve a zoom out effect on a webpage by using Python with Selenium

Can someone provide guidance on zooming out one level after making a GET request in Python? I found the following code snippet for Java: WebElement html = driver.findElement(By.tagName("html")); html.sendKeys(Keys.chord(Keys.CONTROL, Keys.ADD)); ...

Python script encounters syntax error when attempting to install Pip

While attempting to install Pip according to the documentation, I ran get-pip.py and encountered an error. My Python version is 3.2.3. Any suggestions on what steps I should take next? Warning (from warnings module): File "c:\users\ut601039&bs ...

Executing multiple functions concurrently in Python

My IRC channel has a bot that I want to use to remind users of the current time while maintaining interactivity. The script is as follows: *code for logging into the server* def process1(): while 1: time = datetime.datetime.now().time() ...

How to verify if an object exists in two separate lists using Python and Django

Profiles come with tags. In order to render a list of profile_tags and top_tags, I am looking for a way to verify if each tag in top_tags is included in profile_tags. Here's what I've attempted in my views: has_tag = False profile_tags = profil ...

The 'User' object does not contain the attribute 'is_valid' in Django

I am currently developing a registration form for users to sign up using Django 1.8 and Python 3.5 To enhance the default Django Users table with additional fields such as bio, date of birth, etc., I have created a User model by extending the AbstractUser ...

What is the best way to execute a Druid SQL query with the "timeseries" function in pydruid?

I have written the following code in Druid SQL and my objective is to execute it from Python. While I am currently able to do so using DB API, I am curious if there is a way to achieve this using the hydroid function "timeseries" as it would integrate bett ...

Having difficulty generating a virtualenv instance in Python 2.7.5 due to an error during pip installation

As I was following the Flask installation instructions on the website, I ran into an issue after executing "sudo easy_install virtualenv" to set up a virtual environment. Not sure what went wrong. Opals-MacBook-Pro:~ opalkale$ mkdir myproject Opals-MacB ...

How can I substitute the characters r'xb0' with r'260' in Python?

Is there a way to replace the characters r'\xb0' with r'\260' in a string? I have attempted it using the following code: test = u'\xb0C' test = test.encode('latin1') test = test.replace(r'\x ...