Best Python code snippet using lemoncheesecake
test_html_render.py
Source:test_html_render.py
...6"""7from io import StringIO8from html_elements import *9import pytest10def render_result(element, data="", ind=""):11 f = StringIO()12 if data:13 element.render(f, ind)14 else:15 element.render(f, ind)16 return f.getvalue()17# ----------------- STEP 1 ----------------- #18def test_init():19 e = Element()20 e = Element("this is some text")21 print(e.contents)22def test_append():23 e = Element("this is some text")24 e.append("some more text")25def test_render_element():26 e = Element("this is some text")27 e.append("and this is some more text")28 file_contents = render_result(e, ind="").strip()29 print(file_contents)30 assert "this is some text" in file_contents31 assert "and this is some more text" in file_contents32 assert file_contents.index("this is") < file_contents.index("and this")33 assert file_contents.startswith("<>")34 assert file_contents.endswith("</>")35def test_render_element2():36 e = Element()37 e.append("this is some text")38 e.append("and this is some more text")39 file_contents = render_result(e, ind="").strip()40 assert "this is some text" in file_contents41 assert "and this is some more text" in file_contents42 assert file_contents.index("this is") < file_contents.index("and this")43 assert file_contents.startswith("<>")44 assert file_contents.endswith("</>")45# ----------------- STEP 2 ----------------- #46def test_html():47 e = Html("this is some text")48 e.append("and this is some more text")49 file_contents = render_result(e, ind="").strip()50 assert "this is some text" in file_contents51 assert "and this is some more text" in file_contents52 print(file_contents)53 assert file_contents.startswith("<!DOCTYPE html>")54 assert file_contents.endswith("</html>")55def test_body():56 e = Body("this is some text")57 e.append("and this is some more text")58 file_contents = render_result(e, ind="").strip()59 print(file_contents)60 assert "this is some text" in file_contents61 assert "and this is some more text" in file_contents62 assert file_contents.startswith("<body>")63 assert file_contents.endswith("</body>")64def test_p():65 e = P("this is some text")66 e.append("and this is some more text")67 file_contents = render_result(e, ind="").strip()68 assert "this is some text" in file_contents69 assert "and this is some more text" in file_contents70 print(file_contents)71 assert file_contents.startswith("<p>")72 assert file_contents.endswith("</p>")73def test_sub_element():74 page = Html()75 page.append("some plain text.")76 page.append(P("A simple paragraph of text"))77 page.append("Some more plain text.")78 file_contents = render_result(page, ind="")79 print(file_contents) # so we can see it if the test fails80 assert "some plain text" in file_contents81 assert "A simple paragraph of text" in file_contents82 assert "Some more plain text." in file_contents83 assert "some plain text" in file_contents84 assert "<p>" in file_contents85 assert "</p>" in file_contents86# ----------------- STEP 3 ----------------- #87def test_head_element():88 page = Html()89 page.append(Head("A header!"))90 page.append(Head("Another header!"))91 page.append("some plain text.")92 page.append(P("A simple paragraph of text"))93 page.append("Some more plain text.")94 file_contents = render_result(page, ind="")95 print(file_contents) # so we can see it if the test fails96 assert "some plain text" in file_contents97 assert "A simple paragraph of text" in file_contents98 assert "Some more plain text." in file_contents99 assert "some plain text" in file_contents100 assert "<head>" in file_contents101 assert "</head>" in file_contents102 assert "A header!" in file_contents103 assert "Another header!" in file_contents104def test_one_line_tag_append():105 e = OneLineTag()106 with pytest.raises(NotImplementedError):107 e.append("some more content")108 file_contents = render_result(e, ind="").strip()109 print(file_contents)110def test_title():111 e = Title("This is a Title")112 file_contents = render_result(e).strip()113 assert "This is a Title" in file_contents114 print(file_contents)115 assert file_contents.startswith("<title>")116 assert file_contents.endswith("</title>")117# ----------------- STEP 4 ----------------- #118def test_attributes():119 e = P("A paragraph of text", style="text-align: center", id="intro")120 file_contents = render_result(e, ind="").strip()121 print(file_contents)122 assert file_contents.endswith("</p>")123 assert file_contents.startswith("<p")124 assert 'style="text-align: center"' in file_contents125 assert 'id="intro"' in file_contents126# ----------------- STEP 5 ----------------- #127def test_hr():128 hr = Hr()129 file_contents = render_result(hr, ind="")130 print(file_contents)131 assert file_contents == '<hr />\n'132def test_hr_attr():133 hr = Hr(width=400)134 file_contents = render_result(hr, ind="")135 print(file_contents)136 assert file_contents == '<hr width="400" />\n'137def test_br():138 br = Br()139 file_contents = render_result(br, ind="")140 print(file_contents)141 assert file_contents == "<br />\n"142def test_content_in_br():143 with pytest.raises(TypeError):144 br = Br("some content")145def test_append_content_in_br():146 with pytest.raises(TypeError):147 br = Br()148 br.append("some content")149# ----------------- STEP 6 ----------------- #150def test_anchor():151 a = A("http://google.com", "link to google")152 file_contents = render_result(a, ind="").strip()153 print(file_contents)154 assert file_contents.startswith('<a ')155# ----------------- STEP 7 ----------------- #156def test_ul():157 u_list = Ul(id="TheList", style="line-height:200%")158 file_contents = render_result(u_list, ind="").strip()159 print(file_contents)160 assert file_contents.startswith('<ul ')161 assert file_contents.endswith("</ul>")162 assert 'id="TheList"' in file_contents163 assert 'style="line-height:200%"' in file_contents164def test_li():165 a_list = Li("This is the second item", style="color: red")166 file_contents = render_result(a_list, ind="").strip()167 print(file_contents)168 assert file_contents.startswith('<li ')169 assert file_contents.endswith("</li>")170 assert 'style="color: red"' in file_contents171# ----------------- STEP 8 ----------------- #172def test_meta():173 m = Meta()174 file_contents = render_result(m, ind="").strip()175 print(file_contents)176 assert file_contents == '<meta />'177def test_meta_attr():178 m = Meta(charset="UTF-8")179 file_contents = render_result(m, ind="").strip()180 print(file_contents)181 assert file_contents == '<meta charset="UTF-8" />'182# ----------------- STEP 9 ----------------- #183def test_indent():184 html = Html("some content")185 file_contents = render_result(html, ind=" ").rstrip() #remove the end newline186 print(file_contents)187 lines = file_contents.split("\n")188 assert lines[-1].startswith(" <")189 print(repr(lines[-1]))190 assert lines[-1].startswith(" <")191def test_indent_contents():192 html = Element("some content")193 file_contents = render_result(html, ind="")194 print(file_contents)195 lines = file_contents.split("\n")196 assert lines[1].startswith(html.indent)197def test_multiple_indent():198 body = Body()199 body.append(P("some text"))200 html = Html(body)201 file_contents = render_result(html)202 print(file_contents)203 lines = file_contents.split("\n")204 for i in range(3): # this needed to be adapted to the <DOCTYPE> tag205 assert lines[i + 1].startswith(i * html.indent + "<")206 assert lines[4].startswith(3 * html.indent + "some")207def test_element_indent1():208 e = Html("this is some text")209 file_contents = render_result(e).strip()210 print(file_contents)211 assert "this is some text" in file_contents212 lines = file_contents.split('\n')213 assert lines[1] == "<html>"214 assert lines[2].startswith(e._indent + "thi")215 assert lines[3] == "</html>"...
render.py
Source:render.py
1import numpy as np2import cv23import core4from libcpp_render import cpp_render5import os6import util7class camera():8 def __init__(self, focal_length, center_x, center_y, trans):9 self.focal = focal_length.astype(np.float32)10 self.cx = center_x.astype(np.float32)11 self.cy = center_y.astype(np.float32)12 self.trans = trans.astype(np.float32)13 self.renderer = core.SMPLRenderer(face_path="opendr_render/smpl_faces.npy")14 def render_naked(self, verts, img=None):15 ## camera_for_render [focal center_x center_y camera_t_x camera_t_y camera_t_z]16 camera_for_render = np.hstack([self.focal, self.cx, self.cy, self.trans])17 render_result = self.renderer(verts, cam=camera_for_render, img=img, do_alpha=True)18 return render_result19 def render_naked_rotation(self, verts, angle, img=None):20 ## camera_for_render [focal center_x center_y camera_t_x camera_t_y camera_t_z]21 camera_for_render = np.hstack([self.focal, self.cx, self.cy, self.trans])22 render_result = self.renderer.rotated(verts, angle, cam=camera_for_render, img_size=img.shape[:2])23 return render_result24 def generate_uv(self, verts, image=None):25 rt = np.zeros(3)26 t = self.trans27 camera_matrix = np.array([[self.focal, 0.0, self.cx],28 [0.0, self.focal, self.cy],29 [0.0, 0.0, 1.0]])30 k = np.zeros(5)31 uv_real = cv2.projectPoints(verts, rt, t, camera_matrix, k)[0].squeeze()32 width = 600.0 if image is None else float(image.shape[1])33 height = 450.0 if image is None else float(image.shape[0])34 uv_u = (uv_real[:, 0] / width).reshape((len(uv_real), 1))35 uv_v = (uv_real[:, 1] / height).reshape((len(uv_real), 1))36 uv_norm = np.hstack((uv_u, uv_v))37 return uv_real, uv_norm38 def write_camera(self, path):39 f = open(path, "w")40 f.write(str(self.focal) + " " + str(self.trans[0]) + " " + str(self.trans[1]) + " " + str(self.trans[2])41 + " " + str(self.cx) + " " + str(self.cy))42 f.close()43 def write_obj(self, path, verts, uv=None):44 with open(path, 'w') as fp:45 fp.write("mtllib test.mtl\n")46 fp.write("\n")47 for v in verts:48 fp.write('v %f %f %f\n' % (v[0], v[1], v[2]))49 fp.write("\n")50 if uv is not None:51 for uv in uv:52 fp.write('vt %f %f %f\n' % (uv[0], uv[1], 0.))53 fp.write("\n")54 fp.write("o m_avg\n")55 fp.write("g m_avg\n")56 fp.write("usemtl lambert1\n")57 fp.write("s 1\n")58 for face in self.renderer.faces + 1:59 fp.write('f %d/%d %d/%d %d/%d\n' % (face[0], face[0], face[1], face[1], face[2], face[2]))60 '''61 img is texture image, arbitrary size62 '''63 def render_texture(self, verts, img, vt):64 self.write_camera("./render_temp/camera.txt")65 self.write_obj("./render_temp/model.obj", verts, vt)66 cv2.imwrite("./render_temp/HR.png", img)67 cpp_render(util.img_widthheight)68 render_result = cv2.imread("./render_temp/result.png")69 return render_result70 def render_texture_imgbg(self, render_result, bg, method=None):71 bg_img = np.copy(bg)72 for i in range(render_result.shape[0]):73 for j in range(render_result.shape[1]):74 if render_result[i, j, 0] == 0 and render_result[i, j, 1] == 0 and render_result[i, j, 2] == 0:75 continue76 bg_img[i, j, :] = render_result[i, j, :]77 if method == "poisson":78 ###extract mask###79 mask = np.ones_like(render_result) * 25580 for i in range(render_result.shape[0]):81 for j in range(render_result.shape[1]):82 if render_result[i, j, 0] == 0 and render_result[i, j, 1] == 0 and render_result[i, j, 2] == 0:83 continue84 mask[i, j, :] = 25585 center = (render_result.shape[1] / 2, render_result.shape[0] / 2)86 bg_img = cv2.seamlessClone(render_result, bg, mask, center, cv2.NORMAL_CLONE)87 return bg_img88 '''89 save cropped texture90 '''91 def save_texture_img(self, img, mask=None):92 if mask is not None:93 img = cv2.add(img, np.zeros(np.shape(img), dtype=np.uint8),94 mask=mask)95 return img96 '''97 img is texture image, arbitrary size98 '''99 def write_texture_data(self, texture_path, vt):100 if not os.path.exists(texture_path):101 os.makedirs(texture_path)102 np.save(texture_path + "vt.npy", vt)103def read_texture_data(texture_path):104 vt = np.load(texture_path + "vt.npy")105 img = cv2.imread(texture_path + "../../output_nonrigid/texture.png")106 return vt, img107def opencv2render(img):108 b, g, r = cv2.split(img)109 img_ = cv2.merge([r, g, b])110 return img_111def save_nonrigid_template(texture_path, template):...
test_nerf_render.py
Source:test_nerf_render.py
1from typing import Dict, Final2import torch3from torch import Tensor4from neddf.render import NeRFRender5class TestNeRFRender:6 def test_nerf_render_constructor(self, nerf_config_fixture):7 # test construct of nerf_render8 NeRFRender(9 network_config=nerf_config_fixture,10 )11 def test_integrate_volume_render(self, nerf_config_fixture):12 # test data13 batch_size: Final[int] = 3214 sampling_count: Final[int] = 6415 distances: Tensor = (16 torch.linspace(0.0, 2.0, sampling_count, dtype=torch.float32)17 .unsqueeze(0)18 .expand(batch_size, sampling_count)19 )20 densities: Tensor = torch.ones(batch_size, sampling_count)21 colors: Tensor = torch.ones(batch_size, sampling_count, 3)22 # make nerf render instance23 # TODO: add other networks list and test them24 neural_render: NeRFRender = NeRFRender(25 network_config=nerf_config_fixture,26 )27 render_result: Dict[str, Tensor] = neural_render.integrate_volume_render(28 distances,29 densities,30 colors,31 )32 # check that the result dict have collect keys33 assert "depth" in render_result34 assert "color" in render_result35 assert "transmittance" in render_result36 assert render_result["depth"].shape == (batch_size,)37 assert render_result["color"].shape == (batch_size, 3)38 assert render_result["transmittance"].shape == (batch_size,)39 def test_render_rays(self, camera_fixture, nerf_config_fixture):40 # test data: 2D positions in uv41 batch_size: Final[int] = 3242 us: Tensor = torch.linspace(0, 480, batch_size, dtype=torch.float32)43 vs: Tensor = torch.linspace(0, 640, batch_size, dtype=torch.float32)44 uv: Tensor = torch.stack([us, vs], 1)45 # make nerf render instance46 # TODO: add other networks list and test them47 neural_render: NeRFRender = NeRFRender(48 network_config=nerf_config_fixture,49 )50 render_result: Dict[str, Tensor] = neural_render.render_rays(uv, camera_fixture)51 # check that the result dict have collect keys52 assert "depth" in render_result53 assert "color" in render_result54 assert "transmittance" in render_result55 assert render_result["depth"].shape == (batch_size,)56 assert render_result["color"].shape == (batch_size, 3)...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!