How to use test_instantiate method in avocado

Best Python code snippet using avocado_python

test_instantiate.py

Source:test_instantiate.py Github

copy

Full Screen

1import copy2from typing import Any, Dict, List, Optional3import pytest4from genos import instantiate5from genos.instantiate import ObjectConfig, RecursiveClassInstantiationError6from omegaconf import DictConfig, OmegaConf7class Level3:8 def __init__(self, a_3: str, b_3: int = 10):9 self.a_3 = a_310 self.b_3 = b_311 def __eq__(self, other: Any) -> Any:12 """Overrides the default implementation"""13 if isinstance(other, Level3):14 return self.a_3 == other.a_3 and self.b_3 == other.b_315 return NotImplemented16class Level2:17 def __init__(self, a_2: Level3, b_2: int):18 self.a_2 = a_219 self.b_2 = b_220 def __eq__(self, other: Any) -> Any:21 """Overrides the default implementation"""22 if isinstance(other, Level2):23 return self.a_2 == other.a_2 and self.b_2 == other.b_224 return NotImplemented25class Level1:26 def __init__(self, a_1: Level2):27 self.a_1 = a_128 def __eq__(self, other: Any) -> Any:29 """Overrides the default implementation"""30 if isinstance(other, Level1):31 return self.a_1 == other.a_132 return NotImplemented33# The following code block was taken from Hydra34# https://github.com/facebookresearch/hydra/blob/master/tests/tests.test_utils.py35# Start Hydra block36def some_method() -> int:37 return 4238non_callable_object: List = []39class Bar:40 def __init__(self, a: Any, b: Any, c: Any, d: Any = "default_value") -> None:41 self.a = a42 self.b = b43 self.c = c44 self.d = d45 def __repr__(self) -> str:46 return f"a={self.a}, b={self.b}, c={self.c}, d={self.d}"47 @staticmethod48 def static_method() -> int:49 return 4350 def __eq__(self, other: Any) -> Any:51 """Overrides the default implementation"""52 if isinstance(other, Bar):53 return (54 self.a == other.a55 and self.b == other.b56 and self.c == other.c57 and self.d == other.d58 )59 return NotImplemented60 def __ne__(self, other: Any) -> Any:61 """Overrides the default implementation (unnecessary in Python 3)"""62 x = self.__eq__(other)63 if x is not NotImplemented:64 return not x65 return NotImplemented66class Foo:67 def __init__(self, x: int) -> None:68 self.x = x69 def __eq__(self, other: Any) -> Any:70 if isinstance(other, Foo):71 return self.x == other.x72 return False73class Baz(Foo):74 @classmethod75 def class_method(self, y: int) -> Any:76 return self(y + 1)77 @staticmethod78 def static_method(z: int) -> int:79 return z80class Fii:81 def __init__(self, a: Baz = Baz(10)):82 self.a = a83 def __repr__(self) -> str:84 return f"a={self.a}"85 def __eq__(self, other: Any) -> Any:86 """Overrides the default implementation"""87 if isinstance(other, Fii):88 return self.a == other.a89 return NotImplemented90 def __ne__(self, other: Any) -> Any:91 """Overrides the default implementation (unnecessary in Python 3)"""92 x = self.__eq__(other)93 if x is not NotImplemented:94 return not x95 return NotImplemented96fii = Fii()97def fum(k: int) -> int:98 return k + 199@pytest.mark.parametrize( # type: ignore100 "path, expected_type", [("tests.test_instantiate.Bar", Bar)]101)102def test_get_class(path: str, expected_type: type) -> None:103 assert instantiate.get_class(path) == expected_type104@pytest.mark.parametrize( # type: ignore105 "path, return_value, expected_error",106 [107 ("tests.test_instantiate.some_method", 42, None),108 ("tests.test_instantiate.invalid_method", None, ValueError),109 ("cannot.locate.this.package", None, ValueError),110 ("tests.test_instantiate.non_callable_object", None, ValueError),111 ],112)113def test_get_method(path: str, return_value: Any, expected_error: Exception) -> None:114 if expected_error is not None:115 with pytest.raises(expected_error):116 assert instantiate.get_method(path)() == return_value117 else:118 assert instantiate.get_method(path)() == return_value119@pytest.mark.parametrize( # type: ignore120 "path, return_value", [("tests.test_instantiate.Bar.static_method", 43)]121)122def test_get_static_method(path: str, return_value: Any) -> None:123 assert instantiate.get_static_method(path)() == return_value124@pytest.mark.parametrize( # type: ignore125 "input_conf, key_to_get_config, kwargs_to_pass, expected",126 [127 (128 {129 "cls": "tests.test_instantiate.Bar",130 "params": {"a": 10, "b": 20, "c": 30, "d": 40},131 },132 None,133 {},134 Bar(10, 20, 30, 40),135 ),136 (137 {138 "all_params": {139 "main": {140 "cls": "tests.test_instantiate.Bar",141 "params": {"a": 10, "b": 20, "c": "${all_params.aux.c}"},142 },143 "aux": {"c": 30},144 }145 },146 "all_params.main",147 {"d": 40},148 Bar(10, 20, 30, 40),149 ),150 (151 {"cls": "tests.test_instantiate.Bar", "params": {"b": 20, "c": 30}},152 None,153 {"a": 10, "d": 40},154 Bar(10, 20, 30, 40),155 ),156 (157 {158 "cls": "tests.test_instantiate.Bar",159 "params": {"b": 200, "c": "${params.b}"},160 },161 None,162 {"a": 10, "d": 40},163 Bar(10, 200, 200, 40),164 ),165 # Check class and static methods166 (167 {"cls": "tests.test_instantiate.Baz.class_method", "params": {"y": 10}},168 None,169 {},170 Baz(11),171 ),172 (173 {"cls": "tests.test_instantiate.Baz.static_method", "params": {"z": 43}},174 None,175 {},176 43,177 ),178 # Check nested types and static methods179 ({"cls": "tests.test_instantiate.Fii", "params": {}}, None, {}, Fii(Baz(10))),180 (181 {"cls": "tests.test_instantiate.fii.a.class_method", "params": {"y": 10}},182 None,183 {},184 Baz(11),185 ),186 (187 {"cls": "tests.test_instantiate.fii.a.static_method", "params": {"z": 43}},188 None,189 {},190 43,191 ),192 # Check that default value is respected193 (194 {195 "cls": "tests.test_instantiate.Bar",196 "params": {"b": 200, "c": "${params.b}"},197 },198 None,199 {"a": 10},200 Bar(10, 200, 200, "default_value"),201 ),202 (203 {"cls": "tests.test_instantiate.Bar", "params": {}},204 None,205 {"a": 10, "b": 20, "c": 30},206 Bar(10, 20, 30, "default_value"),207 ),208 # call a function from a module209 ({"cls": "tests.test_instantiate.fum", "params": {"k": 43}}, None, {}, 44),210 # Check builtins211 ({"cls": "builtins.str", "params": {"object": 43}}, None, {}, "43"),212 ],213)214def test_class_instantiate(215 input_conf: Dict[str, Any],216 key_to_get_config: Optional[str],217 kwargs_to_pass: Dict[str, Any],218 expected: Any,219) -> Any:220 conf = OmegaConf.create(input_conf)221 assert isinstance(conf, DictConfig)222 if key_to_get_config is None:223 config_to_pass = conf224 else:225 config_to_pass = OmegaConf.select(conf, key_to_get_config)226 config_to_pass_copy = copy.deepcopy(config_to_pass)227 obj = instantiate.instantiate(config_to_pass, **kwargs_to_pass)228 assert obj == expected229 # make sure config is not modified by instantiate230 assert config_to_pass == config_to_pass_copy231def test_class_instantiate_pass_omegaconf_node() -> Any:232 pc = ObjectConfig()233 # This is a bit clunky because it exposes a problem with the backport of dataclass on Python 3.6234 # see: https://github.com/ericvsmith/dataclasses/issues/155235 pc.cls = "tests.test_instantiate.Bar"236 pc.params = {"b": 200, "c": {"x": 10, "y": "${params.b}"}}237 conf = OmegaConf.structured(pc)238 obj = instantiate.instantiate(conf, **{"a": 10, "d": Foo(99)})239 assert obj == Bar(10, 200, {"x": 10, "y": 200}, Foo(99))240 assert OmegaConf.is_config(obj.c)241def test_class_warning() -> None:242 expected = Bar(10, 20, 30, 40)243 config = OmegaConf.structured(244 {245 "cls": "tests.test_instantiate.Bar",246 "params": {"a": 10, "b": 20, "c": 30, "d": 40},247 }248 )249 assert instantiate.instantiate(config) == expected250 config = OmegaConf.structured(251 {252 "cls": "tests.test_instantiate.Bar",253 "params": {"a": 10, "b": 20, "c": 30, "d": 40},254 }255 )256 assert instantiate.instantiate(config) == expected257# End Hydra block258@pytest.mark.parametrize(259 "input_conf, key_to_get_config, kwargs_to_pass, expected",260 [261 (262 {263 "cls": "tests.test_instantiate.Level1",264 "params": {265 "a_1": {266 "cls": "tests.test_instantiate.Level2",267 "params": {268 "a_2": {269 "cls": "tests.test_instantiate.Level3",270 "params": {"a_3": "a_3", "b_3": 11},271 },272 "b_2": 42,273 },274 }275 },276 },277 None,278 {},279 Level1(a_1=Level2(a_2=Level3(a_3="a_3", b_3=11), b_2=42)),280 )281 ],282)283def test_recursive_instantiate(284 input_conf: Dict[str, Any],285 key_to_get_config: Optional[str],286 kwargs_to_pass: Dict[str, Any],287 expected: Any,288) -> Any:289 conf = OmegaConf.create(input_conf)290 assert isinstance(conf, DictConfig)291 if key_to_get_config is None:292 config_to_pass = conf293 else:294 config_to_pass = OmegaConf.select(conf, key_to_get_config)295 config_to_pass_copy = copy.deepcopy(config_to_pass)296 obj = instantiate.recursive_instantiate(config_to_pass, **kwargs_to_pass)297 assert obj == expected298 # make sure config is not modified by instantiate299 assert config_to_pass == config_to_pass_copy300@pytest.mark.parametrize(301 "input_conf, args, expected_instantiate_exception, expected_recursive_instantiate_exception",302 [303 ({"cls": "some.path.that.will.fail", "params": {}}, [], Exception, Exception),304 (305 {"cls": "tests.test_instantiate.SomeLevel", "params": {}},306 [],307 ValueError,308 RecursiveClassInstantiationError,309 ),310 (311 {"cls": "tests.test_instantiate.SomeLevel", "params": {}},312 [],313 ValueError,314 RecursiveClassInstantiationError,315 ),316 (317 {"classsss": "tests.test_instantiate.SomeLevel", "params": {}},318 [],319 ValueError,320 RecursiveClassInstantiationError,321 ),322 (323 None,324 [],325 AssertionError,326 AssertionError,327 ),328 ],329)330def test_invalid_instantiate(331 input_conf: Dict,332 args: List,333 expected_instantiate_exception: Exception,334 expected_recursive_instantiate_exception: Exception,335):336 if input_conf:337 conf = OmegaConf.create(input_conf)338 assert isinstance(conf, DictConfig)339 else:340 conf = input_conf341 with pytest.raises(expected_instantiate_exception):342 instantiate.instantiate(conf)343 with pytest.raises(expected_recursive_instantiate_exception):...

Full Screen

Full Screen

test_items.py

Source:test_items.py Github

copy

Full Screen

...29 def setUp(self):30 """ Autogenerated. """31 pass32 33 def test_instantiate(self):34 """ Autogenerated. """35 obj = BaseMixin() # TODO: may fail!36class ChartItemTests(unittest.TestCase):37 def setUp(self):38 """ Autogenerated. """39 pass40 41 def test_instantiate(self):42 """ Autogenerated. """43 obj = ChartItem() # TODO: may fail!44class ChartItemFlagsTests(unittest.TestCase):45 def setUp(self):46 """ Autogenerated. """47 pass48 49 def test_instantiate(self):50 """ Autogenerated. """51 obj = ChartItemFlags() # TODO: may fail!52class ChartItemGroupTests(unittest.TestCase):53 def setUp(self):54 """ Autogenerated. """55 pass56 57 def test_instantiate(self):58 """ Autogenerated. """59 obj = ChartItemGroup() # TODO: may fail!60class ChartWidgetItemTests(unittest.TestCase):61 def setUp(self):62 """ Autogenerated. """63 pass64 65 def test_instantiate(self):66 """ Autogenerated. """67 obj = ChartWidgetItem() # TODO: may fail!68class ColorSetTests(unittest.TestCase):69 def setUp(self):70 """ Autogenerated. """71 pass72 73 def test_instantiate(self):74 """ Autogenerated. """75 obj = ColorSet() # TODO: may fail!76class CoordCrossTests(unittest.TestCase):77 def setUp(self):78 """ Autogenerated. """79 pass80 81 def test_instantiate(self):82 """ Autogenerated. """83 obj = CoordCross() # TODO: may fail!84class HLineTests(unittest.TestCase):85 def setUp(self):86 """ Autogenerated. """87 pass88 89 def test_instantiate(self):90 """ Autogenerated. """91 obj = HLine() # TODO: may fail!92class LineChartItemTests(unittest.TestCase):93 def setUp(self):94 """ Autogenerated. """95 pass96 97 def test_instantiate(self):98 """ Autogenerated. """99 obj = LineChartItem() # TODO: may fail!100class RectMarkerTests(unittest.TestCase):101 def setUp(self):102 """ Autogenerated. """103 pass104 105 def test_instantiate(self):106 """ Autogenerated. """107 obj = RectMarker(QPointF(0,0)) # TODO: may fail!108class TextItemTests(unittest.TestCase):109 app = None110 @classmethod111 def setUpClass(cls):112 TextItemTests.app = QApplication([])113 def setUp(self):114 """ Autogenerated. """115 pass116 117 def test_instantiate(self):118 """ Autogenerated. """119 obj = TextItem(QPointF(0,0), "Text") # TODO: may fail!120class VLineTests(unittest.TestCase):121 def setUp(self):122 """ Autogenerated. """123 pass124 125 def test_instantiate(self):126 """ Autogenerated. """127 obj = VLine() # TODO: may fail!128class WireItemTests(unittest.TestCase):129 def setUp(self):130 """ Autogenerated. """131 pass132 133 def test_instantiate(self):134 """ Autogenerated. """...

Full Screen

Full Screen

test_pre_tokenizers.py

Source:test_pre_tokenizers.py Github

copy

Full Screen

...9 Metaspace,10 CharDelimiterSplit,11)12class TestByteLevel:13 def test_instantiate(self):14 assert ByteLevel() is not None15 assert ByteLevel(add_prefix_space=True) is not None16 assert ByteLevel(add_prefix_space=False) is not None17 assert isinstance(ByteLevel(), PreTokenizer)18 assert isinstance(ByteLevel(), ByteLevel)19 assert isinstance(pickle.loads(pickle.dumps(ByteLevel())), ByteLevel)20 def test_has_alphabet(self):21 assert isinstance(ByteLevel.alphabet(), list)22 assert len(ByteLevel.alphabet()) == 25623class TestWhitespace:24 def test_instantiate(self):25 assert Whitespace() is not None26 assert isinstance(Whitespace(), PreTokenizer)27 assert isinstance(Whitespace(), Whitespace)28 assert isinstance(pickle.loads(pickle.dumps(Whitespace())), Whitespace)29class TestWhitespaceSplit:30 def test_instantiate(self):31 assert WhitespaceSplit() is not None32 assert isinstance(WhitespaceSplit(), PreTokenizer)33 assert isinstance(WhitespaceSplit(), WhitespaceSplit)34 assert isinstance(pickle.loads(pickle.dumps(WhitespaceSplit())), WhitespaceSplit)35class TestBertPreTokenizer:36 def test_instantiate(self):37 assert BertPreTokenizer() is not None38 assert isinstance(BertPreTokenizer(), PreTokenizer)39 assert isinstance(BertPreTokenizer(), BertPreTokenizer)40 assert isinstance(pickle.loads(pickle.dumps(BertPreTokenizer())), BertPreTokenizer)41class TestMetaspace:42 def test_instantiate(self):43 assert Metaspace() is not None44 assert Metaspace(replacement="-") is not None45 with pytest.raises(Exception, match="replacement must be a character"):46 Metaspace(replacement="")47 assert Metaspace(add_prefix_space=True) is not None48 assert isinstance(Metaspace(), PreTokenizer)49 assert isinstance(Metaspace(), Metaspace)50 assert isinstance(pickle.loads(pickle.dumps(Metaspace())), Metaspace)51class TestCharDelimiterSplit:52 def test_instantiate(self):53 assert CharDelimiterSplit("-") is not None54 with pytest.raises(Exception, match="delimiter must be a single character"):55 CharDelimiterSplit("")56 assert isinstance(CharDelimiterSplit(" "), PreTokenizer)57 assert isinstance(CharDelimiterSplit(" "), CharDelimiterSplit)...

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 avocado 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