|
| 1 | +# Part of OpenSPP. See LICENSE file for full copyright and licensing details. |
| 2 | + |
| 3 | +from unittest.mock import patch |
| 4 | + |
| 5 | +from odoo.tests import TransactionCase, tagged |
| 6 | + |
| 7 | +from odoo.addons.queue_job.exception import FailedJobError |
| 8 | + |
| 9 | +from ..models.base_import import ImportValidationError |
| 10 | + |
| 11 | +OPTIONS = { |
| 12 | + "import_skip_records": [], |
| 13 | + "import_set_empty_fields": [], |
| 14 | + "fallback_values": {}, |
| 15 | + "name_create_enabled_fields": {}, |
| 16 | + "encoding": "utf-8", |
| 17 | + "separator": ",", |
| 18 | + "quoting": '"', |
| 19 | + "date_format": "", |
| 20 | + "datetime_format": "", |
| 21 | + "float_thousand_separator": ",", |
| 22 | + "float_decimal_separator": ".", |
| 23 | + "advanced": True, |
| 24 | + "has_headers": True, |
| 25 | + "keep_matches": False, |
| 26 | + "limit": 2000, |
| 27 | + "sheets": [], |
| 28 | + "sheet": "", |
| 29 | + "skip": 0, |
| 30 | + "tracking_disable": True, |
| 31 | +} |
| 32 | + |
| 33 | + |
| 34 | +@tagged("post_install", "-at_install") |
| 35 | +class TestBaseImportMethods(TransactionCase): |
| 36 | + """Test SPPBaseImport helper methods.""" |
| 37 | + |
| 38 | + @classmethod |
| 39 | + def setUpClass(cls): |
| 40 | + super().setUpClass() |
| 41 | + cls.csv_options = { |
| 42 | + "separator": ",", |
| 43 | + "quoting": '"', |
| 44 | + "encoding": "utf-8", |
| 45 | + } |
| 46 | + cls.import_record = cls.env["base_import.import"].create( |
| 47 | + { |
| 48 | + "res_model": "res.partner", |
| 49 | + "file_name": "test.csv", |
| 50 | + } |
| 51 | + ) |
| 52 | + |
| 53 | + def test_csv_attachment_roundtrip(self): |
| 54 | + """_create_csv_attachment + _read_csv_attachment round-trip.""" |
| 55 | + fields_in = ["name", "email"] |
| 56 | + data_in = [["Alice", "alice@test.com"], ["Bob", "bob@test.com"]] |
| 57 | + attachment = self.import_record._create_csv_attachment(fields_in, data_in, self.csv_options, "roundtrip.csv") |
| 58 | + self.assertTrue(attachment.id) |
| 59 | + self.assertEqual(attachment.name, "roundtrip.csv") |
| 60 | + fields_out, data_out = self.import_record._read_csv_attachment(attachment, self.csv_options) |
| 61 | + self.assertEqual(fields_out, fields_in) |
| 62 | + self.assertEqual(len(data_out), 2) |
| 63 | + self.assertEqual(data_out[0], ["Alice", "alice@test.com"]) |
| 64 | + self.assertEqual(data_out[1], ["Bob", "bob@test.com"]) |
| 65 | + |
| 66 | + def test_csv_attachment_custom_options(self): |
| 67 | + """_create/_read_csv_attachment with custom separator/quoting/encoding.""" |
| 68 | + custom_options = { |
| 69 | + "separator": ";", |
| 70 | + "quoting": "'", |
| 71 | + "encoding": "latin-1", |
| 72 | + } |
| 73 | + fields_in = ["name", "email"] |
| 74 | + data_in = [["TestAccent", "accent@test.com"]] |
| 75 | + attachment = self.import_record._create_csv_attachment(fields_in, data_in, custom_options, "custom.csv") |
| 76 | + fields_out, data_out = self.import_record._read_csv_attachment(attachment, custom_options) |
| 77 | + self.assertEqual(fields_out, fields_in) |
| 78 | + self.assertEqual(data_out[0][0], "TestAccent") |
| 79 | + |
| 80 | + def test_extract_chunks_basic(self): |
| 81 | + """_extract_chunks splits data into chunks >= chunk_size.""" |
| 82 | + model_obj = self.env["res.partner"] |
| 83 | + fields = ["name", "email"] |
| 84 | + data = [[f"P{i}", f"p{i}@test.com"] for i in range(7)] |
| 85 | + chunks = list(self.env["base_import.import"]._extract_chunks(model_obj, fields, data, 3)) |
| 86 | + self.assertTrue(len(chunks) > 1) |
| 87 | + # All rows should be covered |
| 88 | + all_rows = set() |
| 89 | + for start, end in chunks: |
| 90 | + for r in range(start, end + 1): |
| 91 | + all_rows.add(r) |
| 92 | + self.assertEqual(all_rows, set(range(7))) |
| 93 | + |
| 94 | + def test_extract_chunks_small_data(self): |
| 95 | + """_extract_chunks with data smaller than chunk_size yields one chunk.""" |
| 96 | + model_obj = self.env["res.partner"] |
| 97 | + fields = ["name", "email"] |
| 98 | + data = [["A", "a@test.com"], ["B", "b@test.com"]] |
| 99 | + chunks = list(self.env["base_import.import"]._extract_chunks(model_obj, fields, data, 100)) |
| 100 | + self.assertEqual(len(chunks), 1) |
| 101 | + self.assertEqual(chunks[0], (0, 1)) |
| 102 | + |
| 103 | + def test_import_one_chunk_success(self): |
| 104 | + """_import_one_chunk loads data successfully.""" |
| 105 | + attachment = self.import_record._create_csv_attachment( |
| 106 | + ["name"], [["ChunkSuccess99xyz"]], self.csv_options, "chunk.csv" |
| 107 | + ) |
| 108 | + result = self.import_record._import_one_chunk("res.partner", attachment, self.csv_options, {}) |
| 109 | + errors = [m for m in result["messages"] if m.get("type") == "error"] |
| 110 | + self.assertFalse(errors) |
| 111 | + partner = self.env["res.partner"].search([("name", "=", "ChunkSuccess99xyz")]) |
| 112 | + self.assertEqual(len(partner), 1) |
| 113 | + |
| 114 | + def test_import_one_chunk_error(self): |
| 115 | + """_import_one_chunk raises FailedJobError on load errors.""" |
| 116 | + attachment = self.import_record._create_csv_attachment(["name"], [["ErrTest"]], self.csv_options, "err.csv") |
| 117 | + error_result = { |
| 118 | + "messages": [{"type": "error", "message": "Test error"}], |
| 119 | + "ids": [], |
| 120 | + } |
| 121 | + with patch.object(type(self.env["res.partner"]), "load", return_value=error_result): |
| 122 | + with self.assertRaises(FailedJobError): |
| 123 | + self.import_record._import_one_chunk("res.partner", attachment, self.csv_options, {}) |
| 124 | + |
| 125 | + def test_import_validation_error_attributes(self): |
| 126 | + """ImportValidationError stores field, type, and message attrs.""" |
| 127 | + err = ImportValidationError("Bad value", field="name", error_type="warning", field_type="char") |
| 128 | + self.assertEqual(str(err), "Bad value") |
| 129 | + self.assertEqual(err.message, "Bad value") |
| 130 | + self.assertEqual(err.type, "warning") |
| 131 | + self.assertEqual(err.field_path, ["name"]) |
| 132 | + self.assertEqual(err.field_type, "char") |
| 133 | + self.assertFalse(err.record) |
| 134 | + self.assertTrue(err.not_matching_error) |
| 135 | + # Test defaults |
| 136 | + err2 = ImportValidationError("Default error") |
| 137 | + self.assertEqual(err2.type, "error") |
| 138 | + self.assertFalse(err2.field_path) |
| 139 | + self.assertIsNone(err2.field_type) |
| 140 | + |
| 141 | + def test_execute_import_with_match_ids_passes_context(self): |
| 142 | + """execute_import passes import_match_ids and overwrite_match to context.""" |
| 143 | + res_partner_model = self.env["ir.model"].search([("model", "=", "res.partner")]) |
| 144 | + name_field = self.env["ir.model.fields"].search( |
| 145 | + [("name", "=", "name"), ("model_id", "=", res_partner_model.id)] |
| 146 | + ) |
| 147 | + self.env["res.partner"].create({"name": "ExecMatchTest99xyz", "email": "exec@test.com"}) |
| 148 | + match = self.env["spp.import.match"].create({"model_id": res_partner_model.id, "overwrite_match": True}) |
| 149 | + self.env["spp.import.match.fields"].create({"field_id": name_field.id, "match_id": match.id}) |
| 150 | + import_rec = self.env["base_import.import"].create( |
| 151 | + { |
| 152 | + "res_model": "res.partner", |
| 153 | + "file": b"name,email\nExecMatchTest99xyz,updated@test.com", |
| 154 | + "file_name": "test_exec.csv", |
| 155 | + "file_type": "csv", |
| 156 | + } |
| 157 | + ) |
| 158 | + options = dict(OPTIONS) |
| 159 | + options["import_match_ids"] = [match.id] |
| 160 | + options["overwrite_match"] = True |
| 161 | + result = import_rec.execute_import(["name", "email"], [], options, dryrun=True) |
| 162 | + self.assertIn("import_match_counts", result) |
| 163 | + self.assertEqual(result["import_match_counts"]["overwritten"], 1) |
0 commit comments