"An approach to testing and logging multiple times in Python with the help of -nosetest and unittest

Here is a condensed version of the issue:

a = [[1,2,3][0,0,0]]
b = [[1,0,1][0,0,0]]
c = [[0,0,0][1,0,1]]

If level 1 is [] and level 2 is [[]], my goal is to compare every list to see if their level 2's match (disregarding order). In this example, b and c are considered equivalent.

I am utilizing unittesting and nosetests for running these comparisons. To evaluate one table against another, I would typically use:

The function truth() generates the tables for testing

def test_table1_table2(self):
    for row in truth(1,3):
        self.assertIn(row,truth(2,4))

However, I aim to compare all tables against each other (currently around 20 and growing). There are some challenges I am facing and unsure if I should refer to unittest docs or nose tests, or perhaps avoid them altogether!

My approach involves using nested loops to cover all possibilities. But when employing nosetest with assertIn, it halts at the first error, which is not my intended outcome. I need to identify which lists are equivalent (regardless of order or nested lists). Maybe I should create a custom solution without relying on unittests?

Ideally, I want the output to show:

table1 and table2 are not equivalent
table1 and table2 are not equivalent

Or a more concise format could be:

table1 and table10 are equivalent

Presented below is my current code, mostly numeric except for the truth() function that creates the truth table (nested list):

114     def test_all(self):$                                                  |~                      
115         ''' will test all tables'''$                                      |~                      
116         for expression in range(self.count_expressions()):$               |~                      
117             num_var = count_vars(exp_choose(expression))$                 |~                      
118             for row in truth(expression, num_var):$                       |~                      
119                 for expression2 in range(self.count_expressions()):$      |~                      
120                     num_var2 = count_vars(exp_choose(expression2))$       |~                      
121                     for row2 in truth(expression2, num_var2):$            |~                      
122                         self.assertIn(row, truth(expression2,num_var2))

Answer №1

A more streamlined method could involve utilizing the assertItemsEqual function from unittest, specifically designed for this scenario. Taking into account O.P.'s nested lists a, b, & c:

class CheckingEqualityIgnoreOrder(unittest.TestCase):
    def testAB(self):
        self.assertItemsEqual(a, b)
        #does not match

    def testBC(self):
        self.assertItemsEqual(b, c)
        #matches

    def testAC(self):
        self.assertItemsEqual(a, c)
        #does not match

Answer №2

Consider a different strategy: Move the outer loops outside of the test method and have the inner code construct new test methods within the test class.

For inspiration, take a look at this example: How to create dynamic (parametrized) unit tests in python?

Answer №3

Condensed version with improved readability:

def compare_sets(list1, list2):
  sets_list1 = map(set, list1)
  sets_list2 = map(set, list2)
  return ((sets_list1[0] == sets_list2[0]) and (sets_list1[1] == sets_list2[1])) \
      or ((sets_list1[0] == sets_list2[1]) and (sets_list1[1] == sets_list2[0]))

tables_dict = {}
tables_dict['a'] = [[1,2,3],[0,0,0]]
tables_dict['b'] = [[1,0,1],[0,0,0]]
tables_dict['c'] = [[0,0,0],[1,0,1]]
tables_dict['d'] = [[0,0,0],[1,1,0]]

for key_val1, val1 in tables_dict.items():
  for key_val2, val2 in tables_dict.items():
    result = 'equal' if compare_sets(val1, val2) else 'not equal'
    print '%s compared to %s is %s' % (key_val1, key_val2, result)

Although this could be further simplified using functions like map and zip, the main goal is to break down the code into smaller parts to reduce complexity.

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

Enhance the speed of Selenium testing by implementing these proven methods

While attempting to gather information from a website that hides full telephone numbers, I realized I needed to use selenium to search for the complete number. However, in order to retrieve the phone numbers faster, I found that it needs to sleep for 0.2 s ...

Flask static serving causes Vue app to not render

Currently, I am in the process of developing a basic web application utilizing Flask for the backend and Vue for the client side. Here is an overview of my folder structure: . ├── client/ │ ├── dist/ │ │ ├── css/ │ │ ...

Executing various animations at the same time on a single object using Manim

My task involves manipulating a Square by moving and scaling it simultaneously: sq = Square() self.add(sq) self.play(ApplyMethod(sq.scale, 0.5), ApplyMethod(sq.move_to, UP*3)) Unfortunately, the initial animation is not taking place and only the final one ...

ìdentifying Incomplete JSON Data using Python

I'm currently working on an innovative online weather web application. The goal of this app is to allow users to search for any city or town and instantly receive accurate weather statistics. However, I have encountered a hurdle in my project. The fre ...

When data is imported from an external spreadsheet into Heroku, the platform sometimes cuts off lines, not displaying the entire

After successfully deploying my project to Heroku as required by my institute, I noticed a major issue during testing. The problem arises when calling data from my spreadsheet and printing it to the terminal - only 4 out of the intended 8 columns are being ...

What could be causing the xpath to malfunction when using PhantomJS?

I am currently in the process of developing a web scraper that is required to extract pricing information from multiple websites. Since all of these websites utilize JavaScript to display prices, I opted to use selenium to gather the necessary data. Prio ...

What is the process for storing data attributes in a database?

I am in the process of developing a website and I have a requirement to store certain variables from HTML in a database. The main goal is to save the paragraphs of text that users select and display them when the user revisits the page (similar to medium.c ...

Struggling to make image uploading function with Flask and JQuery

Utilize the code snippet below to submit forms and retrieve a modified version of text from Flask using AJAX and JQuery: from flask import Flask, render_template, request, jsonify app = Flask(__name__) @app.route('/') def index(): return re ...

After successfully converting a column of objects into datetimes using pandas, I encountered an issue when saving the data to a CSV file and then reloading it - the column datatype reverted back to objects

My data: ids = [1, 2, 3, 4] start_time = ["2020-04-26 17:45:14", "2020-04-17 17:08:54", "2020-04-01 17:54:13", "2020-04-07 12:50:19"] df = pd.DataFrame({"id": ids, "started_at": star ...

Troubleshooting Issue: Selenium Python ActionChain not functioning due to element being unresponsive

I'm currently stuck on an issue with ActionChains. Despite my best efforts, I can't seem to get the mouse to move as intended. Any ideas or suggestions would be greatly appreciated. from selenium import webdriver from selenium.webdriver.common.ac ...

Unable to change string to floating point in pandas (ValueError)

I have a dataset obtained from a JSON output that appears as follows: Total Revenue Average Revenue Purchase count Rate Date Monday 1,304.40 CA$ 20.07 CA$ 2,345 1.54 % The values stored are in string format ...

Dividing a string while keeping the delimiters intact and avoiding any empty groups in the results

I need help with splitting a string without removing delimiters. I am trying to capture sentences that end in one or more '[!?]' characters using regex. However, I am facing an issue with unwanted empty capture groups. How can I suppress these em ...

do not continue loop if promise is rejected in AngularJS

I've attempted multiple methods, but still haven't found a solution to this issue. Within my code, there is a method called iterator that returns a promise; this method runs in a loop x number of times. If the iterator function returns a rejecte ...

Attempting to display sums in lists alongside strings in the output

Recently, I've been immersed in a Python project that involves analyzing data from a CSV file. However, I'm encountering an issue where the output only displays lists of numbers without summing them up alongside strings. Here's the code sni ...

Developing a Keras model with multiple outputs

Update: I have figured out a part of the solution, please see the conclusion of this post Following the creation of two distinct models for estimating the score of a mastermind player, my current goal is to develop a unified model with dual outputs: rcrp ...

What is the best way to handle serving static files in Django?

Currently, I am working on an E-commerce project using Django. In this project, there are two methods for adding images. The first method involves manually adding photos, but my goal is to allow users to automatically upload a photo of the product via stat ...

Tailored Collaborative Filtering

Currently, I am developing a recommendation engine using Python's surprise library. After testing user-based Collaborative Filtering (CF) and item-based CF, I am interested in exploring a collaborative filtering approach that does not rely on similari ...

Moving a Tkinter window without a frame leads to a glitch where the mouse cursor suddenly teleports to the top left corner of the window

My current method of moving the window involves using the move() function with the following code: window.overrideredirect(True) def move(event): window.geometry(f'+{event.x_root}+{event.y_root}') title_frame= Frame(window,bg='gray&apos ...

Tips for Displaying a Logo Animation at the Start of the Game

Could I display a logo before my game starts, similar to how the SEGA logo appears at the beginning of Sonic The Hedgehog? It would be awesome if this feature is possible! Thank you! ...

Unable to retrieve instrument information using PyVISA

I am attempting to interface with a Rohde & Schwarz signal generator using PyVISA. PyVISA information is as follows. C:\Python27\lib\site-packages\pyvisa\ctwrapper\functions.py:1222: VisaIOWarning: VI_WARN_CONFIG_NLOADED ( ...