1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
|
#!/usr/bin/env python3
#
# Copyright 2019-2020 Micah Cochran
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import datetime
import isodate
import unittest
from pathlib import Path
from typing import List
from scrape_schema_recipe import load, loads, scrape, scrape_url, SSRTypeError
from scrape_schema_recipe import example_output, __version__
DISABLE_NETWORK_TESTS = False
DATA_PATH = "scrape_schema_recipe/test_data"
def lists_are_equal(lst1: List, lst2: List) -> bool:
lst1.sort()
lst2.sort()
if lst1 != lst2:
print("\n[lst1 != lst2]")
print("lst1: {}".format(lst1))
print("lst2: {}".format(lst2))
return lst1 == lst2
class TestParsingFileMicroData(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.recipes = load(f"{DATA_PATH}/foodista-british-treacle-tart.html")
cls.recipe = cls.recipes[0]
def test_recipe_keys(self):
input_keys = list(self.recipe.keys())
expected_output = [
"@context",
"recipeYield",
"@type",
"recipeInstructions",
"recipeIngredient",
"name",
]
assert lists_are_equal(expected_output, input_keys)
def test_name(self):
assert self.recipe["name"] == "British Treacle Tart"
def test_recipe_yield(self):
assert self.recipe["recipeYield"] == "1 servings"
def test_num_recipes(self):
assert len(self.recipes) == 1
class TestUnsetTimeDate(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.recipes = scrape(
f"{DATA_PATH}/allrecipes-moscow-mule.html", python_objects=True
)
cls.recipe = cls.recipes[0]
def test_recipe_keys(self):
input_keys = list(self.recipe.keys())
expected_output = [
"@context",
"@type",
"aggregateRating",
"author",
"datePublished",
"description",
"image",
"mainEntityOfPage",
"name",
"nutrition",
"prepTime",
"recipeCategory",
"recipeCuisine",
"recipeIngredient",
"recipeInstructions",
"recipeYield",
"review",
"totalTime",
"video",
]
assert lists_are_equal(expected_output, input_keys)
def test_name(self):
assert self.recipe["name"] == "Simple Moscow Mule"
def test_recipe_yield(self):
assert self.recipe["recipeYield"] == "1 cocktail"
def test_num_recipes(self):
assert len(self.recipes) == 1
def test_recipe_durations(self):
assert str(self.recipe["prepTime"]) == "0:10:00"
assert str(self.recipe["totalTime"]) == "0:10:00"
assert "cookTime" not in self.recipe.keys()
# also uses the old ingredients name
class TestParsingFileMicroData2(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.recipes = scrape(
f"{DATA_PATH}/sweetestkitchen-truffles.html", python_objects=True
)
cls.recipe = cls.recipes[0]
def test_recipe_keys(self):
input_keys = list(self.recipe.keys())
expected_output = [
"prepTime",
"cookTime",
"name",
"recipeYield",
"recipeCategory",
"image",
"description",
"@type",
"author",
"aggregateRating",
"recipeIngredient",
"recipeInstructions",
"totalTime",
"@context",
]
assert lists_are_equal(expected_output, input_keys)
def test_name(self):
assert self.recipe["name"] == "Rum & Tonka Bean Dark Chocolate Truffles"
def test_recipe_yield(self):
assert self.recipe["recipeYield"] == "15-18 3cm squares"
def test_num_recipes(self):
assert len(self.recipes) == 1
def test_totalTime_sum(self):
r = self.recipe
assert r["prepTime"] + r["cookTime"] == r["totalTime"]
class TestParsingFileLDJSON(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.recipes = scrape(f"{DATA_PATH}/bevvy-irish-coffee-2018.html")
cls.recipe = cls.recipes[0]
def test_category(self):
assert self.recipe["recipeCategory"] == "Cocktail"
def test_duration(self):
assert self.recipe["totalTime"] == "PT5M"
def test_ingredients(self):
ingredients = [
"1.5 oz Irish whiskey",
"1 tsp brown sugar syrup",
"Hot black coffee",
"Unsweetened whipped cream",
]
assert lists_are_equal(ingredients, self.recipe["recipeIngredient"])
# in the 2019 version this was changed
def test_instructions(self):
expected_str = "Add Irish whiskey, brown sugar syrup, and hot coffee to an Irish coffee mug.\nTop with whipped cream."
assert self.recipe["recipeInstructions"] == expected_str
def test_recipe_keys(self):
input_keys = list(self.recipe.keys())
expected_output = [
"author",
"publisher",
"recipeCategory",
"@type",
"recipeIngredient",
"recipeInstructions",
"image",
"@context",
"totalTime",
"description",
"name",
]
assert lists_are_equal(expected_output, input_keys)
def test_name(self):
assert self.recipe["name"] == "Irish Coffee"
def test_num_recipes(self):
assert len(self.recipes) == 1
class TestTimeDelta(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.recipes = scrape(
f"{DATA_PATH}/crumb-lemon-tea-cakes-2018.html", python_objects=True
)
cls.recipe = cls.recipes[0]
def test_timedelta(self):
td = datetime.timedelta(minutes=10)
assert self.recipe["prepTime"] == td
def test_totalTime_sum(self):
r = self.recipe
assert r["prepTime"] + r["cookTime"] == r["totalTime"]
class TestDateTime(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.recipes = load(
f"{DATA_PATH}/google-recipe-example.html", python_objects=True
)
cls.recipe = cls.recipes[0]
# input string (upload_date) is "2018-02-05T08:00:00+08:00"
upload_date = cls.recipe["video"][0]["uploadDate"]
cls.datetime_test = isodate.parse_datetime(upload_date)
def test_publish_date_python_obj(self):
assert self.recipe["datePublished"] == datetime.date(2018, 3, 10)
def test_datetime_tz_python_obj_isodate(self):
tz8 = isodate.FixedOffset(offset_hours=8)
expected = datetime.datetime(2018, 2, 5, 8, 0, tzinfo=tz8)
assert self.datetime_test == expected
def test_datetime_tz_python_obj(self):
tz8 = datetime.timezone(datetime.timedelta(hours=8))
expected = datetime.datetime(2018, 2, 5, 8, 0, tzinfo=tz8)
assert self.datetime_test == expected
# test loads()
class TestLoads(unittest.TestCase):
def test_loads(self):
with open(f"{DATA_PATH}/bevvy-irish-coffee-2019.html") as fp:
s = fp.read()
recipes = loads(s)
recipe = recipes[0]
assert recipe["name"] == "Irish Coffee"
# feed bad types into the functions
class BadTypes(unittest.TestCase):
def test_load(self):
with self.assertRaises(SSRTypeError):
load(0xFEED)
def test_loads(self):
with self.assertRaises(SSRTypeError):
loads(0xDEADBEEF)
def test_scrape(self):
with self.assertRaises(SSRTypeError):
scrape(0xBEE)
def test_scrape_url(self):
with self.assertRaises(SSRTypeError):
scrape_url(0xC0FFEE)
class TestURL(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.url = "https://raw.githubusercontent.com/micahcochran/scrape-schema-recipe/master/scrape_schema_recipe/test_data/bevvy-irish-coffee-2018.html"
@unittest.skipIf(DISABLE_NETWORK_TESTS is True, "network tests disabled")
def test_scrape_url(self):
self.recipes = scrape_url(self.url)
self.recipe = self.recipes[0]
assert self.recipe["name"] == "Irish Coffee"
@unittest.skipIf(DISABLE_NETWORK_TESTS is True, "network tests disabled")
def test_scrape(self):
self.recipes = scrape(self.url)
self.recipe = self.recipes[0]
assert self.recipe["name"] == "Irish Coffee"
# test that the schema still works when not migrated
class TestUnMigratedSchema(unittest.TestCase):
# Some of these examples use 'ingredients', which was superceded by
# 'recipeIngredients' in the http://schema.org/Recipe standard for a list
# of ingredients in a recipe.
def test_recipe1(self):
recipes = load(
f"{DATA_PATH}/foodista-british-treacle-tart.html", migrate_old_schema=False
)
recipe = recipes[0]
input_keys = list(recipe.keys())
# Note: 'ingredients' has been superceded by 'recipeIngredients' in
# the http://schema.org/Recipe standard for a list of ingredients.
expected_output = [
"@context",
"recipeYield",
"@type",
"recipeInstructions",
"ingredients",
"name",
]
assert lists_are_equal(expected_output, input_keys)
def test_recipe2(self):
recipes = scrape(
f"{DATA_PATH}/sweetestkitchen-truffles.html",
python_objects=True,
migrate_old_schema=False,
)
recipe = recipes[0]
input_keys = list(recipe.keys())
expected_output = [
"prepTime",
"cookTime",
"name",
"recipeYield",
"recipeCategory",
"image",
"description",
"@type",
"author",
"aggregateRating",
"ingredients",
"recipeInstructions",
"totalTime",
"@context",
]
assert lists_are_equal(expected_output, input_keys)
class TestExampleOutput(unittest.TestCase):
def test_example_output(self):
name = example_output("tea-cake")[0]["name"]
assert name == "Meyer Lemon Poppyseed Tea Cakes"
class TestVersion(unittest.TestCase):
def test_version_not_null(self):
assert __version__ is not None
def test_version_is_type_string(self):
assert isinstance(__version__, str)
class TestPythonObjects(unittest.TestCase):
@classmethod
def setUpClass(cls):
# these are named based on what is passed via python_objects
cls.true = example_output("google", python_objects=True)[0]
cls.false = example_output("google", python_objects=False)[0]
cls.duration = example_output("google", python_objects=[datetime.timedelta])[0]
cls.dates = example_output("google", python_objects=[datetime.date])[0]
def testDurationTypes(self):
assert isinstance(self.duration["cookTime"], datetime.timedelta)
assert isinstance(self.duration["prepTime"], datetime.timedelta)
assert isinstance(self.duration["totalTime"], datetime.timedelta)
def testDurationEqual(self):
assert self.duration["cookTime"] == self.true["cookTime"]
assert self.duration["prepTime"] == self.true["prepTime"]
assert self.duration["totalTime"] == self.true["totalTime"]
def testDateTypes(self):
assert isinstance(self.dates["datePublished"], datetime.date)
# note that datePublished can also be of type datetime.dateime
def testDatesEqual(self):
assert self.dates["datePublished"] == self.true["datePublished"]
class TestGraph(unittest.TestCase):
# tests @graph, also test Path
def test_graph(self):
recipes_old = load(
f"{DATA_PATH}/crumb-lemon-tea-cakes-2018.html", python_objects=True
)
recipes_graph = load(
Path(f"{DATA_PATH}/crumb-lemon-tea-cakes-2019.html"), python_objects=True
)
r_old = recipes_old[0]
r_graph = recipes_graph[0]
assert r_old["name"] == r_graph["name"]
assert r_old["recipeCategory"] == r_graph["recipeCategory"]
assert r_old["recipeCuisine"] == r_graph["recipeCuisine"]
assert r_old["recipeIngredient"] == r_graph["recipeIngredient"]
assert r_old["recipeYield"] == r_graph["recipeYield"]
assert r_old["totalTime"] == r_graph["totalTime"]
# ---- check differences ----
# the recipeInstructions in 2019 version are HowToStep format, 2018 version are in a list
assert r_old["recipeInstructions"] != r_graph["recipeInstructions"]
# 2019 has a datePublished, 2018 version does not
r_graph["datePublished"] == datetime.date(2018, 3, 19)
assert "datePublished" not in r_old.keys()
if __name__ == "__main__":
unittest.main()
|