How to use plugin_interface method in Nose

Best Python code snippet using nose

write_checkers.py

Source:write_checkers.py Github

copy

Full Screen

1#!/usr/bin/env python2"""3write_checkers.py4=================5Writes checkers for a given project.6Usage:7------8 write_checkers.py <project_id>9"""10# Standard library imports11import os, sys, glob, re12from collections import OrderedDict as OD13# Third-party imports14import simplejson15import yaml16# Local imports17from check_maker.renderers import write_spec_document, write_plugin_module18from checklib.register import get_check_class19CHECK_LIB_GIT_REPO = "https://github.com/cedadev/compliance-check-lib"20OUTPUT_DIR = "output"21INPUTS_DIR = "project"22__INCLUDE_PATTERN__ = "__INCLUDE__"23CHECK_ATTRIBUTE_MAP = OD([24 ("check_id", "Check ID"),25 ("description", "Description"),26 ("vocabulary_ref", "Controlled Vocab ref"),27 ("check_level", "Level"),28 ("check_responses", "Responses"),29 ("comments", "Comments"),30 ("python_interface", "Python check (link to repository)"),31 ("check_unittest", "Python unittest")32])33def _check_exists(dr):34 """35 Ensures a directory ``dr`` exists.36 :param dr: directory path37 :return: None38 """39 if not os.path.isdir(dr): os.makedirs(dr)40def get_check_defn_files(project):41 """42 Returns a list of check definition YAML files for `project`.43 :param project: project ID [string].44 :return: list of file paths.45 """46 yml_files = glob.glob(os.path.join(INPUTS_DIR, project, "[a-zA-Z0-9]*.yml"))47 yml_files.remove(os.path.join(INPUTS_DIR, project, "PROJECT_METADATA.yml"))48 return yml_files49def get_project_metadata(project):50 """51 Return project metadata.52 :return: dictionary of metadata about the project.53 """54 return _read_yaml(os.path.join(INPUTS_DIR, project, "PROJECT_METADATA.yml"))[0]55def _parse_kwargs_string(s):56 """57 Parses string and returns a dictionary. All values are strings.58 :param s: string specifying key/value pairs in format: X=Y,A=10,B=hello59 :return: dictionary of parsed content60 """61 if not s: return {}62 d = dict([item.split("=") for item in s.split(";")])63 return d64def _build_check_specifier(dct, check_prefix, plugin_interface, check_number):65 """66 Parse dictionary `dct` defining check and combines it with information from67 the checklib registers to create and return detailed dictionary.68 :param dct: dictionary of input details for check69 :param check_prefix: prefix string to start each check with70 :param plugin_interface: plugin ID71 :param check_number: number for this check (integer)72 :return: dictionary defining details of a check.73 """74 # Clone the dictionary using empty strings for None values75 d = dict([(key, value or "") for key, value in dct.items()])76 d["kwargs"] = d.get("modifiers", {})77 d["plugin_id"] = plugin_interface78 79 d["vocabulary_ref"] = d.get("vocabulary_ref", "")80 d["comments"] = d.get("comments", "")81 d["check_level"] = d.get("check_level", "HIGH")82 # Get class to work with83 cls = get_check_class(d["check_name"])84 check = cls(d["kwargs"])85 # Update info required for rendering86 d["check_responses"] = dict([(i, response) for i, response in enumerate(check.get_messages())])87 d["description"] = check.get_description()88 # Define python interfaces89 d["python_interface"] = "{}.{}".format(cls.__module__, cls.__name__)90 d["check_unittest"] = ""91 # Define check Id92 d["check_id"] = "{}_{:03d}".format(check_prefix, check_number)93 return d94class ChecksList(object):95 """96 A class to manage a list of checks and their numeric IDs.97 """98 def __init__(self, plugin_interface, prefix):99 self.plugin_interface = plugin_interface100 self.prefix = prefix101 self.checks = []102 def add_check(self, check_dict):103 """104 Takes a dictionary of check details, makes a new check and appends105 it to `self.checks`.106 :param check_dict: dictionary of checks107 :return: None108 """109 n = len(self.checks) + 1110 check = _build_check_specifier(check_dict, self.prefix,111 self.plugin_interface, n)112 self.checks.append(check)113 self._validate_check_ids()114 def _validate_check_ids(self):115 "Validate check IDs are unique."116 check_ids = [check["check_id"] for check in self.checks]117 if len(check_ids) != len(set(check_ids)):118 raise Exception("Duplicate check IDs are not allowed. Found: {}".format(check_ids))119def add_checks(checks_list, checks, project):120 """121 Adds a set of checks to `check_list`.122 :param checks_list: Instance of ChecksList123 :param checks: list of checks to add124 :param project: Project name [string]125 :return: None126 """127 for check in checks:128 # If an "__INCLUDE__" directive used: then include checks from it129 if __INCLUDE_PATTERN__ in check.keys():130 yaml_path = check[__INCLUDE_PATTERN__]131 if not os.path.isfile(yaml_path):132 yaml_path = os.path.join('project/{}'.format(project), yaml_path)133 included_checks = _read_yaml(yaml_path)134 add_checks(checks_list, included_checks, project)135 else:136 checks_list.add_check(check)137def _read_yaml(fpath, loader=yaml.Loader):138 """139 Returns contents of YAML file as parsed by `yaml.load`.140 :param fpath: file path141 :param loader: Loader class.142 :return: contents of YAML file143 """144 with open(fpath, 'r') as reader:145 contents = yaml.load(reader, Loader=loader)146 return contents147def parse_checks_definitions(project, check_defn_file):148 """149 Parses input files defining:150 - plugin interface to compliance checker class151 - a list of checks to implement within that class.152 :param project: Project name [string]153 :param check_defn_file: file path - defining the interface and checks [string]154 :return: tuple of (plugin interface dict, list of dictionaries of checks)155 """156 # Read in the tab-separated set of checks for this set of checks157 yaml_content = _read_yaml(check_defn_file)158 check_defns = yaml_content[1:]159 # Check plugin interface is always first dictionary expand it160 plugin_interface = yaml_content[0]161 pi = plugin_interface162 # Get generic plugin details from YAML file163 pid = pi['ccPluginDetails'].replace(" Check", "")164 pi['ccPluginClass'] = "{}Check".format(pid.replace(" ", ""))165 pi['ccPluginId'] = pid.lower().replace(" ", "-")166 project_metadata = get_project_metadata(project)167 pi['ccPluginPackage'] = "{}.{}".format(project_metadata['plugin'],168 pid.lower().replace(" ", "_"))169 check_prefix = pi['checkIdPrefix']170 # Create ChecksList object and compile list of checks171 checks_list = ChecksList(plugin_interface, check_prefix)172 add_checks(checks_list, check_defns, project)173 return plugin_interface, checks_list.checks174def _html_tidy_cell_item(item, key):175 """176 Returns HTML-tidied item for putting in table cell.177 :param item: item to be tidied178 :param key: dictionary key (for reference)179 :return: tidied HTML item or string180 """181 if isinstance(item, dict):182 resp = "<br/>\n".join(["{}: {}".format(key, value) for key, value in item.items()])183 resp += "<br/>{}: SUCCESS!".format(int(key) + 1)184 return resp185 return item186def _get_check_url(check_module, check_class_name):187 """188 Returns the URL to the line in GitHub that represents that checker class.189 :param check_module: python module containing check190 :param check_class_name: name of check class191 :return: URL to check [string].192 """193 # Try to grep line number for class194 try:195 loc_of_module = "../compliance-check-lib/{}.py".format(check_module)196 with open(loc_of_module) as reader:197 for n, line in enumerate(reader):198 if line.find("class {}".format(check_class_name)) == 0:199 line_number = n + 1200 break201 except:202 line_number = ""203 return "{}/blob/master/{}.py#L{}".format(CHECK_LIB_GIT_REPO, check_module, line_number)204def _get_unittest_details(check_class_name):205 """206 Returns the information about the module in GitHub that contains unit tests for this class.207 Response is a tuple of (unittest_module_name, unittest_url).208 :param check_class_name: name of check class209 :return: Tuple of (unittest_module_name, URL).210 """211 # Grep each module in the unittests folder until we match a function name with212 # the check class name213 candidate_modules = glob.glob("../compliance-check-lib/checklib/test/test_*.py")214 for mod in candidate_modules:215 with open(mod) as reader:216 for line in reader:217 if re.match("^def .*{}".format(check_class_name), line):218 module_name = os.path.split(mod)[-1]219 url = "{}/blob/master/checklib/test/{}".format(CHECK_LIB_GIT_REPO, module_name)220 return module_name, url221 print ("[WARNING] Could not locate unit test for: {}.".format(check_class_name))222 return "", ""223def _get_content_for_html_row(check):224 """225 Returns a list of content for each HTML cell in a table for a given check.226 :param check: check dictionary (from config)227 :return: list of check contents for HTML row.228 """229 contents = []230 for attr in CHECK_ATTRIBUTE_MAP.keys():231 item = _html_tidy_cell_item(check[attr], attr)232 # Handle python interface specifically233 if attr == "python_interface":234 rel_path = item.replace(".", "/")235 base, name = os.path.split(rel_path)236 check_url = _get_check_url(base, name)237 item = "<a href='{}'>{}</a>".format(check_url, name)238 if check["kwargs"]:239 item += "<br/>Parameters:"240 for key, value in check["kwargs"].items():241 item += "<br/><b>{}:</b> '{}'".format(key, value)242 else: # If no parameters tell report i243 item += "<br/>No parameters."244 elif attr == "check_unittest":245 name = check['python_interface'].split(".")[-1]246 unittest_module, unittest_url = _get_unittest_details(name)247 248 if unittest_module:249 item = "<a href='{}'>{}</a>".format(unittest_url, unittest_module)250 elif attr == "check_id":251 item = "<b>{}</b>".format(item)252 contents.append(item)253 return contents254def write_specification(project, plugin_interfaces, checks_dict):255 """256 Writes specification file in HTML format.257 :project: project ID [string]258 :param plugin_interfaces: ordered dictionary of python plugin interfaces259 :param checks_dict: dictionary of details of all checks.260 :return: None261 """262 project_metadata = get_project_metadata(project)263 # Set up output path264 output_dir = os.path.join(OUTPUT_DIR, project, "html")265 _check_exists(output_dir)266 output_path = os.path.join(output_dir, "{}_data_specification_{}.html".format(project,267 project_metadata["checks_version"]))268 content = OD()269 # Build content270 for plugin_interface in plugin_interfaces:271 checks = checks_dict[plugin_interface]272 content[plugin_interface] = [_get_content_for_html_row(check) for check in checks]273 check_headers = CHECK_ATTRIBUTE_MAP.values()274 # Write the HTML specification document275 write_spec_document(project_metadata, plugin_interfaces, content, check_headers, output_path)276 print "Wrote: {}".format(output_path)277def write_cc_plugin_modules(project, plugin_interfaces, checks_dict):278 """279 Writes CC plugin modules in python.280 :project: project ID [string]281 :param plugin_interfaces: ordered dictionary of python plugin interfaces282 :param checks_dict: ditionary of checks283 :return: None284 """285 project_metadata = get_project_metadata(project)286 for plugin_id, details in plugin_interfaces.items():287 # Set up output path288 output_dir = os.path.join(OUTPUT_DIR, project, "py")289 _check_exists(output_dir)290 output_path = os.path.join(output_dir, "{}.py".format(details["ccPluginPackage"].split(".")[1]))291 # Build content292 checks = checks_dict[plugin_id]293 # Write a JSON file for each plugin294 write_plugin_module(project_metadata, plugin_id, details, checks, output_path)295 print "Wrote: {}".format(output_path)296def display_plugin_entry_points(plugin_interfaces):297 """298 Display plugin entry points (for `setup.py` file).299 :param plugin_interfaces: plugin interfaces dicts300 """301 keys = plugin_interfaces.keys()302 for key in sorted(keys):303 pi_dict = plugin_interfaces[key]304 s = " '{} = {}:{}',".format(key, pi_dict['ccPluginPackage'],305 pi_dict['ccPluginClass'])306 print(s)307 print("\nAll entry points:\n")308 print(" ".join(["--test {}".format(test) for test in sorted(keys)]))309def run(project):310 """311 Write JSON rules files, specification document and code stubs.312 :project: project ID [string]313 :return: None314 """315 # Gather the data first as a list of file paths316 check_defn_files = get_check_defn_files(project)317 # Collect each of the plugin interface dicts in a list318 plugin_interfaces = OD()319 # Collect up dictionary of checks320 checks_dict = {}321 # Write a JSON file for each plugin322 for check_defn_file in check_defn_files:323 plugin_interface, checks = parse_checks_definitions(project, check_defn_file)324 plugin_id = plugin_interface['ccPluginId']325 plugin_interfaces[plugin_id] = plugin_interface326 checks_dict[plugin_id] = checks327 # Write the specification doc328 write_specification(project, plugin_interfaces, checks_dict)329 # Write python plugin classes for each plugin330 write_cc_plugin_modules(project, plugin_interfaces, checks_dict)331 # Display plugin entry points (for `setup.py` file)332 display_plugin_entry_points(plugin_interfaces)333def main():334 """335 Run the check maker.336 :return: None337 """338 DEFAULT = "example_proj"339 if len(sys.argv) > 1:340 proj = sys.argv[1]341 else:342 proj = DEFAULT343 run(proj)344if __name__ == "__main__":...

Full Screen

Full Screen

EditorTest.py

Source:EditorTest.py Github

copy

Full Screen

1########################################################################2# This program is free software; you can redistribute it and/or modify3# it under the terms of the GNU General Public License as published by4# the Free Software Foundation; either version 2 of the License, or5# (at your option) any later version.6#7# This program is distributed in the hope that it will be useful,8# but WITHOUT ANY WARRANTY; without even the implied warranty of9# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the10# GNU General Public License for more details.11#12# You should have received a copy of the GNU General Public License13# along with this program; if not, write to the Free Software14# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.15#16# EDU-CIAA Python editor unit tests (2016)17#18# <ernestogigliotti@gmail.com>19#20########################################################################21from unittest import TestCase, main22import gtk23import time24import sys25import os26from os import path27sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )28from Main import Edile29import Main30Main.BASE_PATH = "."31import ciaa_plugin32from snippets.SnippetsParser import SnippetsParser33from ConfigManager import ConfigManager34# Mock GUI refresh35def refresh_gui(delay=0):36 while gtk.events_pending():37 gtk.main_iteration_do(block=False)38 time.sleep(delay)39class EditorTest(TestCase):40 def setUp(self):41 self.editor = Edile()42 def tearDown(self):43 pass44 def test_openFileOk(self):45 flagOk=False46 try:47 self.editor.load_file("tests/test.py")48 flagOk=True49 except:50 pass51 self.assertEqual(flagOk,True)52 def test_openFileInvalid(self):53 flagOk=False54 try:55 self.editor.load_file("tests/test2.py")56 flagOk=True57 except:58 pass59 self.assertEqual(flagOk,False)60 def test_saveFile(self):61 buff = self.editor.text_view.get_buffer()62 buff.insert_at_cursor("Test String")63 self.editor.write_file("tests/testOut.py")64 self.editor.load_file("tests/testOut.py")65 text = buff.get_text(buff.get_start_iter(), buff.get_end_iter())66 self.assertEqual("Test String",text)67class SnippetsWindowTest(TestCase):68 def setUp(self):69 self.editor = Edile()70 def tearDown(self):71 pass72 def test_openSnippets(self):73 plugin = ciaa_plugin.mnu_EDUCIAA()74 plugin.item_Snippets(None,self.editor.plugin_interface)75 plugin.snippetsW.listW.set_cursor(1) # select 2nd snippet76 buff = plugin.snippetsW.txtSrc.get_buffer()77 text = buff.get_text(buff.get_start_iter(), buff.get_end_iter())78 #compare text inserted in text field snippets window79 self.assertEqual("#Number to String example\n# Integer variable\nn = 5\n#n to String\nnString = str(n)\nprint(nString)\t\t\n#___________",text)80 def test_addSnippet(self):81 plugin = ciaa_plugin.mnu_EDUCIAA()82 plugin.item_Snippets(None,self.editor.plugin_interface)83 plugin.snippetsW.listW.set_cursor(1) # select 2nd snippet84 plugin.snippetsW.buttonOk.clicked()85 #compare text inserted in editor86 buff = self.editor.text_view.get_buffer()87 text = buff.get_text(buff.get_start_iter(), buff.get_end_iter())88 self.assertEqual("#Number to String example\n# Integer variable\nn = 5\n#n to String\nnString = str(n)\nprint(nString)\t\t\n#___________",text)89class SnippetsParserTest(TestCase):90 def setUp(self):91 self.parser = SnippetsParser()92 def tearDown(self):93 pass94 def test_parse(self):95 root = self.parser.parseSnippets(Main.BASE_PATH+'/tests/snippetsTest.xml')96 i=197 for child in root:98 self.assertEqual("test"+str(i),child.attrib["name"])99 self.assertEqual("test content "+str(i),child.text)100 i+=1101class ConfigWindowTest(TestCase):102 def setUp(self):103 self.editor = Edile()104 def tearDown(self):105 pass106 def test_openConfig(self):107 plugin = ciaa_plugin.mnu_EDUCIAA()108 plugin.item_Configuration(None,self.editor.plugin_interface)109 portsLen = len(plugin.configW.ports)110 self.assertGreater(portsLen,0,"There is not a serial terminal in the system")111 def test_selectPort(self):112 plugin = ciaa_plugin.mnu_EDUCIAA()113 plugin.item_Configuration(None,self.editor.plugin_interface)114 plugin.configW.buttonOk.clicked()115 if hasattr(plugin.configW,"portSelected"):116 ps = plugin.configW.portSelected117 else:118 self.fail("There is not a serial terminal in the system")119 self.assertEquals("/dev/tty",ps[0:8])120class ConfigManagerTest(TestCase):121 def setUp(self):122 self.cm = ConfigManager()123 def test_write(self):124 flagOk=False125 try:126 self.cm.writeConfig("/dev/ttyUSB1","")127 flagOk=True128 except:129 pass130 self.assertEqual(True,flagOk)131 def test_read(self):132 try:133 self.cm.writeConfig("/dev/ttyUSB1","")134 except:135 pass136 conf = self.cm.readConfig()137 self.assertEqual("/dev/ttyUSB1",conf["port"])138class ConsoleWindowTest(TestCase):139 def setUp(self):140 self.editor = Edile()141 cm = ConfigManager()142 cm.writeConfig("/dev/ttyUSB1","")143 def tearDown(self):144 if self.plugin.console!=None:145 self.plugin.console.closeConsole()146 def test_createConsoleWindow(self):147 self.plugin = ciaa_plugin.mnu_EDUCIAA()148 self.plugin.item_Console(None,self.editor.plugin_interface)149 self.assertIsNotNone(self.plugin.console)150 def test_consoleAddText(self):151 self.plugin = ciaa_plugin.mnu_EDUCIAA()152 self.plugin.item_Console(None,self.editor.plugin_interface)153 buff = self.plugin.console.textbuffer154 textBefore = buff.get_text(buff.get_start_iter(), buff.get_end_iter())155 self.plugin.console.addText("Test String")156 textAfter = buff.get_text(buff.get_start_iter(), buff.get_end_iter())157 self.assertEquals(textBefore+"Test String",textAfter)158 def test_consoleRemoveText(self):159 self.plugin = ciaa_plugin.mnu_EDUCIAA()160 self.plugin.item_Console(None,self.editor.plugin_interface)161 buff = self.plugin.console.textbuffer162 textBefore = buff.get_text(buff.get_start_iter(), buff.get_end_iter())163 self.plugin.console.removeText()164 textAfter = buff.get_text(buff.get_start_iter(), buff.get_end_iter())165 self.assertEquals(textBefore[0:len(textBefore)-1],textAfter)166 def test_consoleRemoveTextLastLine(self):167 self.plugin = ciaa_plugin.mnu_EDUCIAA()168 self.plugin.item_Console(None,self.editor.plugin_interface)169 buff = self.plugin.console.textbuffer170 self.plugin.console.addText("\r\nTest String")171 textBefore = buff.get_text(buff.get_start_iter(), buff.get_end_iter())172 self.plugin.console.removeTextLastLine()173 textAfter = buff.get_text(buff.get_start_iter(), buff.get_end_iter())174 #print("Texto antes:")175 #print(textBefore)176 #print("Texto despues")177 #print(textAfter)178 self.assertEquals(textBefore.split("\r\n")[0]+"\r\n>>> ",textAfter)179 def test_consoleClose(self):180 self.plugin = ciaa_plugin.mnu_EDUCIAA()181 self.plugin.item_Console(None,self.editor.plugin_interface)182 self.plugin.console.closeConsole()183 self.assertIsNone(self.plugin.console.ser)184class LoadingWindowTest(TestCase):185 def setUp(self):186 self.editor = Edile()187 self.cm = ConfigManager()188 self.cm.writeConfig("/dev/ttyUSB1","")189 def tearDown(self):190 pass191 def test_sendScript_without_file(self):192 plugin = ciaa_plugin.mnu_EDUCIAA()193 plugin.item_Load_Script(None,self.editor.plugin_interface)194 timeout=15195 while(plugin.loadScriptWindow.lblStatus.get_text()!="ERROR: Save File first" and timeout>0):196 time.sleep(1)197 print(plugin.loadScriptWindow.lblStatus.get_text())198 timeout-=1199 self.assertGreater(timeout,0)200 def test_sendScript(self):201 self.editor.load_file("tests/test.py")202 plugin = ciaa_plugin.mnu_EDUCIAA()203 plugin.item_Load_Script(None,self.editor.plugin_interface)204 print(">>>>>>>>>>>>>>> PRESS RESET BUTTON MANUALLY")205 timeout=15206 while(plugin.loadScriptWindow.lblStatus.get_text()!="File copied" and timeout>0):207 time.sleep(1)208 print(plugin.loadScriptWindow.lblStatus.get_text())209 timeout-=1210 self.assertGreater(timeout,0)211 def test_sendScript_wrong_port(self):212 self.editor.load_file("tests/test.py")213 self.cm.writeConfig("/dev/ttyUSBXXXXXX","") # wrong port214 plugin = ciaa_plugin.mnu_EDUCIAA()215 plugin.item_Load_Script(None,self.editor.plugin_interface)216 timeout=15217 while(plugin.loadScriptWindow.lblStatus.get_text()!="Invalid PORT" and timeout>0):218 time.sleep(1)219 print(plugin.loadScriptWindow.lblStatus.get_text())220 timeout-=1221 self.assertGreater(timeout,0)222if __name__ == '__main__':...

Full Screen

Full Screen

test_plugins.py

Source:test_plugins.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2#3# This file is part of Exdir, the Experimental Directory Structure.4#5# Copyright 2017 Svenn-Arne Dragly6# Copyright 2017 Simen Tennøe7#8# License: MIT, see "LICENSE" file for the full license terms.9#10# This file contains code from h5py, a Python interface to the HDF5 library,11# licensed under a standard 3-clause BSD license12# with copyright Andrew Collette and contributors.13# See http://www.h5py.org and the "3rdparty/h5py-LICENSE" file for details.14import pytest15import numpy as np16import os17import quantities as pq18import exdir19import exdir.core20def test_plugin_order():21 class DatasetPlugin(exdir.plugin_interface.Dataset):22 def prepare_read(self, dataset_data):23 return values24 def prepare_write(self, dataset_data):25 return dataset_data26 first = exdir.plugin_interface.Plugin(27 "first",28 write_before=["third"],29 read_before=["second"],30 dataset_plugins=[DatasetPlugin()]31 )32 second = exdir.plugin_interface.Plugin(33 "second",34 write_after=["first", "dummy"],35 read_after=["first", "none"],36 read_before=["third", "dummy"],37 dataset_plugins=[DatasetPlugin()]38 )39 third = exdir.plugin_interface.Plugin(40 "third",41 write_after=["second", "test"],42 write_before=["fourth", "test"],43 read_after=["first", "test"],44 read_before=["fourth", "test"],45 dataset_plugins=[DatasetPlugin()]46 )47 fourth = exdir.plugin_interface.Plugin(48 "fourth",49 write_before=["fifth", "test"],50 read_before=["fifth", "something"],51 dataset_plugins=[DatasetPlugin()]52 )53 fifth = exdir.plugin_interface.Plugin(54 "fifth",55 write_after=["first", "second", "third"],56 read_after=["third", "dummy"],57 dataset_plugins=[DatasetPlugin()]58 )59 manager = exdir.plugin_interface.plugin_interface.Manager([first, second, third, fourth, fifth])60 names = [plugin._plugin_module.name for plugin in manager.dataset_plugins.write_order]61 assert(names == ["first", "second", "third", "fourth", "fifth"])62 names = [plugin._plugin_module.name for plugin in manager.dataset_plugins.read_order]63 assert(names == ["first", "second", "third", "fourth", "fifth"])64def test_noop(setup_teardown_folder):65 class DatasetPlugin(exdir.plugin_interface.Dataset):66 def prepare_read(self, dataset_data):67 return dataset_data68 def prepare_write(self, dataset_data):69 return dataset_data70 noop = exdir.plugin_interface.Plugin(71 "noop",72 dataset_plugins=[DatasetPlugin()]73 )74 f = exdir.File(setup_teardown_folder[1], 'w', plugins=noop)75 d = f.create_dataset("foo", data=np.array([1, 2, 3]))76 assert all(d.data == np.array([1, 2, 3]))77 f.close()78def test_fail_reading_without_required(setup_teardown_folder):79 class DatasetPlugin(exdir.plugin_interface.Dataset):80 def prepare_read(self, dataset_data):81 return dataset_data82 def prepare_write(self, dataset_data):83 if "plugins" not in dataset_data.meta:84 dataset_data.meta["plugins"] = {}85 if "required" not in dataset_data.meta["plugins"]:86 dataset_data.meta["plugins"]["required"] = {"required": True}87 return dataset_data88 required = exdir.plugin_interface.Plugin(89 "required",90 dataset_plugins=[DatasetPlugin()]91 )92 f = exdir.File(setup_teardown_folder[1], 'w', plugins=required)93 assert isinstance(f, exdir.File)94 d = f.create_dataset("foo", data=np.array([1, 2, 3]))95 assert all(d.data == np.array([1, 2, 3]))96 f.close()97 f = exdir.File(setup_teardown_folder[1], 'r+')98 assert isinstance(f, exdir.File)99 d = f["foo"]100 with pytest.raises(Exception):101 print(d.data)102 f.close()103def test_one_way_scaling(setup_teardown_folder):104 class DatasetPlugin(exdir.plugin_interface.Dataset):105 def prepare_read(self, dataset_data):106 return dataset_data107 def prepare_write(self, dataset_data):108 if "plugins" not in dataset_data.meta:109 dataset_data.meta["plugins"] = {}110 if "scaling" not in dataset_data.meta["plugins"]:111 dataset_data.meta["plugins"]["scaling"] = {"required": True}112 dataset_data.data *= 2113 return dataset_data114 one_way_scaling = exdir.plugin_interface.Plugin(115 "scaling",116 dataset_plugins=[DatasetPlugin()]117 )118 f = exdir.File(setup_teardown_folder[1], 'w', plugins=[one_way_scaling])119 assert isinstance(f, exdir.File)120 d = f.create_dataset("scaling", data=np.array([1, 2, 3]))121 assert all(d.data == np.array([2, 4, 6]))122 f.close()123def test_scaling(setup_teardown_folder):124 class DatasetPlugin(exdir.plugin_interface.Dataset):125 def prepare_read(self, dataset_data):126 meta = dataset_data.meta127 dataset_data.data = dataset_data.data / 2128 return dataset_data129 def prepare_write(self, dataset_data):130 dataset_data.data *= 2131 if "plugins" not in dataset_data.meta:132 dataset_data.meta["plugins"] = {}133 if "scaling" not in dataset_data.meta["plugins"]:134 dataset_data.meta["plugins"]["scaling"] = {"required": True}135 dataset_data.meta136 return dataset_data137 scaling = exdir.plugin_interface.Plugin(138 "scaling",139 dataset_plugins=[DatasetPlugin()]140 )141 f = exdir.File(setup_teardown_folder[1], 'w', plugins=[scaling])142 assert isinstance(f, exdir.File)143 d = f.create_dataset("scaling", data=np.array([1, 2, 3]))144 assert all(d.data == np.array([1, 2, 3]))145 f.close()146def test_attribute_plugin(setup_teardown_folder):147 class AttributePlugin(exdir.plugin_interface.Attribute):148 def prepare_read(self, attribute_data):149 attribute_data.attrs["value"] = attribute_data.attrs["value"]["value"]150 return attribute_data151 def prepare_write(self, attribute_data):152 meta = attribute_data.meta153 if "plugins" not in meta:154 meta["plugins"] = {}155 if "scaling" not in meta["plugins"]:156 meta["plugins"]["scaling"] = {"required": True}157 old_value = attribute_data.attrs["value"]158 attribute_data.attrs["value"] = {159 "unit": "m",160 "value": old_value * 2161 }162 return attribute_data163 scaling_unit = exdir.plugin_interface.Plugin(164 "scaling",165 attribute_plugins=[AttributePlugin()]166 )167 f = exdir.File(setup_teardown_folder[1], "w", plugins=[scaling_unit])168 assert isinstance(f, exdir.File)169 d = f.create_dataset("foo", data=np.array([1, 2, 3]))170 d.attrs["value"] = 42171 assert d.attrs["value"] == 84172 f.close()173def test_reading_in_order(setup_teardown_folder):174 class DatasetPlugin1(exdir.plugin_interface.Dataset):175 def prepare_read(self, dataset_data):176 dataset_data.data = dataset_data.data * 2177 return dataset_data178 class DatasetPlugin2(exdir.plugin_interface.Dataset):179 def prepare_read(self, dataset_data):180 dataset_data.data = dataset_data.data * 3181 return dataset_data182 plugin1 = exdir.plugin_interface.Plugin(183 "plugin1",184 dataset_plugins=[DatasetPlugin1()]185 )186 plugin2 = exdir.plugin_interface.Plugin(187 "plugin2",188 dataset_plugins=[DatasetPlugin2()]189 )190 f = exdir.File(setup_teardown_folder[1], "w", plugins=[plugin1, plugin2])191 assert isinstance(f, exdir.File)192 d = f.create_dataset("foo", data=np.array([1, 2, 3]))193 assert all(d.data == np.array([6, 12, 18]))...

Full Screen

Full Screen

SConscript

Source:SConscript Github

copy

Full Screen

1#******************************************************************2#3# Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.4#5#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=6#7# Licensed under the Apache License, Version 2.0 (the "License");8# you may not use this file except in compliance with the License.9# You may obtain a copy of the License at10#11# http://www.apache.org/licenses/LICENSE-2.012#13# Unless required by applicable law or agreed to in writing, software14# distributed under the License is distributed on an "AS IS" BASIS,15# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.16# See the License for the specific language governing permissions and17# limitations under the License.18#19#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=20##21# Plugin Interface build script22##23import os.path24Import('env')25target_os = env.get('TARGET_OS')26src_dir = env.get('SRC_DIR')27pi_path = os.path.join(src_dir, 'plugins')28print"Reading PI script"29######################################################################30# Build flags31######################################################################32with_unforked_libcoap = env.get('WITH_UNFORKED_LIBCOAP')33if with_unforked_libcoap == '1':34 # For bring up purposes only, we manually copy the forked version to where the unforked version is downloaded.35 env.PrependUnique(CPPPATH = ['#extlibs/libcoap/libcoap/include'])36else:37 # For bring up purposes only, the forked version will live here.38 env.PrependUnique(CPPPATH = [os.path.join(src_dir, 'resource', 'csdk', 'connectivity', 'lib', 'libcoap-4.1.1', 'include')])39env.PrependUnique(CPPPATH = [ os.path.join(src_dir, 'resource', 'c_common', 'oic_malloc', 'include'),40 os.path.join(src_dir, 'resource', 'c_common', 'oic_string', 'include'),41 os.path.join(src_dir, 'resource', 'c_common', 'oic_time', 'include'),42 os.path.join(src_dir, 'resource', 'oc_logger', 'include'),43 os.path.join(src_dir, 'resource', 'csdk', 'logger', 'include'),44 os.path.join(src_dir, 'resource', 'csdk', 'stack', 'include')45 ])46env.AppendUnique(CPPPATH = [ os.path.join(pi_path, 'include'),47 os.path.join(pi_path, 'include', 'internal'),48 os.path.join(pi_path, 'zigbee_wrapper', 'include'),49 os.path.join(pi_path, 'include', 'internal')50 ])51if target_os not in ['arduino', 'windows']:52 env.AppendUnique(CPPDEFINES = ['WITH_POSIX'])53if target_os in ['darwin','ios']:54 env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE'])55env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-Wextra', '-Werror'])56env.AppendUnique(RPATH = [env.get('BUILD_DIR')])57env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])58env.PrependUnique(LIBS = ['zigbee_wrapper'])59if env.get('LOGGING'):60 env.AppendUnique(CPPDEFINES = ['TB_LOG'])61#####################################################################62# Source files and Target(s)63######################################################################64pi_src = [65 os.path.join(src_dir, 'resource', 'csdk', 'logger', 'src', 'logger.c'),66 'pluginlist.c',67 'plugininterface.c',68 ]69env.AppendUnique(PI_SRC = pi_src)70print "Include path is %s" % env.get('CPPPATH')71print "Files path is %s" % env.get('PI_SRC')72if target_os in ['android', 'tizen']:73 calib = env.SharedLibrary('plugin_interface', env.get('PI_SRC'))74else:75 calib = env.StaticLibrary('plugin_interface', env.get('PI_SRC'))76env.InstallTarget(calib, 'plugin_interface')...

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