Python – How to compare two csv files using the Robot Framework

How to compare two csv files using the Robot Framework… here is a solution to the problem.

How to compare two csv files using the Robot Framework

I want to compare the differences between two csv files that use the bot framework. If there is a difference, the test case should fail, and if there is no difference, it passes. I’ve tried DiffLibrary in the Robot framework, but returns a pass status when the records are unsorted. Can someone guide me on how to achieve this or if there is any alternative way to do this.

My first.csv file has the following data

Benchmark Name,Policy Name,No of Rules,Policy Measurement SLO,Policy Remediation SLO,No of Rules Compliant in MSLO,No of Rules Non-Compliant in RSLO,No of Rules Non-Compliant OUT RSLO
CIS Red Hat Enterprise Linux 6 Benchmark v1.0.0,PCI,281,1 MONTHS,1 MONTHS,150,130
CIS Red Hat Enterprise Linux 7 Benchmark v1.2.0,PCI,281,5 MONTHS,1 MONTHS,150,137
CIS Red Hat Enterprise Linux 7 Benchmark v1.5.0,PCI,281,1 MONTHS,1 MONTHS,150,135

My second.csv file contains the following data

Benchmark Name,Policy Name,No of Rules,Policy Measurement SLO,Policy Remediation SLO,No of Rules Compliant in MSLO,No of Rules Non-Compliant in RSLO,No of Rules Non-Compliant OUT RSLO
CIS Red Hat Enterprise Linux 7 Benchmark v1.2.0,PCI,281,5 MONTHS,1 MONTHS,150,137
CIS Red Hat Enterprise Linux 6 Benchmark v1.0.0,PCI,281,1 MONTHS,1 MONTHS,150,130
CIS Red Hat Enterprise Linux 7 Benchmark v1.5.0,PCI,281,1 MONTHS,1 MONTHS,150,135

The bot code is as follows

*** Settings ***
Library  DiffLibrary
Library  OperatingSystem

 Test Cases ***

Diffing two files one being different
    Run Keyword And Expect Error  differences*  Diff Files  first.csv  second.csv

Solution

How about Should Be Equal As Strings using only BuiltIn?

# Using Get File you easily get a file's content into a string variable
${csvA} =    Get File    ${filePathA}
${csvB} =    Get File    ${filePathB}
Should Be Equal As Strings    ${csvA}    ${csvB}

I’m only using that model to compare lines, and you may need to edit the file string in case the file encoding is different (the BOM leaves a special BOM character at the beginning of the file, etc.).

Related Problems and Solutions