ckanext-xloader 2.5.0__tar.gz → 2.5.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. {ckanext_xloader-2.5.0/ckanext_xloader.egg-info → ckanext_xloader-2.5.2}/PKG-INFO +1 -1
  2. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/cli.py +1 -1
  3. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/db.py +13 -7
  4. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/loader.py +85 -11
  5. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/parser.py +8 -2
  6. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/plugin.py +3 -10
  7. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/tests/test_action.py +42 -15
  8. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/tests/test_db.py +11 -1
  9. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/tests/test_loader.py +67 -2
  10. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2/ckanext_xloader.egg-info}/PKG-INFO +1 -1
  11. ckanext_xloader-2.5.2/dev-requirements.txt +8 -0
  12. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/pyproject.toml +1 -1
  13. ckanext_xloader-2.5.2/requirements.txt +11 -0
  14. ckanext_xloader-2.5.0/dev-requirements.txt +0 -8
  15. ckanext_xloader-2.5.0/requirements.txt +0 -11
  16. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/CHANGELOG +0 -0
  17. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/LICENSE +0 -0
  18. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/MANIFEST.in +0 -0
  19. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/README.md +0 -0
  20. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/__init__.py +0 -0
  21. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/__init__.py +0 -0
  22. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/action.py +0 -0
  23. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/auth.py +0 -0
  24. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/command.py +0 -0
  25. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/config_declaration.yaml +0 -0
  26. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/helpers.py +0 -0
  27. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/interfaces.py +0 -0
  28. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/job_exceptions.py +0 -0
  29. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/jobs.py +0 -0
  30. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/schema.py +0 -0
  31. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/templates/datastore/snippets/dictionary_form.html +0 -0
  32. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/templates/package/resource_edit_base.html +0 -0
  33. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/templates/package/resource_read.html +0 -0
  34. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/templates/package/snippets/resource_info.html +0 -0
  35. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/templates/package/snippets/resource_item.html +0 -0
  36. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/templates/package/snippets/resources.html +0 -0
  37. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/templates/xloader/confirm_datastore_delete.html +0 -0
  38. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/templates/xloader/resource_data.html +0 -0
  39. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/tests/__init__.py +0 -0
  40. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/tests/ckan_setup.py +0 -0
  41. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/tests/fixtures.py +0 -0
  42. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/tests/test_chunks.py +0 -0
  43. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/tests/test_jobs.py +0 -0
  44. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/tests/test_parser.py +0 -0
  45. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/tests/test_plugin.py +0 -0
  46. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/tests/test_utils.py +0 -0
  47. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/utils.py +0 -0
  48. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/views.py +0 -0
  49. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/webassets/css/xloader.css +0 -0
  50. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext/xloader/webassets/webassets.yml +0 -0
  51. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext_xloader.egg-info/SOURCES.txt +0 -0
  52. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext_xloader.egg-info/dependency_links.txt +0 -0
  53. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext_xloader.egg-info/entry_points.txt +0 -0
  54. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext_xloader.egg-info/requires.txt +0 -0
  55. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/ckanext_xloader.egg-info/top_level.txt +0 -0
  56. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/setup.cfg +0 -0
  57. {ckanext_xloader-2.5.0 → ckanext_xloader-2.5.2}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ckanext-xloader
3
- Version: 2.5.0
3
+ Version: 2.5.2
4
4
  Summary: Express Loader - quickly load data into CKAN DataStore
5
5
  Author: David Read (davidread), Patricio Del Boca (pdelboca)
6
6
  Author-email: ThrawnCA <carl.antuar@smartservice.qld.gov.au>, "Jesse Vickery (JVickery-TBS)" <jesse.vickery@tbs-sct.gc.ca>, "Adrià Mercader (amercader)" <amercadero@gmail.com>, "Brett Jones (kowh-ai)" <datashades@linkdigital.com.au>, "William Dutton (duttonw)" <william.dutton@qld.gov.au>
@@ -27,7 +27,7 @@ def status():
27
27
  @click.option('-y', is_flag=True, default=False, help='Always answer yes to questions')
28
28
  @click.option('--dry-run', is_flag=True, default=False, help='Don\'t actually submit any resources')
29
29
  @click.option('--queue', help='Queue name for asynchronous processing, unused if executing immediately')
30
- @click.option('--sync', is_flag=True, default=False,
30
+ @click.option('-s', '--sync', is_flag=True, default=False,
31
31
  help='Execute immediately instead of enqueueing for asynchronous processing')
32
32
  def submit(dataset_spec, y, dry_run, queue, sync):
33
33
  """
@@ -36,13 +36,19 @@ def init(config, echo=False):
36
36
 
37
37
  """
38
38
  global ENGINE, _METADATA, JOBS_TABLE, METADATA_TABLE, LOGS_TABLE
39
- db_uri = config.get('ckanext.xloader.jobs_db.uri',
40
- 'sqlite:////tmp/xloader_jobs.db')
41
- ENGINE = sqlalchemy.create_engine(db_uri, echo=echo)
42
- _METADATA = sqlalchemy.MetaData()
43
- JOBS_TABLE = _init_jobs_table()
44
- METADATA_TABLE = _init_metadata_table()
45
- LOGS_TABLE = _init_logs_table()
39
+ if ENGINE is None:
40
+ db_uri = config.get('ckanext.xloader.jobs_db.uri',
41
+ 'sqlite:////tmp/xloader_jobs.db')
42
+ ENGINE = sqlalchemy.create_engine(db_uri, echo=echo)
43
+ if _METADATA is None:
44
+ _METADATA = sqlalchemy.MetaData()
45
+ if JOBS_TABLE is None:
46
+ JOBS_TABLE = _init_jobs_table()
47
+ if METADATA_TABLE is None:
48
+ METADATA_TABLE = _init_metadata_table()
49
+ if LOGS_TABLE is None:
50
+ LOGS_TABLE = _init_logs_table()
51
+
46
52
  _METADATA.create_all(ENGINE)
47
53
 
48
54
 
@@ -40,7 +40,7 @@ def _notify_datastore_before_update(resource_id, existing_fields, new_headers):
40
40
  new_headers=new_headers,
41
41
  )
42
42
 
43
- from ckan.plugins.toolkit import config
43
+ from ckan.plugins.toolkit import config, _
44
44
 
45
45
  import ckanext.datastore.backend.postgres as datastore_db
46
46
 
@@ -54,8 +54,8 @@ tabulator_config.CSV_SAMPLE_LINES = CSV_SAMPLE_LINES
54
54
  SINGLE_BYTE_ENCODING = 'cp1252'
55
55
 
56
56
 
57
- def _should_keep_cell(index, cell, header_count):
58
- """Decide what to do with a cell whose position may exceed the headers.
57
+ def _should_keep_cell(index, cell, header_count, row_number=None):
58
+ """Return whether a cell should be kept, given it may exceed the headers.
59
59
 
60
60
  Some exporters (notably Microsoft Excel) append extra empty cells to the
61
61
  header and/or body, so a row can be wider than the declared columns. Blank
@@ -63,7 +63,8 @@ def _should_keep_cell(index, cell, header_count):
63
63
  matches the column count.
64
64
 
65
65
  Shared by both load paths (``load_csv`` and ``load_table``) so they treat
66
- surplus cells identically.
66
+ surplus cells identically. When ``row_number`` is given (the file line the
67
+ user sees), it is included in the error to help locate the problem.
67
68
 
68
69
  :returns: ``True`` if the cell is within the declared columns and should be
69
70
  used, ``False`` if it is a surplus blank cell that should be ignored.
@@ -76,9 +77,24 @@ def _should_keep_cell(index, cell, header_count):
76
77
  # row genuinely has more data than the header describes.
77
78
  if cell is None or str(cell).strip() == '':
78
79
  return False
79
- raise LoaderError(
80
- "Found data in column %s but resource only has %s header(s)"
81
- % (index + 1, header_count))
80
+ # A surplus cell holding real data usually means one of the values in the
81
+ # row contained a comma or a double-quote that wasn't wrapped in quotes,
82
+ # which split it into extra columns. Explain that, and point at the offending
83
+ # value (and the row, when we know it) to help the publisher fix the file.
84
+ # The lead falls back to "A row has..." when we don't know the row, and
85
+ # names it ("Row 3 has...") when we do; the rest of the guidance is shared.
86
+ if row_number is None:
87
+ lead = _("A row has more values than the {columns} column(s) in the "
88
+ "header.").format(columns=header_count)
89
+ else:
90
+ lead = _("Row {row} has more values than the {columns} column(s) in "
91
+ "the header.").format(row=row_number, columns=header_count)
92
+ detail = _(
93
+ "The extra value is: '{value}'. This usually means a value in the row "
94
+ "contains a comma or double-quote that is not wrapped in double-quotes, "
95
+ "splitting it into extra columns. If the file genuinely has an extra "
96
+ "column, add it to the header row.").format(value=cell)
97
+ raise LoaderError(lead + " " + detail)
82
98
 
83
99
 
84
100
  class FieldMatch(Enum):
@@ -289,6 +305,44 @@ def split_copy_by_size(input_file, engine, logger, resource_id, headers, delimit
289
305
  cleanup_temp_file(infile)
290
306
 
291
307
 
308
+ # Explicit map of the tabular mimetypes we support to the short format name
309
+ # tabulator expects. Used only as a fallback when the file extension didn't
310
+ # yield a readable format.
311
+ #
312
+ # The previous fallback took the part of the mimetype after '/', but that part
313
+ # isn't always the file extension: for example
314
+ # 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' gives
315
+ # 'vnd.openxmlformats-...sheet' rather than 'xlsx', which tabulator can't open
316
+ # and then reports the misleading "doesn't have a sheet 1" instead of the real
317
+ # cause. Listing every supported mimetype (even ones like 'text/csv' where the
318
+ # suffix already happens to be the extension) keeps this a single, explicit
319
+ # source of truth and independent of whatever the suffix fallback produces.
320
+ MIMETYPE_FORMATS = {
321
+ 'text/csv': 'csv',
322
+ 'application/csv': 'csv',
323
+ 'text/tab-separated-values': 'tsv',
324
+ 'application/vnd.ms-excel': 'xls',
325
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',
326
+ 'application/vnd.oasis.opendocument.spreadsheet': 'ods',
327
+ }
328
+
329
+
330
+ def _format_from_mimetype(mimetype):
331
+ """Best-effort short format name (csv/xls/xlsx/...) from a mimetype.
332
+
333
+ Looks the mimetype up in ``MIMETYPE_FORMATS`` first. Only for an unknown
334
+ mimetype does it fall back to the substring after the last '/' (the
335
+ historical behaviour), which is correct when that suffix happens to be the
336
+ file extension but not otherwise.
337
+ """
338
+ if not mimetype:
339
+ return None
340
+ key = mimetype.lower().split(';')[0].strip()
341
+ if key in MIMETYPE_FORMATS:
342
+ return MIMETYPE_FORMATS[key]
343
+ return key.split('/')[-1]
344
+
345
+
292
346
  def _read_metadata(table_filepath, mimetype, logger):
293
347
  # Determine the header row
294
348
  logger.info('Determining column names and types')
@@ -302,13 +356,28 @@ def _read_metadata(table_filepath, mimetype, logger):
302
356
  header_offset, headers = headers_guess(stream.sample)
303
357
  except TabulatorException:
304
358
  try:
305
- file_format = mimetype.lower().split('/')[-1]
359
+ # Fall back to a format derived from the mimetype, mapping known
360
+ # spreadsheet mimetypes to the name tabulator understands.
361
+ file_format = _format_from_mimetype(mimetype)
306
362
  with UnknownEncodingStream(table_filepath, file_format, decoding_result,
307
363
  skip_rows=[{'type': 'preset', 'value': 'blank'}],
308
364
  post_parse=[TypeConverter().convert_types]) as stream:
309
365
  header_offset, headers = headers_guess(stream.sample)
310
366
  except TabulatorException as e:
311
- raise LoaderError('Tabulator error: {}'.format(e))
367
+ # The low-level tabulator message (e.g. "doesn't have a sheet 1")
368
+ # rarely tells a publisher what to fix. The usual causes are a
369
+ # missing header row, an empty header cell, or a file whose real
370
+ # format doesn't match its name. Surface actionable guidance and
371
+ # keep the technical detail for support.
372
+ raise LoaderError(_(
373
+ "The file could not be read as a table. This usually means the "
374
+ "file is not really in the format its name suggests (for "
375
+ "example a CSV or an older .xls file renamed to .xlsx), or the "
376
+ "file is empty or corrupted. Please open the file and save it "
377
+ "again in the correct format (for example .xlsx or .csv), make "
378
+ "sure the first row contains a header for every column, then "
379
+ "upload it again. (Technical details: {details})").format(
380
+ details=e))
312
381
  except Exception as e:
313
382
  raise FileCouldNotBeLoadedError(e)
314
383
 
@@ -617,11 +686,16 @@ def load_table(table_filepath, resource_id, mimetype='text/csv', logger=None):
617
686
  skip_rows=skip_rows,
618
687
  post_parse=[type_converter.convert_types]) as stream:
619
688
  def row_iterator():
620
- for row in stream:
689
+ # Iterate with extended=True so we get tabulator's physical source
690
+ # row number. That is the line the publisher sees in their file,
691
+ # and it stays correct even when blank rows are skipped (unlike
692
+ # counting yielded rows ourselves).
693
+ for row_number, _headers, row in stream.iter(extended=True):
621
694
  data_row = {}
622
695
  for index, cell in enumerate(row):
623
696
  # Ignore surplus blank cells, error on surplus real data.
624
- if not _should_keep_cell(index, cell, header_count):
697
+ if not _should_keep_cell(index, cell, header_count,
698
+ row_number=row_number):
625
699
  continue
626
700
  data_row[headers[index]] = cell
627
701
  yield data_row
@@ -37,13 +37,19 @@ class TypeConverter:
37
37
  if self.fields[cell_index].get('info', {}).get('strip_extra_white', True) and isinstance(cell_value, six.text_type):
38
38
  cell_value = cell_value.strip()
39
39
  row[cell_index] = cell_value.strip()
40
+ # A row can be wider than the declared columns (e.g. a stray
41
+ # delimiter or an unquoted value split a field). Those surplus
42
+ # cells have no declared type, so index defensively here and
43
+ # let the loader's row handling report the wide row with a
44
+ # clear message instead of an opaque "list index out of range".
45
+ has_type = self.types is not None and cell_index < len(self.types)
40
46
  if not cell_value:
41
47
  # load_csv parody: empty of string type should be None
42
- if self.types and self.types[cell_index] == six.text_type:
48
+ if has_type and self.types[cell_index] == six.text_type:
43
49
  cell_value = None
44
50
  row[cell_index] = None
45
51
  continue
46
- cell_type = self.types[cell_index] if self.types else None
52
+ cell_type = self.types[cell_index] if has_type else None
47
53
  if cell_type in [Decimal, None]:
48
54
  converted_value = to_number(cell_value)
49
55
  # Can't do a simple truthiness check,
@@ -117,18 +117,11 @@ class xloaderPlugin(plugins.SingletonPlugin):
117
117
  See: ckan/model/modification.py.DomainObjectModificationExtension
118
118
  """
119
119
  if operation != DomainObjectOperation.changed \
120
- or not isinstance(entity, Resource):
120
+ or not isinstance(entity, Resource) \
121
+ or entity.state == 'deleted':
121
122
  return
122
123
 
123
- context = {
124
- "ignore_auth": True,
125
- }
126
- resource_dict = toolkit.get_action("resource_show")(
127
- context,
128
- {
129
- "id": entity.id,
130
- },
131
- )
124
+ resource_dict = entity.as_dict()
132
125
 
133
126
  if _should_remove_unsupported_resource_from_datastore(resource_dict):
134
127
  toolkit.enqueue_job(fn=_remove_unsupported_resource_from_datastore, args=[entity.id])
@@ -1,5 +1,6 @@
1
1
  import pytest
2
2
  from ckan.plugins import toolkit
3
+
3
4
  try:
4
5
  from unittest import mock
5
6
  except ImportError:
@@ -7,6 +8,7 @@ except ImportError:
7
8
 
8
9
  from ckan.plugins.toolkit import NotAuthorized
9
10
  from ckan.tests import helpers, factories
11
+ from ckan.model import Resource
10
12
 
11
13
  from ckanext.xloader.utils import get_xloader_user_apitoken
12
14
 
@@ -15,7 +17,7 @@ from ckanext.xloader.utils import get_xloader_user_apitoken
15
17
  def with_api_token(monkeypatch, ckan_config):
16
18
  sysadmin = factories.SysadminWithToken()
17
19
  apikey = sysadmin["token"]
18
- monkeypatch.setitem(ckan_config, 'ckanext.xloader.api_token', apikey)
20
+ monkeypatch.setitem(ckan_config, "ckanext.xloader.api_token", apikey)
19
21
 
20
22
 
21
23
  @pytest.mark.usefixtures("clean_db", "with_plugins")
@@ -39,7 +41,9 @@ class TestAction(object):
39
41
  resource_id=res["id"],
40
42
  )
41
43
  assert 1 == enqueue_mock.call_count
42
- assert enqueue_mock.call_args[1].get('queue') == 'default{}'.format(ord(res['package_id'][0]) % 2)
44
+ assert enqueue_mock.call_args[1].get(
45
+ "queue"
46
+ ) == "default{}".format(ord(res["package_id"][0]) % 2)
43
47
 
44
48
  def test_submit_nonexistent_resource(self, with_api_token):
45
49
  user = factories.User()
@@ -47,11 +51,14 @@ class TestAction(object):
47
51
  "ckanext.xloader.action.enqueue_job",
48
52
  return_value=mock.MagicMock(id=123),
49
53
  ) as enqueue_mock:
50
- assert helpers.call_action(
51
- "xloader_submit",
52
- context=dict(user=user["name"]),
53
- resource_id="aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
54
- ) is False
54
+ assert (
55
+ helpers.call_action(
56
+ "xloader_submit",
57
+ context=dict(user=user["name"]),
58
+ resource_id="aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
59
+ )
60
+ is False
61
+ )
55
62
  assert enqueue_mock.call_count == 0
56
63
 
57
64
  def test_submit_to_custom_queue_without_auth(self):
@@ -61,17 +68,20 @@ class TestAction(object):
61
68
  helpers.call_auth(
62
69
  "xloader_submit",
63
70
  context=dict(user=user["name"], model=None),
64
- queue='foo',
71
+ queue="foo",
65
72
  )
66
73
 
67
74
  def test_submit_to_custom_queue_as_sysadmin(self):
68
75
  # check that xloader_submit allows sysadmins to change queues
69
76
  user = factories.Sysadmin()
70
- assert helpers.call_auth(
71
- "xloader_submit",
72
- context=dict(user=user["name"], model=None),
73
- queue='foo',
74
- ) is True
77
+ assert (
78
+ helpers.call_auth(
79
+ "xloader_submit",
80
+ context=dict(user=user["name"], model=None),
81
+ queue="foo",
82
+ )
83
+ is True
84
+ )
75
85
 
76
86
  def test_duplicated_submits(self, with_api_token):
77
87
  def submit(res, user):
@@ -143,12 +153,16 @@ class TestAction(object):
143
153
  def test_xloader_user_api_token_from_config(self):
144
154
  sysadmin = factories.SysadminWithToken()
145
155
  apikey = sysadmin["token"]
146
- with mock.patch.dict(toolkit.config, {'ckanext.xloader.api_token': apikey}):
156
+ with mock.patch.dict(
157
+ toolkit.config, {"ckanext.xloader.api_token": apikey}
158
+ ):
147
159
  api_token = get_xloader_user_apitoken()
148
160
  assert api_token == apikey
149
161
 
150
162
  @pytest.mark.ckan_config("ckanext.xloader.api_token", "NOT_SET")
151
- def test_xloader_user_api_token_from_config_should_throw_exceptio_when_not_set(self):
163
+ def test_xloader_user_api_token_from_config_should_throw_exceptio_when_not_set(
164
+ self,
165
+ ):
152
166
 
153
167
  hasNotThrownException = True
154
168
  try:
@@ -163,3 +177,16 @@ class TestAction(object):
163
177
  api_token = get_xloader_user_apitoken()
164
178
 
165
179
  assert api_token == "random-api-token"
180
+
181
+ def test_resource_delete(self):
182
+ user = factories.Sysadmin()
183
+ resource = factories.Resource(user=user)
184
+ helpers.call_action(
185
+ "resource_delete",
186
+ id=resource["id"],
187
+ context=dict(user=user["name"]),
188
+ )
189
+
190
+ resource_obj = Resource.get(resource["id"])
191
+ assert resource_obj is not None
192
+ assert resource_obj.state == "deleted"
@@ -3,9 +3,10 @@ from __future__ import annotations
3
3
  import logging
4
4
  from typing import Any
5
5
 
6
+ from faker import Faker
6
7
  import pytest
7
8
  import sqlalchemy as sa
8
- from faker import Faker
9
+ from unittest.mock import patch
9
10
 
10
11
  from ckanext.xloader import db, jobs
11
12
 
@@ -22,6 +23,15 @@ class TestGetJob:
22
23
  conn.execute(sa.delete(db.METADATA_TABLE))
23
24
  conn.execute(sa.delete(db.LOGS_TABLE))
24
25
 
26
+ def test_idempotent_init(self, monkeypatch: pytest.MonkeyPatch):
27
+ assert db.ENGINE is not None
28
+ with patch('sqlalchemy.create_engine') as mock_create_engine:
29
+ db.init({})
30
+ mock_create_engine.assert_not_called()
31
+ monkeypatch.setattr(db, "ENGINE", None)
32
+ db.init({})
33
+ mock_create_engine.assert_called_once()
34
+
25
35
  def test_jobs_table_not_initialized(
26
36
  self, faker: Faker, monkeypatch: pytest.MonkeyPatch
27
37
  ):
@@ -37,6 +37,34 @@ def Session():
37
37
  Session.close()
38
38
 
39
39
 
40
+ class TestFormatFromMimetype(object):
41
+ """_format_from_mimetype maps known mimetypes to the short format name
42
+ tabulator expects. The important case is the xlsx mimetype, whose part
43
+ after '/' isn't the file extension, so the old split-on-'/' fallback
44
+ produced a format tabulator couldn't open."""
45
+
46
+ def test_xlsx_mimetype_maps_to_xlsx(self):
47
+ mimetype = (
48
+ "application/vnd.openxmlformats-officedocument"
49
+ ".spreadsheetml.sheet"
50
+ )
51
+ assert loader._format_from_mimetype(mimetype) == "xlsx"
52
+
53
+ def test_legacy_xls_and_csv(self):
54
+ assert loader._format_from_mimetype("application/vnd.ms-excel") == "xls"
55
+ assert loader._format_from_mimetype("text/csv") == "csv"
56
+
57
+ def test_mimetype_with_charset_parameter(self):
58
+ assert loader._format_from_mimetype("text/csv; charset=utf-8") == "csv"
59
+
60
+ def test_unknown_mimetype_falls_back_to_suffix(self):
61
+ # Preserve the historical behaviour for anything we don't map.
62
+ assert loader._format_from_mimetype("application/json") == "json"
63
+
64
+ def test_none_mimetype(self):
65
+ assert loader._format_from_mimetype(None) is None
66
+
67
+
40
68
  @pytest.mark.skipif(
41
69
  p.toolkit.check_ckan_version(max_version='2.7.99'),
42
70
  reason="fixtures do not have permission populate full_text_trigger")
@@ -665,6 +693,24 @@ class TestLoadCsv(TestLoadBase):
665
693
  )
666
694
  assert len(self._get_records(Session, resource_id)) == 2
667
695
 
696
+ def test_row_with_extra_data_raises_friendly_error(self, Session):
697
+ # A data row wider than the header where the surplus cell holds real
698
+ # data. load_csv can't know the file line number, so the message names
699
+ # the column count and the offending value but no row number.
700
+ csv_filepath = get_sample_filepath("row_with_extra_data.csv")
701
+ resource = factories.Resource()
702
+ resource_id = resource['id']
703
+ with pytest.raises(LoaderError) as exception:
704
+ loader.load_csv(
705
+ csv_filepath,
706
+ resource_id=resource_id,
707
+ mimetype="text/csv",
708
+ logger=logger,
709
+ )
710
+ message = str(exception.value)
711
+ assert "more values than the 3 column(s)" in message
712
+ assert "surplus" in message
713
+
668
714
  def test_with_empty_lines(self, Session):
669
715
  csv_filepath = get_sample_filepath("sample_with_empty_lines.csv")
670
716
  resource = factories.Resource()
@@ -1086,8 +1132,7 @@ class TestLoadUnhandledTypes(TestLoadBase):
1086
1132
  # than that one header. Surplus cells holding real data are now rejected
1087
1133
  # up-front by _should_keep_cell (see load_csv's row-normalizing iter),
1088
1134
  # so the load fails here rather than later at field-definition validation.
1089
- assert "Found data in column" in str(exception.value)
1090
- assert "resource only has 1 header(s)" in str(exception.value)
1135
+ assert "more values than the 1 column(s)" in str(exception.value)
1091
1136
 
1092
1137
  def test_geojson(self):
1093
1138
  filepath = get_sample_filepath("polling_locations.geojson")
@@ -1690,6 +1735,26 @@ class TestLoadTabulator(TestLoadBase):
1690
1735
  )
1691
1736
  assert len(self._get_records(Session, resource_id)) == 2
1692
1737
 
1738
+ def test_row_with_extra_data_reports_row_number(self, Session):
1739
+ # Header has 3 columns; the third data row carries a surplus cell with
1740
+ # real data. load_table should reject it with a friendly, translatable
1741
+ # message that names the offending row (the file line the user sees)
1742
+ # and the extra value, instead of an opaque tabulator error.
1743
+ csv_filepath = get_sample_filepath("row_with_extra_data.csv")
1744
+ resource = factories.Resource()
1745
+ resource_id = resource['id']
1746
+ with pytest.raises(LoaderError) as exception:
1747
+ loader.load_table(
1748
+ csv_filepath,
1749
+ resource_id=resource_id,
1750
+ mimetype="text/csv",
1751
+ logger=logger,
1752
+ )
1753
+ message = str(exception.value)
1754
+ assert "Row 3 has" in message
1755
+ assert "more values than the 3 column(s)" in message
1756
+ assert "surplus" in message
1757
+
1693
1758
  def test_with_mixed_quotes(self, Session):
1694
1759
  csv_filepath = get_sample_filepath("sample_with_mixed_quotes.csv")
1695
1760
  resource = factories.Resource()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ckanext-xloader
3
- Version: 2.5.0
3
+ Version: 2.5.2
4
4
  Summary: Express Loader - quickly load data into CKAN DataStore
5
5
  Author: David Read (davidread), Patricio Del Boca (pdelboca)
6
6
  Author-email: ThrawnCA <carl.antuar@smartservice.qld.gov.au>, "Jesse Vickery (JVickery-TBS)" <jesse.vickery@tbs-sct.gc.ca>, "Adrià Mercader (amercader)" <amercadero@gmail.com>, "Brett Jones (kowh-ai)" <datashades@linkdigital.com.au>, "William Dutton (duttonw)" <william.dutton@qld.gov.au>
@@ -0,0 +1,8 @@
1
+ responses==0.26.3
2
+ mock==5.2.0
3
+ flake8
4
+ pytest-ckan
5
+ pytest-cov
6
+ requests>=2.34.2 # not directly required, pinned by Snyk to avoid a vulnerability
7
+ urllib3>=2.8.0 # not directly required, pinned by Snyk to avoid a vulnerability
8
+ zipp>=4.1.1 # not directly required, pinned by Snyk to avoid a vulnerability
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "ckanext-xloader"
7
- version = "2.5.0"
7
+ version = "2.5.2"
8
8
  description = "Express Loader - quickly load data into CKAN DataStore"
9
9
  classifiers = [ "Development Status :: 5 - Production/Stable",
10
10
  "License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)",
@@ -0,0 +1,11 @@
1
+ ckantoolkit>=0.0.7
2
+ requests>=2.34.2
3
+ six>=1.17.0
4
+ tabulator==1.53.5
5
+ Unidecode==1.4.0
6
+ python-dateutil>=2.9.0.post0
7
+ certifi>=2026.7.22 # not directly required, pinned by Snyk to avoid a vulnerability
8
+ chardet==5.2.0
9
+ idna>=3.20 # not directly required, pinned by Snyk to avoid a vulnerability
10
+ urllib3>=2.8.0 # not directly required, pinned by Snyk to avoid a vulnerability
11
+ zipp>=4.1.1 # not directly required, pinned by Snyk to avoid a vulnerability
@@ -1,8 +0,0 @@
1
- responses==0.10.9
2
- mock==2.0.0
3
- flake8
4
- pytest-ckan
5
- pytest-cov
6
- requests>=2.32.0 # not directly required, pinned by Snyk to avoid a vulnerability
7
- urllib3>=2.2.2 # not directly required, pinned by Snyk to avoid a vulnerability
8
- zipp>=3.19.1 # not directly required, pinned by Snyk to avoid a vulnerability
@@ -1,11 +0,0 @@
1
- ckantoolkit>=0.0.4
2
- requests>=2.31.0
3
- six>=1.12.0
4
- tabulator==1.53.5
5
- Unidecode==1.0.22
6
- python-dateutil>=2.8.2
7
- certifi>=2023.7.22 # not directly required, pinned by Snyk to avoid a vulnerability
8
- chardet==5.2.0
9
- idna>=3.7 # not directly required, pinned by Snyk to avoid a vulnerability
10
- urllib3>=1.26.19 # not directly required, pinned by Snyk to avoid a vulnerability
11
- zipp>=3.19.1 # not directly required, pinned by Snyk to avoid a vulnerability
File without changes