How to use is_file method in assertpy

Best Python code snippet using assertpy_python

test_io_import.py

Source:test_io_import.py Github

copy

Full Screen

1import warnings2from pathlib import Path3from unittest.mock import MagicMock, patch4import numpy as np5from PIL import Image as PILImage6from pytest import raises7import menpo.io as mio8from menpo.shape import PointCloud9def test_import_incorrect_built_in():10 with raises(ValueError):11 mio.import_builtin_asset("adskljasdlkajd.obj")12def test_breaking_bad_import():13 img = mio.import_builtin_asset("breakingbad.jpg")14 assert img.shape == (1080, 1920)15 assert img.n_channels == 316 assert img.landmarks["PTS"].n_points == 6817def test_breaking_bad_import_kwargs():18 img = mio.import_builtin_asset("breakingbad.jpg", normalize=False)19 assert img.pixels.dtype == np.uint820def test_takeo_import():21 img = mio.import_builtin_asset("takeo.ppm")22 assert img.shape == (225, 150)23 assert img.n_channels == 324 assert img.landmarks["PTS"].n_points == 6825def test_einstein_import():26 img = mio.import_builtin_asset("einstein.jpg")27 assert img.shape == (1024, 817)28 assert img.n_channels == 129 assert img.landmarks["PTS"].n_points == 6830def test_lenna_import():31 img = mio.import_builtin_asset("lenna.png")32 assert img.shape == (512, 512)33 assert img.n_channels == 334 assert img.landmarks.n_groups == 235 assert img.landmarks["LJSON"].n_points == 6836 assert img.landmarks["pupils"].n_points == 237def test_import_builtin_ljson():38 lmarks = mio.import_builtin_asset("lenna.ljson")["LJSON"]39 assert lmarks.n_points == 6840def test_import_builtin_pts():41 lmarks = mio.import_builtin_asset("einstein.pts")["PTS"]42 assert lmarks.n_points == 6843def test_resolve_from_paths_single_group():44 def resolver(path):45 test_dict = {"test": path.with_name("takeo.pts")}46 return mio.input.resolve_from_paths(test_dict)47 image = mio.import_image(48 mio.data_path_to("einstein.jpg"), landmark_resolver=resolver49 )50 assert image.landmarks.n_groups == 151 assert image.landmarks["test"].path == mio.data_path_to("takeo.pts")52def test_resolve_from_paths_multi_group():53 def resolver(path):54 test_dict = {"test": path.with_name("lenna.ljson")}55 return mio.input.resolve_from_paths(test_dict)56 image = mio.import_image(57 mio.data_path_to("einstein.jpg"), landmark_resolver=resolver58 )59 assert image.landmarks.n_groups == 260 assert set(image.landmarks.keys()) == {"test_LJSON", "test_pupils"}61def test_path():62 # choose a random asset (all should have it!)63 img = mio.import_builtin_asset("einstein.jpg")64 path = mio.data_path_to("einstein.jpg")65 assert img.path == path66 assert img.path.stem == "einstein"67 assert img.path.suffix == ".jpg"68 assert img.path.parent == mio.data_dir_path()69 assert img.path.name == "einstein.jpg"70@patch("menpo.io.input.base._pathlib_glob_for_pattern")71def test_single_suffix_dot_in_path(pathlib_glob):72 import menpo.io.input.base as mio_base73 from pathlib import Path74 fake_path = Path("fake_path.t0.t1.t2")75 pathlib_glob.return_value = [fake_path]76 ext_map = MagicMock()77 ext_map.__contains__.side_effect = lambda x: x == ".t2"78 ret_val = next(mio_base.glob_with_suffix("*.t0.t1.t2", ext_map))79 assert ret_val == fake_path80 ext_map.__contains__.assert_called_with(".t2")81def test_upper_extension_mapped_to_lower():82 import menpo.io.input.base as mio_base83 from pathlib import Path84 ext_map = MagicMock()85 mio_base.importer_for_filepath(Path("fake_path.JPG"), ext_map)86 ext_map.get.assert_called_with(".jpg")87@patch("menpo.io.input.base._pathlib_glob_for_pattern")88def test_double_suffix(pathlib_glob):89 import menpo.io.input.base as mio_base90 from pathlib import Path91 fake_path = Path("fake_path.t1.t2")92 pathlib_glob.return_value = [fake_path]93 ext_map = MagicMock()94 ext_map.__contains__.side_effect = lambda x: x == ".t1.t2"95 ret_val = next(mio_base.glob_with_suffix("*.t1.t2", ext_map))96 assert ret_val == fake_path97 ext_map.__contains__.assert_any_call(".t1.t2")98 ext_map.__contains__.assert_any_call(".t2")99def test_import_image():100 img_path = mio.data_dir_path() / "einstein.jpg"101 im = mio.import_image(img_path)102 assert im.pixels.dtype == float103 assert im.n_channels == 1104def test_custom_landmark_resolver():105 def lmark_resolver(path):106 return mio.import_landmark_file(mio.data_path_to("takeo.pts"))107 img = mio.import_image(108 mio.data_path_to("lenna.png"), landmark_resolver=lmark_resolver109 )110 assert img.has_landmarks111 takeo_lmarks = mio.import_builtin_asset.takeo_pts()["PTS"]112 np.allclose(img.landmarks["PTS"].points, takeo_lmarks.points)113def test_landmark_resolver_none():114 img = mio.import_image(mio.data_path_to("lenna.png"), landmark_resolver=None)115 assert not img.has_landmarks116def test_import_image_no_norm():117 img_path = mio.data_dir_path() / "einstein.jpg"118 im = mio.import_image(img_path, normalize=False)119 assert im.pixels.dtype == np.uint8120def test_import_landmark_file():121 lm_path = mio.data_dir_path() / "einstein.pts"122 mio.import_landmark_file(lm_path)123def test_import_images():124 imgs = list(mio.import_images(mio.data_dir_path()))125 imgs_filenames = set(i.path.stem for i in imgs)126 exp_imgs_filenames = {127 "einstein",128 "takeo",129 "tongue",130 "breakingbad",131 "lenna",132 "menpo_thumbnail",133 }134 assert exp_imgs_filenames == imgs_filenames135def test_import_images_are_ordered_and_unduplicated():136 # we know that import_images returns images in path order137 imgs = list(mio.import_images(mio.data_dir_path()))138 imgs_filenames = [i.path.stem for i in imgs]139 print(imgs_filenames)140 exp_imgs_filenames = [141 "breakingbad",142 "einstein",143 "lenna",144 "menpo_thumbnail",145 "takeo",146 "tongue",147 ]148 assert exp_imgs_filenames == imgs_filenames149def test_lsimgs_filenamess():150 assert set(mio.ls_builtin_assets()) == {151 "breakingbad.jpg",152 "einstein.jpg",153 "einstein.pts",154 "lenna.png",155 "breakingbad.pts",156 "lenna.ljson",157 "takeo.ppm",158 "takeo.pts",159 "tongue.jpg",160 "tongue.pts",161 "menpo_thumbnail.jpg",162 }163def test_image_paths():164 ls = mio.image_paths(mio.data_dir_path())165 assert len(list(ls)) == 6166def test_import_images_wrong_path_raises_value_error():167 with raises(ValueError):168 list(mio.import_images("asldfjalkgjlaknglkajlekjaltknlaekstjlakj"))169def test_import_landmark_files_wrong_path_raises_value_error():170 with raises(ValueError):171 list(mio.import_landmark_files("asldfjalkgjlaknglkajlekjaltknlaekstjlakj"))172@patch("PIL.Image.open")173@patch("menpo.io.input.base.Path.is_file")174def test_importing_PIL_no_normalize(is_file, mock_image):175 mock_image.return_value = PILImage.new("RGBA", (10, 15))176 is_file.return_value = True177 im = mio.import_image("fake_image_being_mocked.png", normalize=False)178 assert im.shape == (15, 10)179 assert im.n_channels == 4180 assert im.pixels.dtype == np.uint8181@patch("PIL.Image.open")182@patch("menpo.io.input.base.Path.is_file")183def test_importing_PIL_RGBA_normalize(is_file, mock_image):184 from menpo.image import MaskedImage185 mock_image.return_value = PILImage.new("RGBA", (10, 15))186 is_file.return_value = True187 im = mio.import_image("fake_image_being_mocked.ppm", normalize=True)188 assert im.shape == (15, 10)189 assert im.n_channels == 3190 assert im.pixels.dtype == float191 assert type(im) == MaskedImage192@patch("PIL.Image.open")193@patch("menpo.io.input.base.Path.is_file")194def test_importing_PIL_RGBA_no_normalize(is_file, mock_image):195 mock_image.return_value = PILImage.new("RGBA", (10, 15))196 is_file.return_value = True197 im = mio.import_image("fake_image_being_mocked.ppm", normalize=False)198 assert im.shape == (15, 10)199 assert im.n_channels == 4200 assert im.pixels.dtype == np.uint8201@patch("PIL.Image.open")202@patch("menpo.io.input.base.Path.is_file")203def test_importing_PIL_L_no_normalize(is_file, mock_image):204 mock_image.return_value = PILImage.new("L", (10, 15))205 is_file.return_value = True206 im = mio.import_image("fake_image_being_mocked.ppm", normalize=False)207 assert im.shape == (15, 10)208 assert im.n_channels == 1209 assert im.pixels.dtype == np.uint8210@patch("PIL.Image.open")211@patch("menpo.io.input.base.Path.is_file")212def test_importing_PIL_L_normalize(is_file, mock_image):213 mock_image.return_value = PILImage.new("L", (10, 15))214 is_file.return_value = True215 im = mio.import_image("fake_image_being_mocked.ppm", normalize=True)216 assert im.shape == (15, 10)217 assert im.n_channels == 1218 assert im.pixels.dtype == float219@patch("PIL.Image.open")220@patch("menpo.io.input.base.Path.is_file")221def test_importing_PIL_I_normalize(is_file, mock_image):222 mock_image.return_value = PILImage.new("I", (10, 15))223 is_file.return_value = True224 with raises(ValueError):225 mio.import_image("fake_image_being_mocked.ppm", normalize=True)226@patch("PIL.Image.open")227@patch("menpo.io.input.base.Path.is_file")228def test_importing_PIL_I_no_normalize(is_file, mock_image):229 mock_image.return_value = PILImage.new("I", (10, 15))230 is_file.return_value = True231 im = mio.import_image("fake_image_being_mocked.ppm", normalize=False)232 assert im.shape == (15, 10)233 assert im.n_channels == 1234 assert im.pixels.dtype == np.int32235@patch("PIL.Image.open")236@patch("menpo.io.input.base.Path.is_file")237def test_importing_PIL_1_normalize(is_file, mock_image):238 from menpo.image import BooleanImage239 mock_image.return_value = PILImage.new("1", (10, 15))240 is_file.return_value = True241 im = mio.import_image("fake_image_being_mocked.ppm", normalize=True)242 assert im.shape == (15, 10)243 assert im.n_channels == 1244 assert im.pixels.dtype == bool245 assert type(im) == BooleanImage246@patch("PIL.Image.open")247@patch("menpo.io.input.base.Path.is_file")248def test_importing_PIL_1_no_normalize(is_file, mock_image):249 from menpo.image import BooleanImage250 mock_image.return_value = PILImage.new("1", (10, 15))251 is_file.return_value = True252 im = mio.import_image("fake_image_being_mocked.ppm", normalize=False)253 assert im.shape == (15, 10)254 assert im.n_channels == 1255 assert im.pixels.dtype == bool256 assert type(im) == BooleanImage257@patch("PIL.Image.open")258@patch("menpo.io.input.base.Path.is_file")259def test_importing_PIL_1_proper_conversion(is_file, mock_image):260 from menpo.image import BooleanImage261 arr = np.zeros((10, 10), dtype=np.uint8)262 arr[4, 4] = 255263 mock_image.return_value = PILImage.fromarray(arr).convert("1")264 is_file.return_value = True265 im = mio.import_image("fake_image_being_mocked.ppm", normalize=False)266 assert im.shape == (10, 10)267 assert im.n_channels == 1268 assert im.pixels.dtype == bool269 assert type(im) == BooleanImage270 assert np.all(im.pixels == arr.astype(bool))271@patch("PIL.Image.open")272@patch("menpo.io.input.base.Path.is_file")273def test_importing_PIL_P_normalize(is_file, mock_image):274 mock_image.return_value = PILImage.new("P", (10, 10))275 is_file.return_value = True276 im = mio.import_image("fake_image_being_mocked.ppm", normalize=True)277 assert im.shape == (10, 10)278 assert im.n_channels == 3279 assert im.pixels.dtype == float280@patch("PIL.Image.open")281@patch("menpo.io.input.base.Path.is_file")282def test_importing_PIL_P_no_normalize(is_file, mock_image):283 mock_image.return_value = PILImage.new("P", (10, 15))284 is_file.return_value = True285 im = mio.import_image("fake_image_being_mocked.ppm", normalize=False)286 assert im.shape == (15, 10)287 assert im.n_channels == 3288 assert im.pixels.dtype == np.uint8289@patch("subprocess.Popen")290@patch("menpo.io.input.video.video_infos_ffprobe")291@patch("menpo.io.input.base.Path.is_file")292def test_importing_ffmpeg_GIF_normalize(is_file, video_infos_ffprobe, pipe):293 video_infos_ffprobe.return_value = {294 "duration": 2,295 "width": 100,296 "height": 150,297 "n_frames": 10,298 "fps": 5,299 }300 empty_frame = np.zeros(150 * 100 * 3, dtype=np.uint8).tobytes()301 pipe.return_value.stdout.read.return_value = empty_frame302 is_file.return_value = True303 ll = mio.import_image("fake_image_being_mocked.gif", normalize=True)304 assert ll.path.name == "fake_image_being_mocked.gif"305 assert ll.fps == 5306 assert len(ll) == 10307 im = ll[0]308 assert im.shape == (150, 100)309 assert im.n_channels == 3310 assert im.pixels.dtype == float311@patch("subprocess.Popen")312@patch("menpo.io.input.video.video_infos_ffprobe")313@patch("menpo.io.input.base.Path.is_file")314def test_importing_ffmpeg_GIF_no_normalize(is_file, video_infos_ffprobe, pipe):315 video_infos_ffprobe.return_value = {316 "duration": 2,317 "width": 100,318 "height": 150,319 "n_frames": 10,320 "fps": 5,321 }322 empty_frame = np.zeros(150 * 100 * 3, dtype=np.uint8).tobytes()323 pipe.return_value.stdout.read.return_value = empty_frame324 is_file.return_value = True325 ll = mio.import_image("fake_image_being_mocked.gif", normalize=False)326 assert ll.path.name == "fake_image_being_mocked.gif"327 assert ll.fps == 5328 assert len(ll) == 10329 im = ll[0]330 assert im.shape == (150, 100)331 assert im.n_channels == 3332 assert im.pixels.dtype == np.uint8333@patch("menpo.io.input.landmark.json.load")334@patch("menpo.io.input.base.Path.open")335@patch("menpo.io.input.base.Path.is_file")336def test_importing_v1_ljson_null_values(is_file, mock_open, mock_dict):337 v1_ljson = {338 "groups": [339 {340 "connectivity": [[0, 1], [1, 2], [2, 3]],341 "label": "chin",342 "landmarks": [343 {"point": [987.9, 1294.1]},344 {"point": [96.78, 1246.8]},345 {"point": [None, 0.1]},346 {"point": [303.22, 167.2]},347 ],348 },349 {350 "connectivity": [[0, 1]],351 "label": "leye",352 "landmarks": [{"point": [None, None]}, {"point": [None, None]}],353 },354 ],355 "version": 1,356 }357 mock_dict.return_value = v1_ljson358 is_file.return_value = True359 with warnings.catch_warnings(record=True) as found_warnings:360 lmark = mio.import_landmark_file("fake_lmark_being_mocked.ljson", group="LJSON")361 nan_points = np.isnan(lmark.points)362 # Should raise deprecation warning363 assert len(found_warnings) == 1, [w.message for w in found_warnings]364 assert nan_points[2, 0] # y-coord None point is nan365 assert not nan_points[2, 1] # x-coord point is not nan366 assert np.all(nan_points[4:, :]) # all of leye label is nan367@patch("menpo.io.input.landmark.json.load")368@patch("menpo.io.input.base.Path.open")369@patch("menpo.io.input.base.Path.is_file")370def test_importing_v2_ljson_null_values(is_file, mock_open, mock_dict):371 v2_ljson = {372 "labels": [373 {"label": "left_eye", "mask": [0, 1, 2]},374 {"label": "right_eye", "mask": [3, 4, 5]},375 ],376 "landmarks": {377 "connectivity": [[0, 1], [1, 2], [2, 0], [3, 4], [4, 5], [5, 3]],378 "points": [379 [None, 200.5],380 [None, None],381 [316.8, 199.15],382 [339.48, 205.0],383 [358.54, 217.82],384 [375.0, 233.4],385 ],386 },387 "version": 2,388 }389 mock_dict.return_value = v2_ljson390 is_file.return_value = True391 with warnings.catch_warnings(record=True) as w:392 lmark = mio.import_landmark_file("fake_lmark_being_mocked.ljson", group="LJSON")393 nan_points = np.isnan(lmark.points)394 assert nan_points[0, 0] # y-coord None point is nan395 assert not nan_points[0, 1] # x-coord point is not nan396 assert np.all(nan_points[1, :]) # all of leye label is nan397@patch("menpo.io.input.landmark.json.load")398@patch("menpo.io.input.base.Path.open")399@patch("menpo.io.input.base.Path.is_file")400def test_importing_v3_ljson_null_values(is_file, mock_open, mock_dict):401 v3_ljson = {402 "groups": {403 "LJSON": {404 "labels": [405 {"label": "left_eye", "mask": [0, 1, 2]},406 {"label": "right_eye", "mask": [3, 4, 5]},407 ],408 "landmarks": {409 "connectivity": [[0, 1], [1, 2], [2, 0], [3, 4], [4, 5], [5, 3]],410 "points": [411 [None, 200.5],412 [None, None],413 [316.8, 199.15],414 [339.48, 205.0],415 [358.54, 217.82],416 [375.0, 233.4],417 ],418 },419 }420 },421 "version": 3,422 }423 mock_dict.return_value = v3_ljson424 is_file.return_value = True425 lmark_dict = mio.import_landmark_file("fake_lmark_being_mocked.ljson")426 assert isinstance(lmark_dict, dict)427 lmark = lmark_dict["LJSON"]428 nan_points = np.isnan(lmark.points)429 assert nan_points[0, 0] # y-coord None point is nan430 assert not nan_points[0, 1] # x-coord point is not nan431 assert np.all(nan_points[1, :]) # all of leye label is nan432def test_export_import_pointcloud_ljson_v3(tmpdir):433 tmpdir = Path(tmpdir)434 pc = PointCloud(np.random.random([10, 2]), copy=False)435 mio.export_landmark_file(pc, tmpdir / "test.ljson")436 loaded_pc = mio.import_landmark_file(tmpdir / "test.ljson")["LJSON"]437 np.testing.assert_allclose(pc.points, loaded_pc.points)438@patch("random.shuffle")439def test_shuffle_kwarg_true_calls_shuffle(mock):440 list(mio.import_images(mio.data_dir_path(), shuffle=True))441 assert mock.called442def test_import_as_generator():443 import types444 gen = mio.import_images(mio.data_dir_path(), as_generator=True)445 assert isinstance(gen, types.GeneratorType)446 gen = mio.import_landmark_files(mio.data_dir_path(), as_generator=True)447 assert isinstance(gen, types.GeneratorType)448def test_import_lazy_list():449 from menpo.base import LazyList450 data_path = mio.data_dir_path()451 ll = mio.import_images(data_path)452 assert isinstance(ll, LazyList)453 ll = mio.import_landmark_files(data_path)454 assert isinstance(ll, LazyList)455@patch("menpo.io.input.pickle.pickle.load")456@patch("menpo.io.input.base.Path.open")457@patch("menpo.io.input.base.Path.is_file")458def test_importing_pickle(is_file, mock_open, mock_pickle):459 mock_pickle.return_value = {"test": 1}460 is_file.return_value = True461 objs = mio.import_pickle("mocked.pkl")462 assert isinstance(objs, dict)463 assert "test" in objs464 assert objs["test"] == 1465@patch("menpo.io.input.pickle.pickle.load")466@patch("menpo.io.input.base.Path.open")467@patch("menpo.io.input.base.Path.is_file")468@patch("sys.version_info")469def test_importing_pickle_encoding_py3(version_info, is_file, mock_open, mock_pickle):470 version_info.major = 3471 mock_pickle.return_value = {"test": 1}472 is_file.return_value = True473 mio.import_pickle("mocked.pkl", encoding="latin1")474 assert mock_pickle.call_args[1].get("encoding") == "latin1"475@patch("menpo.io.input.pickle.pickle.load")476@patch("menpo.io.input.base.Path.open")477@patch("menpo.io.input.base.Path.is_file")478@patch("sys.version_info")479def test_importing_pickle_encoding_ignored_py2(480 version_info, is_file, mock_open, mock_pickle481):482 version_info.major = 2483 mock_pickle.return_value = {"test": 1}484 is_file.return_value = True485 mio.import_pickle("mocked.pkl", encoding="latin1")486 assert "encoding" not in mock_pickle.call_args[1]487@patch("menpo.io.input.pickle.pickle.load")488@patch("menpo.io.input.base.Path.open")489@patch("menpo.io.input.base.Path.glob")490@patch("menpo.io.input.base.Path.is_file")491def test_importing_pickles(is_file, glob, mock_open, mock_pickle):492 from pathlib import Path493 from menpo.base import LazyList494 mock_pickle.return_value = {"test": 1}495 is_file.return_value = True496 glob.return_value = [Path("mocked1.pkl"), Path("mocked2.pkl")]497 objs = mio.import_pickles("*")498 assert isinstance(objs, LazyList)499 assert len(objs) == 2500 assert objs[0]["test"] == 1501 assert objs[1]["test"] == 1502@patch("menpo.io.input.pickle.pickle.load")503@patch("menpo.io.input.base.Path.open")504@patch("menpo.io.input.base.Path.glob")505@patch("menpo.io.input.base.Path.is_file")506def test_importing_pickles_as_generator(is_file, glob, mock_open, mock_pickle):507 from pathlib import Path508 import types509 mock_pickle.return_value = {"test": 1}510 is_file.return_value = True511 glob.return_value = [Path("mocked1.pkl"), Path("mocked2.pkl")]512 objs = mio.import_pickles("*", as_generator=True)513 assert isinstance(objs, types.GeneratorType)514 objs = list(objs)515 assert len(objs) == 2516 assert objs[0]["test"] == 1517 assert objs[1]["test"] == 1518@patch("subprocess.Popen")519@patch("menpo.io.input.video.video_infos_ffprobe")520@patch("menpo.io.input.base.Path.is_file")521def test_importing_ffmpeg_avi_no_normalize(is_file, video_infos_ffprobe, pipe):522 video_infos_ffprobe.return_value = {523 "duration": 2,524 "width": 100,525 "height": 150,526 "n_frames": 10,527 "fps": 5,528 }529 is_file.return_value = True530 empty_frame = np.zeros(150 * 100 * 3, dtype=np.uint8).tobytes()531 pipe.return_value.stdout.read.return_value = empty_frame532 ll = mio.import_video("fake_image_being_mocked.avi", normalize=False)533 assert ll.path.name == "fake_image_being_mocked.avi"534 assert ll.fps == 5535 assert len(ll) == 5 * 2536 image = ll[0]537 assert image.shape == ((150, 100))538 assert image.n_channels == 3539 assert image.pixels.dtype == np.uint8540@patch("subprocess.Popen")541@patch("menpo.io.input.video.video_infos_ffprobe")542@patch("menpo.io.input.base.Path.is_file")543def test_importing_ffmpeg_avi_normalize(is_file, video_infos_ffprobe, pipe):544 video_infos_ffprobe.return_value = {545 "duration": 2,546 "width": 100,547 "height": 150,548 "n_frames": 10,549 "fps": 5,550 }551 is_file.return_value = True552 empty_frame = np.zeros(150 * 100 * 3, dtype=np.uint8).tobytes()553 pipe.return_value.stdout.read.return_value = empty_frame554 ll = mio.import_video("fake_image_being_mocked.avi", normalize=True)555 assert ll.path.name == "fake_image_being_mocked.avi"556 assert ll.fps == 5557 assert len(ll) == 5 * 2558 image = ll[0]559 assert image.shape == (150, 100)560 assert image.n_channels == 3561 assert image.pixels.dtype == float562@patch("menpo.io.input.video.video_infos_ffprobe")563@patch("menpo.io.input.base.Path.is_file")564def test_importing_ffmpeg_exact_frame_count_no_ffprobe(is_file, video_infos_ffprobe):565 video_infos_ffprobe.side_effect = ValueError566 is_file.return_value = True567 with raises(ValueError):568 mio.import_video(569 "fake_image_being_mocked.avi", normalize=True, exact_frame_count=True570 )571@patch("subprocess.Popen")572@patch("menpo.io.input.video.video_infos_ffprobe")573@patch("menpo.io.input.video.video_infos_ffmpeg")574@patch("menpo.io.input.base.Path.is_file")575def test_importing_ffmpeg_no_exact_frame_count_no_ffprobe(576 is_file, video_infos_ffmpeg, video_infos_ffprobe, pipe577):578 video_infos_ffprobe.side_effect = ValueError579 video_infos_ffmpeg.return_value = {580 "duration": 2,581 "width": 100,582 "height": 150,583 "n_frames": 10,584 "fps": 5,585 }586 is_file.return_value = True587 empty_frame = np.zeros(150 * 100 * 3, dtype=np.uint8).tobytes()588 pipe.return_value.stdout.read.return_value = empty_frame589 ll = mio.import_video(590 "fake_image_being_mocked.avi", normalize=True, exact_frame_count=False591 )592 assert ll.path.name == "fake_image_being_mocked.avi"593 assert ll.fps == 5594 assert len(ll) == 5 * 2595 image = ll[0]596 assert image.shape == (150, 100)597 assert image.n_channels == 3598 assert image.pixels.dtype == float599def test_import_images_negative_max_images():600 with raises(ValueError):601 list(mio.import_images(mio.data_dir_path(), max_images=-2))602def test_import_images_zero_max_images():603 with raises(ValueError):604 # different since the conditional 'if max_assets' is skipped,605 # thus all images might be imported.606 list(mio.import_images(mio.data_dir_path(), max_images=0))607# TODO: remove once the normalise argument is removed.608def test_import_image_deprecated_normalise_kwarg():609 with warnings.catch_warnings(record=True) as w:610 img = mio.import_builtin_asset("breakingbad.jpg", normalise=False)611 assert len(w) == 1612 assert img.pixels.dtype == np.uint8613@patch("menpo.io.input.base.Path.is_file")614def test_register_image_importer(is_file):615 from menpo.image import Image616 image = Image.init_blank((10, 10))617 def foo_importer(filepath, **kwargs):618 return image619 is_file.return_value = True620 with patch.dict(mio.input.extensions.image_types, {}, clear=True):621 mio.register_image_importer(".foo", foo_importer)622 new_image = mio.import_image("fake.foo")623 assert image is new_image624@patch("menpo.io.input.base.Path.is_file")625def test_register_landmark_importer(is_file):626 from menpo.shape import PointCloud627 lmark = PointCloud.init_2d_grid((1, 1))628 def foo_importer(filepath, **kwargs):629 return lmark630 is_file.return_value = True631 with patch.dict(mio.input.extensions.image_landmark_types, {}, clear=True):632 mio.register_landmark_importer(".foo", foo_importer)633 new_lmark = mio.import_landmark_file("fake.foo")634 assert lmark is new_lmark635@patch("menpo.io.input.base.Path.is_file")636def test_register_video_importer(is_file):637 from menpo.image import Image638 from menpo.base import LazyList639 def foo_importer(filepath, **kwargs):640 return LazyList([lambda: Image.init_blank((10, 10))])641 is_file.return_value = True642 with patch.dict(mio.input.extensions.ffmpeg_video_types, {}, clear=True):643 mio.register_video_importer(".foo", foo_importer)644 new_video = mio.import_video("fake.foo")645 assert len(new_video) == 1646@patch("menpo.io.input.base.Path.is_file")647def test_register_pickle_importer(is_file):648 obj = object()649 def foo_importer(filepath, **kwargs):650 return obj651 is_file.return_value = True652 with patch.dict(mio.input.extensions.pickle_types, {}, clear=True):653 mio.register_pickle_importer(".foo", foo_importer)654 new_obj = mio.import_pickle("fake.foo")655 assert new_obj is obj656def test_register_no_leading_period():657 ext_map = {}658 mio.input.base._register_importer(ext_map, "foo", lambda x: x)659 assert ".foo" in ext_map...

Full Screen

Full Screen

contenthandling.py

Source:contenthandling.py Github

copy

Full Screen

1import os2import sys3from . import parsing4from .parsing import *5# Python 2/3 switches6PYTHON_MAJOR_VERSION = sys.version_info[0]7if PYTHON_MAJOR_VERSION > 2:8 from past.builtins import basestring9"""10Encapsulates contend handling logic, for pulling file content into tests11"""12class ContentHandler:13 """ Handles content that may be (lazily) read from filesystem and/or templated to various degrees14 Also creates pixie dust and unicorn farts on demand15 This is pulled out because logic gets complex rather fast16 Covers 6 states:17 - Inline body content, no templating18 - Inline body content, with templating19 - File path to content, NO templating20 - File path to content, content gets templated21 - Templated path to file content (path itself is templated), file content UNtemplated22 - Templated path to file content (path itself is templated), file content TEMPLATED23 """24 content = None # Inline content25 is_file = False26 is_template_path = False27 is_template_content = False28 def is_dynamic(self):29 """ Is templating used? """30 return self.is_template_path or self.is_template_content31 def get_content(self, context=None):32 """ Does all context binding and pathing to get content, templated out """33 if self.is_file:34 path = self.content35 if self.is_template_path and context:36 path = string.Template(path).safe_substitute(37 context.get_values())38 data = None39 with open(path, 'r') as f:40 data = f.read()41 if self.is_template_content and context:42 return string.Template(data).safe_substitute(context.get_values())43 else:44 return data45 else:46 if self.is_template_content and context:47 return safe_substitute_unicode_template(self.content, context.get_values())48 else:49 return self.content50 def create_noread_version(self):51 """ Read file content if it is static and return content handler with no I/O """52 if not self.is_file or self.is_template_path:53 return self54 output = ContentHandler()55 output.is_template_content = self.is_template_content56 with open(self.content, 'r') as f:57 output.content = f.read()58 return output59 def setup(self, input, is_file=False, is_template_path=False, is_template_content=False):60 """ Self explanatory, input is inline content or file path. """61 if not isinstance(input, basestring):62 raise TypeError("Input is not a string")63 if is_file:64 input = os.path.abspath(input)65 self.content = input66 self.is_file = is_file67 self.is_template_path = is_template_path68 self.is_template_content = is_template_content69 @staticmethod70 def parse_content(node):71 """ Parse content from input node and returns ContentHandler object72 it'll look like:73 - template:74 - file:75 - temple: path76 or something77 """78 # Tread carefully, this one is a bit narly because of nesting79 output = ContentHandler()80 is_template_path = False81 is_template_content = False82 is_file = False83 is_done = False84 while (node and not is_done): # Dive through the configuration tree85 # Finally we've found the value!86 if isinstance(node, basestring):87 output.content = node88 output.setup(node, is_file=is_file, is_template_path=is_template_path,89 is_template_content=is_template_content)90 return output91 elif not isinstance(node, dict) and not isinstance(node, list):92 raise TypeError(93 "Content must be a string, dictionary, or list of dictionaries")94 is_done = True95 # Dictionary or list of dictionaries96 flat = lowercase_keys(flatten_dictionaries(node))97 for key, value in flat.items():98 if key == u'template':99 if isinstance(value, basestring):100 if is_file:101 value = os.path.abspath(value)102 output.content = value103 is_template_content = is_template_content or not is_file104 output.is_template_content = is_template_content105 output.is_template_path = is_file106 output.is_file = is_file107 return output108 else:109 is_template_content = True110 node = value111 is_done = False112 break113 elif key == 'file':114 if isinstance(value, basestring):115 output.content = os.path.abspath(value)116 output.is_file = True117 output.is_template_content = is_template_content118 return output119 else:120 is_file = True121 node = value122 is_done = False123 break...

Full Screen

Full Screen

project.py

Source:project.py Github

copy

Full Screen

...7 https://help.github.com/en/github/visualizing-repository-data-with-graphs/8 listing-the-packages-that-a-repository-depends-on#supported-package-ecosystems9 """10 cmfn = path / "codemeta.json"11 if cmfn.is_file():12 try:13 meta = json.loads(cmfn.read_text(errors="ignore"))14 if "programmingLanguage" in meta:15 return [L.lower() for L in meta["programmingLanguage"]]16 except json.decoder.JSONDecodeError:17 pass18 # fallback to heuristic19 if (path / "pyproject.toml").is_file() or (path / "pipfile.lock").is_file():20 return ["python"]21 if (path / "package-lock.json").is_file() or (path / "yarn.lock").is_file():22 return ["javascript"]23 if (path / "composer.lock").is_file():24 return ["php"]25 if (path / "Gemfile.lock").is_file():26 return ["ruby"]...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run assertpy automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful