如何在 2scraper 目錄匯出資料中核對價格與庫存單位
Check Price and Stock Units in a 2scraper Catalog Export
文章説明如何為 2scraper 目錄匯出資料的價格與可售單位建立欄位契約和測試,避免把數值欄位誤當成其他含義。測試區分空白庫存與零庫存,並指出即使價格和庫存數字都符合格式,欄位對調仍需透過來源資料已知的測試核實。報告還應標明數量所用單位,並記錄欄位映射、轉換方式及空值處理。
When I prepare a report using an authorized catalog export from 2scraper, I assign meaning to each numeric field before adding it to a chart. A cell containing 12 can describe a price, an inventory count, or the number of items included in a package. The CSV parser will accept the same text in each role. A small contract test can catch several mistakes before they become price changes or inventory gaps in a dashboard.
Written with AI assistance. The catalog rows are synthetic and were checked locally. The examples demonstrate an internal reporting schema, and the cover was prepared with AI assistance.
Write a contract for the inputs the report actually uses
For one fictional catalog the report accepts an item ID, a price, a currency code, and an available-unit count. The price is a currency amount. The available-unit count is an integer describing units ready for sale under the report's definition. Package size and assortment count can appear in the underlying dataset, but they require their own names and units. A configuration reviewer should know which source field feeds each displayed column.
In a reusable exporter, different projects can use different fields or omit a column. Preserve a mapping per project and input schema, with a short example for each input field. Support an explicit blank when evidence was missing. For example, a blank inventory count leaves the status unknown, while a figure of zero says that the source observed no available units. The quoted CSV spelling should survive until your importer determines which interpretation applies.
A contract can specify a report that includes just two known currencies and homogeneous integer unit counts. Such a rule is appropriate for that observed population. Other catalogs might have fractional inventory or a different price basis. Add and document another approved mapping or parser only when the meaning of the new data is supported. Quietly broadening the accepted input can let it enter reports whose totals still assume the earlier definition.
Exercise a few cheap checks with synthetic rows
The fixture accepts a narrow price grammar, then checks a known currency and a whole count separately. It treats an empty count as missing and accepts zero as a real count. The sample price amounts are invented. The script reads dictionaries shaped like already decoded CSV rows. It makes no network calls and does not claim that these examples describe the actual fields of every project.
from decimal import Decimal
import re
PRICE = re.compile(r"[0-9]+(?:\.[0-9]{1,2})?")
STOCK = re.compile(r"[0-9]+")
CURRENCIES = {"USD", "EUR"}
def catalog_row(row):
price = row.get("price", "")
currency = row.get("currency", "")
stock = row.get("stock", "")
errors = []
if not PRICE.fullmatch(price):
errors.append("price")
if currency not in CURRENCIES:
errors.append("currency")
if stock and not STOCK.fullmatch(stock):
errors.append("inventory count")
if errors:
return None, tuple(errors)
return (Decimal(price), currency, int(stock) if stock else None), ()
good = {"price": "12.50", "currency": "USD", "stock": "0"}
missing = {**good, "stock": ""}
switched = {**good, "price": "25", "stock": "12.50"}
assert catalog_row(good) == ((Decimal("12.50"), "USD", 0), ())
assert catalog_row(missing) == ((Decimal("12.50"), "USD", None), ())
assert catalog_row(switched) == (None, ("inventory count",))
assert catalog_row({**good, "currency": "", "price": "NaN"}) == (None, ("price", "currency"))
assert catalog_row({**good, "price": "19,99"}) == (None, ("price",))
print("Zero inventory preserved; unknown inventory separated; fractional inventory held")
The local run printed Zero inventory preserved; unknown inventory separated; fractional inventory held. One assertion catches a common-looking decimal that appears in an integer field. Another catches absent currency together with an invalid price. Decimal commas are outside this report's synthetic input grammar, and an explicit locale-specific importer would need its own fixtures.
Add a negative control that the decimal check cannot catch
Consider a second synthetic export where an item costs 12 and has 27 available units. If those cells are swapped, 27 still satisfies the price grammar, and 12 still satisfies the integer grammar. The numbers pass the same validation while carrying the wrong meanings. To catch this reliably, test the mapping against an input where the source values and expected roles are independently known.
For example, prepare a fixture with one approved source snapshot containing a price of 12 and a separate inventory observation of 27. Assert the result of the full export path, including the column named price and the column named stock. Keep those values unequal so the test catches a swap. Save the expected comparison on the parsed representation along with the evidence version, so an output format change does not invalidate a logically equivalent record.
A mapping checklist also helps before changing the export view. Record the meaning of the source field, the unit and any conversion, how a blank is represented, and the permitted downstream calculation. Have a reviewer follow one stored source record to its output values. If the mapping cannot explain why a number appears under a particular heading, reject the rule change before relying on aggregate values.
Compare quantity, package scale, and available inventory separately
An item may be sold in packages containing six pieces while the supplier reports three available packages. A count of three belongs with the unit the supplier actually recorded. Multiplying gives a possible value of 18 pieces if the business has explicitly chosen that conversion. The published report should show whether it counts each, package, or another unit. The same numeric count can be correct at one level and misleading at another.
Price has its own basis. A displayed amount might be for one item or for a package. If the report compares a cost per piece, the price and package size must refer to the same offer observation. Record the source fields used and test an example where the package changes. An inventory field supplies no evidence for the number of pieces included in a package unless the data contract says it does.
For spreadsheet inputs, lock the unit into its own column or stable field metadata. A header such as amount is too ambiguous for reuse across views that contain both prices and counts. Preserve the price currency even if all accepted data in yesterday's run happened to use one. A missing currency in tomorrow's run needs an explicit status, especially when rows can represent several marketplaces.
Keep the decision when you reject or quarantine a row
If a row has a valid price and an invalid stock value, different consumers can reasonably make different choices. A price-only historical calculation might retain the price when the authorized source and currency are valid. A joint low-stock alert needs both observations. The fixture returns no normalized tuple when a field is invalid because it models a combined catalog view. A larger system can attach separate statuses to the fields and choose eligible data for each report.
I would count rows held by each rule and include one safe sample that reproduces the reason. The person investigating can see whether the issue came from a malformed column, absent evidence, or a recognized source mapped into the wrong destination. The error output should use a controlled row reference. Raw upstream text can contain metadata that a public review export does not need to share.
Treat an explicit source correction differently from a re-run that happens to remove an invalid row. Keep the original snapshot under the approved retention policy, attach the revised record and explain which rule now accepts it. Stable source identifiers and batch references make that comparison possible. A dashboard that only retains the newest values cannot tell the report owner why yesterday's totals changed.
Test the whole path from accepted rows to spreadsheet formulas
Validation in the import is helpful only if the downstream formulas use the validated fields. I would use a test workbook with one accepted tuple, one missing inventory observation, and one invalid row. The stock total should include the counted zero only as a measured inventory value and report missing observations separately. The aggregate price summary should state which currencies and rows were eligible.
Test that the workbook imports a currency amount as the intended decimal value. Text-based parsing can treat punctuation differently depending on its locale. Feed a value that the exporter intentionally rejects, reopen the report, and confirm whether the file kept the review status. An empty column that looks clean can still hide a failure if the number of accepted input rows was never compared with the produced rows.
One release gate can compare the most recent two fixture runs. Count accepted, incomplete, and rejected rows. For the synthetic rows expected to pass, check both numeric values and the unit columns. For the fixture in which integer values were swapped, check the recorded holding reason from the mapping validation, even though each individual numeric grammar still accepts the content.
Review evidence when prices and quantities change over time
I would preserve the time the price was observed and the time the available units were recorded. A combined export assembled from two sources might contain the Monday price and the Tuesday stock count. Both may individually be valid facts. Showing them in a row with a single Tuesday observation date invites a shopper or analyst to infer that one observation supported both. Record the two timestamps or require a documented tolerance that makes their relationship useful for the report.
One useful acceptance case runs through a price update and a stock update in opposite orders. The final row can carry both changes if the report preserves which source time belongs to each field. Assert that an unavailable quantity stays unavailable when only a price update arrives. If you require a contemporaneous view, have a separate assertion that prevents a stale field from being used in a calculated low-stock price alert. The declared rule makes it possible to explain why a technically correct individual value was excluded from a combined calculation.
Adopt the rule on a single documented catalog
Start with a representative product group, a pair of approved samples that look numeric in both fields, and one complicated case such as a missing quantity. The review should make it clear which input field means which quantity. Configure one report whose status and totals agree for that known population, then extend deliberately to other catalogs and units.
If you are comparing projects in 2scraper, choose one authorized or synthetic export and document the units in two numeric columns before relying on a chart. Run the checks and ask someone to reproduce the expected price and count from the evidence. A fixture with two different integer values is a particularly useful addition because it keeps the type-only check honest.
Further reading
Find Duplicate JSON Keys Before They Overwrite an Amazon Price describes another input case where a successful parse can hide a bad result.
Reject Nonfinite 2Captcha Balance Values Before Storing Them gives a separate example of checking numeric evidence before it becomes report data.
Show Ties Honestly in a CaptchaTheCat Scorecard examines how to document units, scope, and precision before publishing a comparison.
來源:DEV Community · dev.to