prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>download_entered_data_test.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoAlertPresentException import unittest, time, re class DownloadEnteredDataTest(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() self.driver.implicitly_wait(30) self.base_url = "http://kc.kbtdev.org/" self.verificationErrors = [] self.accept_next_alert = True def test_download_entered_data(self): # Open KoBoCAT. driver = self.driver driver.get(self.base_url + "") # Assert that our form's title is in the list of projects and follow its link. self.assertTrue(self.is_element_present(By.LINK_TEXT, "Selenium test form title.")) driver.find_element_by_link_text("Selenium test form title.").click() # Wait for and click the "Download data" link. for _ in xrange(self.DEFAULT_WAIT_SECONDS): self.check_timeout('Waiting for "Download data" link.') try: if self.is_element_present(By.LINK_TEXT, "Download data"): break except: pass time.sleep(1) else: self.fail("time out") driver.find_element_by_link_text("Download data").click() # Wait for and click the "XLS" link. for _ in xrange(self.DEFAULT_WAIT_SECONDS): self.check_timeout('Waiting for "XLS" link.') try: if self.is_element_present(By.LINK_TEXT, "XLS"): break except: pass time.sleep(1) else: self.fail("time out") driver.find_element_by_link_text("XLS").click() # Wait for the download page's header and ensure it contains the word "excel" (case insensitive). for _ in xrange(self.DEFAULT_WAIT_SECONDS): self.check_timeout('Waiting for download page\'s header.') try: if self.is_element_present(By.CSS_SELECTOR, ".data-page__header"): break except: pass time.sleep(1) else: self.fail("time out") self.assertIsNotNone(re.compile('excel', re.IGNORECASE).search(driver.find_element_by_css_selector(".data-page__header").text)) # Wait for the export progress status. for _ in xrange(self.DEFAULT_WAIT_SECONDS): self.check_timeout('Waiting for the export progress status.') try: if self.is_element_present(By.CSS_SELECTOR, ".refresh-export-progress"): break except: pass time.sleep(1) else: self.fail("time out") # Wait (a little more than usual) for the export's download link and click it. for _ in xrange(30): self.check_timeout('Waiting for the export\'s download link.') try: if re.search(r"^Selenium_test_form_title_[\s\S]*$", driver.find_element_by_css_selector("#forms-table a").text): break except: pass time.sleep(1) else: self.fail("time out") driver.find_element_by_css_selector("#forms-table a").click() def is_element_present(self, how, what): try: self.driver.find_element(by=how, value=what) except NoSuchElementException: return False return True def <|fim_middle|>(self): try: self.driver.switch_to_alert() except NoAlertPresentException: return False return True def close_alert_and_get_its_text(self): try: alert = self.driver.switch_to_alert() alert_text = alert.text if self.accept_next_alert: alert.accept() else: alert.dismiss() return alert_text finally: self.accept_next_alert = True def tearDown(self): self.driver.quit() self.assertEqual([], self.verificationErrors) if __name__ == "__main__": unittest.main() <|fim▁end|>
is_alert_present
<|file_name|>download_entered_data_test.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoAlertPresentException import unittest, time, re class DownloadEnteredDataTest(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() self.driver.implicitly_wait(30) self.base_url = "http://kc.kbtdev.org/" self.verificationErrors = [] self.accept_next_alert = True def test_download_entered_data(self): # Open KoBoCAT. driver = self.driver driver.get(self.base_url + "") # Assert that our form's title is in the list of projects and follow its link. self.assertTrue(self.is_element_present(By.LINK_TEXT, "Selenium test form title.")) driver.find_element_by_link_text("Selenium test form title.").click() # Wait for and click the "Download data" link. for _ in xrange(self.DEFAULT_WAIT_SECONDS): self.check_timeout('Waiting for "Download data" link.') try: if self.is_element_present(By.LINK_TEXT, "Download data"): break except: pass time.sleep(1) else: self.fail("time out") driver.find_element_by_link_text("Download data").click() # Wait for and click the "XLS" link. for _ in xrange(self.DEFAULT_WAIT_SECONDS): self.check_timeout('Waiting for "XLS" link.') try: if self.is_element_present(By.LINK_TEXT, "XLS"): break except: pass time.sleep(1) else: self.fail("time out") driver.find_element_by_link_text("XLS").click() # Wait for the download page's header and ensure it contains the word "excel" (case insensitive). for _ in xrange(self.DEFAULT_WAIT_SECONDS): self.check_timeout('Waiting for download page\'s header.') try: if self.is_element_present(By.CSS_SELECTOR, ".data-page__header"): break except: pass time.sleep(1) else: self.fail("time out") self.assertIsNotNone(re.compile('excel', re.IGNORECASE).search(driver.find_element_by_css_selector(".data-page__header").text)) # Wait for the export progress status. for _ in xrange(self.DEFAULT_WAIT_SECONDS): self.check_timeout('Waiting for the export progress status.') try: if self.is_element_present(By.CSS_SELECTOR, ".refresh-export-progress"): break except: pass time.sleep(1) else: self.fail("time out") # Wait (a little more than usual) for the export's download link and click it. for _ in xrange(30): self.check_timeout('Waiting for the export\'s download link.') try: if re.search(r"^Selenium_test_form_title_[\s\S]*$", driver.find_element_by_css_selector("#forms-table a").text): break except: pass time.sleep(1) else: self.fail("time out") driver.find_element_by_css_selector("#forms-table a").click() def is_element_present(self, how, what): try: self.driver.find_element(by=how, value=what) except NoSuchElementException: return False return True def is_alert_present(self): try: self.driver.switch_to_alert() except NoAlertPresentException: return False return True def <|fim_middle|>(self): try: alert = self.driver.switch_to_alert() alert_text = alert.text if self.accept_next_alert: alert.accept() else: alert.dismiss() return alert_text finally: self.accept_next_alert = True def tearDown(self): self.driver.quit() self.assertEqual([], self.verificationErrors) if __name__ == "__main__": unittest.main() <|fim▁end|>
close_alert_and_get_its_text
<|file_name|>download_entered_data_test.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from selenium import webdriver from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoAlertPresentException import unittest, time, re class DownloadEnteredDataTest(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() self.driver.implicitly_wait(30) self.base_url = "http://kc.kbtdev.org/" self.verificationErrors = [] self.accept_next_alert = True def test_download_entered_data(self): # Open KoBoCAT. driver = self.driver driver.get(self.base_url + "") # Assert that our form's title is in the list of projects and follow its link. self.assertTrue(self.is_element_present(By.LINK_TEXT, "Selenium test form title.")) driver.find_element_by_link_text("Selenium test form title.").click() # Wait for and click the "Download data" link. for _ in xrange(self.DEFAULT_WAIT_SECONDS): self.check_timeout('Waiting for "Download data" link.') try: if self.is_element_present(By.LINK_TEXT, "Download data"): break except: pass time.sleep(1) else: self.fail("time out") driver.find_element_by_link_text("Download data").click() # Wait for and click the "XLS" link. for _ in xrange(self.DEFAULT_WAIT_SECONDS): self.check_timeout('Waiting for "XLS" link.') try: if self.is_element_present(By.LINK_TEXT, "XLS"): break except: pass time.sleep(1) else: self.fail("time out") driver.find_element_by_link_text("XLS").click() # Wait for the download page's header and ensure it contains the word "excel" (case insensitive). for _ in xrange(self.DEFAULT_WAIT_SECONDS): self.check_timeout('Waiting for download page\'s header.') try: if self.is_element_present(By.CSS_SELECTOR, ".data-page__header"): break except: pass time.sleep(1) else: self.fail("time out") self.assertIsNotNone(re.compile('excel', re.IGNORECASE).search(driver.find_element_by_css_selector(".data-page__header").text)) # Wait for the export progress status. for _ in xrange(self.DEFAULT_WAIT_SECONDS): self.check_timeout('Waiting for the export progress status.') try: if self.is_element_present(By.CSS_SELECTOR, ".refresh-export-progress"): break except: pass time.sleep(1) else: self.fail("time out") # Wait (a little more than usual) for the export's download link and click it. for _ in xrange(30): self.check_timeout('Waiting for the export\'s download link.') try: if re.search(r"^Selenium_test_form_title_[\s\S]*$", driver.find_element_by_css_selector("#forms-table a").text): break except: pass time.sleep(1) else: self.fail("time out") driver.find_element_by_css_selector("#forms-table a").click() def is_element_present(self, how, what): try: self.driver.find_element(by=how, value=what) except NoSuchElementException: return False return True def is_alert_present(self): try: self.driver.switch_to_alert() except NoAlertPresentException: return False return True def close_alert_and_get_its_text(self): try: alert = self.driver.switch_to_alert() alert_text = alert.text if self.accept_next_alert: alert.accept() else: alert.dismiss() return alert_text finally: self.accept_next_alert = True def <|fim_middle|>(self): self.driver.quit() self.assertEqual([], self.verificationErrors) if __name__ == "__main__": unittest.main() <|fim▁end|>
tearDown
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Verisure Smartplugs.""" import logging from time import monotonic from homeassistant.components.switch import SwitchEntity from . import CONF_SMARTPLUGS, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure switch platform.""" if not int(hub.config.get(CONF_SMARTPLUGS, 1)): return False hub.update_overview() switches = [] switches.extend( [ VerisureSmartplug(device_label) for device_label in hub.get("$.smartPlugs[*].deviceLabel") ] ) add_entities(switches) class VerisureSmartplug(SwitchEntity): """Representation of a Verisure smartplug.""" def __init__(self, device_id): """Initialize the Verisure device.""" self._device_label = device_id self._change_timestamp = 0 self._state = False @property<|fim▁hole|> def name(self): """Return the name or location of the smartplug.""" return hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].area", self._device_label ) @property def is_on(self): """Return true if on.""" if monotonic() - self._change_timestamp < 10: return self._state self._state = ( hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].currentState", self._device_label, ) == "ON" ) return self._state @property def available(self): """Return True if entity is available.""" return ( hub.get_first("$.smartPlugs[?(@.deviceLabel == '%s')]", self._device_label) is not None ) def turn_on(self, **kwargs): """Set smartplug status on.""" hub.session.set_smartplug_state(self._device_label, True) self._state = True self._change_timestamp = monotonic() def turn_off(self, **kwargs): """Set smartplug status off.""" hub.session.set_smartplug_state(self._device_label, False) self._state = False self._change_timestamp = monotonic() # pylint: disable=no-self-use def update(self): """Get the latest date of the smartplug.""" hub.update_overview()<|fim▁end|>
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Verisure Smartplugs.""" import logging from time import monotonic from homeassistant.components.switch import SwitchEntity from . import CONF_SMARTPLUGS, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): <|fim_middle|> class VerisureSmartplug(SwitchEntity): """Representation of a Verisure smartplug.""" def __init__(self, device_id): """Initialize the Verisure device.""" self._device_label = device_id self._change_timestamp = 0 self._state = False @property def name(self): """Return the name or location of the smartplug.""" return hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].area", self._device_label ) @property def is_on(self): """Return true if on.""" if monotonic() - self._change_timestamp < 10: return self._state self._state = ( hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].currentState", self._device_label, ) == "ON" ) return self._state @property def available(self): """Return True if entity is available.""" return ( hub.get_first("$.smartPlugs[?(@.deviceLabel == '%s')]", self._device_label) is not None ) def turn_on(self, **kwargs): """Set smartplug status on.""" hub.session.set_smartplug_state(self._device_label, True) self._state = True self._change_timestamp = monotonic() def turn_off(self, **kwargs): """Set smartplug status off.""" hub.session.set_smartplug_state(self._device_label, False) self._state = False self._change_timestamp = monotonic() # pylint: disable=no-self-use def update(self): """Get the latest date of the smartplug.""" hub.update_overview() <|fim▁end|>
"""Set up the Verisure switch platform.""" if not int(hub.config.get(CONF_SMARTPLUGS, 1)): return False hub.update_overview() switches = [] switches.extend( [ VerisureSmartplug(device_label) for device_label in hub.get("$.smartPlugs[*].deviceLabel") ] ) add_entities(switches)
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Verisure Smartplugs.""" import logging from time import monotonic from homeassistant.components.switch import SwitchEntity from . import CONF_SMARTPLUGS, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure switch platform.""" if not int(hub.config.get(CONF_SMARTPLUGS, 1)): return False hub.update_overview() switches = [] switches.extend( [ VerisureSmartplug(device_label) for device_label in hub.get("$.smartPlugs[*].deviceLabel") ] ) add_entities(switches) class VerisureSmartplug(SwitchEntity): <|fim_middle|> <|fim▁end|>
"""Representation of a Verisure smartplug.""" def __init__(self, device_id): """Initialize the Verisure device.""" self._device_label = device_id self._change_timestamp = 0 self._state = False @property def name(self): """Return the name or location of the smartplug.""" return hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].area", self._device_label ) @property def is_on(self): """Return true if on.""" if monotonic() - self._change_timestamp < 10: return self._state self._state = ( hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].currentState", self._device_label, ) == "ON" ) return self._state @property def available(self): """Return True if entity is available.""" return ( hub.get_first("$.smartPlugs[?(@.deviceLabel == '%s')]", self._device_label) is not None ) def turn_on(self, **kwargs): """Set smartplug status on.""" hub.session.set_smartplug_state(self._device_label, True) self._state = True self._change_timestamp = monotonic() def turn_off(self, **kwargs): """Set smartplug status off.""" hub.session.set_smartplug_state(self._device_label, False) self._state = False self._change_timestamp = monotonic() # pylint: disable=no-self-use def update(self): """Get the latest date of the smartplug.""" hub.update_overview()
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Verisure Smartplugs.""" import logging from time import monotonic from homeassistant.components.switch import SwitchEntity from . import CONF_SMARTPLUGS, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure switch platform.""" if not int(hub.config.get(CONF_SMARTPLUGS, 1)): return False hub.update_overview() switches = [] switches.extend( [ VerisureSmartplug(device_label) for device_label in hub.get("$.smartPlugs[*].deviceLabel") ] ) add_entities(switches) class VerisureSmartplug(SwitchEntity): """Representation of a Verisure smartplug.""" def __init__(self, device_id): <|fim_middle|> @property def name(self): """Return the name or location of the smartplug.""" return hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].area", self._device_label ) @property def is_on(self): """Return true if on.""" if monotonic() - self._change_timestamp < 10: return self._state self._state = ( hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].currentState", self._device_label, ) == "ON" ) return self._state @property def available(self): """Return True if entity is available.""" return ( hub.get_first("$.smartPlugs[?(@.deviceLabel == '%s')]", self._device_label) is not None ) def turn_on(self, **kwargs): """Set smartplug status on.""" hub.session.set_smartplug_state(self._device_label, True) self._state = True self._change_timestamp = monotonic() def turn_off(self, **kwargs): """Set smartplug status off.""" hub.session.set_smartplug_state(self._device_label, False) self._state = False self._change_timestamp = monotonic() # pylint: disable=no-self-use def update(self): """Get the latest date of the smartplug.""" hub.update_overview() <|fim▁end|>
"""Initialize the Verisure device.""" self._device_label = device_id self._change_timestamp = 0 self._state = False
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Verisure Smartplugs.""" import logging from time import monotonic from homeassistant.components.switch import SwitchEntity from . import CONF_SMARTPLUGS, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure switch platform.""" if not int(hub.config.get(CONF_SMARTPLUGS, 1)): return False hub.update_overview() switches = [] switches.extend( [ VerisureSmartplug(device_label) for device_label in hub.get("$.smartPlugs[*].deviceLabel") ] ) add_entities(switches) class VerisureSmartplug(SwitchEntity): """Representation of a Verisure smartplug.""" def __init__(self, device_id): """Initialize the Verisure device.""" self._device_label = device_id self._change_timestamp = 0 self._state = False @property def name(self): <|fim_middle|> @property def is_on(self): """Return true if on.""" if monotonic() - self._change_timestamp < 10: return self._state self._state = ( hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].currentState", self._device_label, ) == "ON" ) return self._state @property def available(self): """Return True if entity is available.""" return ( hub.get_first("$.smartPlugs[?(@.deviceLabel == '%s')]", self._device_label) is not None ) def turn_on(self, **kwargs): """Set smartplug status on.""" hub.session.set_smartplug_state(self._device_label, True) self._state = True self._change_timestamp = monotonic() def turn_off(self, **kwargs): """Set smartplug status off.""" hub.session.set_smartplug_state(self._device_label, False) self._state = False self._change_timestamp = monotonic() # pylint: disable=no-self-use def update(self): """Get the latest date of the smartplug.""" hub.update_overview() <|fim▁end|>
"""Return the name or location of the smartplug.""" return hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].area", self._device_label )
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Verisure Smartplugs.""" import logging from time import monotonic from homeassistant.components.switch import SwitchEntity from . import CONF_SMARTPLUGS, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure switch platform.""" if not int(hub.config.get(CONF_SMARTPLUGS, 1)): return False hub.update_overview() switches = [] switches.extend( [ VerisureSmartplug(device_label) for device_label in hub.get("$.smartPlugs[*].deviceLabel") ] ) add_entities(switches) class VerisureSmartplug(SwitchEntity): """Representation of a Verisure smartplug.""" def __init__(self, device_id): """Initialize the Verisure device.""" self._device_label = device_id self._change_timestamp = 0 self._state = False @property def name(self): """Return the name or location of the smartplug.""" return hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].area", self._device_label ) @property def is_on(self): <|fim_middle|> @property def available(self): """Return True if entity is available.""" return ( hub.get_first("$.smartPlugs[?(@.deviceLabel == '%s')]", self._device_label) is not None ) def turn_on(self, **kwargs): """Set smartplug status on.""" hub.session.set_smartplug_state(self._device_label, True) self._state = True self._change_timestamp = monotonic() def turn_off(self, **kwargs): """Set smartplug status off.""" hub.session.set_smartplug_state(self._device_label, False) self._state = False self._change_timestamp = monotonic() # pylint: disable=no-self-use def update(self): """Get the latest date of the smartplug.""" hub.update_overview() <|fim▁end|>
"""Return true if on.""" if monotonic() - self._change_timestamp < 10: return self._state self._state = ( hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].currentState", self._device_label, ) == "ON" ) return self._state
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Verisure Smartplugs.""" import logging from time import monotonic from homeassistant.components.switch import SwitchEntity from . import CONF_SMARTPLUGS, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure switch platform.""" if not int(hub.config.get(CONF_SMARTPLUGS, 1)): return False hub.update_overview() switches = [] switches.extend( [ VerisureSmartplug(device_label) for device_label in hub.get("$.smartPlugs[*].deviceLabel") ] ) add_entities(switches) class VerisureSmartplug(SwitchEntity): """Representation of a Verisure smartplug.""" def __init__(self, device_id): """Initialize the Verisure device.""" self._device_label = device_id self._change_timestamp = 0 self._state = False @property def name(self): """Return the name or location of the smartplug.""" return hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].area", self._device_label ) @property def is_on(self): """Return true if on.""" if monotonic() - self._change_timestamp < 10: return self._state self._state = ( hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].currentState", self._device_label, ) == "ON" ) return self._state @property def available(self): <|fim_middle|> def turn_on(self, **kwargs): """Set smartplug status on.""" hub.session.set_smartplug_state(self._device_label, True) self._state = True self._change_timestamp = monotonic() def turn_off(self, **kwargs): """Set smartplug status off.""" hub.session.set_smartplug_state(self._device_label, False) self._state = False self._change_timestamp = monotonic() # pylint: disable=no-self-use def update(self): """Get the latest date of the smartplug.""" hub.update_overview() <|fim▁end|>
"""Return True if entity is available.""" return ( hub.get_first("$.smartPlugs[?(@.deviceLabel == '%s')]", self._device_label) is not None )
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Verisure Smartplugs.""" import logging from time import monotonic from homeassistant.components.switch import SwitchEntity from . import CONF_SMARTPLUGS, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure switch platform.""" if not int(hub.config.get(CONF_SMARTPLUGS, 1)): return False hub.update_overview() switches = [] switches.extend( [ VerisureSmartplug(device_label) for device_label in hub.get("$.smartPlugs[*].deviceLabel") ] ) add_entities(switches) class VerisureSmartplug(SwitchEntity): """Representation of a Verisure smartplug.""" def __init__(self, device_id): """Initialize the Verisure device.""" self._device_label = device_id self._change_timestamp = 0 self._state = False @property def name(self): """Return the name or location of the smartplug.""" return hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].area", self._device_label ) @property def is_on(self): """Return true if on.""" if monotonic() - self._change_timestamp < 10: return self._state self._state = ( hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].currentState", self._device_label, ) == "ON" ) return self._state @property def available(self): """Return True if entity is available.""" return ( hub.get_first("$.smartPlugs[?(@.deviceLabel == '%s')]", self._device_label) is not None ) def turn_on(self, **kwargs): <|fim_middle|> def turn_off(self, **kwargs): """Set smartplug status off.""" hub.session.set_smartplug_state(self._device_label, False) self._state = False self._change_timestamp = monotonic() # pylint: disable=no-self-use def update(self): """Get the latest date of the smartplug.""" hub.update_overview() <|fim▁end|>
"""Set smartplug status on.""" hub.session.set_smartplug_state(self._device_label, True) self._state = True self._change_timestamp = monotonic()
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Verisure Smartplugs.""" import logging from time import monotonic from homeassistant.components.switch import SwitchEntity from . import CONF_SMARTPLUGS, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure switch platform.""" if not int(hub.config.get(CONF_SMARTPLUGS, 1)): return False hub.update_overview() switches = [] switches.extend( [ VerisureSmartplug(device_label) for device_label in hub.get("$.smartPlugs[*].deviceLabel") ] ) add_entities(switches) class VerisureSmartplug(SwitchEntity): """Representation of a Verisure smartplug.""" def __init__(self, device_id): """Initialize the Verisure device.""" self._device_label = device_id self._change_timestamp = 0 self._state = False @property def name(self): """Return the name or location of the smartplug.""" return hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].area", self._device_label ) @property def is_on(self): """Return true if on.""" if monotonic() - self._change_timestamp < 10: return self._state self._state = ( hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].currentState", self._device_label, ) == "ON" ) return self._state @property def available(self): """Return True if entity is available.""" return ( hub.get_first("$.smartPlugs[?(@.deviceLabel == '%s')]", self._device_label) is not None ) def turn_on(self, **kwargs): """Set smartplug status on.""" hub.session.set_smartplug_state(self._device_label, True) self._state = True self._change_timestamp = monotonic() def turn_off(self, **kwargs): <|fim_middle|> # pylint: disable=no-self-use def update(self): """Get the latest date of the smartplug.""" hub.update_overview() <|fim▁end|>
"""Set smartplug status off.""" hub.session.set_smartplug_state(self._device_label, False) self._state = False self._change_timestamp = monotonic()
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Verisure Smartplugs.""" import logging from time import monotonic from homeassistant.components.switch import SwitchEntity from . import CONF_SMARTPLUGS, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure switch platform.""" if not int(hub.config.get(CONF_SMARTPLUGS, 1)): return False hub.update_overview() switches = [] switches.extend( [ VerisureSmartplug(device_label) for device_label in hub.get("$.smartPlugs[*].deviceLabel") ] ) add_entities(switches) class VerisureSmartplug(SwitchEntity): """Representation of a Verisure smartplug.""" def __init__(self, device_id): """Initialize the Verisure device.""" self._device_label = device_id self._change_timestamp = 0 self._state = False @property def name(self): """Return the name or location of the smartplug.""" return hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].area", self._device_label ) @property def is_on(self): """Return true if on.""" if monotonic() - self._change_timestamp < 10: return self._state self._state = ( hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].currentState", self._device_label, ) == "ON" ) return self._state @property def available(self): """Return True if entity is available.""" return ( hub.get_first("$.smartPlugs[?(@.deviceLabel == '%s')]", self._device_label) is not None ) def turn_on(self, **kwargs): """Set smartplug status on.""" hub.session.set_smartplug_state(self._device_label, True) self._state = True self._change_timestamp = monotonic() def turn_off(self, **kwargs): """Set smartplug status off.""" hub.session.set_smartplug_state(self._device_label, False) self._state = False self._change_timestamp = monotonic() # pylint: disable=no-self-use def update(self): <|fim_middle|> <|fim▁end|>
"""Get the latest date of the smartplug.""" hub.update_overview()
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Verisure Smartplugs.""" import logging from time import monotonic from homeassistant.components.switch import SwitchEntity from . import CONF_SMARTPLUGS, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure switch platform.""" if not int(hub.config.get(CONF_SMARTPLUGS, 1)): <|fim_middle|> hub.update_overview() switches = [] switches.extend( [ VerisureSmartplug(device_label) for device_label in hub.get("$.smartPlugs[*].deviceLabel") ] ) add_entities(switches) class VerisureSmartplug(SwitchEntity): """Representation of a Verisure smartplug.""" def __init__(self, device_id): """Initialize the Verisure device.""" self._device_label = device_id self._change_timestamp = 0 self._state = False @property def name(self): """Return the name or location of the smartplug.""" return hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].area", self._device_label ) @property def is_on(self): """Return true if on.""" if monotonic() - self._change_timestamp < 10: return self._state self._state = ( hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].currentState", self._device_label, ) == "ON" ) return self._state @property def available(self): """Return True if entity is available.""" return ( hub.get_first("$.smartPlugs[?(@.deviceLabel == '%s')]", self._device_label) is not None ) def turn_on(self, **kwargs): """Set smartplug status on.""" hub.session.set_smartplug_state(self._device_label, True) self._state = True self._change_timestamp = monotonic() def turn_off(self, **kwargs): """Set smartplug status off.""" hub.session.set_smartplug_state(self._device_label, False) self._state = False self._change_timestamp = monotonic() # pylint: disable=no-self-use def update(self): """Get the latest date of the smartplug.""" hub.update_overview() <|fim▁end|>
return False
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Verisure Smartplugs.""" import logging from time import monotonic from homeassistant.components.switch import SwitchEntity from . import CONF_SMARTPLUGS, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure switch platform.""" if not int(hub.config.get(CONF_SMARTPLUGS, 1)): return False hub.update_overview() switches = [] switches.extend( [ VerisureSmartplug(device_label) for device_label in hub.get("$.smartPlugs[*].deviceLabel") ] ) add_entities(switches) class VerisureSmartplug(SwitchEntity): """Representation of a Verisure smartplug.""" def __init__(self, device_id): """Initialize the Verisure device.""" self._device_label = device_id self._change_timestamp = 0 self._state = False @property def name(self): """Return the name or location of the smartplug.""" return hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].area", self._device_label ) @property def is_on(self): """Return true if on.""" if monotonic() - self._change_timestamp < 10: <|fim_middle|> self._state = ( hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].currentState", self._device_label, ) == "ON" ) return self._state @property def available(self): """Return True if entity is available.""" return ( hub.get_first("$.smartPlugs[?(@.deviceLabel == '%s')]", self._device_label) is not None ) def turn_on(self, **kwargs): """Set smartplug status on.""" hub.session.set_smartplug_state(self._device_label, True) self._state = True self._change_timestamp = monotonic() def turn_off(self, **kwargs): """Set smartplug status off.""" hub.session.set_smartplug_state(self._device_label, False) self._state = False self._change_timestamp = monotonic() # pylint: disable=no-self-use def update(self): """Get the latest date of the smartplug.""" hub.update_overview() <|fim▁end|>
return self._state
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Verisure Smartplugs.""" import logging from time import monotonic from homeassistant.components.switch import SwitchEntity from . import CONF_SMARTPLUGS, HUB as hub _LOGGER = logging.getLogger(__name__) def <|fim_middle|>(hass, config, add_entities, discovery_info=None): """Set up the Verisure switch platform.""" if not int(hub.config.get(CONF_SMARTPLUGS, 1)): return False hub.update_overview() switches = [] switches.extend( [ VerisureSmartplug(device_label) for device_label in hub.get("$.smartPlugs[*].deviceLabel") ] ) add_entities(switches) class VerisureSmartplug(SwitchEntity): """Representation of a Verisure smartplug.""" def __init__(self, device_id): """Initialize the Verisure device.""" self._device_label = device_id self._change_timestamp = 0 self._state = False @property def name(self): """Return the name or location of the smartplug.""" return hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].area", self._device_label ) @property def is_on(self): """Return true if on.""" if monotonic() - self._change_timestamp < 10: return self._state self._state = ( hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].currentState", self._device_label, ) == "ON" ) return self._state @property def available(self): """Return True if entity is available.""" return ( hub.get_first("$.smartPlugs[?(@.deviceLabel == '%s')]", self._device_label) is not None ) def turn_on(self, **kwargs): """Set smartplug status on.""" hub.session.set_smartplug_state(self._device_label, True) self._state = True self._change_timestamp = monotonic() def turn_off(self, **kwargs): """Set smartplug status off.""" hub.session.set_smartplug_state(self._device_label, False) self._state = False self._change_timestamp = monotonic() # pylint: disable=no-self-use def update(self): """Get the latest date of the smartplug.""" hub.update_overview() <|fim▁end|>
setup_platform
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Verisure Smartplugs.""" import logging from time import monotonic from homeassistant.components.switch import SwitchEntity from . import CONF_SMARTPLUGS, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure switch platform.""" if not int(hub.config.get(CONF_SMARTPLUGS, 1)): return False hub.update_overview() switches = [] switches.extend( [ VerisureSmartplug(device_label) for device_label in hub.get("$.smartPlugs[*].deviceLabel") ] ) add_entities(switches) class VerisureSmartplug(SwitchEntity): """Representation of a Verisure smartplug.""" def <|fim_middle|>(self, device_id): """Initialize the Verisure device.""" self._device_label = device_id self._change_timestamp = 0 self._state = False @property def name(self): """Return the name or location of the smartplug.""" return hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].area", self._device_label ) @property def is_on(self): """Return true if on.""" if monotonic() - self._change_timestamp < 10: return self._state self._state = ( hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].currentState", self._device_label, ) == "ON" ) return self._state @property def available(self): """Return True if entity is available.""" return ( hub.get_first("$.smartPlugs[?(@.deviceLabel == '%s')]", self._device_label) is not None ) def turn_on(self, **kwargs): """Set smartplug status on.""" hub.session.set_smartplug_state(self._device_label, True) self._state = True self._change_timestamp = monotonic() def turn_off(self, **kwargs): """Set smartplug status off.""" hub.session.set_smartplug_state(self._device_label, False) self._state = False self._change_timestamp = monotonic() # pylint: disable=no-self-use def update(self): """Get the latest date of the smartplug.""" hub.update_overview() <|fim▁end|>
__init__
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Verisure Smartplugs.""" import logging from time import monotonic from homeassistant.components.switch import SwitchEntity from . import CONF_SMARTPLUGS, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure switch platform.""" if not int(hub.config.get(CONF_SMARTPLUGS, 1)): return False hub.update_overview() switches = [] switches.extend( [ VerisureSmartplug(device_label) for device_label in hub.get("$.smartPlugs[*].deviceLabel") ] ) add_entities(switches) class VerisureSmartplug(SwitchEntity): """Representation of a Verisure smartplug.""" def __init__(self, device_id): """Initialize the Verisure device.""" self._device_label = device_id self._change_timestamp = 0 self._state = False @property def <|fim_middle|>(self): """Return the name or location of the smartplug.""" return hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].area", self._device_label ) @property def is_on(self): """Return true if on.""" if monotonic() - self._change_timestamp < 10: return self._state self._state = ( hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].currentState", self._device_label, ) == "ON" ) return self._state @property def available(self): """Return True if entity is available.""" return ( hub.get_first("$.smartPlugs[?(@.deviceLabel == '%s')]", self._device_label) is not None ) def turn_on(self, **kwargs): """Set smartplug status on.""" hub.session.set_smartplug_state(self._device_label, True) self._state = True self._change_timestamp = monotonic() def turn_off(self, **kwargs): """Set smartplug status off.""" hub.session.set_smartplug_state(self._device_label, False) self._state = False self._change_timestamp = monotonic() # pylint: disable=no-self-use def update(self): """Get the latest date of the smartplug.""" hub.update_overview() <|fim▁end|>
name
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Verisure Smartplugs.""" import logging from time import monotonic from homeassistant.components.switch import SwitchEntity from . import CONF_SMARTPLUGS, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure switch platform.""" if not int(hub.config.get(CONF_SMARTPLUGS, 1)): return False hub.update_overview() switches = [] switches.extend( [ VerisureSmartplug(device_label) for device_label in hub.get("$.smartPlugs[*].deviceLabel") ] ) add_entities(switches) class VerisureSmartplug(SwitchEntity): """Representation of a Verisure smartplug.""" def __init__(self, device_id): """Initialize the Verisure device.""" self._device_label = device_id self._change_timestamp = 0 self._state = False @property def name(self): """Return the name or location of the smartplug.""" return hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].area", self._device_label ) @property def <|fim_middle|>(self): """Return true if on.""" if monotonic() - self._change_timestamp < 10: return self._state self._state = ( hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].currentState", self._device_label, ) == "ON" ) return self._state @property def available(self): """Return True if entity is available.""" return ( hub.get_first("$.smartPlugs[?(@.deviceLabel == '%s')]", self._device_label) is not None ) def turn_on(self, **kwargs): """Set smartplug status on.""" hub.session.set_smartplug_state(self._device_label, True) self._state = True self._change_timestamp = monotonic() def turn_off(self, **kwargs): """Set smartplug status off.""" hub.session.set_smartplug_state(self._device_label, False) self._state = False self._change_timestamp = monotonic() # pylint: disable=no-self-use def update(self): """Get the latest date of the smartplug.""" hub.update_overview() <|fim▁end|>
is_on
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Verisure Smartplugs.""" import logging from time import monotonic from homeassistant.components.switch import SwitchEntity from . import CONF_SMARTPLUGS, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure switch platform.""" if not int(hub.config.get(CONF_SMARTPLUGS, 1)): return False hub.update_overview() switches = [] switches.extend( [ VerisureSmartplug(device_label) for device_label in hub.get("$.smartPlugs[*].deviceLabel") ] ) add_entities(switches) class VerisureSmartplug(SwitchEntity): """Representation of a Verisure smartplug.""" def __init__(self, device_id): """Initialize the Verisure device.""" self._device_label = device_id self._change_timestamp = 0 self._state = False @property def name(self): """Return the name or location of the smartplug.""" return hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].area", self._device_label ) @property def is_on(self): """Return true if on.""" if monotonic() - self._change_timestamp < 10: return self._state self._state = ( hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].currentState", self._device_label, ) == "ON" ) return self._state @property def <|fim_middle|>(self): """Return True if entity is available.""" return ( hub.get_first("$.smartPlugs[?(@.deviceLabel == '%s')]", self._device_label) is not None ) def turn_on(self, **kwargs): """Set smartplug status on.""" hub.session.set_smartplug_state(self._device_label, True) self._state = True self._change_timestamp = monotonic() def turn_off(self, **kwargs): """Set smartplug status off.""" hub.session.set_smartplug_state(self._device_label, False) self._state = False self._change_timestamp = monotonic() # pylint: disable=no-self-use def update(self): """Get the latest date of the smartplug.""" hub.update_overview() <|fim▁end|>
available
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Verisure Smartplugs.""" import logging from time import monotonic from homeassistant.components.switch import SwitchEntity from . import CONF_SMARTPLUGS, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure switch platform.""" if not int(hub.config.get(CONF_SMARTPLUGS, 1)): return False hub.update_overview() switches = [] switches.extend( [ VerisureSmartplug(device_label) for device_label in hub.get("$.smartPlugs[*].deviceLabel") ] ) add_entities(switches) class VerisureSmartplug(SwitchEntity): """Representation of a Verisure smartplug.""" def __init__(self, device_id): """Initialize the Verisure device.""" self._device_label = device_id self._change_timestamp = 0 self._state = False @property def name(self): """Return the name or location of the smartplug.""" return hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].area", self._device_label ) @property def is_on(self): """Return true if on.""" if monotonic() - self._change_timestamp < 10: return self._state self._state = ( hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].currentState", self._device_label, ) == "ON" ) return self._state @property def available(self): """Return True if entity is available.""" return ( hub.get_first("$.smartPlugs[?(@.deviceLabel == '%s')]", self._device_label) is not None ) def <|fim_middle|>(self, **kwargs): """Set smartplug status on.""" hub.session.set_smartplug_state(self._device_label, True) self._state = True self._change_timestamp = monotonic() def turn_off(self, **kwargs): """Set smartplug status off.""" hub.session.set_smartplug_state(self._device_label, False) self._state = False self._change_timestamp = monotonic() # pylint: disable=no-self-use def update(self): """Get the latest date of the smartplug.""" hub.update_overview() <|fim▁end|>
turn_on
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Verisure Smartplugs.""" import logging from time import monotonic from homeassistant.components.switch import SwitchEntity from . import CONF_SMARTPLUGS, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure switch platform.""" if not int(hub.config.get(CONF_SMARTPLUGS, 1)): return False hub.update_overview() switches = [] switches.extend( [ VerisureSmartplug(device_label) for device_label in hub.get("$.smartPlugs[*].deviceLabel") ] ) add_entities(switches) class VerisureSmartplug(SwitchEntity): """Representation of a Verisure smartplug.""" def __init__(self, device_id): """Initialize the Verisure device.""" self._device_label = device_id self._change_timestamp = 0 self._state = False @property def name(self): """Return the name or location of the smartplug.""" return hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].area", self._device_label ) @property def is_on(self): """Return true if on.""" if monotonic() - self._change_timestamp < 10: return self._state self._state = ( hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].currentState", self._device_label, ) == "ON" ) return self._state @property def available(self): """Return True if entity is available.""" return ( hub.get_first("$.smartPlugs[?(@.deviceLabel == '%s')]", self._device_label) is not None ) def turn_on(self, **kwargs): """Set smartplug status on.""" hub.session.set_smartplug_state(self._device_label, True) self._state = True self._change_timestamp = monotonic() def <|fim_middle|>(self, **kwargs): """Set smartplug status off.""" hub.session.set_smartplug_state(self._device_label, False) self._state = False self._change_timestamp = monotonic() # pylint: disable=no-self-use def update(self): """Get the latest date of the smartplug.""" hub.update_overview() <|fim▁end|>
turn_off
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Support for Verisure Smartplugs.""" import logging from time import monotonic from homeassistant.components.switch import SwitchEntity from . import CONF_SMARTPLUGS, HUB as hub _LOGGER = logging.getLogger(__name__) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Verisure switch platform.""" if not int(hub.config.get(CONF_SMARTPLUGS, 1)): return False hub.update_overview() switches = [] switches.extend( [ VerisureSmartplug(device_label) for device_label in hub.get("$.smartPlugs[*].deviceLabel") ] ) add_entities(switches) class VerisureSmartplug(SwitchEntity): """Representation of a Verisure smartplug.""" def __init__(self, device_id): """Initialize the Verisure device.""" self._device_label = device_id self._change_timestamp = 0 self._state = False @property def name(self): """Return the name or location of the smartplug.""" return hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].area", self._device_label ) @property def is_on(self): """Return true if on.""" if monotonic() - self._change_timestamp < 10: return self._state self._state = ( hub.get_first( "$.smartPlugs[?(@.deviceLabel == '%s')].currentState", self._device_label, ) == "ON" ) return self._state @property def available(self): """Return True if entity is available.""" return ( hub.get_first("$.smartPlugs[?(@.deviceLabel == '%s')]", self._device_label) is not None ) def turn_on(self, **kwargs): """Set smartplug status on.""" hub.session.set_smartplug_state(self._device_label, True) self._state = True self._change_timestamp = monotonic() def turn_off(self, **kwargs): """Set smartplug status off.""" hub.session.set_smartplug_state(self._device_label, False) self._state = False self._change_timestamp = monotonic() # pylint: disable=no-self-use def <|fim_middle|>(self): """Get the latest date of the smartplug.""" hub.update_overview() <|fim▁end|>
update
<|file_name|>0f3a25.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # # @author : [email protected] from headers.BeaEnginePython import * from nose.tools import * class TestSuite: def test(self): # EVEX.256.66.0F3A.W0 25 /r ib # vpternlogd ymm1{k1}{z}, ymm2, ymm3/m256/m32bcst, imm8 myEVEX = EVEX('EVEX.256.66.0F3A.W0') Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix())) myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(myDisasm.infos.Instruction.Opcode, 0x25) assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogd') assert_equal(myDisasm.repr(), 'vpternlogd ymm28, ymm16, ymmword ptr [r8], 11h') # EVEX.512.66.0F3A.W0 25 /r ib # vpternlogd zmm1{k1}{z}, zmm2, zmm3/m512/m32bcst, imm8 myEVEX = EVEX('EVEX.512.66.0F3A.W0') Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix())) myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(myDisasm.infos.Instruction.Opcode, 0x25) assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogd') assert_equal(myDisasm.repr(), 'vpternlogd zmm28, zmm16, zmmword ptr [r8], 11h') # EVEX.256.66.0F3A.W1 25 /r ib # vpternlogq ymm1{k1}{z}, ymm2, ymm3/m256/m64bcst, imm8 myEVEX = EVEX('EVEX.256.66.0F3A.W1') Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix())) myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(myDisasm.infos.Instruction.Opcode, 0x25) assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogq') assert_equal(myDisasm.repr(), 'vpternlogq ymm28, ymm16, ymmword ptr [r8], 11h') # EVEX.512.66.0F3A.W1 25 /r ib # vpternlogq zmm1{k1}{z}, zmm2, zmm3/m512/m64bcst, imm8 myEVEX = EVEX('EVEX.512.66.0F3A.W1') Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix())) myDisasm = Disasm(Buffer) myDisasm.read()<|fim▁hole|> assert_equal(myDisasm.infos.Instruction.Opcode, 0x25) assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogq') assert_equal(myDisasm.repr(), 'vpternlogq zmm28, zmm16, zmmword ptr [r8], 11h')<|fim▁end|>
<|file_name|>0f3a25.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # # @author : [email protected] from headers.BeaEnginePython import * from nose.tools import * class TestSuite: <|fim_middle|> <|fim▁end|>
def test(self): # EVEX.256.66.0F3A.W0 25 /r ib # vpternlogd ymm1{k1}{z}, ymm2, ymm3/m256/m32bcst, imm8 myEVEX = EVEX('EVEX.256.66.0F3A.W0') Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix())) myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(myDisasm.infos.Instruction.Opcode, 0x25) assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogd') assert_equal(myDisasm.repr(), 'vpternlogd ymm28, ymm16, ymmword ptr [r8], 11h') # EVEX.512.66.0F3A.W0 25 /r ib # vpternlogd zmm1{k1}{z}, zmm2, zmm3/m512/m32bcst, imm8 myEVEX = EVEX('EVEX.512.66.0F3A.W0') Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix())) myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(myDisasm.infos.Instruction.Opcode, 0x25) assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogd') assert_equal(myDisasm.repr(), 'vpternlogd zmm28, zmm16, zmmword ptr [r8], 11h') # EVEX.256.66.0F3A.W1 25 /r ib # vpternlogq ymm1{k1}{z}, ymm2, ymm3/m256/m64bcst, imm8 myEVEX = EVEX('EVEX.256.66.0F3A.W1') Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix())) myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(myDisasm.infos.Instruction.Opcode, 0x25) assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogq') assert_equal(myDisasm.repr(), 'vpternlogq ymm28, ymm16, ymmword ptr [r8], 11h') # EVEX.512.66.0F3A.W1 25 /r ib # vpternlogq zmm1{k1}{z}, zmm2, zmm3/m512/m64bcst, imm8 myEVEX = EVEX('EVEX.512.66.0F3A.W1') Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix())) myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(myDisasm.infos.Instruction.Opcode, 0x25) assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogq') assert_equal(myDisasm.repr(), 'vpternlogq zmm28, zmm16, zmmword ptr [r8], 11h')
<|file_name|>0f3a25.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # # @author : [email protected] from headers.BeaEnginePython import * from nose.tools import * class TestSuite: def test(self): # EVEX.256.66.0F3A.W0 25 /r ib # vpternlogd ymm1{k1}{z}, ymm2, ymm3/m256/m32bcst, imm8 <|fim_middle|> <|fim▁end|>
myEVEX = EVEX('EVEX.256.66.0F3A.W0') Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix())) myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(myDisasm.infos.Instruction.Opcode, 0x25) assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogd') assert_equal(myDisasm.repr(), 'vpternlogd ymm28, ymm16, ymmword ptr [r8], 11h') # EVEX.512.66.0F3A.W0 25 /r ib # vpternlogd zmm1{k1}{z}, zmm2, zmm3/m512/m32bcst, imm8 myEVEX = EVEX('EVEX.512.66.0F3A.W0') Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix())) myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(myDisasm.infos.Instruction.Opcode, 0x25) assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogd') assert_equal(myDisasm.repr(), 'vpternlogd zmm28, zmm16, zmmword ptr [r8], 11h') # EVEX.256.66.0F3A.W1 25 /r ib # vpternlogq ymm1{k1}{z}, ymm2, ymm3/m256/m64bcst, imm8 myEVEX = EVEX('EVEX.256.66.0F3A.W1') Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix())) myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(myDisasm.infos.Instruction.Opcode, 0x25) assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogq') assert_equal(myDisasm.repr(), 'vpternlogq ymm28, ymm16, ymmword ptr [r8], 11h') # EVEX.512.66.0F3A.W1 25 /r ib # vpternlogq zmm1{k1}{z}, zmm2, zmm3/m512/m64bcst, imm8 myEVEX = EVEX('EVEX.512.66.0F3A.W1') Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix())) myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(myDisasm.infos.Instruction.Opcode, 0x25) assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogq') assert_equal(myDisasm.repr(), 'vpternlogq zmm28, zmm16, zmmword ptr [r8], 11h')
<|file_name|>0f3a25.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # # @author : [email protected] from headers.BeaEnginePython import * from nose.tools import * class TestSuite: def <|fim_middle|>(self): # EVEX.256.66.0F3A.W0 25 /r ib # vpternlogd ymm1{k1}{z}, ymm2, ymm3/m256/m32bcst, imm8 myEVEX = EVEX('EVEX.256.66.0F3A.W0') Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix())) myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(myDisasm.infos.Instruction.Opcode, 0x25) assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogd') assert_equal(myDisasm.repr(), 'vpternlogd ymm28, ymm16, ymmword ptr [r8], 11h') # EVEX.512.66.0F3A.W0 25 /r ib # vpternlogd zmm1{k1}{z}, zmm2, zmm3/m512/m32bcst, imm8 myEVEX = EVEX('EVEX.512.66.0F3A.W0') Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix())) myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(myDisasm.infos.Instruction.Opcode, 0x25) assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogd') assert_equal(myDisasm.repr(), 'vpternlogd zmm28, zmm16, zmmword ptr [r8], 11h') # EVEX.256.66.0F3A.W1 25 /r ib # vpternlogq ymm1{k1}{z}, ymm2, ymm3/m256/m64bcst, imm8 myEVEX = EVEX('EVEX.256.66.0F3A.W1') Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix())) myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(myDisasm.infos.Instruction.Opcode, 0x25) assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogq') assert_equal(myDisasm.repr(), 'vpternlogq ymm28, ymm16, ymmword ptr [r8], 11h') # EVEX.512.66.0F3A.W1 25 /r ib # vpternlogq zmm1{k1}{z}, zmm2, zmm3/m512/m64bcst, imm8 myEVEX = EVEX('EVEX.512.66.0F3A.W1') Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix())) myDisasm = Disasm(Buffer) myDisasm.read() assert_equal(myDisasm.infos.Instruction.Opcode, 0x25) assert_equal(myDisasm.infos.Instruction.Mnemonic, b'vpternlogq') assert_equal(myDisasm.repr(), 'vpternlogq zmm28, zmm16, zmmword ptr [r8], 11h') <|fim▁end|>
test
<|file_name|>summarize_chipseq_qc.py<|end_file_name|><|fim▁begin|>import gzip import glob import numpy as np import pandas as pd from scipy.stats import pearsonr from scipy.stats import spearmanr def get_num_lines_gz(filename): num_lines = 0 with gzip.open(filename, "r") as fp: for line in fp: num_lines += 1 return num_lines def main(): """get stats from PAS-seq - num reads per file - gene quant level spearman correlations """ # files DATA_DIR = "/mnt/lab_data/kundaje/projects/skin/data/bds/processed.chipseq.2017-01-23.histones" # params marks = ["H3K27ac", "H3K4me1", "H3K27me3", "CTCF"] days = np.arange(0, 7, 3) days = ["d{}".format(day).replace(".", "") for day in days] reps = ["1", "2"] # results results = {} results["mark_or_tf"] = [] results["timepoint"] = [] results["replicate"] = [] #results["num_input_reads"] = [] results["num_nodup_reads"] = [] results["NRF"] = [] results["PBC1"] = [] results["PBC2"] = [] results["num_macs2_peaks"] = [] results["num_overlap_peaks"] = [] results["num_idr_peaks"] = [] for mark in marks: print mark for day in days: for rep in reps: # timepoint, rep results["mark_or_tf"].append(mark) results["timepoint"].append(day) results["replicate"].append(rep) # nodup reads nodup_log = glob.glob( "{}/*{}*{}*/qc/rep{}/*nodup.flagstat.qc".format( DATA_DIR, day, mark, rep))[0] with open(nodup_log, "r") as fp: for line in fp: if "in total" in line: num_nodup_reads = line.split("+")[0].strip() results["num_nodup_reads"].append(num_nodup_reads) # NRF/PBC1/PBC2 lib_log = glob.glob( "{}/*{}*{}*/qc/rep{}/*nodup.pbc.qc".format( DATA_DIR, day, mark, rep))[0] with open(lib_log, "r") as fp: # cols 5,6,7 is NRF/PBC1/PBC2 for line in fp: fields = line.strip().split() results["NRF"].append(fields[4]) results["PBC1"].append(fields[5]) results["PBC2"].append(fields[6]) # peak files macs2_peaks = glob.glob(<|fim▁hole|> DATA_DIR, day, mark, rep))[0] num_macs2 = get_num_lines_gz(macs2_peaks) results["num_macs2_peaks"].append(num_macs2) if "CTCF" in mark: idr_peaks = glob.glob( "{}/*{}*{}*/peak/idr/true_reps/rep1-rep2/*filt.narrowPeak.gz".format( DATA_DIR, day, mark))[0] num_idr = get_num_lines_gz(idr_peaks) results["num_idr_peaks"].append(num_idr) results["num_overlap_peaks"].append("NA") else: results["num_idr_peaks"].append("NA") overlap_peaks = glob.glob( "{}/*{}*{}*/peak/macs2/overlap/*filt.narrowPeak.gz".format( DATA_DIR, day, mark, rep))[0] num_overlap = get_num_lines_gz(overlap_peaks) results["num_overlap_peaks"].append(num_overlap) # dataframe results = pd.DataFrame(results) ordered_headers = [ "mark_or_tf", "timepoint", "replicate", #"num_input_reads", "num_nodup_reads", "NRF", "PBC1", "PBC2", "num_macs2_peaks", "num_overlap_peaks", "num_idr_peaks"] results = results[ordered_headers] out_file = "ggr.ChIP-seq.QC.summary.txt" results.to_csv(out_file, sep="\t", header=True, index=False) return main()<|fim▁end|>
"{}/*{}*{}*/peak/macs2/rep{}/*narrowPeak.gz".format(
<|file_name|>summarize_chipseq_qc.py<|end_file_name|><|fim▁begin|> import gzip import glob import numpy as np import pandas as pd from scipy.stats import pearsonr from scipy.stats import spearmanr def get_num_lines_gz(filename): <|fim_middle|> def main(): """get stats from PAS-seq - num reads per file - gene quant level spearman correlations """ # files DATA_DIR = "/mnt/lab_data/kundaje/projects/skin/data/bds/processed.chipseq.2017-01-23.histones" # params marks = ["H3K27ac", "H3K4me1", "H3K27me3", "CTCF"] days = np.arange(0, 7, 3) days = ["d{}".format(day).replace(".", "") for day in days] reps = ["1", "2"] # results results = {} results["mark_or_tf"] = [] results["timepoint"] = [] results["replicate"] = [] #results["num_input_reads"] = [] results["num_nodup_reads"] = [] results["NRF"] = [] results["PBC1"] = [] results["PBC2"] = [] results["num_macs2_peaks"] = [] results["num_overlap_peaks"] = [] results["num_idr_peaks"] = [] for mark in marks: print mark for day in days: for rep in reps: # timepoint, rep results["mark_or_tf"].append(mark) results["timepoint"].append(day) results["replicate"].append(rep) # nodup reads nodup_log = glob.glob( "{}/*{}*{}*/qc/rep{}/*nodup.flagstat.qc".format( DATA_DIR, day, mark, rep))[0] with open(nodup_log, "r") as fp: for line in fp: if "in total" in line: num_nodup_reads = line.split("+")[0].strip() results["num_nodup_reads"].append(num_nodup_reads) # NRF/PBC1/PBC2 lib_log = glob.glob( "{}/*{}*{}*/qc/rep{}/*nodup.pbc.qc".format( DATA_DIR, day, mark, rep))[0] with open(lib_log, "r") as fp: # cols 5,6,7 is NRF/PBC1/PBC2 for line in fp: fields = line.strip().split() results["NRF"].append(fields[4]) results["PBC1"].append(fields[5]) results["PBC2"].append(fields[6]) # peak files macs2_peaks = glob.glob( "{}/*{}*{}*/peak/macs2/rep{}/*narrowPeak.gz".format( DATA_DIR, day, mark, rep))[0] num_macs2 = get_num_lines_gz(macs2_peaks) results["num_macs2_peaks"].append(num_macs2) if "CTCF" in mark: idr_peaks = glob.glob( "{}/*{}*{}*/peak/idr/true_reps/rep1-rep2/*filt.narrowPeak.gz".format( DATA_DIR, day, mark))[0] num_idr = get_num_lines_gz(idr_peaks) results["num_idr_peaks"].append(num_idr) results["num_overlap_peaks"].append("NA") else: results["num_idr_peaks"].append("NA") overlap_peaks = glob.glob( "{}/*{}*{}*/peak/macs2/overlap/*filt.narrowPeak.gz".format( DATA_DIR, day, mark, rep))[0] num_overlap = get_num_lines_gz(overlap_peaks) results["num_overlap_peaks"].append(num_overlap) # dataframe results = pd.DataFrame(results) ordered_headers = [ "mark_or_tf", "timepoint", "replicate", #"num_input_reads", "num_nodup_reads", "NRF", "PBC1", "PBC2", "num_macs2_peaks", "num_overlap_peaks", "num_idr_peaks"] results = results[ordered_headers] out_file = "ggr.ChIP-seq.QC.summary.txt" results.to_csv(out_file, sep="\t", header=True, index=False) return main() <|fim▁end|>
num_lines = 0 with gzip.open(filename, "r") as fp: for line in fp: num_lines += 1 return num_lines
<|file_name|>summarize_chipseq_qc.py<|end_file_name|><|fim▁begin|> import gzip import glob import numpy as np import pandas as pd from scipy.stats import pearsonr from scipy.stats import spearmanr def get_num_lines_gz(filename): num_lines = 0 with gzip.open(filename, "r") as fp: for line in fp: num_lines += 1 return num_lines def main(): <|fim_middle|> main() <|fim▁end|>
"""get stats from PAS-seq - num reads per file - gene quant level spearman correlations """ # files DATA_DIR = "/mnt/lab_data/kundaje/projects/skin/data/bds/processed.chipseq.2017-01-23.histones" # params marks = ["H3K27ac", "H3K4me1", "H3K27me3", "CTCF"] days = np.arange(0, 7, 3) days = ["d{}".format(day).replace(".", "") for day in days] reps = ["1", "2"] # results results = {} results["mark_or_tf"] = [] results["timepoint"] = [] results["replicate"] = [] #results["num_input_reads"] = [] results["num_nodup_reads"] = [] results["NRF"] = [] results["PBC1"] = [] results["PBC2"] = [] results["num_macs2_peaks"] = [] results["num_overlap_peaks"] = [] results["num_idr_peaks"] = [] for mark in marks: print mark for day in days: for rep in reps: # timepoint, rep results["mark_or_tf"].append(mark) results["timepoint"].append(day) results["replicate"].append(rep) # nodup reads nodup_log = glob.glob( "{}/*{}*{}*/qc/rep{}/*nodup.flagstat.qc".format( DATA_DIR, day, mark, rep))[0] with open(nodup_log, "r") as fp: for line in fp: if "in total" in line: num_nodup_reads = line.split("+")[0].strip() results["num_nodup_reads"].append(num_nodup_reads) # NRF/PBC1/PBC2 lib_log = glob.glob( "{}/*{}*{}*/qc/rep{}/*nodup.pbc.qc".format( DATA_DIR, day, mark, rep))[0] with open(lib_log, "r") as fp: # cols 5,6,7 is NRF/PBC1/PBC2 for line in fp: fields = line.strip().split() results["NRF"].append(fields[4]) results["PBC1"].append(fields[5]) results["PBC2"].append(fields[6]) # peak files macs2_peaks = glob.glob( "{}/*{}*{}*/peak/macs2/rep{}/*narrowPeak.gz".format( DATA_DIR, day, mark, rep))[0] num_macs2 = get_num_lines_gz(macs2_peaks) results["num_macs2_peaks"].append(num_macs2) if "CTCF" in mark: idr_peaks = glob.glob( "{}/*{}*{}*/peak/idr/true_reps/rep1-rep2/*filt.narrowPeak.gz".format( DATA_DIR, day, mark))[0] num_idr = get_num_lines_gz(idr_peaks) results["num_idr_peaks"].append(num_idr) results["num_overlap_peaks"].append("NA") else: results["num_idr_peaks"].append("NA") overlap_peaks = glob.glob( "{}/*{}*{}*/peak/macs2/overlap/*filt.narrowPeak.gz".format( DATA_DIR, day, mark, rep))[0] num_overlap = get_num_lines_gz(overlap_peaks) results["num_overlap_peaks"].append(num_overlap) # dataframe results = pd.DataFrame(results) ordered_headers = [ "mark_or_tf", "timepoint", "replicate", #"num_input_reads", "num_nodup_reads", "NRF", "PBC1", "PBC2", "num_macs2_peaks", "num_overlap_peaks", "num_idr_peaks"] results = results[ordered_headers] out_file = "ggr.ChIP-seq.QC.summary.txt" results.to_csv(out_file, sep="\t", header=True, index=False) return
<|file_name|>summarize_chipseq_qc.py<|end_file_name|><|fim▁begin|> import gzip import glob import numpy as np import pandas as pd from scipy.stats import pearsonr from scipy.stats import spearmanr def get_num_lines_gz(filename): num_lines = 0 with gzip.open(filename, "r") as fp: for line in fp: num_lines += 1 return num_lines def main(): """get stats from PAS-seq - num reads per file - gene quant level spearman correlations """ # files DATA_DIR = "/mnt/lab_data/kundaje/projects/skin/data/bds/processed.chipseq.2017-01-23.histones" # params marks = ["H3K27ac", "H3K4me1", "H3K27me3", "CTCF"] days = np.arange(0, 7, 3) days = ["d{}".format(day).replace(".", "") for day in days] reps = ["1", "2"] # results results = {} results["mark_or_tf"] = [] results["timepoint"] = [] results["replicate"] = [] #results["num_input_reads"] = [] results["num_nodup_reads"] = [] results["NRF"] = [] results["PBC1"] = [] results["PBC2"] = [] results["num_macs2_peaks"] = [] results["num_overlap_peaks"] = [] results["num_idr_peaks"] = [] for mark in marks: print mark for day in days: for rep in reps: # timepoint, rep results["mark_or_tf"].append(mark) results["timepoint"].append(day) results["replicate"].append(rep) # nodup reads nodup_log = glob.glob( "{}/*{}*{}*/qc/rep{}/*nodup.flagstat.qc".format( DATA_DIR, day, mark, rep))[0] with open(nodup_log, "r") as fp: for line in fp: if "in total" in line: <|fim_middle|> # NRF/PBC1/PBC2 lib_log = glob.glob( "{}/*{}*{}*/qc/rep{}/*nodup.pbc.qc".format( DATA_DIR, day, mark, rep))[0] with open(lib_log, "r") as fp: # cols 5,6,7 is NRF/PBC1/PBC2 for line in fp: fields = line.strip().split() results["NRF"].append(fields[4]) results["PBC1"].append(fields[5]) results["PBC2"].append(fields[6]) # peak files macs2_peaks = glob.glob( "{}/*{}*{}*/peak/macs2/rep{}/*narrowPeak.gz".format( DATA_DIR, day, mark, rep))[0] num_macs2 = get_num_lines_gz(macs2_peaks) results["num_macs2_peaks"].append(num_macs2) if "CTCF" in mark: idr_peaks = glob.glob( "{}/*{}*{}*/peak/idr/true_reps/rep1-rep2/*filt.narrowPeak.gz".format( DATA_DIR, day, mark))[0] num_idr = get_num_lines_gz(idr_peaks) results["num_idr_peaks"].append(num_idr) results["num_overlap_peaks"].append("NA") else: results["num_idr_peaks"].append("NA") overlap_peaks = glob.glob( "{}/*{}*{}*/peak/macs2/overlap/*filt.narrowPeak.gz".format( DATA_DIR, day, mark, rep))[0] num_overlap = get_num_lines_gz(overlap_peaks) results["num_overlap_peaks"].append(num_overlap) # dataframe results = pd.DataFrame(results) ordered_headers = [ "mark_or_tf", "timepoint", "replicate", #"num_input_reads", "num_nodup_reads", "NRF", "PBC1", "PBC2", "num_macs2_peaks", "num_overlap_peaks", "num_idr_peaks"] results = results[ordered_headers] out_file = "ggr.ChIP-seq.QC.summary.txt" results.to_csv(out_file, sep="\t", header=True, index=False) return main() <|fim▁end|>
num_nodup_reads = line.split("+")[0].strip() results["num_nodup_reads"].append(num_nodup_reads)
<|file_name|>summarize_chipseq_qc.py<|end_file_name|><|fim▁begin|> import gzip import glob import numpy as np import pandas as pd from scipy.stats import pearsonr from scipy.stats import spearmanr def get_num_lines_gz(filename): num_lines = 0 with gzip.open(filename, "r") as fp: for line in fp: num_lines += 1 return num_lines def main(): """get stats from PAS-seq - num reads per file - gene quant level spearman correlations """ # files DATA_DIR = "/mnt/lab_data/kundaje/projects/skin/data/bds/processed.chipseq.2017-01-23.histones" # params marks = ["H3K27ac", "H3K4me1", "H3K27me3", "CTCF"] days = np.arange(0, 7, 3) days = ["d{}".format(day).replace(".", "") for day in days] reps = ["1", "2"] # results results = {} results["mark_or_tf"] = [] results["timepoint"] = [] results["replicate"] = [] #results["num_input_reads"] = [] results["num_nodup_reads"] = [] results["NRF"] = [] results["PBC1"] = [] results["PBC2"] = [] results["num_macs2_peaks"] = [] results["num_overlap_peaks"] = [] results["num_idr_peaks"] = [] for mark in marks: print mark for day in days: for rep in reps: # timepoint, rep results["mark_or_tf"].append(mark) results["timepoint"].append(day) results["replicate"].append(rep) # nodup reads nodup_log = glob.glob( "{}/*{}*{}*/qc/rep{}/*nodup.flagstat.qc".format( DATA_DIR, day, mark, rep))[0] with open(nodup_log, "r") as fp: for line in fp: if "in total" in line: num_nodup_reads = line.split("+")[0].strip() results["num_nodup_reads"].append(num_nodup_reads) # NRF/PBC1/PBC2 lib_log = glob.glob( "{}/*{}*{}*/qc/rep{}/*nodup.pbc.qc".format( DATA_DIR, day, mark, rep))[0] with open(lib_log, "r") as fp: # cols 5,6,7 is NRF/PBC1/PBC2 for line in fp: fields = line.strip().split() results["NRF"].append(fields[4]) results["PBC1"].append(fields[5]) results["PBC2"].append(fields[6]) # peak files macs2_peaks = glob.glob( "{}/*{}*{}*/peak/macs2/rep{}/*narrowPeak.gz".format( DATA_DIR, day, mark, rep))[0] num_macs2 = get_num_lines_gz(macs2_peaks) results["num_macs2_peaks"].append(num_macs2) if "CTCF" in mark: <|fim_middle|> else: results["num_idr_peaks"].append("NA") overlap_peaks = glob.glob( "{}/*{}*{}*/peak/macs2/overlap/*filt.narrowPeak.gz".format( DATA_DIR, day, mark, rep))[0] num_overlap = get_num_lines_gz(overlap_peaks) results["num_overlap_peaks"].append(num_overlap) # dataframe results = pd.DataFrame(results) ordered_headers = [ "mark_or_tf", "timepoint", "replicate", #"num_input_reads", "num_nodup_reads", "NRF", "PBC1", "PBC2", "num_macs2_peaks", "num_overlap_peaks", "num_idr_peaks"] results = results[ordered_headers] out_file = "ggr.ChIP-seq.QC.summary.txt" results.to_csv(out_file, sep="\t", header=True, index=False) return main() <|fim▁end|>
idr_peaks = glob.glob( "{}/*{}*{}*/peak/idr/true_reps/rep1-rep2/*filt.narrowPeak.gz".format( DATA_DIR, day, mark))[0] num_idr = get_num_lines_gz(idr_peaks) results["num_idr_peaks"].append(num_idr) results["num_overlap_peaks"].append("NA")
<|file_name|>summarize_chipseq_qc.py<|end_file_name|><|fim▁begin|> import gzip import glob import numpy as np import pandas as pd from scipy.stats import pearsonr from scipy.stats import spearmanr def get_num_lines_gz(filename): num_lines = 0 with gzip.open(filename, "r") as fp: for line in fp: num_lines += 1 return num_lines def main(): """get stats from PAS-seq - num reads per file - gene quant level spearman correlations """ # files DATA_DIR = "/mnt/lab_data/kundaje/projects/skin/data/bds/processed.chipseq.2017-01-23.histones" # params marks = ["H3K27ac", "H3K4me1", "H3K27me3", "CTCF"] days = np.arange(0, 7, 3) days = ["d{}".format(day).replace(".", "") for day in days] reps = ["1", "2"] # results results = {} results["mark_or_tf"] = [] results["timepoint"] = [] results["replicate"] = [] #results["num_input_reads"] = [] results["num_nodup_reads"] = [] results["NRF"] = [] results["PBC1"] = [] results["PBC2"] = [] results["num_macs2_peaks"] = [] results["num_overlap_peaks"] = [] results["num_idr_peaks"] = [] for mark in marks: print mark for day in days: for rep in reps: # timepoint, rep results["mark_or_tf"].append(mark) results["timepoint"].append(day) results["replicate"].append(rep) # nodup reads nodup_log = glob.glob( "{}/*{}*{}*/qc/rep{}/*nodup.flagstat.qc".format( DATA_DIR, day, mark, rep))[0] with open(nodup_log, "r") as fp: for line in fp: if "in total" in line: num_nodup_reads = line.split("+")[0].strip() results["num_nodup_reads"].append(num_nodup_reads) # NRF/PBC1/PBC2 lib_log = glob.glob( "{}/*{}*{}*/qc/rep{}/*nodup.pbc.qc".format( DATA_DIR, day, mark, rep))[0] with open(lib_log, "r") as fp: # cols 5,6,7 is NRF/PBC1/PBC2 for line in fp: fields = line.strip().split() results["NRF"].append(fields[4]) results["PBC1"].append(fields[5]) results["PBC2"].append(fields[6]) # peak files macs2_peaks = glob.glob( "{}/*{}*{}*/peak/macs2/rep{}/*narrowPeak.gz".format( DATA_DIR, day, mark, rep))[0] num_macs2 = get_num_lines_gz(macs2_peaks) results["num_macs2_peaks"].append(num_macs2) if "CTCF" in mark: idr_peaks = glob.glob( "{}/*{}*{}*/peak/idr/true_reps/rep1-rep2/*filt.narrowPeak.gz".format( DATA_DIR, day, mark))[0] num_idr = get_num_lines_gz(idr_peaks) results["num_idr_peaks"].append(num_idr) results["num_overlap_peaks"].append("NA") else: <|fim_middle|> # dataframe results = pd.DataFrame(results) ordered_headers = [ "mark_or_tf", "timepoint", "replicate", #"num_input_reads", "num_nodup_reads", "NRF", "PBC1", "PBC2", "num_macs2_peaks", "num_overlap_peaks", "num_idr_peaks"] results = results[ordered_headers] out_file = "ggr.ChIP-seq.QC.summary.txt" results.to_csv(out_file, sep="\t", header=True, index=False) return main() <|fim▁end|>
results["num_idr_peaks"].append("NA") overlap_peaks = glob.glob( "{}/*{}*{}*/peak/macs2/overlap/*filt.narrowPeak.gz".format( DATA_DIR, day, mark, rep))[0] num_overlap = get_num_lines_gz(overlap_peaks) results["num_overlap_peaks"].append(num_overlap)
<|file_name|>summarize_chipseq_qc.py<|end_file_name|><|fim▁begin|> import gzip import glob import numpy as np import pandas as pd from scipy.stats import pearsonr from scipy.stats import spearmanr def <|fim_middle|>(filename): num_lines = 0 with gzip.open(filename, "r") as fp: for line in fp: num_lines += 1 return num_lines def main(): """get stats from PAS-seq - num reads per file - gene quant level spearman correlations """ # files DATA_DIR = "/mnt/lab_data/kundaje/projects/skin/data/bds/processed.chipseq.2017-01-23.histones" # params marks = ["H3K27ac", "H3K4me1", "H3K27me3", "CTCF"] days = np.arange(0, 7, 3) days = ["d{}".format(day).replace(".", "") for day in days] reps = ["1", "2"] # results results = {} results["mark_or_tf"] = [] results["timepoint"] = [] results["replicate"] = [] #results["num_input_reads"] = [] results["num_nodup_reads"] = [] results["NRF"] = [] results["PBC1"] = [] results["PBC2"] = [] results["num_macs2_peaks"] = [] results["num_overlap_peaks"] = [] results["num_idr_peaks"] = [] for mark in marks: print mark for day in days: for rep in reps: # timepoint, rep results["mark_or_tf"].append(mark) results["timepoint"].append(day) results["replicate"].append(rep) # nodup reads nodup_log = glob.glob( "{}/*{}*{}*/qc/rep{}/*nodup.flagstat.qc".format( DATA_DIR, day, mark, rep))[0] with open(nodup_log, "r") as fp: for line in fp: if "in total" in line: num_nodup_reads = line.split("+")[0].strip() results["num_nodup_reads"].append(num_nodup_reads) # NRF/PBC1/PBC2 lib_log = glob.glob( "{}/*{}*{}*/qc/rep{}/*nodup.pbc.qc".format( DATA_DIR, day, mark, rep))[0] with open(lib_log, "r") as fp: # cols 5,6,7 is NRF/PBC1/PBC2 for line in fp: fields = line.strip().split() results["NRF"].append(fields[4]) results["PBC1"].append(fields[5]) results["PBC2"].append(fields[6]) # peak files macs2_peaks = glob.glob( "{}/*{}*{}*/peak/macs2/rep{}/*narrowPeak.gz".format( DATA_DIR, day, mark, rep))[0] num_macs2 = get_num_lines_gz(macs2_peaks) results["num_macs2_peaks"].append(num_macs2) if "CTCF" in mark: idr_peaks = glob.glob( "{}/*{}*{}*/peak/idr/true_reps/rep1-rep2/*filt.narrowPeak.gz".format( DATA_DIR, day, mark))[0] num_idr = get_num_lines_gz(idr_peaks) results["num_idr_peaks"].append(num_idr) results["num_overlap_peaks"].append("NA") else: results["num_idr_peaks"].append("NA") overlap_peaks = glob.glob( "{}/*{}*{}*/peak/macs2/overlap/*filt.narrowPeak.gz".format( DATA_DIR, day, mark, rep))[0] num_overlap = get_num_lines_gz(overlap_peaks) results["num_overlap_peaks"].append(num_overlap) # dataframe results = pd.DataFrame(results) ordered_headers = [ "mark_or_tf", "timepoint", "replicate", #"num_input_reads", "num_nodup_reads", "NRF", "PBC1", "PBC2", "num_macs2_peaks", "num_overlap_peaks", "num_idr_peaks"] results = results[ordered_headers] out_file = "ggr.ChIP-seq.QC.summary.txt" results.to_csv(out_file, sep="\t", header=True, index=False) return main() <|fim▁end|>
get_num_lines_gz
<|file_name|>summarize_chipseq_qc.py<|end_file_name|><|fim▁begin|> import gzip import glob import numpy as np import pandas as pd from scipy.stats import pearsonr from scipy.stats import spearmanr def get_num_lines_gz(filename): num_lines = 0 with gzip.open(filename, "r") as fp: for line in fp: num_lines += 1 return num_lines def <|fim_middle|>(): """get stats from PAS-seq - num reads per file - gene quant level spearman correlations """ # files DATA_DIR = "/mnt/lab_data/kundaje/projects/skin/data/bds/processed.chipseq.2017-01-23.histones" # params marks = ["H3K27ac", "H3K4me1", "H3K27me3", "CTCF"] days = np.arange(0, 7, 3) days = ["d{}".format(day).replace(".", "") for day in days] reps = ["1", "2"] # results results = {} results["mark_or_tf"] = [] results["timepoint"] = [] results["replicate"] = [] #results["num_input_reads"] = [] results["num_nodup_reads"] = [] results["NRF"] = [] results["PBC1"] = [] results["PBC2"] = [] results["num_macs2_peaks"] = [] results["num_overlap_peaks"] = [] results["num_idr_peaks"] = [] for mark in marks: print mark for day in days: for rep in reps: # timepoint, rep results["mark_or_tf"].append(mark) results["timepoint"].append(day) results["replicate"].append(rep) # nodup reads nodup_log = glob.glob( "{}/*{}*{}*/qc/rep{}/*nodup.flagstat.qc".format( DATA_DIR, day, mark, rep))[0] with open(nodup_log, "r") as fp: for line in fp: if "in total" in line: num_nodup_reads = line.split("+")[0].strip() results["num_nodup_reads"].append(num_nodup_reads) # NRF/PBC1/PBC2 lib_log = glob.glob( "{}/*{}*{}*/qc/rep{}/*nodup.pbc.qc".format( DATA_DIR, day, mark, rep))[0] with open(lib_log, "r") as fp: # cols 5,6,7 is NRF/PBC1/PBC2 for line in fp: fields = line.strip().split() results["NRF"].append(fields[4]) results["PBC1"].append(fields[5]) results["PBC2"].append(fields[6]) # peak files macs2_peaks = glob.glob( "{}/*{}*{}*/peak/macs2/rep{}/*narrowPeak.gz".format( DATA_DIR, day, mark, rep))[0] num_macs2 = get_num_lines_gz(macs2_peaks) results["num_macs2_peaks"].append(num_macs2) if "CTCF" in mark: idr_peaks = glob.glob( "{}/*{}*{}*/peak/idr/true_reps/rep1-rep2/*filt.narrowPeak.gz".format( DATA_DIR, day, mark))[0] num_idr = get_num_lines_gz(idr_peaks) results["num_idr_peaks"].append(num_idr) results["num_overlap_peaks"].append("NA") else: results["num_idr_peaks"].append("NA") overlap_peaks = glob.glob( "{}/*{}*{}*/peak/macs2/overlap/*filt.narrowPeak.gz".format( DATA_DIR, day, mark, rep))[0] num_overlap = get_num_lines_gz(overlap_peaks) results["num_overlap_peaks"].append(num_overlap) # dataframe results = pd.DataFrame(results) ordered_headers = [ "mark_or_tf", "timepoint", "replicate", #"num_input_reads", "num_nodup_reads", "NRF", "PBC1", "PBC2", "num_macs2_peaks", "num_overlap_peaks", "num_idr_peaks"] results = results[ordered_headers] out_file = "ggr.ChIP-seq.QC.summary.txt" results.to_csv(out_file, sep="\t", header=True, index=False) return main() <|fim▁end|>
main
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess<|fim▁hole|> config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main()<|fim▁end|>
import sys def main():
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): <|fim_middle|> def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main() <|fim▁end|>
config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf)
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): <|fim_middle|> def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main() <|fim▁end|>
""" Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0)
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): <|fim_middle|> def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main() <|fim▁end|>
"""Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): <|fim_middle|> if __name__ == '__main__': main() <|fim▁end|>
"""Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt)
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: <|fim_middle|> else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main() <|fim▁end|>
level = logging.DEBUG
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: <|fim_middle|> formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main() <|fim▁end|>
level = logging.ERROR
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: <|fim_middle|> else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main() <|fim▁end|>
error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1)
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: <|fim_middle|> def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main() <|fim▁end|>
sys.exit(0)
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: <|fim_middle|> # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main() <|fim▁end|>
filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: <|fim_middle|> # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main() <|fim▁end|>
outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: <|fim_middle|> if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main() <|fim▁end|>
logging.error("Output data missing for " + outputFn) raise Exception
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: <|fim_middle|> # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main() <|fim▁end|>
logging.error("Output file %s does not have a file extension" % outputFn) raise Exception
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: <|fim_middle|> # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main() <|fim▁end|>
data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: <|fim_middle|> # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main() <|fim▁end|>
logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: <|fim_middle|> assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main() <|fim▁end|>
error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: <|fim_middle|> if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main() <|fim▁end|>
wantRC = testObj['return_code']
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: <|fim_middle|> if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main() <|fim▁end|>
logging.error("Return code mismatch for " + outputFn) raise Exception
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: <|fim_middle|> def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main() <|fim▁end|>
want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: <|fim_middle|> def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main() <|fim▁end|>
logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data <|fim_middle|> elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main() <|fim▁end|>
return json.loads(a)
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data <|fim_middle|> else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main() <|fim▁end|>
return binascii.a2b_hex(a.strip())
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: <|fim_middle|> if __name__ == '__main__': main() <|fim▁end|>
raise NotImplementedError("Don't know how to compare %s" % fmt)
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': <|fim_middle|> <|fim▁end|>
main()
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def <|fim_middle|>(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main() <|fim▁end|>
main
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def <|fim_middle|>(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main() <|fim▁end|>
bctester
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def <|fim_middle|>(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def parse_output(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main() <|fim▁end|>
bctest
<|file_name|>syscoin-util-test.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright 2014 BitPay Inc. # Copyright 2016-2017 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test framework for syscoin utils. Runs automatically during `make check`. Can also be run manually.""" import argparse import binascii import configparser import difflib import json import logging import os import pprint import subprocess import sys def main(): config = configparser.ConfigParser() config.optionxform = str config.read_file(open(os.path.join(os.path.dirname(__file__), "../config.ini"), encoding="utf8")) env_conf = dict(config.items('environment')) parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('-v', '--verbose', action='store_true') args = parser.parse_args() verbose = args.verbose if verbose: level = logging.DEBUG else: level = logging.ERROR formatter = '%(asctime)s - %(levelname)s - %(message)s' # Add the format/level to the logger logging.basicConfig(format=formatter, level=level) bctester(os.path.join(env_conf["SRCDIR"], "test", "util", "data"), "syscoin-util-test.json", env_conf) def bctester(testDir, input_basename, buildenv): """ Loads and parses the input file, runs all tests and reports results""" input_filename = os.path.join(testDir, input_basename) raw_data = open(input_filename, encoding="utf8").read() input_data = json.loads(raw_data) failed_testcases = [] for testObj in input_data: try: bctest(testDir, testObj, buildenv) logging.info("PASSED: " + testObj["description"]) except: logging.info("FAILED: " + testObj["description"]) failed_testcases.append(testObj["description"]) if failed_testcases: error_message = "FAILED_TESTCASES:\n" error_message += pprint.pformat(failed_testcases, width=400) logging.error(error_message) sys.exit(1) else: sys.exit(0) def bctest(testDir, testObj, buildenv): """Runs a single test, comparing output and RC to expected output and RC. Raises an error if input can't be read, executable fails, or output/RC are not as expected. Error is caught by bctester() and reported. """ # Get the exec names and arguments execprog = os.path.join(buildenv["BUILDDIR"], "src", testObj["exec"] + buildenv["EXEEXT"]) execargs = testObj['args'] execrun = [execprog] + execargs # Read the input data (if there is any) stdinCfg = None inputData = None if "input" in testObj: filename = os.path.join(testDir, testObj["input"]) inputData = open(filename, encoding="utf8").read() stdinCfg = subprocess.PIPE # Read the expected output data (if there is any) outputFn = None outputData = None outputType = None if "output_cmp" in testObj: outputFn = testObj['output_cmp'] outputType = os.path.splitext(outputFn)[1][1:] # output type from file extension (determines how to compare) try: outputData = open(os.path.join(testDir, outputFn), encoding="utf8").read() except: logging.error("Output file " + outputFn + " can not be opened") raise if not outputData: logging.error("Output data missing for " + outputFn) raise Exception if not outputType: logging.error("Output file %s does not have a file extension" % outputFn) raise Exception # Run the test proc = subprocess.Popen(execrun, stdin=stdinCfg, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) try: outs = proc.communicate(input=inputData) except OSError: logging.error("OSError, Failed to execute " + execprog) raise if outputData: data_mismatch, formatting_mismatch = False, False # Parse command output and expected output try: a_parsed = parse_output(outs[0], outputType) except Exception as e: logging.error('Error parsing command output as %s: %s' % (outputType, e)) raise try: b_parsed = parse_output(outputData, outputType) except Exception as e: logging.error('Error parsing expected output %s as %s: %s' % (outputFn, outputType, e)) raise # Compare data if a_parsed != b_parsed: logging.error("Output data mismatch for " + outputFn + " (format " + outputType + ")") data_mismatch = True # Compare formatting if outs[0] != outputData: error_message = "Output formatting mismatch for " + outputFn + ":\n" error_message += "".join(difflib.context_diff(outputData.splitlines(True), outs[0].splitlines(True), fromfile=outputFn, tofile="returned")) logging.error(error_message) formatting_mismatch = True assert not data_mismatch and not formatting_mismatch # Compare the return code to the expected return code wantRC = 0 if "return_code" in testObj: wantRC = testObj['return_code'] if proc.returncode != wantRC: logging.error("Return code mismatch for " + outputFn) raise Exception if "error_txt" in testObj: want_error = testObj["error_txt"] # Compare error text # TODO: ideally, we'd compare the strings exactly and also assert # That stderr is empty if no errors are expected. However, syscoin-tx # emits DISPLAY errors when running as a windows application on # linux through wine. Just assert that the expected error text appears # somewhere in stderr. if want_error not in outs[1]: logging.error("Error mismatch:\n" + "Expected: " + want_error + "\nReceived: " + outs[1].rstrip()) raise Exception def <|fim_middle|>(a, fmt): """Parse the output according to specified format. Raise an error if the output can't be parsed.""" if fmt == 'json': # json: compare parsed data return json.loads(a) elif fmt == 'hex': # hex: parse and compare binary data return binascii.a2b_hex(a.strip()) else: raise NotImplementedError("Don't know how to compare %s" % fmt) if __name__ == '__main__': main() <|fim▁end|>
parse_output
<|file_name|>1_5_migrating_work_u_1212f113f03b.py<|end_file_name|><|fim▁begin|>"""1.5 : Migrating work unity Revision ID: 1212f113f03b Revises: 1f07ae132ac8 Create Date: 2013-01-21 11:53:56.598914 """ # revision identifiers, used by Alembic. revision = '1212f113f03b' down_revision = '1f07ae132ac8' from alembic import op import sqlalchemy as sa UNITIES = dict(NONE="", HOUR=u"heure(s)", DAY=u"jour(s)", WEEK=u"semaine(s)", MONTH=u"mois", FEUIL=u"feuillet(s)", PACK=u"forfait") UNITS = (u"heure(s)", u"jour(s)", u"semaine(s)", u"mois", u"forfait", u"feuillet(s)",) def translate_unity(unity): return UNITIES.get(unity, UNITIES["NONE"]) def translate_inverse(unity): for key, value in UNITIES.items(): if unity == value: return key else: return u"NONE"<|fim▁hole|> def upgrade(): from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION # Adding some characters to the Lines for table in "estimation_line", "invoice_line", "cancelinvoice_line": op.alter_column(table, "unity", type_=sa.String(100)) for value in UNITS: unit = WorkUnit(label=value) DBSESSION().add(unit) for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_unity(line.unity) DBSESSION().merge(line) def downgrade(): from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_inverse(line.unity) DBSESSION().merge(line) for value in WorkUnit.query(): DBSESSION().delete(value)<|fim▁end|>
<|file_name|>1_5_migrating_work_u_1212f113f03b.py<|end_file_name|><|fim▁begin|>"""1.5 : Migrating work unity Revision ID: 1212f113f03b Revises: 1f07ae132ac8 Create Date: 2013-01-21 11:53:56.598914 """ # revision identifiers, used by Alembic. revision = '1212f113f03b' down_revision = '1f07ae132ac8' from alembic import op import sqlalchemy as sa UNITIES = dict(NONE="", HOUR=u"heure(s)", DAY=u"jour(s)", WEEK=u"semaine(s)", MONTH=u"mois", FEUIL=u"feuillet(s)", PACK=u"forfait") UNITS = (u"heure(s)", u"jour(s)", u"semaine(s)", u"mois", u"forfait", u"feuillet(s)",) def translate_unity(unity): <|fim_middle|> def translate_inverse(unity): for key, value in UNITIES.items(): if unity == value: return key else: return u"NONE" def upgrade(): from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION # Adding some characters to the Lines for table in "estimation_line", "invoice_line", "cancelinvoice_line": op.alter_column(table, "unity", type_=sa.String(100)) for value in UNITS: unit = WorkUnit(label=value) DBSESSION().add(unit) for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_unity(line.unity) DBSESSION().merge(line) def downgrade(): from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_inverse(line.unity) DBSESSION().merge(line) for value in WorkUnit.query(): DBSESSION().delete(value) <|fim▁end|>
return UNITIES.get(unity, UNITIES["NONE"])
<|file_name|>1_5_migrating_work_u_1212f113f03b.py<|end_file_name|><|fim▁begin|>"""1.5 : Migrating work unity Revision ID: 1212f113f03b Revises: 1f07ae132ac8 Create Date: 2013-01-21 11:53:56.598914 """ # revision identifiers, used by Alembic. revision = '1212f113f03b' down_revision = '1f07ae132ac8' from alembic import op import sqlalchemy as sa UNITIES = dict(NONE="", HOUR=u"heure(s)", DAY=u"jour(s)", WEEK=u"semaine(s)", MONTH=u"mois", FEUIL=u"feuillet(s)", PACK=u"forfait") UNITS = (u"heure(s)", u"jour(s)", u"semaine(s)", u"mois", u"forfait", u"feuillet(s)",) def translate_unity(unity): return UNITIES.get(unity, UNITIES["NONE"]) def translate_inverse(unity): <|fim_middle|> def upgrade(): from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION # Adding some characters to the Lines for table in "estimation_line", "invoice_line", "cancelinvoice_line": op.alter_column(table, "unity", type_=sa.String(100)) for value in UNITS: unit = WorkUnit(label=value) DBSESSION().add(unit) for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_unity(line.unity) DBSESSION().merge(line) def downgrade(): from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_inverse(line.unity) DBSESSION().merge(line) for value in WorkUnit.query(): DBSESSION().delete(value) <|fim▁end|>
for key, value in UNITIES.items(): if unity == value: return key else: return u"NONE"
<|file_name|>1_5_migrating_work_u_1212f113f03b.py<|end_file_name|><|fim▁begin|>"""1.5 : Migrating work unity Revision ID: 1212f113f03b Revises: 1f07ae132ac8 Create Date: 2013-01-21 11:53:56.598914 """ # revision identifiers, used by Alembic. revision = '1212f113f03b' down_revision = '1f07ae132ac8' from alembic import op import sqlalchemy as sa UNITIES = dict(NONE="", HOUR=u"heure(s)", DAY=u"jour(s)", WEEK=u"semaine(s)", MONTH=u"mois", FEUIL=u"feuillet(s)", PACK=u"forfait") UNITS = (u"heure(s)", u"jour(s)", u"semaine(s)", u"mois", u"forfait", u"feuillet(s)",) def translate_unity(unity): return UNITIES.get(unity, UNITIES["NONE"]) def translate_inverse(unity): for key, value in UNITIES.items(): if unity == value: return key else: return u"NONE" def upgrade(): <|fim_middle|> def downgrade(): from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_inverse(line.unity) DBSESSION().merge(line) for value in WorkUnit.query(): DBSESSION().delete(value) <|fim▁end|>
from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION # Adding some characters to the Lines for table in "estimation_line", "invoice_line", "cancelinvoice_line": op.alter_column(table, "unity", type_=sa.String(100)) for value in UNITS: unit = WorkUnit(label=value) DBSESSION().add(unit) for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_unity(line.unity) DBSESSION().merge(line)
<|file_name|>1_5_migrating_work_u_1212f113f03b.py<|end_file_name|><|fim▁begin|>"""1.5 : Migrating work unity Revision ID: 1212f113f03b Revises: 1f07ae132ac8 Create Date: 2013-01-21 11:53:56.598914 """ # revision identifiers, used by Alembic. revision = '1212f113f03b' down_revision = '1f07ae132ac8' from alembic import op import sqlalchemy as sa UNITIES = dict(NONE="", HOUR=u"heure(s)", DAY=u"jour(s)", WEEK=u"semaine(s)", MONTH=u"mois", FEUIL=u"feuillet(s)", PACK=u"forfait") UNITS = (u"heure(s)", u"jour(s)", u"semaine(s)", u"mois", u"forfait", u"feuillet(s)",) def translate_unity(unity): return UNITIES.get(unity, UNITIES["NONE"]) def translate_inverse(unity): for key, value in UNITIES.items(): if unity == value: return key else: return u"NONE" def upgrade(): from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION # Adding some characters to the Lines for table in "estimation_line", "invoice_line", "cancelinvoice_line": op.alter_column(table, "unity", type_=sa.String(100)) for value in UNITS: unit = WorkUnit(label=value) DBSESSION().add(unit) for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_unity(line.unity) DBSESSION().merge(line) def downgrade(): <|fim_middle|> <|fim▁end|>
from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_inverse(line.unity) DBSESSION().merge(line) for value in WorkUnit.query(): DBSESSION().delete(value)
<|file_name|>1_5_migrating_work_u_1212f113f03b.py<|end_file_name|><|fim▁begin|>"""1.5 : Migrating work unity Revision ID: 1212f113f03b Revises: 1f07ae132ac8 Create Date: 2013-01-21 11:53:56.598914 """ # revision identifiers, used by Alembic. revision = '1212f113f03b' down_revision = '1f07ae132ac8' from alembic import op import sqlalchemy as sa UNITIES = dict(NONE="", HOUR=u"heure(s)", DAY=u"jour(s)", WEEK=u"semaine(s)", MONTH=u"mois", FEUIL=u"feuillet(s)", PACK=u"forfait") UNITS = (u"heure(s)", u"jour(s)", u"semaine(s)", u"mois", u"forfait", u"feuillet(s)",) def translate_unity(unity): return UNITIES.get(unity, UNITIES["NONE"]) def translate_inverse(unity): for key, value in UNITIES.items(): if unity == value: <|fim_middle|> else: return u"NONE" def upgrade(): from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION # Adding some characters to the Lines for table in "estimation_line", "invoice_line", "cancelinvoice_line": op.alter_column(table, "unity", type_=sa.String(100)) for value in UNITS: unit = WorkUnit(label=value) DBSESSION().add(unit) for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_unity(line.unity) DBSESSION().merge(line) def downgrade(): from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_inverse(line.unity) DBSESSION().merge(line) for value in WorkUnit.query(): DBSESSION().delete(value) <|fim▁end|>
return key
<|file_name|>1_5_migrating_work_u_1212f113f03b.py<|end_file_name|><|fim▁begin|>"""1.5 : Migrating work unity Revision ID: 1212f113f03b Revises: 1f07ae132ac8 Create Date: 2013-01-21 11:53:56.598914 """ # revision identifiers, used by Alembic. revision = '1212f113f03b' down_revision = '1f07ae132ac8' from alembic import op import sqlalchemy as sa UNITIES = dict(NONE="", HOUR=u"heure(s)", DAY=u"jour(s)", WEEK=u"semaine(s)", MONTH=u"mois", FEUIL=u"feuillet(s)", PACK=u"forfait") UNITS = (u"heure(s)", u"jour(s)", u"semaine(s)", u"mois", u"forfait", u"feuillet(s)",) def translate_unity(unity): return UNITIES.get(unity, UNITIES["NONE"]) def translate_inverse(unity): for key, value in UNITIES.items(): if unity == value: return key else: <|fim_middle|> def upgrade(): from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION # Adding some characters to the Lines for table in "estimation_line", "invoice_line", "cancelinvoice_line": op.alter_column(table, "unity", type_=sa.String(100)) for value in UNITS: unit = WorkUnit(label=value) DBSESSION().add(unit) for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_unity(line.unity) DBSESSION().merge(line) def downgrade(): from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_inverse(line.unity) DBSESSION().merge(line) for value in WorkUnit.query(): DBSESSION().delete(value) <|fim▁end|>
return u"NONE"
<|file_name|>1_5_migrating_work_u_1212f113f03b.py<|end_file_name|><|fim▁begin|>"""1.5 : Migrating work unity Revision ID: 1212f113f03b Revises: 1f07ae132ac8 Create Date: 2013-01-21 11:53:56.598914 """ # revision identifiers, used by Alembic. revision = '1212f113f03b' down_revision = '1f07ae132ac8' from alembic import op import sqlalchemy as sa UNITIES = dict(NONE="", HOUR=u"heure(s)", DAY=u"jour(s)", WEEK=u"semaine(s)", MONTH=u"mois", FEUIL=u"feuillet(s)", PACK=u"forfait") UNITS = (u"heure(s)", u"jour(s)", u"semaine(s)", u"mois", u"forfait", u"feuillet(s)",) def <|fim_middle|>(unity): return UNITIES.get(unity, UNITIES["NONE"]) def translate_inverse(unity): for key, value in UNITIES.items(): if unity == value: return key else: return u"NONE" def upgrade(): from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION # Adding some characters to the Lines for table in "estimation_line", "invoice_line", "cancelinvoice_line": op.alter_column(table, "unity", type_=sa.String(100)) for value in UNITS: unit = WorkUnit(label=value) DBSESSION().add(unit) for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_unity(line.unity) DBSESSION().merge(line) def downgrade(): from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_inverse(line.unity) DBSESSION().merge(line) for value in WorkUnit.query(): DBSESSION().delete(value) <|fim▁end|>
translate_unity
<|file_name|>1_5_migrating_work_u_1212f113f03b.py<|end_file_name|><|fim▁begin|>"""1.5 : Migrating work unity Revision ID: 1212f113f03b Revises: 1f07ae132ac8 Create Date: 2013-01-21 11:53:56.598914 """ # revision identifiers, used by Alembic. revision = '1212f113f03b' down_revision = '1f07ae132ac8' from alembic import op import sqlalchemy as sa UNITIES = dict(NONE="", HOUR=u"heure(s)", DAY=u"jour(s)", WEEK=u"semaine(s)", MONTH=u"mois", FEUIL=u"feuillet(s)", PACK=u"forfait") UNITS = (u"heure(s)", u"jour(s)", u"semaine(s)", u"mois", u"forfait", u"feuillet(s)",) def translate_unity(unity): return UNITIES.get(unity, UNITIES["NONE"]) def <|fim_middle|>(unity): for key, value in UNITIES.items(): if unity == value: return key else: return u"NONE" def upgrade(): from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION # Adding some characters to the Lines for table in "estimation_line", "invoice_line", "cancelinvoice_line": op.alter_column(table, "unity", type_=sa.String(100)) for value in UNITS: unit = WorkUnit(label=value) DBSESSION().add(unit) for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_unity(line.unity) DBSESSION().merge(line) def downgrade(): from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_inverse(line.unity) DBSESSION().merge(line) for value in WorkUnit.query(): DBSESSION().delete(value) <|fim▁end|>
translate_inverse
<|file_name|>1_5_migrating_work_u_1212f113f03b.py<|end_file_name|><|fim▁begin|>"""1.5 : Migrating work unity Revision ID: 1212f113f03b Revises: 1f07ae132ac8 Create Date: 2013-01-21 11:53:56.598914 """ # revision identifiers, used by Alembic. revision = '1212f113f03b' down_revision = '1f07ae132ac8' from alembic import op import sqlalchemy as sa UNITIES = dict(NONE="", HOUR=u"heure(s)", DAY=u"jour(s)", WEEK=u"semaine(s)", MONTH=u"mois", FEUIL=u"feuillet(s)", PACK=u"forfait") UNITS = (u"heure(s)", u"jour(s)", u"semaine(s)", u"mois", u"forfait", u"feuillet(s)",) def translate_unity(unity): return UNITIES.get(unity, UNITIES["NONE"]) def translate_inverse(unity): for key, value in UNITIES.items(): if unity == value: return key else: return u"NONE" def <|fim_middle|>(): from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION # Adding some characters to the Lines for table in "estimation_line", "invoice_line", "cancelinvoice_line": op.alter_column(table, "unity", type_=sa.String(100)) for value in UNITS: unit = WorkUnit(label=value) DBSESSION().add(unit) for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_unity(line.unity) DBSESSION().merge(line) def downgrade(): from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_inverse(line.unity) DBSESSION().merge(line) for value in WorkUnit.query(): DBSESSION().delete(value) <|fim▁end|>
upgrade
<|file_name|>1_5_migrating_work_u_1212f113f03b.py<|end_file_name|><|fim▁begin|>"""1.5 : Migrating work unity Revision ID: 1212f113f03b Revises: 1f07ae132ac8 Create Date: 2013-01-21 11:53:56.598914 """ # revision identifiers, used by Alembic. revision = '1212f113f03b' down_revision = '1f07ae132ac8' from alembic import op import sqlalchemy as sa UNITIES = dict(NONE="", HOUR=u"heure(s)", DAY=u"jour(s)", WEEK=u"semaine(s)", MONTH=u"mois", FEUIL=u"feuillet(s)", PACK=u"forfait") UNITS = (u"heure(s)", u"jour(s)", u"semaine(s)", u"mois", u"forfait", u"feuillet(s)",) def translate_unity(unity): return UNITIES.get(unity, UNITIES["NONE"]) def translate_inverse(unity): for key, value in UNITIES.items(): if unity == value: return key else: return u"NONE" def upgrade(): from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION # Adding some characters to the Lines for table in "estimation_line", "invoice_line", "cancelinvoice_line": op.alter_column(table, "unity", type_=sa.String(100)) for value in UNITS: unit = WorkUnit(label=value) DBSESSION().add(unit) for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_unity(line.unity) DBSESSION().merge(line) def <|fim_middle|>(): from autonomie.models.task import WorkUnit from autonomie.models.task.estimation import EstimationLine from autonomie.models.task.invoice import InvoiceLine from autonomie.models.task.invoice import CancelInvoiceLine from autonomie_base.models.base import DBSESSION for factory in (EstimationLine, InvoiceLine, CancelInvoiceLine): for line in factory.query(): line.unity = translate_inverse(line.unity) DBSESSION().merge(line) for value in WorkUnit.query(): DBSESSION().delete(value) <|fim▁end|>
downgrade
<|file_name|>dicco_numbers.py<|end_file_name|><|fim▁begin|>def freq_month(obj): if obj is None or obj == []: return months = {1: 'jan', 2: 'feb', 3: 'mar', 4: 'apr', 5: 'may', 6: 'jun',<|fim▁hole|> 7: 'jul', 8: 'aug', 9: 'sep', 10: 'oct', 11: 'nov', 12: 'dec', } frequencies = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] # for i in range(0, len(obj)): # frequencies[ obj[i] -1] += 1 for i in obj: frequencies[ i-1 ] += 1 print "The following month(s) have a birthday celebration" for i in range(0, len(frequencies)): if frequencies[i] > 0: print str(months[i+1]) + " has " + str(frequencies[i]) return frequencies in_array = [3,6,2,7,7,7,] print freq_month(in_array) print freq_month([])<|fim▁end|>
<|file_name|>dicco_numbers.py<|end_file_name|><|fim▁begin|>def freq_month(obj): <|fim_middle|> in_array = [3,6,2,7,7,7,] print freq_month(in_array) print freq_month([]) <|fim▁end|>
if obj is None or obj == []: return months = {1: 'jan', 2: 'feb', 3: 'mar', 4: 'apr', 5: 'may', 6: 'jun', 7: 'jul', 8: 'aug', 9: 'sep', 10: 'oct', 11: 'nov', 12: 'dec', } frequencies = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] # for i in range(0, len(obj)): # frequencies[ obj[i] -1] += 1 for i in obj: frequencies[ i-1 ] += 1 print "The following month(s) have a birthday celebration" for i in range(0, len(frequencies)): if frequencies[i] > 0: print str(months[i+1]) + " has " + str(frequencies[i]) return frequencies
<|file_name|>dicco_numbers.py<|end_file_name|><|fim▁begin|>def freq_month(obj): if obj is None or obj == []: <|fim_middle|> months = {1: 'jan', 2: 'feb', 3: 'mar', 4: 'apr', 5: 'may', 6: 'jun', 7: 'jul', 8: 'aug', 9: 'sep', 10: 'oct', 11: 'nov', 12: 'dec', } frequencies = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] # for i in range(0, len(obj)): # frequencies[ obj[i] -1] += 1 for i in obj: frequencies[ i-1 ] += 1 print "The following month(s) have a birthday celebration" for i in range(0, len(frequencies)): if frequencies[i] > 0: print str(months[i+1]) + " has " + str(frequencies[i]) return frequencies in_array = [3,6,2,7,7,7,] print freq_month(in_array) print freq_month([]) <|fim▁end|>
return
<|file_name|>dicco_numbers.py<|end_file_name|><|fim▁begin|>def freq_month(obj): if obj is None or obj == []: return months = {1: 'jan', 2: 'feb', 3: 'mar', 4: 'apr', 5: 'may', 6: 'jun', 7: 'jul', 8: 'aug', 9: 'sep', 10: 'oct', 11: 'nov', 12: 'dec', } frequencies = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] # for i in range(0, len(obj)): # frequencies[ obj[i] -1] += 1 for i in obj: frequencies[ i-1 ] += 1 print "The following month(s) have a birthday celebration" for i in range(0, len(frequencies)): if frequencies[i] > 0: <|fim_middle|> return frequencies in_array = [3,6,2,7,7,7,] print freq_month(in_array) print freq_month([]) <|fim▁end|>
print str(months[i+1]) + " has " + str(frequencies[i])
<|file_name|>dicco_numbers.py<|end_file_name|><|fim▁begin|>def <|fim_middle|>(obj): if obj is None or obj == []: return months = {1: 'jan', 2: 'feb', 3: 'mar', 4: 'apr', 5: 'may', 6: 'jun', 7: 'jul', 8: 'aug', 9: 'sep', 10: 'oct', 11: 'nov', 12: 'dec', } frequencies = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] # for i in range(0, len(obj)): # frequencies[ obj[i] -1] += 1 for i in obj: frequencies[ i-1 ] += 1 print "The following month(s) have a birthday celebration" for i in range(0, len(frequencies)): if frequencies[i] > 0: print str(months[i+1]) + " has " + str(frequencies[i]) return frequencies in_array = [3,6,2,7,7,7,] print freq_month(in_array) print freq_month([]) <|fim▁end|>
freq_month
<|file_name|>0001_initial.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('trans', '0045_auto_20150916_1007'), ] operations = [ migrations.CreateModel( name='Billing', fields=[<|fim▁hole|> ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ], ), migrations.CreateModel( name='Plan', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(unique=True, max_length=100)), ('price', models.IntegerField()), ('limit_strings', models.IntegerField()), ('limit_languages', models.IntegerField()), ('limit_repositories', models.IntegerField()), ('limit_projects', models.IntegerField()), ], options={ 'ordering': ['name'], }, ), migrations.AddField( model_name='billing', name='plan', field=models.ForeignKey(to='billing.Plan'), ), migrations.AddField( model_name='billing', name='projects', field=models.ManyToManyField(to='trans.Project', blank=True), ), migrations.AddField( model_name='billing', name='user', field=models.OneToOneField(to=settings.AUTH_USER_MODEL), ), ]<|fim▁end|>
<|file_name|>0001_initial.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): <|fim_middle|> <|fim▁end|>
dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('trans', '0045_auto_20150916_1007'), ] operations = [ migrations.CreateModel( name='Billing', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ], ), migrations.CreateModel( name='Plan', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(unique=True, max_length=100)), ('price', models.IntegerField()), ('limit_strings', models.IntegerField()), ('limit_languages', models.IntegerField()), ('limit_repositories', models.IntegerField()), ('limit_projects', models.IntegerField()), ], options={ 'ordering': ['name'], }, ), migrations.AddField( model_name='billing', name='plan', field=models.ForeignKey(to='billing.Plan'), ), migrations.AddField( model_name='billing', name='projects', field=models.ManyToManyField(to='trans.Project', blank=True), ), migrations.AddField( model_name='billing', name='user', field=models.OneToOneField(to=settings.AUTH_USER_MODEL), ), ]
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>#!python # log/urls.py from django.conf.urls import url from . import views # We are adding a URL called /home urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^clients/$', views.clients, name='clients'), url(r'^clients/(?P<id>\d+)/$', views.client_detail, name='client_detail'), url(r'^clients/new/$', views.client_new, name='client_new'), url(r'^clients/(?P<id>\d+)/edit/$', views.client_edit, name='client_edit'), url(r'^clients/sevices/$', views.clients_services_count, name='clients_services_count'), url(r'^clients/bills/(?P<id>\d+)/$', views.all_clients_bills, name='all_clients_bills'), url(r'^clients/bills/$', views.fresh_clients, name='fresh_clients'), url(r'^clients/del/(?P<id>\d+)/$', views.delete_client, name='delete_client'), url(r'^contracts/$', views.contracts, name='contracts'), url(r'^contracts/(?P<id>\d+)/$', views.contract_detail, name='contract_detail'), url(r'^contracts/new/$', views.contract_new, name='contract_new'), url(r'^contracts/(?P<id>\d+)/edit/$', views.contract_edit, name='contract_edit'), url(r'^contracts/list/(?P<id>\d+)/$', views.all_clients_contracts, name='all_clients_contracts'), url(r'^contracts/list/$', views.contracts_services, name='contracts_services'), url(r'^contracts/del/(?P<id>\d+)/$', views.delete_contract, name='delete_contract'), url(r'^manager/$', views.managers, name='managers'), url(r'^manager/(?P<id>\d+)/$', views.manager_detail, name='manager_detail'), url(r'^manager/new/$', views.manager_new, name='manager_new'), url(r'^manager/(?P<id>\d+)/edit/$', views.manager_edit, name='manager_edit'), url(r'^manager/clients/$', views.managers_clients_count, name='managers_clients_count'), url(r'^managers/del/(?P<id>\d+)/$', views.delete_manager, name='delete_manager'), url(r'^briefs/$', views.brief, name='briefs'), url(r'^briefs/(?P<id>\d+)/$', views.brief_detail, name='brief_detail'), url(r'^briefs/new/$', views.brief_new, name='brief_new'), url(r'^briefs/(?P<id>\d+)/edit/$', views.brief_edit, name='brief_edit'), url(r'^briefs/del/(?P<id>\d+)/$', views.delete_brief, name='delete_brief'), url(r'^briefs/list/(?P<id>\d+)/$', views.all_clients_briefs, name='all_clients_briefs'), url(r'^services/$', views.services, name='services'), url(r'^services/(?P<id>\d+)/$', views.service_detail, name='service_detail'), url(r'^services/new/$', views.services_new, name='services_new'), url(r'^services/(?P<id>\d+)/edit/$', views.service_edit, name='service_edit'), url(r'^services/table/(?P<id>\d+)/$', views.service_all_clients, name='service_all_clients'), url(r'^services/del/(?P<id>\d+)/$', views.delete_service, name='delete_service'), url(r'^contractors/$', views.contractors, name='contractors'), url(r'^contractors/(?P<id>\d+)/$', views.contractor_detail, name='contractor_detail'), url(r'^contractors/new/$', views.contractors_new, name='contractors_new'), url(r'^contractors/(?P<id>\d+)/edit/$', views.contractor_edit, name='contractor_edit'), url(r'^contractors/newest/$', views.newest_contractors, name='newest_contractors'), url(r'^contractors/del/(?P<id>\d+)/$', views.delete_contractor, name='delete_contractor'), url(r'^acts/$', views.acts, name='acts'), url(r'^acts/(?P<id>\d+)/$', views.act_detail, name='act_detail'), url(r'^acts/new/$', views.act_new, name='act_new'), url(r'^acts/(?P<id>\d+)/edit/$', views.act_edit, name='act_edit'), url(r'^acts/del/(?P<id>\d+)/$', views.delete_act, name='delete_act'), url(r'^bills/$', views.bills, name='bills'), url(r'^bills/(?P<id>\d+)/$', views.bills_detail, name='bills_detail'), url(r'^bills/new/$', views.bills_new, name='bills_new'),<|fim▁hole|> url(r'^bill/del/(?P<id>\d+)/$', views.delete_bill, name='delete_bill'), ]<|fim▁end|>
url(r'^bills/(?P<id>\d+)/edit/$', views.bills_edit, name='bills_edit'),
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### old_bl_idnames = { 'CentersPolsNode' : "centers", # 'BakeryNode' : "bakery", 'CircleNode' : "circle", 'ListItemNode' : "list_item", 'GenRangeNode' : "range", 'GenSeriesNode' : "series", # 'Test1Node' : "test", # 'Test2Node' : "test", # 'ToolsNode' : "tools", 'SvReRouteNode': "reroute", 'VoronoiNode': "voronoi", 'ViewerNode': "viewer", 'EvalKnievalNode': "eval_knieval", 'FormulaNode': 'formula', } # we should add some functions to load things there import importlib import inspect import traceback import bpy from sverchok.node_tree import SverchCustomTreeNode imported_mods = {} def is_old(node_info): ''' Check if node or node.bl_idname is among the old nodes ''' if isinstance(node_info, str): # assumes bl_idname return node_info in old_bl_idnames elif isinstance(node_info, bpy.types.Node): return node_info.bl_idname in old_bl_idnames else: return False def scan_for_old(ng): nodes = [n for n in ng.nodes if n.bl_idname in old_bl_idnames] for node in nodes: mark_old(node) def mark_old(node): if node.parent and node.parent.label == "Deprecated node!": return ng = node.id_data frame = ng.nodes.new("NodeFrame") if node.parent: frame.parent = node.parent node.parent = frame frame.label = "Deprecated node!" frame.use_custom_color = True frame.color = (.8, 0, 0) frame.shrink = True def reload_old(ng=False): if ng: bl_idnames = {n.bl_idname for n in ng.nodes if n.bl_idname in old_bl_idnames} for bl_id in bl_idnames: mod = register_old(bl_id) if mod: importlib.reload(mod) else: print("Couldn't reload {}".format(bl_id)) else: for ng in bpy.data.node_groups: reload_old(ng) #if ng.bl_idname in { 'SverchCustomTreeType', 'SverchGroupTreeType'}:<|fim▁hole|> def load_old(ng): """ This approach didn't work, bl_idname of undefined node isn't as I expected bl_idnames = {n.bl_idname for n in ng.nodes} old_bl_ids = bl_idnames.intersection(old_bl_idnames) if old_bl_ids: """ not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) if not_reged_nodes: for bl_id in old_bl_idnames: register_old(bl_id) nodes = [n for n in ng.nodes if n.bl_idname == bl_id] if nodes: for node in nodes: mark_old(node) not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) node_count = len(not_reged_nodes) print("Loaded {}. {} nodes are left unregisted.".format(bl_id, node_count)) if node_count == 0: return else: # didn't help remove unregister_old(bl_id) def register_old(bl_id): if bl_id in old_bl_idnames: mod = importlib.import_module(".{}".format(old_bl_idnames[bl_id]), __name__) res = inspect.getmembers(mod) for name, cls in res: if inspect.isclass(cls): if issubclass(cls, bpy.types.Node) and cls.bl_idname == bl_id: if bl_id not in imported_mods: try: mod.register() except: traceback.print_exc() imported_mods[bl_id] = mod return mod print("Cannot find {} among old nodes".format(bl_id)) return None def unregister_old(bl_id): global imported_mods mod = imported_mods.get(bl_id) if mod: #print("Unloaded old node type {}".format(bl_id)) mod.unregister() del imported_mods[bl_id] def unregister(): global imported_mods print(imported_mods) for mod in imported_mods.values(): mod.unregister() imported_mods = {}<|fim▁end|>
# reload_old(ng)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### old_bl_idnames = { 'CentersPolsNode' : "centers", # 'BakeryNode' : "bakery", 'CircleNode' : "circle", 'ListItemNode' : "list_item", 'GenRangeNode' : "range", 'GenSeriesNode' : "series", # 'Test1Node' : "test", # 'Test2Node' : "test", # 'ToolsNode' : "tools", 'SvReRouteNode': "reroute", 'VoronoiNode': "voronoi", 'ViewerNode': "viewer", 'EvalKnievalNode': "eval_knieval", 'FormulaNode': 'formula', } # we should add some functions to load things there import importlib import inspect import traceback import bpy from sverchok.node_tree import SverchCustomTreeNode imported_mods = {} def is_old(node_info): <|fim_middle|> def scan_for_old(ng): nodes = [n for n in ng.nodes if n.bl_idname in old_bl_idnames] for node in nodes: mark_old(node) def mark_old(node): if node.parent and node.parent.label == "Deprecated node!": return ng = node.id_data frame = ng.nodes.new("NodeFrame") if node.parent: frame.parent = node.parent node.parent = frame frame.label = "Deprecated node!" frame.use_custom_color = True frame.color = (.8, 0, 0) frame.shrink = True def reload_old(ng=False): if ng: bl_idnames = {n.bl_idname for n in ng.nodes if n.bl_idname in old_bl_idnames} for bl_id in bl_idnames: mod = register_old(bl_id) if mod: importlib.reload(mod) else: print("Couldn't reload {}".format(bl_id)) else: for ng in bpy.data.node_groups: reload_old(ng) #if ng.bl_idname in { 'SverchCustomTreeType', 'SverchGroupTreeType'}: # reload_old(ng) def load_old(ng): """ This approach didn't work, bl_idname of undefined node isn't as I expected bl_idnames = {n.bl_idname for n in ng.nodes} old_bl_ids = bl_idnames.intersection(old_bl_idnames) if old_bl_ids: """ not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) if not_reged_nodes: for bl_id in old_bl_idnames: register_old(bl_id) nodes = [n for n in ng.nodes if n.bl_idname == bl_id] if nodes: for node in nodes: mark_old(node) not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) node_count = len(not_reged_nodes) print("Loaded {}. {} nodes are left unregisted.".format(bl_id, node_count)) if node_count == 0: return else: # didn't help remove unregister_old(bl_id) def register_old(bl_id): if bl_id in old_bl_idnames: mod = importlib.import_module(".{}".format(old_bl_idnames[bl_id]), __name__) res = inspect.getmembers(mod) for name, cls in res: if inspect.isclass(cls): if issubclass(cls, bpy.types.Node) and cls.bl_idname == bl_id: if bl_id not in imported_mods: try: mod.register() except: traceback.print_exc() imported_mods[bl_id] = mod return mod print("Cannot find {} among old nodes".format(bl_id)) return None def unregister_old(bl_id): global imported_mods mod = imported_mods.get(bl_id) if mod: #print("Unloaded old node type {}".format(bl_id)) mod.unregister() del imported_mods[bl_id] def unregister(): global imported_mods print(imported_mods) for mod in imported_mods.values(): mod.unregister() imported_mods = {} <|fim▁end|>
''' Check if node or node.bl_idname is among the old nodes ''' if isinstance(node_info, str): # assumes bl_idname return node_info in old_bl_idnames elif isinstance(node_info, bpy.types.Node): return node_info.bl_idname in old_bl_idnames else: return False
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### old_bl_idnames = { 'CentersPolsNode' : "centers", # 'BakeryNode' : "bakery", 'CircleNode' : "circle", 'ListItemNode' : "list_item", 'GenRangeNode' : "range", 'GenSeriesNode' : "series", # 'Test1Node' : "test", # 'Test2Node' : "test", # 'ToolsNode' : "tools", 'SvReRouteNode': "reroute", 'VoronoiNode': "voronoi", 'ViewerNode': "viewer", 'EvalKnievalNode': "eval_knieval", 'FormulaNode': 'formula', } # we should add some functions to load things there import importlib import inspect import traceback import bpy from sverchok.node_tree import SverchCustomTreeNode imported_mods = {} def is_old(node_info): ''' Check if node or node.bl_idname is among the old nodes ''' if isinstance(node_info, str): # assumes bl_idname return node_info in old_bl_idnames elif isinstance(node_info, bpy.types.Node): return node_info.bl_idname in old_bl_idnames else: return False def scan_for_old(ng): <|fim_middle|> def mark_old(node): if node.parent and node.parent.label == "Deprecated node!": return ng = node.id_data frame = ng.nodes.new("NodeFrame") if node.parent: frame.parent = node.parent node.parent = frame frame.label = "Deprecated node!" frame.use_custom_color = True frame.color = (.8, 0, 0) frame.shrink = True def reload_old(ng=False): if ng: bl_idnames = {n.bl_idname for n in ng.nodes if n.bl_idname in old_bl_idnames} for bl_id in bl_idnames: mod = register_old(bl_id) if mod: importlib.reload(mod) else: print("Couldn't reload {}".format(bl_id)) else: for ng in bpy.data.node_groups: reload_old(ng) #if ng.bl_idname in { 'SverchCustomTreeType', 'SverchGroupTreeType'}: # reload_old(ng) def load_old(ng): """ This approach didn't work, bl_idname of undefined node isn't as I expected bl_idnames = {n.bl_idname for n in ng.nodes} old_bl_ids = bl_idnames.intersection(old_bl_idnames) if old_bl_ids: """ not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) if not_reged_nodes: for bl_id in old_bl_idnames: register_old(bl_id) nodes = [n for n in ng.nodes if n.bl_idname == bl_id] if nodes: for node in nodes: mark_old(node) not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) node_count = len(not_reged_nodes) print("Loaded {}. {} nodes are left unregisted.".format(bl_id, node_count)) if node_count == 0: return else: # didn't help remove unregister_old(bl_id) def register_old(bl_id): if bl_id in old_bl_idnames: mod = importlib.import_module(".{}".format(old_bl_idnames[bl_id]), __name__) res = inspect.getmembers(mod) for name, cls in res: if inspect.isclass(cls): if issubclass(cls, bpy.types.Node) and cls.bl_idname == bl_id: if bl_id not in imported_mods: try: mod.register() except: traceback.print_exc() imported_mods[bl_id] = mod return mod print("Cannot find {} among old nodes".format(bl_id)) return None def unregister_old(bl_id): global imported_mods mod = imported_mods.get(bl_id) if mod: #print("Unloaded old node type {}".format(bl_id)) mod.unregister() del imported_mods[bl_id] def unregister(): global imported_mods print(imported_mods) for mod in imported_mods.values(): mod.unregister() imported_mods = {} <|fim▁end|>
nodes = [n for n in ng.nodes if n.bl_idname in old_bl_idnames] for node in nodes: mark_old(node)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### old_bl_idnames = { 'CentersPolsNode' : "centers", # 'BakeryNode' : "bakery", 'CircleNode' : "circle", 'ListItemNode' : "list_item", 'GenRangeNode' : "range", 'GenSeriesNode' : "series", # 'Test1Node' : "test", # 'Test2Node' : "test", # 'ToolsNode' : "tools", 'SvReRouteNode': "reroute", 'VoronoiNode': "voronoi", 'ViewerNode': "viewer", 'EvalKnievalNode': "eval_knieval", 'FormulaNode': 'formula', } # we should add some functions to load things there import importlib import inspect import traceback import bpy from sverchok.node_tree import SverchCustomTreeNode imported_mods = {} def is_old(node_info): ''' Check if node or node.bl_idname is among the old nodes ''' if isinstance(node_info, str): # assumes bl_idname return node_info in old_bl_idnames elif isinstance(node_info, bpy.types.Node): return node_info.bl_idname in old_bl_idnames else: return False def scan_for_old(ng): nodes = [n for n in ng.nodes if n.bl_idname in old_bl_idnames] for node in nodes: mark_old(node) def mark_old(node): <|fim_middle|> def reload_old(ng=False): if ng: bl_idnames = {n.bl_idname for n in ng.nodes if n.bl_idname in old_bl_idnames} for bl_id in bl_idnames: mod = register_old(bl_id) if mod: importlib.reload(mod) else: print("Couldn't reload {}".format(bl_id)) else: for ng in bpy.data.node_groups: reload_old(ng) #if ng.bl_idname in { 'SverchCustomTreeType', 'SverchGroupTreeType'}: # reload_old(ng) def load_old(ng): """ This approach didn't work, bl_idname of undefined node isn't as I expected bl_idnames = {n.bl_idname for n in ng.nodes} old_bl_ids = bl_idnames.intersection(old_bl_idnames) if old_bl_ids: """ not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) if not_reged_nodes: for bl_id in old_bl_idnames: register_old(bl_id) nodes = [n for n in ng.nodes if n.bl_idname == bl_id] if nodes: for node in nodes: mark_old(node) not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) node_count = len(not_reged_nodes) print("Loaded {}. {} nodes are left unregisted.".format(bl_id, node_count)) if node_count == 0: return else: # didn't help remove unregister_old(bl_id) def register_old(bl_id): if bl_id in old_bl_idnames: mod = importlib.import_module(".{}".format(old_bl_idnames[bl_id]), __name__) res = inspect.getmembers(mod) for name, cls in res: if inspect.isclass(cls): if issubclass(cls, bpy.types.Node) and cls.bl_idname == bl_id: if bl_id not in imported_mods: try: mod.register() except: traceback.print_exc() imported_mods[bl_id] = mod return mod print("Cannot find {} among old nodes".format(bl_id)) return None def unregister_old(bl_id): global imported_mods mod = imported_mods.get(bl_id) if mod: #print("Unloaded old node type {}".format(bl_id)) mod.unregister() del imported_mods[bl_id] def unregister(): global imported_mods print(imported_mods) for mod in imported_mods.values(): mod.unregister() imported_mods = {} <|fim▁end|>
if node.parent and node.parent.label == "Deprecated node!": return ng = node.id_data frame = ng.nodes.new("NodeFrame") if node.parent: frame.parent = node.parent node.parent = frame frame.label = "Deprecated node!" frame.use_custom_color = True frame.color = (.8, 0, 0) frame.shrink = True
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### old_bl_idnames = { 'CentersPolsNode' : "centers", # 'BakeryNode' : "bakery", 'CircleNode' : "circle", 'ListItemNode' : "list_item", 'GenRangeNode' : "range", 'GenSeriesNode' : "series", # 'Test1Node' : "test", # 'Test2Node' : "test", # 'ToolsNode' : "tools", 'SvReRouteNode': "reroute", 'VoronoiNode': "voronoi", 'ViewerNode': "viewer", 'EvalKnievalNode': "eval_knieval", 'FormulaNode': 'formula', } # we should add some functions to load things there import importlib import inspect import traceback import bpy from sverchok.node_tree import SverchCustomTreeNode imported_mods = {} def is_old(node_info): ''' Check if node or node.bl_idname is among the old nodes ''' if isinstance(node_info, str): # assumes bl_idname return node_info in old_bl_idnames elif isinstance(node_info, bpy.types.Node): return node_info.bl_idname in old_bl_idnames else: return False def scan_for_old(ng): nodes = [n for n in ng.nodes if n.bl_idname in old_bl_idnames] for node in nodes: mark_old(node) def mark_old(node): if node.parent and node.parent.label == "Deprecated node!": return ng = node.id_data frame = ng.nodes.new("NodeFrame") if node.parent: frame.parent = node.parent node.parent = frame frame.label = "Deprecated node!" frame.use_custom_color = True frame.color = (.8, 0, 0) frame.shrink = True def reload_old(ng=False): <|fim_middle|> def load_old(ng): """ This approach didn't work, bl_idname of undefined node isn't as I expected bl_idnames = {n.bl_idname for n in ng.nodes} old_bl_ids = bl_idnames.intersection(old_bl_idnames) if old_bl_ids: """ not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) if not_reged_nodes: for bl_id in old_bl_idnames: register_old(bl_id) nodes = [n for n in ng.nodes if n.bl_idname == bl_id] if nodes: for node in nodes: mark_old(node) not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) node_count = len(not_reged_nodes) print("Loaded {}. {} nodes are left unregisted.".format(bl_id, node_count)) if node_count == 0: return else: # didn't help remove unregister_old(bl_id) def register_old(bl_id): if bl_id in old_bl_idnames: mod = importlib.import_module(".{}".format(old_bl_idnames[bl_id]), __name__) res = inspect.getmembers(mod) for name, cls in res: if inspect.isclass(cls): if issubclass(cls, bpy.types.Node) and cls.bl_idname == bl_id: if bl_id not in imported_mods: try: mod.register() except: traceback.print_exc() imported_mods[bl_id] = mod return mod print("Cannot find {} among old nodes".format(bl_id)) return None def unregister_old(bl_id): global imported_mods mod = imported_mods.get(bl_id) if mod: #print("Unloaded old node type {}".format(bl_id)) mod.unregister() del imported_mods[bl_id] def unregister(): global imported_mods print(imported_mods) for mod in imported_mods.values(): mod.unregister() imported_mods = {} <|fim▁end|>
if ng: bl_idnames = {n.bl_idname for n in ng.nodes if n.bl_idname in old_bl_idnames} for bl_id in bl_idnames: mod = register_old(bl_id) if mod: importlib.reload(mod) else: print("Couldn't reload {}".format(bl_id)) else: for ng in bpy.data.node_groups: reload_old(ng) #if ng.bl_idname in { 'SverchCustomTreeType', 'SverchGroupTreeType'}: # reload_old(ng)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### old_bl_idnames = { 'CentersPolsNode' : "centers", # 'BakeryNode' : "bakery", 'CircleNode' : "circle", 'ListItemNode' : "list_item", 'GenRangeNode' : "range", 'GenSeriesNode' : "series", # 'Test1Node' : "test", # 'Test2Node' : "test", # 'ToolsNode' : "tools", 'SvReRouteNode': "reroute", 'VoronoiNode': "voronoi", 'ViewerNode': "viewer", 'EvalKnievalNode': "eval_knieval", 'FormulaNode': 'formula', } # we should add some functions to load things there import importlib import inspect import traceback import bpy from sverchok.node_tree import SverchCustomTreeNode imported_mods = {} def is_old(node_info): ''' Check if node or node.bl_idname is among the old nodes ''' if isinstance(node_info, str): # assumes bl_idname return node_info in old_bl_idnames elif isinstance(node_info, bpy.types.Node): return node_info.bl_idname in old_bl_idnames else: return False def scan_for_old(ng): nodes = [n for n in ng.nodes if n.bl_idname in old_bl_idnames] for node in nodes: mark_old(node) def mark_old(node): if node.parent and node.parent.label == "Deprecated node!": return ng = node.id_data frame = ng.nodes.new("NodeFrame") if node.parent: frame.parent = node.parent node.parent = frame frame.label = "Deprecated node!" frame.use_custom_color = True frame.color = (.8, 0, 0) frame.shrink = True def reload_old(ng=False): if ng: bl_idnames = {n.bl_idname for n in ng.nodes if n.bl_idname in old_bl_idnames} for bl_id in bl_idnames: mod = register_old(bl_id) if mod: importlib.reload(mod) else: print("Couldn't reload {}".format(bl_id)) else: for ng in bpy.data.node_groups: reload_old(ng) #if ng.bl_idname in { 'SverchCustomTreeType', 'SverchGroupTreeType'}: # reload_old(ng) def load_old(ng): <|fim_middle|> def register_old(bl_id): if bl_id in old_bl_idnames: mod = importlib.import_module(".{}".format(old_bl_idnames[bl_id]), __name__) res = inspect.getmembers(mod) for name, cls in res: if inspect.isclass(cls): if issubclass(cls, bpy.types.Node) and cls.bl_idname == bl_id: if bl_id not in imported_mods: try: mod.register() except: traceback.print_exc() imported_mods[bl_id] = mod return mod print("Cannot find {} among old nodes".format(bl_id)) return None def unregister_old(bl_id): global imported_mods mod = imported_mods.get(bl_id) if mod: #print("Unloaded old node type {}".format(bl_id)) mod.unregister() del imported_mods[bl_id] def unregister(): global imported_mods print(imported_mods) for mod in imported_mods.values(): mod.unregister() imported_mods = {} <|fim▁end|>
""" This approach didn't work, bl_idname of undefined node isn't as I expected bl_idnames = {n.bl_idname for n in ng.nodes} old_bl_ids = bl_idnames.intersection(old_bl_idnames) if old_bl_ids: """ not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) if not_reged_nodes: for bl_id in old_bl_idnames: register_old(bl_id) nodes = [n for n in ng.nodes if n.bl_idname == bl_id] if nodes: for node in nodes: mark_old(node) not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) node_count = len(not_reged_nodes) print("Loaded {}. {} nodes are left unregisted.".format(bl_id, node_count)) if node_count == 0: return else: # didn't help remove unregister_old(bl_id)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### old_bl_idnames = { 'CentersPolsNode' : "centers", # 'BakeryNode' : "bakery", 'CircleNode' : "circle", 'ListItemNode' : "list_item", 'GenRangeNode' : "range", 'GenSeriesNode' : "series", # 'Test1Node' : "test", # 'Test2Node' : "test", # 'ToolsNode' : "tools", 'SvReRouteNode': "reroute", 'VoronoiNode': "voronoi", 'ViewerNode': "viewer", 'EvalKnievalNode': "eval_knieval", 'FormulaNode': 'formula', } # we should add some functions to load things there import importlib import inspect import traceback import bpy from sverchok.node_tree import SverchCustomTreeNode imported_mods = {} def is_old(node_info): ''' Check if node or node.bl_idname is among the old nodes ''' if isinstance(node_info, str): # assumes bl_idname return node_info in old_bl_idnames elif isinstance(node_info, bpy.types.Node): return node_info.bl_idname in old_bl_idnames else: return False def scan_for_old(ng): nodes = [n for n in ng.nodes if n.bl_idname in old_bl_idnames] for node in nodes: mark_old(node) def mark_old(node): if node.parent and node.parent.label == "Deprecated node!": return ng = node.id_data frame = ng.nodes.new("NodeFrame") if node.parent: frame.parent = node.parent node.parent = frame frame.label = "Deprecated node!" frame.use_custom_color = True frame.color = (.8, 0, 0) frame.shrink = True def reload_old(ng=False): if ng: bl_idnames = {n.bl_idname for n in ng.nodes if n.bl_idname in old_bl_idnames} for bl_id in bl_idnames: mod = register_old(bl_id) if mod: importlib.reload(mod) else: print("Couldn't reload {}".format(bl_id)) else: for ng in bpy.data.node_groups: reload_old(ng) #if ng.bl_idname in { 'SverchCustomTreeType', 'SverchGroupTreeType'}: # reload_old(ng) def load_old(ng): """ This approach didn't work, bl_idname of undefined node isn't as I expected bl_idnames = {n.bl_idname for n in ng.nodes} old_bl_ids = bl_idnames.intersection(old_bl_idnames) if old_bl_ids: """ not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) if not_reged_nodes: for bl_id in old_bl_idnames: register_old(bl_id) nodes = [n for n in ng.nodes if n.bl_idname == bl_id] if nodes: for node in nodes: mark_old(node) not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) node_count = len(not_reged_nodes) print("Loaded {}. {} nodes are left unregisted.".format(bl_id, node_count)) if node_count == 0: return else: # didn't help remove unregister_old(bl_id) def register_old(bl_id): <|fim_middle|> def unregister_old(bl_id): global imported_mods mod = imported_mods.get(bl_id) if mod: #print("Unloaded old node type {}".format(bl_id)) mod.unregister() del imported_mods[bl_id] def unregister(): global imported_mods print(imported_mods) for mod in imported_mods.values(): mod.unregister() imported_mods = {} <|fim▁end|>
if bl_id in old_bl_idnames: mod = importlib.import_module(".{}".format(old_bl_idnames[bl_id]), __name__) res = inspect.getmembers(mod) for name, cls in res: if inspect.isclass(cls): if issubclass(cls, bpy.types.Node) and cls.bl_idname == bl_id: if bl_id not in imported_mods: try: mod.register() except: traceback.print_exc() imported_mods[bl_id] = mod return mod print("Cannot find {} among old nodes".format(bl_id)) return None
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### old_bl_idnames = { 'CentersPolsNode' : "centers", # 'BakeryNode' : "bakery", 'CircleNode' : "circle", 'ListItemNode' : "list_item", 'GenRangeNode' : "range", 'GenSeriesNode' : "series", # 'Test1Node' : "test", # 'Test2Node' : "test", # 'ToolsNode' : "tools", 'SvReRouteNode': "reroute", 'VoronoiNode': "voronoi", 'ViewerNode': "viewer", 'EvalKnievalNode': "eval_knieval", 'FormulaNode': 'formula', } # we should add some functions to load things there import importlib import inspect import traceback import bpy from sverchok.node_tree import SverchCustomTreeNode imported_mods = {} def is_old(node_info): ''' Check if node or node.bl_idname is among the old nodes ''' if isinstance(node_info, str): # assumes bl_idname return node_info in old_bl_idnames elif isinstance(node_info, bpy.types.Node): return node_info.bl_idname in old_bl_idnames else: return False def scan_for_old(ng): nodes = [n for n in ng.nodes if n.bl_idname in old_bl_idnames] for node in nodes: mark_old(node) def mark_old(node): if node.parent and node.parent.label == "Deprecated node!": return ng = node.id_data frame = ng.nodes.new("NodeFrame") if node.parent: frame.parent = node.parent node.parent = frame frame.label = "Deprecated node!" frame.use_custom_color = True frame.color = (.8, 0, 0) frame.shrink = True def reload_old(ng=False): if ng: bl_idnames = {n.bl_idname for n in ng.nodes if n.bl_idname in old_bl_idnames} for bl_id in bl_idnames: mod = register_old(bl_id) if mod: importlib.reload(mod) else: print("Couldn't reload {}".format(bl_id)) else: for ng in bpy.data.node_groups: reload_old(ng) #if ng.bl_idname in { 'SverchCustomTreeType', 'SverchGroupTreeType'}: # reload_old(ng) def load_old(ng): """ This approach didn't work, bl_idname of undefined node isn't as I expected bl_idnames = {n.bl_idname for n in ng.nodes} old_bl_ids = bl_idnames.intersection(old_bl_idnames) if old_bl_ids: """ not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) if not_reged_nodes: for bl_id in old_bl_idnames: register_old(bl_id) nodes = [n for n in ng.nodes if n.bl_idname == bl_id] if nodes: for node in nodes: mark_old(node) not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) node_count = len(not_reged_nodes) print("Loaded {}. {} nodes are left unregisted.".format(bl_id, node_count)) if node_count == 0: return else: # didn't help remove unregister_old(bl_id) def register_old(bl_id): if bl_id in old_bl_idnames: mod = importlib.import_module(".{}".format(old_bl_idnames[bl_id]), __name__) res = inspect.getmembers(mod) for name, cls in res: if inspect.isclass(cls): if issubclass(cls, bpy.types.Node) and cls.bl_idname == bl_id: if bl_id not in imported_mods: try: mod.register() except: traceback.print_exc() imported_mods[bl_id] = mod return mod print("Cannot find {} among old nodes".format(bl_id)) return None def unregister_old(bl_id): <|fim_middle|> def unregister(): global imported_mods print(imported_mods) for mod in imported_mods.values(): mod.unregister() imported_mods = {} <|fim▁end|>
global imported_mods mod = imported_mods.get(bl_id) if mod: #print("Unloaded old node type {}".format(bl_id)) mod.unregister() del imported_mods[bl_id]
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### old_bl_idnames = { 'CentersPolsNode' : "centers", # 'BakeryNode' : "bakery", 'CircleNode' : "circle", 'ListItemNode' : "list_item", 'GenRangeNode' : "range", 'GenSeriesNode' : "series", # 'Test1Node' : "test", # 'Test2Node' : "test", # 'ToolsNode' : "tools", 'SvReRouteNode': "reroute", 'VoronoiNode': "voronoi", 'ViewerNode': "viewer", 'EvalKnievalNode': "eval_knieval", 'FormulaNode': 'formula', } # we should add some functions to load things there import importlib import inspect import traceback import bpy from sverchok.node_tree import SverchCustomTreeNode imported_mods = {} def is_old(node_info): ''' Check if node or node.bl_idname is among the old nodes ''' if isinstance(node_info, str): # assumes bl_idname return node_info in old_bl_idnames elif isinstance(node_info, bpy.types.Node): return node_info.bl_idname in old_bl_idnames else: return False def scan_for_old(ng): nodes = [n for n in ng.nodes if n.bl_idname in old_bl_idnames] for node in nodes: mark_old(node) def mark_old(node): if node.parent and node.parent.label == "Deprecated node!": return ng = node.id_data frame = ng.nodes.new("NodeFrame") if node.parent: frame.parent = node.parent node.parent = frame frame.label = "Deprecated node!" frame.use_custom_color = True frame.color = (.8, 0, 0) frame.shrink = True def reload_old(ng=False): if ng: bl_idnames = {n.bl_idname for n in ng.nodes if n.bl_idname in old_bl_idnames} for bl_id in bl_idnames: mod = register_old(bl_id) if mod: importlib.reload(mod) else: print("Couldn't reload {}".format(bl_id)) else: for ng in bpy.data.node_groups: reload_old(ng) #if ng.bl_idname in { 'SverchCustomTreeType', 'SverchGroupTreeType'}: # reload_old(ng) def load_old(ng): """ This approach didn't work, bl_idname of undefined node isn't as I expected bl_idnames = {n.bl_idname for n in ng.nodes} old_bl_ids = bl_idnames.intersection(old_bl_idnames) if old_bl_ids: """ not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) if not_reged_nodes: for bl_id in old_bl_idnames: register_old(bl_id) nodes = [n for n in ng.nodes if n.bl_idname == bl_id] if nodes: for node in nodes: mark_old(node) not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) node_count = len(not_reged_nodes) print("Loaded {}. {} nodes are left unregisted.".format(bl_id, node_count)) if node_count == 0: return else: # didn't help remove unregister_old(bl_id) def register_old(bl_id): if bl_id in old_bl_idnames: mod = importlib.import_module(".{}".format(old_bl_idnames[bl_id]), __name__) res = inspect.getmembers(mod) for name, cls in res: if inspect.isclass(cls): if issubclass(cls, bpy.types.Node) and cls.bl_idname == bl_id: if bl_id not in imported_mods: try: mod.register() except: traceback.print_exc() imported_mods[bl_id] = mod return mod print("Cannot find {} among old nodes".format(bl_id)) return None def unregister_old(bl_id): global imported_mods mod = imported_mods.get(bl_id) if mod: #print("Unloaded old node type {}".format(bl_id)) mod.unregister() del imported_mods[bl_id] def unregister(): <|fim_middle|> <|fim▁end|>
global imported_mods print(imported_mods) for mod in imported_mods.values(): mod.unregister() imported_mods = {}
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### old_bl_idnames = { 'CentersPolsNode' : "centers", # 'BakeryNode' : "bakery", 'CircleNode' : "circle", 'ListItemNode' : "list_item", 'GenRangeNode' : "range", 'GenSeriesNode' : "series", # 'Test1Node' : "test", # 'Test2Node' : "test", # 'ToolsNode' : "tools", 'SvReRouteNode': "reroute", 'VoronoiNode': "voronoi", 'ViewerNode': "viewer", 'EvalKnievalNode': "eval_knieval", 'FormulaNode': 'formula', } # we should add some functions to load things there import importlib import inspect import traceback import bpy from sverchok.node_tree import SverchCustomTreeNode imported_mods = {} def is_old(node_info): ''' Check if node or node.bl_idname is among the old nodes ''' if isinstance(node_info, str): # assumes bl_idname <|fim_middle|> elif isinstance(node_info, bpy.types.Node): return node_info.bl_idname in old_bl_idnames else: return False def scan_for_old(ng): nodes = [n for n in ng.nodes if n.bl_idname in old_bl_idnames] for node in nodes: mark_old(node) def mark_old(node): if node.parent and node.parent.label == "Deprecated node!": return ng = node.id_data frame = ng.nodes.new("NodeFrame") if node.parent: frame.parent = node.parent node.parent = frame frame.label = "Deprecated node!" frame.use_custom_color = True frame.color = (.8, 0, 0) frame.shrink = True def reload_old(ng=False): if ng: bl_idnames = {n.bl_idname for n in ng.nodes if n.bl_idname in old_bl_idnames} for bl_id in bl_idnames: mod = register_old(bl_id) if mod: importlib.reload(mod) else: print("Couldn't reload {}".format(bl_id)) else: for ng in bpy.data.node_groups: reload_old(ng) #if ng.bl_idname in { 'SverchCustomTreeType', 'SverchGroupTreeType'}: # reload_old(ng) def load_old(ng): """ This approach didn't work, bl_idname of undefined node isn't as I expected bl_idnames = {n.bl_idname for n in ng.nodes} old_bl_ids = bl_idnames.intersection(old_bl_idnames) if old_bl_ids: """ not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) if not_reged_nodes: for bl_id in old_bl_idnames: register_old(bl_id) nodes = [n for n in ng.nodes if n.bl_idname == bl_id] if nodes: for node in nodes: mark_old(node) not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) node_count = len(not_reged_nodes) print("Loaded {}. {} nodes are left unregisted.".format(bl_id, node_count)) if node_count == 0: return else: # didn't help remove unregister_old(bl_id) def register_old(bl_id): if bl_id in old_bl_idnames: mod = importlib.import_module(".{}".format(old_bl_idnames[bl_id]), __name__) res = inspect.getmembers(mod) for name, cls in res: if inspect.isclass(cls): if issubclass(cls, bpy.types.Node) and cls.bl_idname == bl_id: if bl_id not in imported_mods: try: mod.register() except: traceback.print_exc() imported_mods[bl_id] = mod return mod print("Cannot find {} among old nodes".format(bl_id)) return None def unregister_old(bl_id): global imported_mods mod = imported_mods.get(bl_id) if mod: #print("Unloaded old node type {}".format(bl_id)) mod.unregister() del imported_mods[bl_id] def unregister(): global imported_mods print(imported_mods) for mod in imported_mods.values(): mod.unregister() imported_mods = {} <|fim▁end|>
return node_info in old_bl_idnames
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### old_bl_idnames = { 'CentersPolsNode' : "centers", # 'BakeryNode' : "bakery", 'CircleNode' : "circle", 'ListItemNode' : "list_item", 'GenRangeNode' : "range", 'GenSeriesNode' : "series", # 'Test1Node' : "test", # 'Test2Node' : "test", # 'ToolsNode' : "tools", 'SvReRouteNode': "reroute", 'VoronoiNode': "voronoi", 'ViewerNode': "viewer", 'EvalKnievalNode': "eval_knieval", 'FormulaNode': 'formula', } # we should add some functions to load things there import importlib import inspect import traceback import bpy from sverchok.node_tree import SverchCustomTreeNode imported_mods = {} def is_old(node_info): ''' Check if node or node.bl_idname is among the old nodes ''' if isinstance(node_info, str): # assumes bl_idname return node_info in old_bl_idnames elif isinstance(node_info, bpy.types.Node): <|fim_middle|> else: return False def scan_for_old(ng): nodes = [n for n in ng.nodes if n.bl_idname in old_bl_idnames] for node in nodes: mark_old(node) def mark_old(node): if node.parent and node.parent.label == "Deprecated node!": return ng = node.id_data frame = ng.nodes.new("NodeFrame") if node.parent: frame.parent = node.parent node.parent = frame frame.label = "Deprecated node!" frame.use_custom_color = True frame.color = (.8, 0, 0) frame.shrink = True def reload_old(ng=False): if ng: bl_idnames = {n.bl_idname for n in ng.nodes if n.bl_idname in old_bl_idnames} for bl_id in bl_idnames: mod = register_old(bl_id) if mod: importlib.reload(mod) else: print("Couldn't reload {}".format(bl_id)) else: for ng in bpy.data.node_groups: reload_old(ng) #if ng.bl_idname in { 'SverchCustomTreeType', 'SverchGroupTreeType'}: # reload_old(ng) def load_old(ng): """ This approach didn't work, bl_idname of undefined node isn't as I expected bl_idnames = {n.bl_idname for n in ng.nodes} old_bl_ids = bl_idnames.intersection(old_bl_idnames) if old_bl_ids: """ not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) if not_reged_nodes: for bl_id in old_bl_idnames: register_old(bl_id) nodes = [n for n in ng.nodes if n.bl_idname == bl_id] if nodes: for node in nodes: mark_old(node) not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) node_count = len(not_reged_nodes) print("Loaded {}. {} nodes are left unregisted.".format(bl_id, node_count)) if node_count == 0: return else: # didn't help remove unregister_old(bl_id) def register_old(bl_id): if bl_id in old_bl_idnames: mod = importlib.import_module(".{}".format(old_bl_idnames[bl_id]), __name__) res = inspect.getmembers(mod) for name, cls in res: if inspect.isclass(cls): if issubclass(cls, bpy.types.Node) and cls.bl_idname == bl_id: if bl_id not in imported_mods: try: mod.register() except: traceback.print_exc() imported_mods[bl_id] = mod return mod print("Cannot find {} among old nodes".format(bl_id)) return None def unregister_old(bl_id): global imported_mods mod = imported_mods.get(bl_id) if mod: #print("Unloaded old node type {}".format(bl_id)) mod.unregister() del imported_mods[bl_id] def unregister(): global imported_mods print(imported_mods) for mod in imported_mods.values(): mod.unregister() imported_mods = {} <|fim▁end|>
return node_info.bl_idname in old_bl_idnames
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### old_bl_idnames = { 'CentersPolsNode' : "centers", # 'BakeryNode' : "bakery", 'CircleNode' : "circle", 'ListItemNode' : "list_item", 'GenRangeNode' : "range", 'GenSeriesNode' : "series", # 'Test1Node' : "test", # 'Test2Node' : "test", # 'ToolsNode' : "tools", 'SvReRouteNode': "reroute", 'VoronoiNode': "voronoi", 'ViewerNode': "viewer", 'EvalKnievalNode': "eval_knieval", 'FormulaNode': 'formula', } # we should add some functions to load things there import importlib import inspect import traceback import bpy from sverchok.node_tree import SverchCustomTreeNode imported_mods = {} def is_old(node_info): ''' Check if node or node.bl_idname is among the old nodes ''' if isinstance(node_info, str): # assumes bl_idname return node_info in old_bl_idnames elif isinstance(node_info, bpy.types.Node): return node_info.bl_idname in old_bl_idnames else: <|fim_middle|> def scan_for_old(ng): nodes = [n for n in ng.nodes if n.bl_idname in old_bl_idnames] for node in nodes: mark_old(node) def mark_old(node): if node.parent and node.parent.label == "Deprecated node!": return ng = node.id_data frame = ng.nodes.new("NodeFrame") if node.parent: frame.parent = node.parent node.parent = frame frame.label = "Deprecated node!" frame.use_custom_color = True frame.color = (.8, 0, 0) frame.shrink = True def reload_old(ng=False): if ng: bl_idnames = {n.bl_idname for n in ng.nodes if n.bl_idname in old_bl_idnames} for bl_id in bl_idnames: mod = register_old(bl_id) if mod: importlib.reload(mod) else: print("Couldn't reload {}".format(bl_id)) else: for ng in bpy.data.node_groups: reload_old(ng) #if ng.bl_idname in { 'SverchCustomTreeType', 'SverchGroupTreeType'}: # reload_old(ng) def load_old(ng): """ This approach didn't work, bl_idname of undefined node isn't as I expected bl_idnames = {n.bl_idname for n in ng.nodes} old_bl_ids = bl_idnames.intersection(old_bl_idnames) if old_bl_ids: """ not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) if not_reged_nodes: for bl_id in old_bl_idnames: register_old(bl_id) nodes = [n for n in ng.nodes if n.bl_idname == bl_id] if nodes: for node in nodes: mark_old(node) not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) node_count = len(not_reged_nodes) print("Loaded {}. {} nodes are left unregisted.".format(bl_id, node_count)) if node_count == 0: return else: # didn't help remove unregister_old(bl_id) def register_old(bl_id): if bl_id in old_bl_idnames: mod = importlib.import_module(".{}".format(old_bl_idnames[bl_id]), __name__) res = inspect.getmembers(mod) for name, cls in res: if inspect.isclass(cls): if issubclass(cls, bpy.types.Node) and cls.bl_idname == bl_id: if bl_id not in imported_mods: try: mod.register() except: traceback.print_exc() imported_mods[bl_id] = mod return mod print("Cannot find {} among old nodes".format(bl_id)) return None def unregister_old(bl_id): global imported_mods mod = imported_mods.get(bl_id) if mod: #print("Unloaded old node type {}".format(bl_id)) mod.unregister() del imported_mods[bl_id] def unregister(): global imported_mods print(imported_mods) for mod in imported_mods.values(): mod.unregister() imported_mods = {} <|fim▁end|>
return False
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### old_bl_idnames = { 'CentersPolsNode' : "centers", # 'BakeryNode' : "bakery", 'CircleNode' : "circle", 'ListItemNode' : "list_item", 'GenRangeNode' : "range", 'GenSeriesNode' : "series", # 'Test1Node' : "test", # 'Test2Node' : "test", # 'ToolsNode' : "tools", 'SvReRouteNode': "reroute", 'VoronoiNode': "voronoi", 'ViewerNode': "viewer", 'EvalKnievalNode': "eval_knieval", 'FormulaNode': 'formula', } # we should add some functions to load things there import importlib import inspect import traceback import bpy from sverchok.node_tree import SverchCustomTreeNode imported_mods = {} def is_old(node_info): ''' Check if node or node.bl_idname is among the old nodes ''' if isinstance(node_info, str): # assumes bl_idname return node_info in old_bl_idnames elif isinstance(node_info, bpy.types.Node): return node_info.bl_idname in old_bl_idnames else: return False def scan_for_old(ng): nodes = [n for n in ng.nodes if n.bl_idname in old_bl_idnames] for node in nodes: mark_old(node) def mark_old(node): if node.parent and node.parent.label == "Deprecated node!": <|fim_middle|> ng = node.id_data frame = ng.nodes.new("NodeFrame") if node.parent: frame.parent = node.parent node.parent = frame frame.label = "Deprecated node!" frame.use_custom_color = True frame.color = (.8, 0, 0) frame.shrink = True def reload_old(ng=False): if ng: bl_idnames = {n.bl_idname for n in ng.nodes if n.bl_idname in old_bl_idnames} for bl_id in bl_idnames: mod = register_old(bl_id) if mod: importlib.reload(mod) else: print("Couldn't reload {}".format(bl_id)) else: for ng in bpy.data.node_groups: reload_old(ng) #if ng.bl_idname in { 'SverchCustomTreeType', 'SverchGroupTreeType'}: # reload_old(ng) def load_old(ng): """ This approach didn't work, bl_idname of undefined node isn't as I expected bl_idnames = {n.bl_idname for n in ng.nodes} old_bl_ids = bl_idnames.intersection(old_bl_idnames) if old_bl_ids: """ not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) if not_reged_nodes: for bl_id in old_bl_idnames: register_old(bl_id) nodes = [n for n in ng.nodes if n.bl_idname == bl_id] if nodes: for node in nodes: mark_old(node) not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) node_count = len(not_reged_nodes) print("Loaded {}. {} nodes are left unregisted.".format(bl_id, node_count)) if node_count == 0: return else: # didn't help remove unregister_old(bl_id) def register_old(bl_id): if bl_id in old_bl_idnames: mod = importlib.import_module(".{}".format(old_bl_idnames[bl_id]), __name__) res = inspect.getmembers(mod) for name, cls in res: if inspect.isclass(cls): if issubclass(cls, bpy.types.Node) and cls.bl_idname == bl_id: if bl_id not in imported_mods: try: mod.register() except: traceback.print_exc() imported_mods[bl_id] = mod return mod print("Cannot find {} among old nodes".format(bl_id)) return None def unregister_old(bl_id): global imported_mods mod = imported_mods.get(bl_id) if mod: #print("Unloaded old node type {}".format(bl_id)) mod.unregister() del imported_mods[bl_id] def unregister(): global imported_mods print(imported_mods) for mod in imported_mods.values(): mod.unregister() imported_mods = {} <|fim▁end|>
return
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### old_bl_idnames = { 'CentersPolsNode' : "centers", # 'BakeryNode' : "bakery", 'CircleNode' : "circle", 'ListItemNode' : "list_item", 'GenRangeNode' : "range", 'GenSeriesNode' : "series", # 'Test1Node' : "test", # 'Test2Node' : "test", # 'ToolsNode' : "tools", 'SvReRouteNode': "reroute", 'VoronoiNode': "voronoi", 'ViewerNode': "viewer", 'EvalKnievalNode': "eval_knieval", 'FormulaNode': 'formula', } # we should add some functions to load things there import importlib import inspect import traceback import bpy from sverchok.node_tree import SverchCustomTreeNode imported_mods = {} def is_old(node_info): ''' Check if node or node.bl_idname is among the old nodes ''' if isinstance(node_info, str): # assumes bl_idname return node_info in old_bl_idnames elif isinstance(node_info, bpy.types.Node): return node_info.bl_idname in old_bl_idnames else: return False def scan_for_old(ng): nodes = [n for n in ng.nodes if n.bl_idname in old_bl_idnames] for node in nodes: mark_old(node) def mark_old(node): if node.parent and node.parent.label == "Deprecated node!": return ng = node.id_data frame = ng.nodes.new("NodeFrame") if node.parent: <|fim_middle|> node.parent = frame frame.label = "Deprecated node!" frame.use_custom_color = True frame.color = (.8, 0, 0) frame.shrink = True def reload_old(ng=False): if ng: bl_idnames = {n.bl_idname for n in ng.nodes if n.bl_idname in old_bl_idnames} for bl_id in bl_idnames: mod = register_old(bl_id) if mod: importlib.reload(mod) else: print("Couldn't reload {}".format(bl_id)) else: for ng in bpy.data.node_groups: reload_old(ng) #if ng.bl_idname in { 'SverchCustomTreeType', 'SverchGroupTreeType'}: # reload_old(ng) def load_old(ng): """ This approach didn't work, bl_idname of undefined node isn't as I expected bl_idnames = {n.bl_idname for n in ng.nodes} old_bl_ids = bl_idnames.intersection(old_bl_idnames) if old_bl_ids: """ not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) if not_reged_nodes: for bl_id in old_bl_idnames: register_old(bl_id) nodes = [n for n in ng.nodes if n.bl_idname == bl_id] if nodes: for node in nodes: mark_old(node) not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) node_count = len(not_reged_nodes) print("Loaded {}. {} nodes are left unregisted.".format(bl_id, node_count)) if node_count == 0: return else: # didn't help remove unregister_old(bl_id) def register_old(bl_id): if bl_id in old_bl_idnames: mod = importlib.import_module(".{}".format(old_bl_idnames[bl_id]), __name__) res = inspect.getmembers(mod) for name, cls in res: if inspect.isclass(cls): if issubclass(cls, bpy.types.Node) and cls.bl_idname == bl_id: if bl_id not in imported_mods: try: mod.register() except: traceback.print_exc() imported_mods[bl_id] = mod return mod print("Cannot find {} among old nodes".format(bl_id)) return None def unregister_old(bl_id): global imported_mods mod = imported_mods.get(bl_id) if mod: #print("Unloaded old node type {}".format(bl_id)) mod.unregister() del imported_mods[bl_id] def unregister(): global imported_mods print(imported_mods) for mod in imported_mods.values(): mod.unregister() imported_mods = {} <|fim▁end|>
frame.parent = node.parent
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### old_bl_idnames = { 'CentersPolsNode' : "centers", # 'BakeryNode' : "bakery", 'CircleNode' : "circle", 'ListItemNode' : "list_item", 'GenRangeNode' : "range", 'GenSeriesNode' : "series", # 'Test1Node' : "test", # 'Test2Node' : "test", # 'ToolsNode' : "tools", 'SvReRouteNode': "reroute", 'VoronoiNode': "voronoi", 'ViewerNode': "viewer", 'EvalKnievalNode': "eval_knieval", 'FormulaNode': 'formula', } # we should add some functions to load things there import importlib import inspect import traceback import bpy from sverchok.node_tree import SverchCustomTreeNode imported_mods = {} def is_old(node_info): ''' Check if node or node.bl_idname is among the old nodes ''' if isinstance(node_info, str): # assumes bl_idname return node_info in old_bl_idnames elif isinstance(node_info, bpy.types.Node): return node_info.bl_idname in old_bl_idnames else: return False def scan_for_old(ng): nodes = [n for n in ng.nodes if n.bl_idname in old_bl_idnames] for node in nodes: mark_old(node) def mark_old(node): if node.parent and node.parent.label == "Deprecated node!": return ng = node.id_data frame = ng.nodes.new("NodeFrame") if node.parent: frame.parent = node.parent node.parent = frame frame.label = "Deprecated node!" frame.use_custom_color = True frame.color = (.8, 0, 0) frame.shrink = True def reload_old(ng=False): if ng: <|fim_middle|> else: for ng in bpy.data.node_groups: reload_old(ng) #if ng.bl_idname in { 'SverchCustomTreeType', 'SverchGroupTreeType'}: # reload_old(ng) def load_old(ng): """ This approach didn't work, bl_idname of undefined node isn't as I expected bl_idnames = {n.bl_idname for n in ng.nodes} old_bl_ids = bl_idnames.intersection(old_bl_idnames) if old_bl_ids: """ not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) if not_reged_nodes: for bl_id in old_bl_idnames: register_old(bl_id) nodes = [n for n in ng.nodes if n.bl_idname == bl_id] if nodes: for node in nodes: mark_old(node) not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) node_count = len(not_reged_nodes) print("Loaded {}. {} nodes are left unregisted.".format(bl_id, node_count)) if node_count == 0: return else: # didn't help remove unregister_old(bl_id) def register_old(bl_id): if bl_id in old_bl_idnames: mod = importlib.import_module(".{}".format(old_bl_idnames[bl_id]), __name__) res = inspect.getmembers(mod) for name, cls in res: if inspect.isclass(cls): if issubclass(cls, bpy.types.Node) and cls.bl_idname == bl_id: if bl_id not in imported_mods: try: mod.register() except: traceback.print_exc() imported_mods[bl_id] = mod return mod print("Cannot find {} among old nodes".format(bl_id)) return None def unregister_old(bl_id): global imported_mods mod = imported_mods.get(bl_id) if mod: #print("Unloaded old node type {}".format(bl_id)) mod.unregister() del imported_mods[bl_id] def unregister(): global imported_mods print(imported_mods) for mod in imported_mods.values(): mod.unregister() imported_mods = {} <|fim▁end|>
bl_idnames = {n.bl_idname for n in ng.nodes if n.bl_idname in old_bl_idnames} for bl_id in bl_idnames: mod = register_old(bl_id) if mod: importlib.reload(mod) else: print("Couldn't reload {}".format(bl_id))
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### old_bl_idnames = { 'CentersPolsNode' : "centers", # 'BakeryNode' : "bakery", 'CircleNode' : "circle", 'ListItemNode' : "list_item", 'GenRangeNode' : "range", 'GenSeriesNode' : "series", # 'Test1Node' : "test", # 'Test2Node' : "test", # 'ToolsNode' : "tools", 'SvReRouteNode': "reroute", 'VoronoiNode': "voronoi", 'ViewerNode': "viewer", 'EvalKnievalNode': "eval_knieval", 'FormulaNode': 'formula', } # we should add some functions to load things there import importlib import inspect import traceback import bpy from sverchok.node_tree import SverchCustomTreeNode imported_mods = {} def is_old(node_info): ''' Check if node or node.bl_idname is among the old nodes ''' if isinstance(node_info, str): # assumes bl_idname return node_info in old_bl_idnames elif isinstance(node_info, bpy.types.Node): return node_info.bl_idname in old_bl_idnames else: return False def scan_for_old(ng): nodes = [n for n in ng.nodes if n.bl_idname in old_bl_idnames] for node in nodes: mark_old(node) def mark_old(node): if node.parent and node.parent.label == "Deprecated node!": return ng = node.id_data frame = ng.nodes.new("NodeFrame") if node.parent: frame.parent = node.parent node.parent = frame frame.label = "Deprecated node!" frame.use_custom_color = True frame.color = (.8, 0, 0) frame.shrink = True def reload_old(ng=False): if ng: bl_idnames = {n.bl_idname for n in ng.nodes if n.bl_idname in old_bl_idnames} for bl_id in bl_idnames: mod = register_old(bl_id) if mod: <|fim_middle|> else: print("Couldn't reload {}".format(bl_id)) else: for ng in bpy.data.node_groups: reload_old(ng) #if ng.bl_idname in { 'SverchCustomTreeType', 'SverchGroupTreeType'}: # reload_old(ng) def load_old(ng): """ This approach didn't work, bl_idname of undefined node isn't as I expected bl_idnames = {n.bl_idname for n in ng.nodes} old_bl_ids = bl_idnames.intersection(old_bl_idnames) if old_bl_ids: """ not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) if not_reged_nodes: for bl_id in old_bl_idnames: register_old(bl_id) nodes = [n for n in ng.nodes if n.bl_idname == bl_id] if nodes: for node in nodes: mark_old(node) not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) node_count = len(not_reged_nodes) print("Loaded {}. {} nodes are left unregisted.".format(bl_id, node_count)) if node_count == 0: return else: # didn't help remove unregister_old(bl_id) def register_old(bl_id): if bl_id in old_bl_idnames: mod = importlib.import_module(".{}".format(old_bl_idnames[bl_id]), __name__) res = inspect.getmembers(mod) for name, cls in res: if inspect.isclass(cls): if issubclass(cls, bpy.types.Node) and cls.bl_idname == bl_id: if bl_id not in imported_mods: try: mod.register() except: traceback.print_exc() imported_mods[bl_id] = mod return mod print("Cannot find {} among old nodes".format(bl_id)) return None def unregister_old(bl_id): global imported_mods mod = imported_mods.get(bl_id) if mod: #print("Unloaded old node type {}".format(bl_id)) mod.unregister() del imported_mods[bl_id] def unregister(): global imported_mods print(imported_mods) for mod in imported_mods.values(): mod.unregister() imported_mods = {} <|fim▁end|>
importlib.reload(mod)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### old_bl_idnames = { 'CentersPolsNode' : "centers", # 'BakeryNode' : "bakery", 'CircleNode' : "circle", 'ListItemNode' : "list_item", 'GenRangeNode' : "range", 'GenSeriesNode' : "series", # 'Test1Node' : "test", # 'Test2Node' : "test", # 'ToolsNode' : "tools", 'SvReRouteNode': "reroute", 'VoronoiNode': "voronoi", 'ViewerNode': "viewer", 'EvalKnievalNode': "eval_knieval", 'FormulaNode': 'formula', } # we should add some functions to load things there import importlib import inspect import traceback import bpy from sverchok.node_tree import SverchCustomTreeNode imported_mods = {} def is_old(node_info): ''' Check if node or node.bl_idname is among the old nodes ''' if isinstance(node_info, str): # assumes bl_idname return node_info in old_bl_idnames elif isinstance(node_info, bpy.types.Node): return node_info.bl_idname in old_bl_idnames else: return False def scan_for_old(ng): nodes = [n for n in ng.nodes if n.bl_idname in old_bl_idnames] for node in nodes: mark_old(node) def mark_old(node): if node.parent and node.parent.label == "Deprecated node!": return ng = node.id_data frame = ng.nodes.new("NodeFrame") if node.parent: frame.parent = node.parent node.parent = frame frame.label = "Deprecated node!" frame.use_custom_color = True frame.color = (.8, 0, 0) frame.shrink = True def reload_old(ng=False): if ng: bl_idnames = {n.bl_idname for n in ng.nodes if n.bl_idname in old_bl_idnames} for bl_id in bl_idnames: mod = register_old(bl_id) if mod: importlib.reload(mod) else: <|fim_middle|> else: for ng in bpy.data.node_groups: reload_old(ng) #if ng.bl_idname in { 'SverchCustomTreeType', 'SverchGroupTreeType'}: # reload_old(ng) def load_old(ng): """ This approach didn't work, bl_idname of undefined node isn't as I expected bl_idnames = {n.bl_idname for n in ng.nodes} old_bl_ids = bl_idnames.intersection(old_bl_idnames) if old_bl_ids: """ not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) if not_reged_nodes: for bl_id in old_bl_idnames: register_old(bl_id) nodes = [n for n in ng.nodes if n.bl_idname == bl_id] if nodes: for node in nodes: mark_old(node) not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) node_count = len(not_reged_nodes) print("Loaded {}. {} nodes are left unregisted.".format(bl_id, node_count)) if node_count == 0: return else: # didn't help remove unregister_old(bl_id) def register_old(bl_id): if bl_id in old_bl_idnames: mod = importlib.import_module(".{}".format(old_bl_idnames[bl_id]), __name__) res = inspect.getmembers(mod) for name, cls in res: if inspect.isclass(cls): if issubclass(cls, bpy.types.Node) and cls.bl_idname == bl_id: if bl_id not in imported_mods: try: mod.register() except: traceback.print_exc() imported_mods[bl_id] = mod return mod print("Cannot find {} among old nodes".format(bl_id)) return None def unregister_old(bl_id): global imported_mods mod = imported_mods.get(bl_id) if mod: #print("Unloaded old node type {}".format(bl_id)) mod.unregister() del imported_mods[bl_id] def unregister(): global imported_mods print(imported_mods) for mod in imported_mods.values(): mod.unregister() imported_mods = {} <|fim▁end|>
print("Couldn't reload {}".format(bl_id))
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### old_bl_idnames = { 'CentersPolsNode' : "centers", # 'BakeryNode' : "bakery", 'CircleNode' : "circle", 'ListItemNode' : "list_item", 'GenRangeNode' : "range", 'GenSeriesNode' : "series", # 'Test1Node' : "test", # 'Test2Node' : "test", # 'ToolsNode' : "tools", 'SvReRouteNode': "reroute", 'VoronoiNode': "voronoi", 'ViewerNode': "viewer", 'EvalKnievalNode': "eval_knieval", 'FormulaNode': 'formula', } # we should add some functions to load things there import importlib import inspect import traceback import bpy from sverchok.node_tree import SverchCustomTreeNode imported_mods = {} def is_old(node_info): ''' Check if node or node.bl_idname is among the old nodes ''' if isinstance(node_info, str): # assumes bl_idname return node_info in old_bl_idnames elif isinstance(node_info, bpy.types.Node): return node_info.bl_idname in old_bl_idnames else: return False def scan_for_old(ng): nodes = [n for n in ng.nodes if n.bl_idname in old_bl_idnames] for node in nodes: mark_old(node) def mark_old(node): if node.parent and node.parent.label == "Deprecated node!": return ng = node.id_data frame = ng.nodes.new("NodeFrame") if node.parent: frame.parent = node.parent node.parent = frame frame.label = "Deprecated node!" frame.use_custom_color = True frame.color = (.8, 0, 0) frame.shrink = True def reload_old(ng=False): if ng: bl_idnames = {n.bl_idname for n in ng.nodes if n.bl_idname in old_bl_idnames} for bl_id in bl_idnames: mod = register_old(bl_id) if mod: importlib.reload(mod) else: print("Couldn't reload {}".format(bl_id)) else: <|fim_middle|> def load_old(ng): """ This approach didn't work, bl_idname of undefined node isn't as I expected bl_idnames = {n.bl_idname for n in ng.nodes} old_bl_ids = bl_idnames.intersection(old_bl_idnames) if old_bl_ids: """ not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) if not_reged_nodes: for bl_id in old_bl_idnames: register_old(bl_id) nodes = [n for n in ng.nodes if n.bl_idname == bl_id] if nodes: for node in nodes: mark_old(node) not_reged_nodes = list(n for n in ng.nodes if not n.is_registered_node_type()) node_count = len(not_reged_nodes) print("Loaded {}. {} nodes are left unregisted.".format(bl_id, node_count)) if node_count == 0: return else: # didn't help remove unregister_old(bl_id) def register_old(bl_id): if bl_id in old_bl_idnames: mod = importlib.import_module(".{}".format(old_bl_idnames[bl_id]), __name__) res = inspect.getmembers(mod) for name, cls in res: if inspect.isclass(cls): if issubclass(cls, bpy.types.Node) and cls.bl_idname == bl_id: if bl_id not in imported_mods: try: mod.register() except: traceback.print_exc() imported_mods[bl_id] = mod return mod print("Cannot find {} among old nodes".format(bl_id)) return None def unregister_old(bl_id): global imported_mods mod = imported_mods.get(bl_id) if mod: #print("Unloaded old node type {}".format(bl_id)) mod.unregister() del imported_mods[bl_id] def unregister(): global imported_mods print(imported_mods) for mod in imported_mods.values(): mod.unregister() imported_mods = {} <|fim▁end|>
for ng in bpy.data.node_groups: reload_old(ng) #if ng.bl_idname in { 'SverchCustomTreeType', 'SverchGroupTreeType'}: # reload_old(ng)