civicrm-update-tester/civicrm_tester/contact_export.py

83 lines
3.1 KiB
Python

import csv
import io
from selenium.webdriver.common.keys import Keys
from .base import SearchExportTester
class ContactExport(SearchExportTester):
"""Tests if exporting contacts from a search returns a CSV file with all contacts."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.title("Contact Export")
self.desc(
"Testing if exporting contacts from a search returns a CSV file with all expected contacts."
)
self.contact_exportoption_id = "select2-result-label-15"
def download_csv(self):
# Data of the request that is specific for this export and not generic like qr_key
data = {
"_qf_Select_next": "Continue",
"exportOption": 1,
"mergeOption": 0,
"postal_greeting": 1,
"addressee": 1,
}
return self.download_export(data)
def calculate_exported_contacts_number(self) -> int:
"""
Downloads csv, opens it in a string buffer using StringIO and passes it to the csv lib
Counts number of rows (excl. header) and returns that value
"""
res = self.download_csv()
csv_file = io.StringIO(res.text)
# DictReader removes header from count
exported_csv = csv.DictReader(csv_file)
exported_number_exports = sum(1 for row in exported_csv)
self.debug(
"found %d rows in exported csv excluding header row" %
exported_number_exports
)
return exported_number_exports
def _test(self, search_term: str):
"""
Test Description:
Go to the contact search url
Search for the search term
Select all contacts and set them to export
Get the login cookie and search ID and download the export manually with requests
Save the file in tmp
Read it to check the number of exported contacts is the same as reported in the UI
"""
self.browser.get(self.search_url)
search_box = self.find_element_by_id("sort_name")
search_box.send_keys(search_term)
search_box.send_keys(Keys.ENTER)
self.debug("searching for contacts with term '%s'" % search_term)
self._wait_for_search_to_load()
result_no = self._get_contact_search_number()
self._select_option_from_magic_dropdown(self.contact_exportoption_id)
exported_number_exports = self.calculate_exported_contacts_number()
if exported_number_exports == (result_no):
self.passed(
"Number of expected contact exports for '%s' matches actual number of exports - Expected: %d, Actual: %d"
% (search_term, result_no, exported_number_exports)
)
else:
self.failed(
"Number of expected contact exports for '%s' WAS NOT EQUAL to actual number of exports - Expected: %d, Actual: %d"
% (search_term, result_no, exported_number_exports)
)
def test_hardcoded_search_terms(self):
"""Loops over the test with three hardcoded search terms"""
search_terms = ("John", "e", "Smith")
self._test_all(search_terms)