<commit_before>"""
 Pylibui test suite.

"""

from pylibui import libui
from pylibui.controls import Control
from tests.utils import WindowTestCase

class ControlTest(WindowTestCase):

    def setUp(self):
        super().setUp()
        self.control = Control(libui.uiNewButton(''))

    def test_visible_initial_value(self):
        """Tests the control's `visible` initial value is True."""
        self.assertEqual(self.control.getVisible(), True)

    def test_show(self):
        """Tests the control can be shown."""
        self.control.show()
        self.assertEqual(self.control.getVisible(), True)

    def test_hide(self):
        """Tests the control can be hidden."""
        self.control.hide()
        self.assertEqual(self.control.getVisible(), False)

    def test_enabled_initial_value(self):
        """A control's `enabled` initial value should be True."""
        self.assertEqual(self.control.getEnabled(), True)

    def test_can_enable_control(self):
        """Tests a control can be enabled."""
        self.control.setEnabled(True)
        self.assertEqual(self.control.getEnabled(), True)

    def test_can_disable_control(self):
        """Tests a control can be disabled."""
        self.control.setEnabled(False)
        self.assertEqual(self.control.getEnabled(), False)
<commit_msg>fix visibility test<commit_after>"""
 Pylibui test suite.

"""

from pylibui import libui
from pylibui.controls import Control
from tests.utils import WindowTestCase

class ControlTest(WindowTestCase):

    def setUp(self):
        super().setUp()
        self.control = Control(libui.uiNewButton(''))

    def test_visible_initial_value(self):
        """Tests the control's `visible` initial value is False."""
        self.assertEqual(self.control.getVisible(), False)

    def test_show(self):
        """Tests the control can be shown."""
        self.control.show()
        self.assertEqual(self.control.getVisible(), True)

    def test_hide(self):
        """Tests the control can be hidden."""
        self.control.hide()
        self.assertEqual(self.control.getVisible(), False)

    def test_enabled_initial_value(self):
        """A control's `enabled` initial value should be True."""
        self.assertEqual(self.control.getEnabled(), True)

    def test_can_enable_control(self):
        """Tests a control can be enabled."""
        self.control.setEnabled(True)
        self.assertEqual(self.control.getEnabled(), True)

    def test_can_disable_control(self):
        """Tests a control can be disabled."""
        self.control.setEnabled(False)
        self.assertEqual(self.control.getEnabled(), False)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

# Copyright(C) 2010-2012 Romain Bignon
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# weboob 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, see <http://www.gnu.org/licenses/>.

from PyQt4.QtGui import QListWidgetItem, QImage, QPixmap, QLabel, QIcon
from PyQt4.QtCore import SIGNAL, Qt

from weboob.tools.application.qt import QtMainWindow, QtDo, HTMLDelegate
from weboob.tools.application.qt.backendcfg import BackendCfg
from weboob.capabilities.housing import ICapHousing, Query, City
from weboob.capabilities.base import NotLoaded

from .ui.main_window_ui import Ui_MainWindow
from .query import QueryDialog

class MainWindow(QtMainWindow):
    def __init__(self, config, weboob, parent=None):
        QtMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.config = config
        self.weboob = weboob
        self.process = None
        self.housing = None
        self.displayed_photo_idx = 0
        self.process_photo = {}

        self.ui.housingsList.setItemDelegate(HTMLDelegate())
        self.ui.housingFrame.hide()

        self.connect(self.ui.actionBackends, SIGNAL("triggered()"), self.backendsConfig)
        self.connect(self.ui.queriesList, SIGNAL('currentIndexChanged(int)'), self.queryChanged)
        self.connect(self.ui.addQueryButton, SIGNAL('clicked()'), self.addQuery)
        self.connect(self.ui.housingsList, SIGNAL('itemClicked(QListWidgetItem*)'), self.housingSelected)
        self.connect(self.ui.previousButton, SIGNAL('clicked()'), self.previousClicked)
        self.connect(self.ui.nextButton, SIGNAL('clicked()'), self.nextClicked)

        self.reloadQueriesList()
        self.refreshHousingsList()

        if self.weboob.count_backends() == 0:
            self.backendsConfig()

    def backendsConfig(self):
        bckndcfg = BackendCfg(self.weboob, (ICapHousing,), self)
        if bckndcfg.run():
            pass

    def reloadQueriesList(self, select_name=None):
        self.disconnect(self.ui.queriesList, SIGNAL('currentIndexChanged(int)'), self.queryChanged)
        self.ui.queriesList.clear()
        for name in self.config.get('queries', default={}).iterkeys():
            self.ui.queriesList.addItem(name)
            if name == select_name:
                self.ui.queriesList.setCurrentIndex(len(self.ui.queriesList))
        self.connect(self.ui.queriesList, SIGNAL('currentIndexChanged(int)'), self.queryChanged)

    def addQuery(self):
        querydlg = QueryDialog(self.weboob, self)
        if querydlg.exec_():
            name = unicode(querydlg.ui.nameEdit.text())
            query = {}
            query['cities'] = []
            for i in xrange(len(querydlg.ui.citiesList)):
                item = querydlg.ui.citiesList.item(i)
                city = item.data(Qt.UserRole).toPyObject()
                query['cities'].append({'id': city.id, 'backend': city.backend, 'name': city.name})
            query['area_min'] = querydlg.ui.areaMin.value()
            query['area_max'] = querydlg.ui.areaMax.value()
            query['cost_min'] = querydlg.ui.costMin.value()
            query['cost_max'] = querydlg.ui.costMax.value()
            try:
                query['nb_rooms'] = int(querydlg.ui.nbRooms.itemText(querydlg.ui.nbRooms.currentIndex()))
            except ValueError:
                query['nb_rooms'] = 0
            self.config.set('queries', name, query)
            self.config.save()

            self.reloadQueriesList(name)

    def queryChanged(self, i):
        self.refreshHousingsList()

    def refreshHousingsList(self):
        name = unicode(self.ui.queriesList.itemText(self.ui.queriesList.currentIndex()))
        q = self.config.get('queries', name)

        self.ui.housingsList.clear()
        self.ui.queriesList.setEnabled(False)

        query = Query()
        query.cities = []
        for c in q['cities']:
            city = City(c['id'])
            city.backend = c['backend']
            city.name = c['name']
            query.cities.append(city)

        query.area_min = int(q['area_min']) or None
        query.area_max = int(q['area_max']) or None
        query.cost_min = int(q['cost_min']) or None
        query.cost_max = int(q['cost_max']) or None
        query.nb_rooms = int(q['nb_rooms']) or None

        self.process = QtDo(self.weboob, self.addHousing)
        self.process.do('search_housings', query)

    def addHousing(self, backend, housing):
        if not backend:
            self.ui.queriesList.setEnabled(True)
            self.process = None
            return

        item = QListWidgetItem()
        item.setText(u'
%s
%s — %sm² — %s%s (%s)
%s' % (housing.title, housing.date.strftime('%Y-%m-%d') if housing.date else 'Unknown',
                                                        housing.area, housing.cost, housing.currency, housing.backend, housing.text))
        item.setData(Qt.UserRole, housing)

        if housing.photos is NotLoaded:
            process = QtDo(self.weboob, lambda b, c: self.setPhoto(c, item))
            process.do('fillobj', housing, ['photos'], backends=housing.backend)
            self.process_photo[housing.id] = process
        elif len(housing.photos) > 0:
            if not self.setPhoto(housing, item):
                photo = housing.photos[0]
                process = QtDo(self.weboob, lambda b, p: self.setPhoto(housing, item))
                process.do('fillobj', photo, ['data'], backends=housing.backend)
                self.process_photo[housing.id] = process

        self.ui.housingsList.addItem(item)

    def housingSelected(self, item):
        housing = item.data(Qt.UserRole).toPyObject()
        self.ui.queriesFrame.setEnabled(False)

        self.setHousing(housing)

        self.process = QtDo(self.weboob, self.gotHousing)
        self.process.do('fillobj', housing, backends=housing.backend)

    def setPhoto(self, housing, item):
        if not housing:
            return False

        try:
            self.process_photo.pop(housing.id, None)
        except KeyError:
            pass

        img = None
        for photo in housing.photos:
            if photo.data:
                img = QImage.fromData(photo.data)
                break

        if img:
            item.setIcon(QIcon(QPixmap.fromImage(img)))
            return True

        return False

    def setHousing(self, housing, nottext='Loading...'):
        self.housing = housing

        self.ui.housingFrame.show()

        self.display_photo()

        self.ui.titleLabel.setText('
%s
' % housing.title)
        self.ui.areaLabel.setText(u'%s m²' % housing.area)
        self.ui.costLabel.setText(u'%s %s' % (housing.cost, housing.currency))
        self.ui.dateLabel.setText(housing.date.strftime('%Y-%m-%d') if housing.date else nottext)
        self.ui.phoneLabel.setText(housing.phone or nottext)
        self.ui.locationLabel.setText(housing.location or nottext)
        self.ui.stationLabel.setText(housing.station or nottext)

        if housing.text:
            self.ui.descriptionEdit.setText(housing.text.replace('\n', '
'))
        else:
            self.ui.descriptionEdit.setText(nottext)

        while self.ui.detailsFrame.layout().count() > 0:
            child = self.ui.detailsFrame.layout().takeAt(0)
            child.widget().hide()
            child.widget().deleteLater()

        if housing.details:
            for key, value in housing.details.iteritems():
                label = QLabel(value)
                label.setTextInteractionFlags(Qt.TextSelectableByMouse|Qt.LinksAccessibleByMouse)
                self.ui.detailsFrame.layout().addRow('%s:' % key, label)

    def gotHousing(self, backend, housing):
        if not backend:
            self.ui.queriesFrame.setEnabled(True)
            self.process = None
            return

        self.setHousing(housing, nottext='')

    def previousClicked(self):
        if len(self.housing.photos) == 0:
            return
        self.displayed_photo_idx = (self.displayed_photo_idx - 1) % len(self.housing.photos)
        self.display_photo()

    def nextClicked(self):
        if len(self.housing.photos) == 0:
            return
        self.displayed_photo_idx = (self.displayed_photo_idx + 1) % len(self.housing.photos)
        self.display_photo()

    def display_photo(self):
        if not self.housing.photos:
            self.ui.photoUrlLabel.setText('')
            self.ui.photoLabel.setText('')
            return

        if self.displayed_photo_idx >= len(self.housing.photos):
            self.displayed_photo_idx = len(self.housing.photos) - 1
        if self.displayed_photo_idx < 0:
            self.ui.photoLabel.setText('')
            self.ui.photoUrlLabel.setText('')
            return

        photo = self.housing.photos[self.displayed_photo_idx]
        if photo.data:
            data = photo.data
            if photo.id in self.process_photo:
                self.process_photo.pop(photo.id)
        else:
            self.process_photo[photo.id] = QtDo(self.weboob, lambda b,p: self.display_photo())
            self.process_photo[photo.id].do('fillobj', photo, ['data'], backends=self.housing.backend)

            return

        img = QImage.fromData(data)
        img = img.scaledToWidth(self.width()/3)

        self.ui.photoLabel.setPixmap(QPixmap.fromImage(img))
        if photo.url is not NotLoaded:
            text = '%s' % (photo.url, photo.url)
            self.ui.photoUrlLabel.setText(text)
<commit_msg>fix refresh of results when the selected query is missing<commit_after># -*- coding: utf-8 -*-

# Copyright(C) 2010-2012 Romain Bignon
#
# This file is part of weboob.
#
# weboob is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# weboob 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with weboob. If not, see <http://www.gnu.org/licenses/>.

from PyQt4.QtGui import QListWidgetItem, QImage, QPixmap, QLabel, QIcon
from PyQt4.QtCore import SIGNAL, Qt

from weboob.tools.application.qt import QtMainWindow, QtDo, HTMLDelegate
from weboob.tools.application.qt.backendcfg import BackendCfg
from weboob.capabilities.housing import ICapHousing, Query, City
from weboob.capabilities.base import NotLoaded

from .ui.main_window_ui import Ui_MainWindow
from .query import QueryDialog

class MainWindow(QtMainWindow):
    def __init__(self, config, weboob, parent=None):
        QtMainWindow.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.config = config
        self.weboob = weboob
        self.process = None
        self.housing = None
        self.displayed_photo_idx = 0
        self.process_photo = {}

        self.ui.housingsList.setItemDelegate(HTMLDelegate())
        self.ui.housingFrame.hide()

        self.connect(self.ui.actionBackends, SIGNAL("triggered()"), self.backendsConfig)
        self.connect(self.ui.queriesList, SIGNAL('currentIndexChanged(int)'), self.queryChanged)
        self.connect(self.ui.addQueryButton, SIGNAL('clicked()'), self.addQuery)
        self.connect(self.ui.housingsList, SIGNAL('itemClicked(QListWidgetItem*)'), self.housingSelected)
        self.connect(self.ui.previousButton, SIGNAL('clicked()'), self.previousClicked)
        self.connect(self.ui.nextButton, SIGNAL('clicked()'), self.nextClicked)

        self.reloadQueriesList()
        self.refreshHousingsList()

        if self.weboob.count_backends() == 0:
            self.backendsConfig()

    def backendsConfig(self):
        bckndcfg = BackendCfg(self.weboob, (ICapHousing,), self)
        if bckndcfg.run():
            pass

    def reloadQueriesList(self, select_name=None):
        self.disconnect(self.ui.queriesList, SIGNAL('currentIndexChanged(int)'), self.queryChanged)
        self.ui.queriesList.clear()
        for name in self.config.get('queries', default={}).iterkeys():
            self.ui.queriesList.addItem(name)
            if name == select_name:
                self.ui.queriesList.setCurrentIndex(len(self.ui.queriesList)-1)
        self.connect(self.ui.queriesList, SIGNAL('currentIndexChanged(int)'), self.queryChanged)

    def addQuery(self):
        querydlg = QueryDialog(self.weboob, self)
        if querydlg.exec_():
            name = unicode(querydlg.ui.nameEdit.text())
            query = {}
            query['cities'] = []
            for i in xrange(len(querydlg.ui.citiesList)):
                item = querydlg.ui.citiesList.item(i)
                city = item.data(Qt.UserRole).toPyObject()
                query['cities'].append({'id': city.id, 'backend': city.backend, 'name': city.name})
            query['area_min'] = querydlg.ui.areaMin.value()
            query['area_max'] = querydlg.ui.areaMax.value()
            query['cost_min'] = querydlg.ui.costMin.value()
            query['cost_max'] = querydlg.ui.costMax.value()
            try:
                query['nb_rooms'] = int(querydlg.ui.nbRooms.itemText(querydlg.ui.nbRooms.currentIndex()))
            except ValueError:
                query['nb_rooms'] = 0
            self.config.set('queries', name, query)
            self.config.save()

            self.reloadQueriesList(name)

    def queryChanged(self, i):
        self.refreshHousingsList()

    def refreshHousingsList(self):
        name = unicode(self.ui.queriesList.itemText(self.ui.queriesList.currentIndex()))
        q = self.config.get('queries', name)

        if q is None:
            return q

        self.ui.housingsList.clear()
        self.ui.queriesList.setEnabled(False)

        query = Query()
        query.cities = []
        for c in q['cities']:
            city = City(c['id'])
            city.backend = c['backend']
            city.name = c['name']
            query.cities.append(city)

        query.area_min = int(q['area_min']) or None
        query.area_max = int(q['area_max']) or None
        query.cost_min = int(q['cost_min']) or None
        query.cost_max = int(q['cost_max']) or None
        query.nb_rooms = int(q['nb_rooms']) or None

        self.process = QtDo(self.weboob, self.addHousing)
        self.process.do('search_housings', query)

    def addHousing(self, backend, housing):
        if not backend:
            self.ui.queriesList.setEnabled(True)
            self.process = None
            return

        item = QListWidgetItem()
        item.setText(u'
%s
%s — %sm² — %s%s (%s)
%s' % (housing.title, housing.date.strftime('%Y-%m-%d') if housing.date else 'Unknown',
                                                        housing.area, housing.cost, housing.currency, housing.backend, housing.text))
        item.setData(Qt.UserRole, housing)

        if housing.photos is NotLoaded:
            process = QtDo(self.weboob, lambda b, c: self.setPhoto(c, item))
            process.do('fillobj', housing, ['photos'], backends=housing.backend)
            self.process_photo[housing.id] = process
        elif len(housing.photos) > 0:
            if not self.setPhoto(housing, item):
                photo = housing.photos[0]
                process = QtDo(self.weboob, lambda b, p: self.setPhoto(housing, item))
                process.do('fillobj', photo, ['data'], backends=housing.backend)
                self.process_photo[housing.id] = process

        self.ui.housingsList.addItem(item)

    def housingSelected(self, item):
        housing = item.data(Qt.UserRole).toPyObject()
        self.ui.queriesFrame.setEnabled(False)

        self.setHousing(housing)

        self.process = QtDo(self.weboob, self.gotHousing)
        self.process.do('fillobj', housing, backends=housing.backend)

    def setPhoto(self, housing, item):
        if not housing:
            return False

        try:
            self.process_photo.pop(housing.id, None)
        except KeyError:
            pass

        img = None
        for photo in housing.photos:
            if photo.data:
                img = QImage.fromData(photo.data)
                break

        if img:
            item.setIcon(QIcon(QPixmap.fromImage(img)))
            return True

        return False

    def setHousing(self, housing, nottext='Loading...'):
        self.housing = housing

        self.ui.housingFrame.show()

        self.display_photo()

        self.ui.titleLabel.setText('
%s
' % housing.title)
        self.ui.areaLabel.setText(u'%s m²' % housing.area)
        self.ui.costLabel.setText(u'%s %s' % (housing.cost, housing.currency))
        self.ui.dateLabel.setText(housing.date.strftime('%Y-%m-%d') if housing.date else nottext)
        self.ui.phoneLabel.setText(housing.phone or nottext)
        self.ui.locationLabel.setText(housing.location or nottext)
        self.ui.stationLabel.setText(housing.station or nottext)

        if housing.text:
            self.ui.descriptionEdit.setText(housing.text.replace('\n', '
'))
        else:
            self.ui.descriptionEdit.setText(nottext)

        while self.ui.detailsFrame.layout().count() > 0:
            child = self.ui.detailsFrame.layout().takeAt(0)
            child.widget().hide()
            child.widget().deleteLater()

        if housing.details:
            for key, value in housing.details.iteritems():
                label = QLabel(value)
                label.setTextInteractionFlags(Qt.TextSelectableByMouse|Qt.LinksAccessibleByMouse)
                self.ui.detailsFrame.layout().addRow('%s:' % key, label)

    def gotHousing(self, backend, housing):
        if not backend:
            self.ui.queriesFrame.setEnabled(True)
            self.process = None
            return

        self.setHousing(housing, nottext='')

    def previousClicked(self):
        if len(self.housing.photos) == 0:
            return
        self.displayed_photo_idx = (self.displayed_photo_idx - 1) % len(self.housing.photos)
        self.display_photo()

    def nextClicked(self):
        if len(self.housing.photos) == 0:
            return
        self.displayed_photo_idx = (self.displayed_photo_idx + 1) % len(self.housing.photos)
        self.display_photo()

    def display_photo(self):
        if not self.housing.photos:
            self.ui.photoUrlLabel.setText('')
            self.ui.photoLabel.setText('')
            return

        if self.displayed_photo_idx >= len(self.housing.photos):
            self.displayed_photo_idx = len(self.housing.photos) - 1
        if self.displayed_photo_idx < 0:
            self.ui.photoLabel.setText('')
            self.ui.photoUrlLabel.setText('')
            return

        photo = self.housing.photos[self.displayed_photo_idx]
        if photo.data:
            data = photo.data
            if photo.id in self.process_photo:
                self.process_photo.pop(photo.id)
        else:
            self.process_photo[photo.id] = QtDo(self.weboob, lambda b,p: self.display_photo())
            self.process_photo[photo.id].do('fillobj', photo, ['data'], backends=self.housing.backend)

            return

        img = QImage.fromData(data)
        img = img.scaledToWidth(self.width()/3)

        self.ui.photoLabel.setPixmap(QPixmap.fromImage(img))
        if photo.url is not NotLoaded:
            text = '%s' % (photo.url, photo.url)
            self.ui.photoUrlLabel.setText(text)
<|endoftext|>


<commit_before>#!/usr/bin/env python3

from dipper.sources.Coriell import Coriell
from tests.test_source import SourceTestCase

import unittest
import logging

logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger(__name__)

class CoriellTestCase(SourceTestCase):

    def setUp(self):
        self.source = Coriell()
        self.source.settestonly(True)
        self._setDirToSource()
        return

    def tearDown(self):
        self.source = None
        return

    # @unittest.skip('Coriell-specific tests not yet defined')
    # def test_coriell(self):
    #    logger.info("A Coriell-specific test")
    #
    #    return

if __name__ == '__main__':
    unittest.main()<commit_msg>update coriell test to set nobnodes<commit_after>#!/usr/bin/env python3

from dipper.sources.Coriell import Coriell
from tests.test_source import SourceTestCase

import unittest
import logging

logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger(__name__)

class CoriellTestCase(SourceTestCase):

    def setUp(self):
        self.source = Coriell()
        self.source.settestonly(True)
        self.source.setnobnodes(True)
        self._setDirToSource()
        return

    def tearDown(self):
        self.source = None
        return

    # @unittest.skip('Coriell-specific tests not yet defined')
    # def test_coriell(self):
    #    logger.info("A Coriell-specific test")
    #
    #    return

if __name__ == '__main__':
    unittest.main()<|endoftext|>


<commit_before>"""Simple test."""

import os
import json
import time
import signal
import requests
import websocket
import subprocess

DAEMON = None

def setup_module():
    global DAEMON

    # call os.setsid so that all subprocesses terminate when the
    # main process receives SIGTERM
    DAEMON = subprocess.Popen(['databench', '--with-coverage'],
                              close_fds=True,
                              stdin=subprocess.PIPE,
                              stdout=subprocess.PIPE,
                              preexec_fn=os.setsid)
    time.sleep(1)

def teardown_module():
    global DAEMON

    # simply DAEMON.terminate() would only terminate the main process,
    # but the nested processes also need to be terminated
    #
    # SIGUSR1 does not exist on Windows
    if hasattr(signal, 'SIGUSR1'):
        os.killpg(DAEMON.pid, signal.SIGUSR1)
    else:
        os.killpg(DAEMON.pid, signal.SIGTERM)
    DAEMON.wait()

"""

Testing a default Python analysis
---------------------------------
"""

def test_get_dummypi():
    r = requests.get('http://127.0.0.1:5000/dummypi/')
    assert r.status_code == 200

def test_ws_dummypi():
    websocket.enableTrace(True)
    ws = websocket.create_connection('ws://127.0.0.1:5000/dummypi/ws')
    ws.send('{"__connect": null}')
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == '__connect'
    assert 'analysis_id' in r['load']
    ws.send('{"signal":"run", "load":{"__action_id":123}}')
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == '__action'
    assert r['load']['id'] == 123
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == 'log'
    assert 'inside' in r['load']
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == 'status'
    assert 'pi-uncertainty' in r['load']
    ws.close()

def test_multiple_ws_dummypi():
    websocket.enableTrace(True)
    wss = [websocket.create_connection('ws://127.0.0.1:5000/dummypi/ws')
           for _ in range(4)]
    for ws in wss:
        ws.send('{"__connect": null}')
        r = json.loads(ws.recv())
        print(r)
        assert r['signal'] == '__connect'
        assert 'analysis_id' in r['load']
    for ws in wss:
        ws.close()

"""

Python Language Kernel tests
----------------------------
"""

def test_get_dummypi_py():
    r = requests.get('http://127.0.0.1:5000/dummypi_py/')
    assert r.status_code == 200

def test_multiple_ws_dummypi_py():
    # websocket.enableTrace(True)
    wss = [websocket.create_connection('ws://127.0.0.1:5000/dummypi_py/ws')
           for _ in range(4)]
    for ws in wss:
        ws.send('{"__connect": null}')
        r = json.loads(ws.recv())
        print(r)
        assert r['signal'] == '__connect'
        assert 'analysis_id' in r['load']
    for ws in wss:
        ws.close()

def test_ws_dummypi_py():
    websocket.enableTrace(True)
    ws = websocket.create_connection('ws://127.0.0.1:5000/dummypi_py/ws')
    ws.send('{"__connect": null}')
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == '__connect'
    assert 'analysis_id' in r['load']
    time.sleep(1)
    ws.send('{"signal":"run", "load":{"__action_id":123}}')
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == '__action'
    assert r['load']['id'] == 123
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == 'log'
    assert 'inside' in r['load']
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == 'status'
    assert 'pi-uncertainty' in r['load']
    ws.close()

"""

Function Argument Tests
-----------------------
"""

def _fn_call(name='dummypi'):
    websocket.enableTrace(True)
    ws = websocket.create_connection('ws://127.0.0.1:5000/'+name+'/ws')
    ws.send('{"__connect": null}')
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == '__connect'
    assert 'analysis_id' in r['load']
    time.sleep(1)
    ws.send('{"signal":"test_fn", "load": 1}')
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == 'test_fn'
    assert r['load']['first_param'] == 1
    assert r['load']['second_param'] == 100
    ws.close()

def _fn_call_array(name='dummypi'):
    websocket.enableTrace(True)
    ws = websocket.create_connection('ws://127.0.0.1:5000/'+name+'/ws')
    ws.send('{"__connect": null}')
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == '__connect'
    assert 'analysis_id' in r['load']
    time.sleep(1)
    ws.send('{"signal":"test_fn", "load": [1, 2]}')
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == 'test_fn'
    assert r['load']['first_param'] == 1
    assert r['load']['second_param'] == 2
    ws.close()

def _fn_call_dict(name='dummypi'):
    websocket.enableTrace(True)
    ws = websocket.create_connection('ws://127.0.0.1:5000/'+name+'/ws')
    ws.send('{"__connect": null}')
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == '__connect'
    assert 'analysis_id' in r['load']
    time.sleep(1)
    ws.send('{"signal":"test_fn", "load": '
            '{"first_param": 1, "second_param": 2}}')
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == 'test_fn'
    assert r['load']['first_param'] == 1
    assert r['load']['second_param'] == 2
    ws.close()

def test_fn_call_dummypi():
    _fn_call()

def test_fn_call_dummypi_array():
    _fn_call_array()

def test_fn_call_dummypi_dict():
    _fn_call_dict()

def test_fn_call_dummypi_py():
    _fn_call(name='dummypi_py')

def test_fn_call_dummypi_py_array():
    _fn_call_array(name='dummypi_py')

def test_fn_call_dummypi_py_dict():
    _fn_call_dict(name='dummypi_py')

if __name__ == '__main__':
    test_multiple_ws_dummypi_py()
<commit_msg>launch databench with --log=INFO in tests<commit_after>"""Simple test."""

import os
import json
import time
import signal
import requests
import websocket
import subprocess

DAEMON = None

def setup_module():
    global DAEMON

    # call os.setsid so that all subprocesses terminate when the
    # main process receives SIGTERM
    DAEMON = subprocess.Popen(['databench', '--with-coverage', '--log=INFO'],
                              close_fds=True,
                              stdin=subprocess.PIPE,
                              stdout=subprocess.PIPE,
                              preexec_fn=os.setsid)
    time.sleep(1)

def teardown_module():
    global DAEMON

    # simply DAEMON.terminate() would only terminate the main process,
    # but the nested processes also need to be terminated
    #
    # SIGUSR1 does not exist on Windows
    if hasattr(signal, 'SIGUSR1'):
        os.killpg(DAEMON.pid, signal.SIGUSR1)
    else:
        os.killpg(DAEMON.pid, signal.SIGTERM)
    DAEMON.wait()

"""

Testing a default Python analysis
---------------------------------
"""

def test_get_dummypi():
    r = requests.get('http://127.0.0.1:5000/dummypi/')
    assert r.status_code == 200

def test_ws_dummypi():
    websocket.enableTrace(True)
    ws = websocket.create_connection('ws://127.0.0.1:5000/dummypi/ws')
    ws.send('{"__connect": null}')
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == '__connect'
    assert 'analysis_id' in r['load']
    ws.send('{"signal":"run", "load":{"__action_id":123}}')
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == '__action'
    assert r['load']['id'] == 123
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == 'log'
    assert 'inside' in r['load']
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == 'status'
    assert 'pi-uncertainty' in r['load']
    ws.close()

def test_multiple_ws_dummypi():
    websocket.enableTrace(True)
    wss = [websocket.create_connection('ws://127.0.0.1:5000/dummypi/ws')
           for _ in range(4)]
    for ws in wss:
        ws.send('{"__connect": null}')
        r = json.loads(ws.recv())
        print(r)
        assert r['signal'] == '__connect'
        assert 'analysis_id' in r['load']
    for ws in wss:
        ws.close()

"""

Python Language Kernel tests
----------------------------
"""

def test_get_dummypi_py():
    r = requests.get('http://127.0.0.1:5000/dummypi_py/')
    assert r.status_code == 200

def test_multiple_ws_dummypi_py():
    # websocket.enableTrace(True)
    wss = [websocket.create_connection('ws://127.0.0.1:5000/dummypi_py/ws')
           for _ in range(4)]
    for ws in wss:
        ws.send('{"__connect": null}')
        r = json.loads(ws.recv())
        print(r)
        assert r['signal'] == '__connect'
        assert 'analysis_id' in r['load']
    for ws in wss:
        ws.close()

def test_ws_dummypi_py():
    websocket.enableTrace(True)
    ws = websocket.create_connection('ws://127.0.0.1:5000/dummypi_py/ws')
    ws.send('{"__connect": null}')
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == '__connect'
    assert 'analysis_id' in r['load']
    time.sleep(1)
    ws.send('{"signal":"run", "load":{"__action_id":123}}')
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == '__action'
    assert r['load']['id'] == 123
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == 'log'
    assert 'inside' in r['load']
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == 'status'
    assert 'pi-uncertainty' in r['load']
    ws.close()

"""

Function Argument Tests
-----------------------
"""

def _fn_call(name='dummypi'):
    websocket.enableTrace(True)
    ws = websocket.create_connection('ws://127.0.0.1:5000/'+name+'/ws')
    ws.send('{"__connect": null}')
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == '__connect'
    assert 'analysis_id' in r['load']
    time.sleep(1)
    ws.send('{"signal":"test_fn", "load": 1}')
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == 'test_fn'
    assert r['load']['first_param'] == 1
    assert r['load']['second_param'] == 100
    ws.close()

def _fn_call_array(name='dummypi'):
    websocket.enableTrace(True)
    ws = websocket.create_connection('ws://127.0.0.1:5000/'+name+'/ws')
    ws.send('{"__connect": null}')
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == '__connect'
    assert 'analysis_id' in r['load']
    time.sleep(1)
    ws.send('{"signal":"test_fn", "load": [1, 2]}')
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == 'test_fn'
    assert r['load']['first_param'] == 1
    assert r['load']['second_param'] == 2
    ws.close()

def _fn_call_dict(name='dummypi'):
    websocket.enableTrace(True)
    ws = websocket.create_connection('ws://127.0.0.1:5000/'+name+'/ws')
    ws.send('{"__connect": null}')
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == '__connect'
    assert 'analysis_id' in r['load']
    time.sleep(1)
    ws.send('{"signal":"test_fn", "load": '
            '{"first_param": 1, "second_param": 2}}')
    r = json.loads(ws.recv())
    print(r)
    assert r['signal'] == 'test_fn'
    assert r['load']['first_param'] == 1
    assert r['load']['second_param'] == 2
    ws.close()

def test_fn_call_dummypi():
    _fn_call()

def test_fn_call_dummypi_array():
    _fn_call_array()

def test_fn_call_dummypi_dict():
    _fn_call_dict()

def test_fn_call_dummypi_py():
    _fn_call(name='dummypi_py')

def test_fn_call_dummypi_py_array():
    _fn_call_array(name='dummypi_py')

def test_fn_call_dummypi_py_dict():
    _fn_call_dict(name='dummypi_py')

if __name__ == '__main__':
    test_multiple_ws_dummypi_py()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# (c) 2015 Antiun Ingeniería S.L. - Sergio Teruel
# (c) 2015 Antiun Ingeniería S.L. - Carlos Dauden
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
import base64

from openerp import http
from openerp.http import request

from openerp.addons.website_portal.controllers.main import WebsiteAccount

PPG = 10  # Products Per Page

class WebsiteProductSupplier(http.Controller):

    mandatory_product_fields = ['product_name']
    optional_product_fields = ['product_code']

    def _get_mandatory_product_fields(self):
        return self.mandatory_product_fields

    def _get_optional_product_fields(self):
        return self.optional_product_fields

    def check_product_form_validate(self, data):
        error = dict()
        for field_name in self._get_mandatory_product_fields():
            if not data.get(field_name):
                error[field_name] = 'missing'
        return error

    def _post_prepare_supplierinfo_query(self, supplierinfo_dic, data):
        return supplierinfo_dic

    def supplierinfo_field_parse(self, data):
        # set mandatory and optional fields
        all_fields = (
            self._get_mandatory_product_fields() +
            self._get_optional_product_fields())
        # set data
        if isinstance(data, dict):
            supplierinfo_dic = dict(
                (field_name, data[field_name]) for field_name in
                all_fields if field_name in data)
        else:
            supplierinfo_dic = dict(
                (field_name, getattr(data, field_name)) for field_name in
                all_fields)
        supplierinfo_dic = self._post_prepare_supplierinfo_query(
            supplierinfo_dic, data)
        return supplierinfo_dic

    @http.route([
        '/my/supplier/product/<model("product.supplierinfo"):supplierinfo>',
        '/my/supplier/product/new'
    ], type='http', auth="user", website=True)
    def supplier_info(self, supplierinfo=None, category='', search='', **post):
        if supplierinfo and supplierinfo.name != request.env.user.partner_id:
            return request.website.render('website.404')

        values = {
            'search': search,
            'category': category,
            'error': {},
            'user': request.env.user,
        }
        if supplierinfo is None:
            supplierinfo = request.env['product.supplierinfo']
        supplierinfo = supplierinfo.sudo()
        form_vals = self.supplierinfo_field_parse(supplierinfo)
        values.update(self._prepare_render_values(supplierinfo, form_vals))
        return request.website.render(
            "website_product_supplier.product", values)

    def _prepare_render_values(self, supplierinfo, form_vals):
        values = {
            'main_obj': supplierinfo,
            'supplierinfo': form_vals,
            'product': supplierinfo.product_tmpl_id,
            'user': request.env.user,
            'pricelist': supplierinfo.pricelist_ids,
        }
        return values

    @http.route('/my/supplier/product/save/', type='http', auth="user",
                website=True)
    def supplier_info_create(self, **post):
        supplierinfo = request.env['product.supplierinfo'].sudo()
        form_vals = self.supplierinfo_field_parse(post)
        values = self._prepare_render_values(supplierinfo, form_vals)
        values['error'] = self.check_product_form_validate(form_vals)
        if values["error"]:
            return request.website.render(
                "website_product_supplier.product",
                values)

        product_vals = {'name': form_vals.get('product_name')}
        if post.get('ufile', False):
            product_vals.update(
                image=base64.encodestring(post['ufile'].read()))
        product = supplierinfo.product_tmpl_id.create(
            self._prepare_product_values(product_vals))
        form_vals.update({
            'name': request.env.user.partner_id.id,
            'product_tmpl_id': product.id,
            'pricelist_ids': [(0, 0, {
                'min_quantity': post.get('min_quantity', 0.0),
                'price': post.get('price', 0.0)})]
        })
        values['product'] = product
        try:
            supplierinfo = supplierinfo.create(
                self._prepare_supplierinfo_values(
                    supplierinfo, product, form_vals, post))
            values.update({
                'product': product,
                'main_obj': supplierinfo,
                'pricelist': supplierinfo.pricelist_ids
            })
        except:
            values.update(error={'error_name': 'Invalid fields'})
            return request.website.render(
                "website_product_supplier.product",
                values)
        return http.redirect_with_hash(
            '/my/supplier/product/%s' % supplierinfo.id)

    @http.route('/my/supplier/product/save/<model("product.supplierinfo"):supp'
                'lierinfo>', type='http', auth="user", website=True)
    def supplier_info_save(self, supplierinfo=None, **post):
        if supplierinfo.name != request.env.user.partner_id:
            return request.website.render('website.404')
        supplierinfo = supplierinfo.sudo()
        form_vals = self.supplierinfo_field_parse(post)
        values = self._prepare_render_values(supplierinfo, form_vals)
        values['error'] = self.check_product_form_validate(form_vals)
        if values["error"]:
            return request.website.render(
                "website_product_supplier.product",
                values)
        try:
            form_vals.update({
                'pricelist_ids': [(1, supplierinfo.pricelist_ids[0].id, {
                    'min_quantity': post.get('min_quantity', 0.0),
                    'price': post.get('price', 0.0)})]})
            supplierinfo.write(self._prepare_supplierinfo_values(
                supplierinfo, supplierinfo.product_tmpl_id, form_vals, post))
        except:
            values.update(error={'error_name': 'Invalid fields'})
            return request.website.render(
                "website_product_supplier.product",
                values)
        return http.redirect_with_hash(
            '/my/supplier/product/%s' % supplierinfo.id)

    def _prepare_supplierinfo_values(self, supplierinfo, product, vals, post):
        # Hook to rewrite
        return vals

    def _prepare_product_values(self, vals):
        # Hook to rewrite
        return vals

    def _prepare_supplierinfo_list(self, supplierinfo, pager):
        values = {
            'suppliersinfo': supplierinfo,
            'pager': pager,
            'user': request.env.user,
        }
        return values

    def _get_search_domain(self, search=None):
        domain = [('name', '=', request.env.user.partner_id.id)]
        if search:
            for srch in search.split(" "):
                domain += [
                    ('product_name', 'ilike', srch),
                ]
        return domain

    @http.route(['/my/supplier/product/list',
                 '/my/supplier/product/list/page/<int:page>'],
                type='http', auth="user", website=True)
    def supplierinfo_list(self, page=0, **post):
        supplierinfo_obj = request.env['product.supplierinfo']
        domain = self._get_search_domain(post.get('search', ''))
        url = "/my/supplier/product/list_only"
        supplierinfo_count = supplierinfo_obj.search_count(domain)

        pager = request.website.pager(
            url=url, total=supplierinfo_count, page=page, step=PPG, scope=7,
            url_args=post)
        supplierinfo = supplierinfo_obj.search(
            domain, limit=PPG, offset=pager['offset'])

        values = self._prepare_supplierinfo_list(supplierinfo, pager)

        return request.website.render(
            "website_product_supplier.product", values)

    @http.route(['/my/supplier/product/list_only',
                 '/my/supplier/product/list_only/page/<int:page>'],
                type='http', auth="user", website=True)
    def supplier_product_list(self, page=0, **post):
        res = self.supplierinfo_list(page, **post)
        res.template = "website_product_supplier.supplier_product_list"
        return res

    @http.route(['/my/supplier/product/delete'], type='json',
                auth="user", website=True)
    def delete_product(self, supplierinfo_id):
        supplierinfo = request.env['product.supplierinfo'].browse(
            int(supplierinfo_id))
        if len(supplierinfo.product_tmpl_id.seller_ids) == 1:
            res = supplierinfo.product_tmpl_id.unlink()
        else:
            res = supplierinfo.unlink()
        return res

class ProductSupplierWebsiteAccount(WebsiteAccount):

    @http.route(['/my/home'], type='http', auth="user", website=True)
    def account(self, **kw):
        response = super(ProductSupplierWebsiteAccount, self).account(**kw)
        if not request.env.user.partner_id.supplier:
            return response
        supplierinfo_obj = request.env['product.supplierinfo']
        domain = [('name', '=', request.env.user.partner_id.id)]
        supplierinfo = supplierinfo_obj.search(domain, limit=PPG)
        values = {
            'suppliersinfo': supplierinfo,
            'pager': False,
            'user': request.env.user,
        }
        response.qcontext.update(values)
        return response
<commit_msg>[FIX] website_product_supplier: Fix save fields.<commit_after># -*- coding: utf-8 -*-
# (c) 2015 Antiun Ingeniería S.L. - Sergio Teruel
# (c) 2015 Antiun Ingeniería S.L. - Carlos Dauden
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
import base64

from openerp import http
from openerp.http import request

from openerp.addons.website_portal.controllers.main import WebsiteAccount

PPG = 10  # Products Per Page

class WebsiteProductSupplier(http.Controller):

    mandatory_product_fields = ['product_name']
    optional_product_fields = ['product_code', 'min_qty', 'delay']

    def _get_mandatory_product_fields(self):
        return self.mandatory_product_fields

    def _get_optional_product_fields(self):
        return self.optional_product_fields

    def check_product_form_validate(self, data):
        error = dict()
        for field_name in self._get_mandatory_product_fields():
            if not data.get(field_name):
                error[field_name] = 'missing'
        return error

    def _post_prepare_supplierinfo_query(self, supplierinfo_dic, data):
        return supplierinfo_dic

    def supplierinfo_field_parse(self, data):
        # set mandatory and optional fields
        all_fields = (
            self._get_mandatory_product_fields() +
            self._get_optional_product_fields())
        # set data
        if isinstance(data, dict):
            supplierinfo_dic = dict(
                (field_name, data[field_name]) for field_name in
                all_fields if field_name in data)
        else:
            supplierinfo_dic = dict(
                (field_name, getattr(data, field_name)) for field_name in
                all_fields)
        supplierinfo_dic = self._post_prepare_supplierinfo_query(
            supplierinfo_dic, data)
        return supplierinfo_dic

    @http.route([
        '/my/supplier/product/<model("product.supplierinfo"):supplierinfo>',
        '/my/supplier/product/new'
    ], type='http', auth="user", website=True)
    def supplier_info(self, supplierinfo=None, category='', search='', **post):
        if supplierinfo and supplierinfo.name != request.env.user.partner_id:
            return request.website.render('website.404')

        values = {
            'search': search,
            'category': category,
            'error': {},
            'user': request.env.user,
        }
        if supplierinfo is None:
            supplierinfo = request.env['product.supplierinfo']
        supplierinfo = supplierinfo.sudo()
        form_vals = self.supplierinfo_field_parse(supplierinfo)
        values.update(self._prepare_render_values(supplierinfo, form_vals))
        return request.website.render(
            "website_product_supplier.product", values)

    def _prepare_render_values(self, supplierinfo, form_vals):
        values = {
            'main_obj': supplierinfo,
            'supplierinfo': form_vals,
            'product': supplierinfo.product_tmpl_id,
            'user': request.env.user,
            'pricelist': supplierinfo.pricelist_ids,
        }
        return values

    @http.route('/my/supplier/product/save/', type='http', auth="user",
                website=True)
    def supplier_info_create(self, **post):
        supplierinfo = request.env['product.supplierinfo'].sudo()
        form_vals = self.supplierinfo_field_parse(post)
        values = self._prepare_render_values(supplierinfo, form_vals)
        values['error'] = self.check_product_form_validate(form_vals)
        if values["error"]:
            return request.website.render(
                "website_product_supplier.product",
                values)

        product_vals = {'name': form_vals.get('product_name')}
        if post.get('ufile', False):
            product_vals.update(
                image=base64.encodestring(post['ufile'].read()))
        product = supplierinfo.product_tmpl_id.create(
            self._prepare_product_values(product_vals))
        form_vals.update({
            'name': request.env.user.partner_id.id,
            'product_tmpl_id': product.id,
            'pricelist_ids': [(0, 0, {
                'min_quantity': post.get('min_quantity', 0.0),
                'price': post.get('price', 0.0)})]
        })
        values['product'] = product
        try:
            supplierinfo = supplierinfo.create(
                self._prepare_supplierinfo_values(
                    supplierinfo, product, form_vals, post))
            values.update({
                'product': product,
                'main_obj': supplierinfo,
                'pricelist': supplierinfo.pricelist_ids
            })
        except:
            values.update(error={'error_name': 'Invalid fields'})
            return request.website.render(
                "website_product_supplier.product",
                values)
        return http.redirect_with_hash(
            '/my/supplier/product/%s' % supplierinfo.id)

    @http.route('/my/supplier/product/save/<model("product.supplierinfo"):supp'
                'lierinfo>', type='http', auth="user", website=True)
    def supplier_info_save(self, supplierinfo=None, **post):
        if supplierinfo.name != request.env.user.partner_id:
            return request.website.render('website.404')
        supplierinfo = supplierinfo.sudo()
        form_vals = self.supplierinfo_field_parse(post)
        values = self._prepare_render_values(supplierinfo, form_vals)
        values['error'] = self.check_product_form_validate(form_vals)
        if values["error"]:
            return request.website.render(
                "website_product_supplier.product",
                values)
        try:
            form_vals.update({
                'pricelist_ids': [(1, supplierinfo.pricelist_ids[0].id, {
                    'min_quantity': post.get('min_quantity', 0.0),
                    'price': post.get('price', 0.0)})]})
            supplierinfo.write(self._prepare_supplierinfo_values(
                supplierinfo, supplierinfo.product_tmpl_id, form_vals, post))
        except:
            values.update(error={'error_name': 'Invalid fields'})
            return request.website.render(
                "website_product_supplier.product",
                values)
        return http.redirect_with_hash(
            '/my/supplier/product/%s' % supplierinfo.id)

    def _prepare_supplierinfo_values(self, supplierinfo, product, vals, post):
        # Hook to rewrite
        return vals

    def _prepare_product_values(self, vals):
        # Hook to rewrite
        return vals

    def _prepare_supplierinfo_list(self, supplierinfo, pager):
        values = {
            'suppliersinfo': supplierinfo,
            'pager': pager,
            'user': request.env.user,
        }
        return values

    def _get_search_domain(self, search=None):
        domain = [('name', '=', request.env.user.partner_id.id)]
        if search:
            for srch in search.split(" "):
                domain += [
                    ('product_name', 'ilike', srch),
                ]
        return domain

    @http.route(['/my/supplier/product/list',
                 '/my/supplier/product/list/page/<int:page>'],
                type='http', auth="user", website=True)
    def supplierinfo_list(self, page=0, **post):
        supplierinfo_obj = request.env['product.supplierinfo']
        domain = self._get_search_domain(post.get('search', ''))
        url = "/my/supplier/product/list_only"
        supplierinfo_count = supplierinfo_obj.search_count(domain)

        pager = request.website.pager(
            url=url, total=supplierinfo_count, page=page, step=PPG, scope=7,
            url_args=post)
        supplierinfo = supplierinfo_obj.search(
            domain, limit=PPG, offset=pager['offset'])

        values = self._prepare_supplierinfo_list(supplierinfo, pager)

        return request.website.render(
            "website_product_supplier.product", values)

    @http.route(['/my/supplier/product/list_only',
                 '/my/supplier/product/list_only/page/<int:page>'],
                type='http', auth="user", website=True)
    def supplier_product_list(self, page=0, **post):
        res = self.supplierinfo_list(page, **post)
        res.template = "website_product_supplier.supplier_product_list"
        return res

    @http.route(['/my/supplier/product/delete'], type='json',
                auth="user", website=True)
    def delete_product(self, supplierinfo_id):
        supplierinfo = request.env['product.supplierinfo'].browse(
            int(supplierinfo_id))
        if len(supplierinfo.product_tmpl_id.seller_ids) == 1:
            res = supplierinfo.product_tmpl_id.unlink()
        else:
            res = supplierinfo.unlink()
        return res

class ProductSupplierWebsiteAccount(WebsiteAccount):

    @http.route(['/my/home'], type='http', auth="user", website=True)
    def account(self, **kw):
        response = super(ProductSupplierWebsiteAccount, self).account(**kw)
        if not request.env.user.partner_id.supplier:
            return response
        supplierinfo_obj = request.env['product.supplierinfo']
        domain = [('name', '=', request.env.user.partner_id.id)]
        supplierinfo = supplierinfo_obj.search(domain, limit=PPG)
        values = {
            'suppliersinfo': supplierinfo,
            'pager': False,
            'user': request.env.user,
        }
        response.qcontext.update(values)
        return response
<|endoftext|>


<commit_before>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import unittest
import vectormath

import properties

class TestDynamic(unittest.TestCase):

    def test_dynamic_getter(self):

        class HasDynamicProperty(properties.HasProperties):
            my_int = properties.Integer('an int')

            @properties.Integer('a dynamic int')
            def my_doubled_int(self):
                if self.my_int is None:
                    raise ValueError('my_doubled_int depends on my_int')
                return self.my_int*2

            @properties.Vector3('a vector')
            def my_vector(self):
                if self.my_int is None:
                    raise ValueError('my_vector depends on my_int')
                val = [float(val) for val in [self.my_int, self.my_int,
                                              self.my_doubled_int]]
                return val

        hdp = HasDynamicProperty()
        with self.assertRaises(ValueError):
            hdp.my_doubled_int
        hdp.my_int = 10
        assert hdp.my_doubled_int == 20
        assert isinstance(hdp.my_vector, vectormath.Vector3)

        with self.assertRaises(AttributeError):
            hdp.my_doubled_int = 50

    def test_dynamic_setter(self):

        class HasDynamicProperty(properties.HasProperties):
            my_float = properties.Float('a float')

            @properties.Integer('a dynamic int')
            def my_doubled_int(self):
                if self.my_float is None:
                    raise ValueError('my_doubled_int depends on my_int')
                return self.my_float*2

            @my_doubled_int.setter
            def my_doubled_int(self, value):
                self.my_float = value/2.

        hdp = HasDynamicProperty()

        with self.assertRaises(ValueError):
            hdp.my_doubled_int = .5

        hdp.my_doubled_int = 10
        assert hdp.my_float == 5.

    def test_dynamic_errors(self):

        with self.assertRaises(TypeError):
            class HasBadDynamicProp(properties.HasProperties):
                @properties.Integer('an int')
                def my_int(self, a, b, c):
                    return a+b+c

        with self.assertRaises(TypeError):
            class HasBadDynamicProp(properties.HasProperties):

                def calc_int(self):
                    return 5
                my_int = properties.basic.DynamicProperty(
                    'my dynamic prop', calc_int, 5
                )

        with self.assertRaises(TypeError):
            class HasBadDynamicProp(properties.HasProperties):

                def calc_int(self):
                    return 5
                my_int = properties.basic.DynamicProperty(
                    'my dynamic prop', 5, properties.Integer('an int')
                )

if __name__ == '__main__':
    unittest.main()
<commit_msg>Expand testing of DynamicProperty<commit_after>from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import unittest
import vectormath

import properties

class TestDynamic(unittest.TestCase):

    def test_dynamic_getter(self):

        class HasDynamicProperty(properties.HasProperties):
            my_int = properties.Integer('an int')

            @properties.Integer('a dynamic int')
            def my_doubled_int(self):
                if self.my_int is None:
                    raise ValueError('my_doubled_int depends on my_int')
                return self.my_int*2

            @properties.Vector3('a vector')
            def my_vector(self):
                if self.my_int is None:
                    raise ValueError('my_vector depends on my_int')
                val = [float(val) for val in [self.my_int, self.my_int,
                                              self.my_doubled_int]]
                return val

        hdp = HasDynamicProperty()
        with self.assertRaises(ValueError):
            hdp.my_doubled_int
        hdp.my_int = 10
        assert hdp.my_doubled_int == 20
        assert isinstance(hdp.my_vector, vectormath.Vector3)

        with self.assertRaises(AttributeError):
            hdp.my_doubled_int = 50

    def test_dynamic_setter(self):

        class HasDynamicProperty(properties.HasProperties):
            my_float = properties.Float('a float')

            @properties.Integer('a dynamic int')
            def my_doubled_int(self):
                if self.my_float is None:
                    raise ValueError('my_doubled_int depends on my_int')
                return self.my_float*2

            @my_doubled_int.setter
            def my_doubled_int(self, value):
                self.my_float = value/2.

        hdp = HasDynamicProperty()

        with self.assertRaises(ValueError):
            hdp.my_doubled_int = .5

        hdp.my_doubled_int = 10
        assert hdp.my_float == 5.

        serialized = hdp.serialize()
        assert 'my_float' in serialized
        assert 'my_doubled_int' not in serialized

        hdp2 = HasDynamicProperty.deserialize(serialized)
        assert hdp2.my_float == 5.
        assert hdp2.my_doubled_int == 10

    def test_dynamic_errors(self):

        with self.assertRaises(TypeError):
            class HasBadDynamicProp(properties.HasProperties):
                @properties.Integer('an int')
                def my_int(self, a, b, c):
                    return a+b+c

        with self.assertRaises(TypeError):
            class HasBadDynamicProp(properties.HasProperties):

                def calc_int(self):
                    return 5
                my_int = properties.basic.DynamicProperty(
                    'my dynamic prop', calc_int, 5
                )

        with self.assertRaises(TypeError):
            class HasBadDynamicProp(properties.HasProperties):

                def calc_int(self):
                    return 5
                my_int = properties.basic.DynamicProperty(
                    'my dynamic prop', 5, properties.Integer('an int')
                )

        with self.assertRaises(TypeError):
            class HasDynamicProperty(properties.HasProperties):
                my_float = properties.Float('a float')

                @properties.Integer('a dynamic int')
                def my_doubled_int(self):
                    return self.my_float*2

                @my_doubled_int.setter
                def mdi_setter(self, value):
                    self.my_float = value/2.

        with self.assertRaises(TypeError):
            class HasDynamicProperty(properties.HasProperties):
                my_float = properties.Float('a float')

                @properties.Integer('a dynamic int')
                def my_doubled_int(self):
                    return self.my_float*2

                my_doubled_int.setter(5)

        with self.assertRaises(TypeError):
            class HasDynamicProperty(properties.HasProperties):
                my_float = properties.Float('a float')

                @properties.Integer('a dynamic int')
                def my_doubled_int(self):
                    return self.my_float*2

                @my_doubled_int.setter
                def my_doubled_int(self, value, extra):
                    self.my_float = value/2.

if __name__ == '__main__':
    unittest.main()
<|endoftext|>


<commit_before>import unittest2

from twiggy import filters, message

from . import make_mesg

m = make_mesg()

class msgFilterTestCase(unittest2.TestCase):

    def test_None(self):
        f = filters.msgFilter(None)
        assert callable(f)
        assert f(m)

    def test_bool(self):
        f = filters.msgFilter(True)
        assert callable(f)
        assert f(m)

        f = filters.msgFilter(False)
        assert callable(f)
        assert not f(m)

    def test_basestring(self):
        f = filters.msgFilter("^Hello.*$")
        assert callable(f)
        assert f(m)

        f = filters.msgFilter("^Goodbye.*$")
        assert callable(f)
        assert not f(m)

    def test_callable(self):
        my_func = lambda mesg: True
        f = filters.msgFilter(my_func)
        assert f is my_func

    def test_bad_arg(self):
        with self.assertRaises(ValueError):
            f = filters.msgFilter(42)

class namesTestCase(unittest2.TestCase):

    def test_names(self):
        n = filters.names("foo", "bar")
        assert n.names == ("foo", "bar")

        assert filters.names("jose", "frank")(m)
        assert not filters.names("bob", "frank")(m)

    def test_glob_names(self):
        n = filters.glob_names("foo", "bar")
        assert n.names == ("foo", "bar")

        assert filters.glob_names("jo*", "frank")(m)
        assert not filters.glob_names("*bob", "frank")(m)
<commit_msg>full test coverage for filters module<commit_after>import unittest2

import re

from twiggy import filters, message, levels

from . import make_mesg

m = make_mesg()

class msgFilterTestCase(unittest2.TestCase):

    # XXX more robust testing of the exact type/func.__name__ of the returned f
    # might be nice (instead of just callable), but eh.

    def test_None(self):
        f = filters.msgFilter(None)
        assert callable(f)
        assert f(m)

    def test_bool(self):
        f = filters.msgFilter(True)
        assert callable(f)
        assert f(m)

        f = filters.msgFilter(False)
        assert callable(f)
        assert not f(m)

    def test_basestring(self):
        f = filters.msgFilter("^Hello.*$")
        assert callable(f)
        assert f(m)

        f = filters.msgFilter("^Goodbye.*$")
        assert callable(f)
        assert not f(m)

    def test_regex(self):
        f = filters.msgFilter(re.compile("^Hello.*$"))
        assert callable(f)
        assert f(m)

        f = filters.msgFilter(re.compile("^Goodbye.*$"))
        assert callable(f)
        assert not f(m)

    def test_callable(self):
        my_func = lambda mesg: True
        f = filters.msgFilter(my_func)
        assert f is my_func

    def test_bad_arg(self):
        with self.assertRaises(ValueError):
            f = filters.msgFilter(42)

class namesTestCase(unittest2.TestCase):

    def test_names(self):
        n = filters.names("foo", "bar")
        assert n.names == ("foo", "bar")

        assert filters.names("jose", "frank")(m)
        assert not filters.names("bob", "frank")(m)

    def test_glob_names(self):
        n = filters.glob_names("foo", "bar")
        assert n.names == ("foo", "bar")

        assert filters.glob_names("jo*", "frank")(m)
        assert not filters.glob_names("*bob", "frank")(m)

class EmitterTestCase(unittest2.TestCase):

    def test_bad_min_level(self):
        with self.assertRaises(ValueError):
            filters.Emitter(42, None, None)

    def test_filter_property(self):
        # XXX we really should mock & test that msgFilter is being called. eh.

        e = filters.Emitter(levels.INFO, "^Hello.*$", 'output-unused')

        f = e.filter
        assert callable(f)
        assert f(m)

        e.filter = "^Goodbye.*$"
        f = e.filter
        assert callable(f)
        assert not f(m)
<|endoftext|>


<commit_before>'''
Created on 16.04.15

@author = mharder
'''

from __future__ import division, print_function
from bonfire.formats import tail_format, dump_format
from bonfire.graylog_api import Message

def test_dump_format():
    formatter = dump_format(["a", "b", "c"])

    assert formatter(Message({"message": {}})) == "'';'';''"
    assert formatter(Message({"message": {"a": "d"}})) == "'d';'';''"
    assert formatter(Message({"message": {"a": "d", "b": "e", "c": "f"}})) == "'d';'e';'f'"
    assert formatter(Message({"message": {"a": "d", "b": "e", "c": "f", "g": "h"}})) == "'d';'e';'f'"<commit_msg>Added tests for formatters<commit_after>'''
Created on 16.04.15

@author = mharder
'''

from __future__ import division, print_function
from bonfire.formats import tail_format, dump_format
from bonfire.graylog_api import Message
import arrow

def test_dump_format():
    formatter = dump_format(["a", "b", "c"])

    assert formatter(Message({"message": {}})) == "'';'';''"
    assert formatter(Message({"message": {"a": "d"}})) == "'d';'';''"
    assert formatter(Message({"message": {"a": "d", "b": "e", "c": "f"}})) == "'d';'e';'f'"
    assert formatter(Message({"message": {"a": "d", "b": "e", "c": "f", "g": "h"}})) == "'d';'e';'f'"

def test_tail_format():
    formatter = tail_format(["source", "facility", "line", "module"])
    run_tail_test_with_formatter(formatter)

    formatter = tail_format(["source", "facility", "line", "module", "message"])
    run_tail_test_with_formatter(formatter)

def run_tail_test_with_formatter(formatter):
    ts = arrow.get()

    message = {
        "message": "Hallo World",
        "source": "a",
        "level": 2,
        "facility": "b",
        "line": 10,
        "module": "c",
        "timestamp": ts
    }

    result = "\x1b[41m\x1b[37mCRITICAL[{}] Hallo World # source:a; facility:b; line:10; module:c\x1b[0m".format(
        ts.to('local').format("YYYY-MM-DD HH:mm:ss.SS")
    )

    assert formatter(Message({"message": message})) == result

    message["level"] = 3
    result = "\x1b[31mERROR   [{}] Hallo World # source:a; facility:b; line:10; module:c\x1b[0m".format(
        ts.to('local').format("YYYY-MM-DD HH:mm:ss.SS")
    )
    assert formatter(Message({"message": message})) == result

    message["level"] = 4
    result = "\x1b[33mWARNING [{}] Hallo World # source:a; facility:b; line:10; module:c\x1b[0m".format(
        ts.to('local').format("YYYY-MM-DD HH:mm:ss.SS")
    )
    assert formatter(Message({"message": message})) == result

    message["level"] = 5
    result = "\x1b[32mNOTICE  [{}] Hallo World # source:a; facility:b; line:10; module:c\x1b[0m".format(
        ts.to('local').format("YYYY-MM-DD HH:mm:ss.SS")
    )
    assert formatter(Message({"message": message})) == result

    message["level"] = 6
    result = "\x1b[32mINFO    [{}] Hallo World # source:a; facility:b; line:10; module:c\x1b[0m".format(
        ts.to('local').format("YYYY-MM-DD HH:mm:ss.SS")
    )
    assert formatter(Message({"message": message})) == result

    message["level"] = 7
    result = "\x1b[34mDEBUG   [{}] Hallo World # source:a; facility:b; line:10; module:c\x1b[0m".format(
        ts.to('local').format("YYYY-MM-DD HH:mm:ss.SS")
    )
    assert formatter(Message({"message": message})) == result<|endoftext|>


<commit_before>from hypothesis import (
    example,
    given,
    strategies as st,
)
import pytest

from eth_abi.exceptions import (
    ABITypeError,
    ParseError,
)
from eth_abi.grammar import (
    TYPE_ALIASES,
    BasicType,
    TupleType,
    normalize,
    parse,
)

from .common.strategies import (
    malformed_type_strs,
    type_strs,
)

@pytest.mark.parametrize(
    'type_str, expected_type',
    (
        ('uint', BasicType('uint')),
        ('uint256', BasicType('uint', 256)),
        ('uint256[]', BasicType('uint', 256, ((),))),
        ('uint256[][1][23][]', BasicType('uint', 256, ((), (1,), (23,), ()))),
        ('uint[]', BasicType('uint', None, ((),))),
        ('int[2]', BasicType('int', None, ((2,),))),
        ('fixed128x19', BasicType('fixed', (128, 19))),
        ('ufixed128x19[][]', BasicType('ufixed', (128, 19), ((), ()))),
        (
            '(int,ufixed128x19[][])',
            TupleType((
                BasicType('int'),
                BasicType('ufixed', (128, 19), ((), ())),
            )),
        ),
        (
            '(int,(address,function))',
            TupleType((
                BasicType('int'),
                TupleType((
                    BasicType('address'),
                    BasicType('function'),
                )),
            )),
        ),
        (
            '((address,(fixed,bool)),(uint256[][1][],fixed128x19))',
            TupleType((
                TupleType((
                    BasicType('address'),
                    TupleType((
                        BasicType('fixed'),
                        BasicType('bool'),
                    )),
                )),
                TupleType((
                    BasicType('uint', 256, ((), (1,), ())),
                    BasicType('fixed', (128, 19)),
                )),
            )),
        ),
        ('()', TupleType(tuple())),
        (
            '(int,(),())',
            TupleType((BasicType('int'), TupleType(tuple()), TupleType(tuple()))),
        ),
    )
)
def test_parsing_with_parsimonious_grammar_and_node_visitor_works(type_str, expected_type):
    assert parse(type_str) == expected_type

@given(malformed_type_strs, st.none())
@example('int0', 4)
@example('fixed128x0', 9)
@example('ufixed128x0', 10)
@example('int!', 4)
@example('(int, bool)', 6)
@example('(int,bool,)', 11)
@example('(int,(address,uint256[][])', 27)
def test_parsing_invalid_type_str_causes_parse_error(type_str, error_col):
    if error_col is not None:
        pattern = r'Parse error at .* \(column {}\)'.format(error_col)
    else:
        pattern = r'Parse error at .*'

    with pytest.raises(ParseError, match=pattern):
        parse(type_str)

def test_parse_raises_type_error_for_wrong_data_type():
    with pytest.raises(TypeError):
        parse(b'uint256')

@given(type_strs)
def test_end_to_end_parsing_and_collapsing(type_str):
    assert str(parse(type_str)) == type_str

@pytest.mark.parametrize(
    'type_str, pattern',
    (
        ('string1x1', 'string type cannot have suffix'),
        ('string33', 'string type cannot have suffix'),
        ('bytes1x1', 'no suffix or a numerical'),
        ('bytes33', 'maximum 32 bytes'),
        ('int', 'must have numerical suffix'),
        ('int7', 'size out of bounds'),
        ('int257', 'size out of bounds'),
        ('int9', 'must be multiple of 8'),
        ('uint', 'must have numerical suffix'),
        ('uint7', 'size out of bounds'),
        ('uint257', 'size out of bounds'),
        ('uint9', 'must be multiple of 8'),
        ('fixed', 'must have suffix of form'),
        ('fixed8', 'must have suffix of form'),
        ('fixed7x19', 'fixed size out of bounds'),
        ('fixed257x19', 'fixed size out of bounds'),
        ('fixed17x19', 'must be multiple of 8'),
        ('fixed128x81', 'exponent size out of bounds'),
        ('ufixed', 'must have suffix of form'),
        ('ufixed8', 'must have suffix of form'),
        ('ufixed7x19', 'fixed size out of bounds'),
        ('ufixed257x19', 'fixed size out of bounds'),
        ('ufixed17x19', 'must be multiple of 8'),
        ('ufixed128x81', 'exponent size out of bounds'),
        ('hash', 'must have numerical suffix'),
        ('hash128x128', 'must have numerical suffix'),
        ('address128', 'cannot have suffix'),
        ('address128x128', 'cannot have suffix'),
        (
            '(int256,(address,(ufixed7x19,fixed)))',
            "For 'ufixed7x19' type at column 19 "
            r"in '\(int256,\(address,\(ufixed7x19,fixed\)\)\)': "
            "fixed size out of bounds",
        ),
        (
            '(int256,(address,(ufixed128x19,fixed)))',
            "For 'fixed' type at column 32 "
            r"in '\(int256,\(address,\(ufixed128x19,fixed\)\)\)': "
            "fixed type must have suffix of form",
        ),
    )
)
def test_invalid_abi_types(type_str, pattern):
    with pytest.raises(ABITypeError, match=pattern):
        parse(type_str).validate()

@pytest.mark.parametrize(
    'type_str',
    (
        'string',
        'bytes24',
        'int256',
        'uint128',
        'fixed128x19',
        'ufixed256x19',
        'hash256',
        'address',
        '(int256,(address,(ufixed128x19,fixed128x19)))',
    )
)
def test_valid_abi_types(type_str):
    parse(type_str).validate()

@pytest.mark.parametrize(
    'type_str, normalized',
    tuple(TYPE_ALIASES.items()) + (
        ('(int,uint,fixed,ufixed)', '(int256,uint256,fixed128x18,ufixed128x18)'),
        ('(function,function,function)', '(bytes24,bytes24,bytes24)'),
    ),
)
def test_normalize(type_str, normalized):
    assert normalize(type_str) == normalized

def test_basic_type_item_type_throws_errors():
    bt = parse('int256')

    pattern = "Cannot determine item type for non-array type 'int256'"
    with pytest.raises(ValueError, match=pattern):
        bt.item_type
<commit_msg>Add more parsing tests<commit_after>from hypothesis import (
    example,
    given,
    strategies as st,
)
import pytest

from eth_abi.exceptions import (
    ABITypeError,
    ParseError,
)
from eth_abi.grammar import (
    TYPE_ALIASES,
    BasicType,
    TupleType,
    normalize,
    parse,
)

from .common.strategies import (
    malformed_type_strs,
    type_strs,
)

@pytest.mark.parametrize(
    'type_str, expected_type',
    (
        ('uint', BasicType('uint')),
        ('uint256', BasicType('uint', 256)),
        ('uint256[]', BasicType('uint', 256, ((),))),
        ('uint256[][1][23][]', BasicType('uint', 256, ((), (1,), (23,), ()))),
        ('uint[]', BasicType('uint', None, ((),))),
        ('int[2]', BasicType('int', None, ((2,),))),
        ('fixed128x19', BasicType('fixed', (128, 19))),
        ('ufixed128x19[][]', BasicType('ufixed', (128, 19), ((), ()))),
        (
            '(int,ufixed128x19[][])',
            TupleType((
                BasicType('int'),
                BasicType('ufixed', (128, 19), ((), ())),
            )),
        ),
        (
            '(int,(address,function))',
            TupleType((
                BasicType('int'),
                TupleType((
                    BasicType('address'),
                    BasicType('function'),
                )),
            )),
        ),
        (
            '((address,(fixed,bool)),(uint256[][1][],fixed128x19))',
            TupleType((
                TupleType((
                    BasicType('address'),
                    TupleType((
                        BasicType('fixed'),
                        BasicType('bool'),
                    )),
                )),
                TupleType((
                    BasicType('uint', 256, ((), (1,), ())),
                    BasicType('fixed', (128, 19)),
                )),
            )),
        ),
        ('()', TupleType(tuple())),
        (
            '(int,(),())',
            TupleType((BasicType('int'), TupleType(tuple()), TupleType(tuple()))),
        ),
    )
)
def test_parsing_with_parsimonious_grammar_and_node_visitor_works(type_str, expected_type):
    assert parse(type_str) == expected_type

@pytest.mark.parametrize(
    'type_str, expected_type',
    (
        ('uint', BasicType('uint', 256)),
        ('uint256[]', BasicType('uint', 256, ((),))),
        ('function', BasicType('bytes', 24)),
        ('fixed', BasicType('fixed', (128, 18))),
        ('ufixed', BasicType('ufixed', (128, 18))),
    )
)
def test_normalizing_and_parsing_works(type_str, expected_type):
    assert parse(normalize(type_str)) == expected_type

@given(malformed_type_strs, st.none())
@example('int0', 4)
@example('fixed128x0', 9)
@example('ufixed128x0', 10)
@example('int!', 4)
@example('(int, bool)', 6)
@example('(int,bool,)', 11)
@example('(int,(address,uint256[][])', 27)
def test_parsing_invalid_type_str_causes_parse_error(type_str, error_col):
    if error_col is not None:
        pattern = r'Parse error at .* \(column {}\)'.format(error_col)
    else:
        pattern = r'Parse error at .*'

    with pytest.raises(ParseError, match=pattern):
        parse(type_str)

def test_parse_raises_type_error_for_wrong_data_type():
    with pytest.raises(TypeError):
        parse(b'uint256')

@given(type_strs)
def test_end_to_end_parsing_and_collapsing(type_str):
    assert str(parse(type_str)) == type_str

@pytest.mark.parametrize(
    'type_str, pattern',
    (
        ('string1x1', 'string type cannot have suffix'),
        ('string33', 'string type cannot have suffix'),
        ('bytes1x1', 'no suffix or a numerical'),
        ('bytes33', 'maximum 32 bytes'),
        ('int', 'must have numerical suffix'),
        ('int7', 'size out of bounds'),
        ('int257', 'size out of bounds'),
        ('int9', 'must be multiple of 8'),
        ('uint', 'must have numerical suffix'),
        ('uint7', 'size out of bounds'),
        ('uint257', 'size out of bounds'),
        ('uint9', 'must be multiple of 8'),
        ('fixed', 'must have suffix of form'),
        ('fixed8', 'must have suffix of form'),
        ('fixed7x19', 'fixed size out of bounds'),
        ('fixed257x19', 'fixed size out of bounds'),
        ('fixed17x19', 'must be multiple of 8'),
        ('fixed128x81', 'exponent size out of bounds'),
        ('ufixed', 'must have suffix of form'),
        ('ufixed8', 'must have suffix of form'),
        ('ufixed7x19', 'fixed size out of bounds'),
        ('ufixed257x19', 'fixed size out of bounds'),
        ('ufixed17x19', 'must be multiple of 8'),
        ('ufixed128x81', 'exponent size out of bounds'),
        ('hash', 'must have numerical suffix'),
        ('hash128x128', 'must have numerical suffix'),
        ('address128', 'cannot have suffix'),
        ('address128x128', 'cannot have suffix'),
        (
            '(int256,(address,(ufixed7x19,fixed)))',
            "For 'ufixed7x19' type at column 19 "
            r"in '\(int256,\(address,\(ufixed7x19,fixed\)\)\)': "
            "fixed size out of bounds",
        ),
        (
            '(int256,(address,(ufixed128x19,fixed)))',
            "For 'fixed' type at column 32 "
            r"in '\(int256,\(address,\(ufixed128x19,fixed\)\)\)': "
            "fixed type must have suffix of form",
        ),
    )
)
def test_invalid_abi_types(type_str, pattern):
    with pytest.raises(ABITypeError, match=pattern):
        parse(type_str).validate()

@pytest.mark.parametrize(
    'type_str',
    (
        'string',
        'bytes24',
        'int256',
        'uint128',
        'fixed128x19',
        'ufixed256x19',
        'hash256',
        'address',
        '(int256,(address,(ufixed128x19,fixed128x19)))',
    )
)
def test_valid_abi_types(type_str):
    parse(type_str).validate()

@pytest.mark.parametrize(
    'type_str, normalized',
    tuple(TYPE_ALIASES.items()) + (
        ('(int,uint,fixed,ufixed)', '(int256,uint256,fixed128x18,ufixed128x18)'),
        ('(function,function,function)', '(bytes24,bytes24,bytes24)'),
    ),
)
def test_normalize(type_str, normalized):
    assert normalize(type_str) == normalized

def test_basic_type_item_type_throws_errors():
    bt = parse('int256')

    pattern = "Cannot determine item type for non-array type 'int256'"
    with pytest.raises(ValueError, match=pattern):
        bt.item_type
<|endoftext|>


<commit_before>import sys
import os
import pytest
import tempfile
import pyethereum.indexdb
import pyethereum.utils
import pyethereum.db

tempdir = tempfile.mktemp()

def act(num):
    return pyethereum.utils.sha3(str(num)).encode('hex')[:40]

def mktx(a, b):
    return 'tx(%d,%d)' % (a, b)

@pytest.fixture(scope="module")
def mkindex():
    idx = pyethereum.indexdb.AccountTxIndex()
    idx.db = pyethereum.db.DB(tempfile.mktemp())
    return idx

def test_adding():
    acct = act(10000)
    acct2 = act(10000)
    tx0 = mktx(0, 0)
    tx1 = mktx(0, 1)
    tx2 = mktx(0, 2)
    tx3 = mktx(0, 3)

    idx = mkindex()

    idx.add_transaction(acct, 0, tx0)
    idx.db.commit()
    txs = list(idx.get_transactions(acct, offset=0))
    assert txs == [tx0]

    idx.add_transaction(acct2, 0, tx0)
    idx.db.commit()
    txs = list(idx.get_transactions(acct2, offset=0))
    assert txs == [tx0]

    idx.add_transaction(acct, 1, tx1)
    idx.db.commit()
    txs = list(idx.get_transactions(acct, offset=0))
    assert txs == [tx0, tx1]

    idx.add_transaction(acct, 2, tx2)
    idx.db.commit()
    txs = list(idx.get_transactions(acct, offset=0))
    assert txs == [tx0, tx1, tx2]

    idx.add_transaction(acct, 3, tx3)
    idx.db.commit()
    txs = list(idx.get_transactions(acct, offset=0))
    assert txs == [tx0, tx1, tx2, tx3]

    txs = list(idx.get_transactions(acct, offset=2))
    assert txs == [tx2, tx3]

    # delete transaction
    for keep in reversed(range(4)):
        idx.delete_transactions(acct, offset=keep)
        idx.db.commit()
        txs = list(idx.get_transactions(acct, offset=0))
        assert txs == [tx0, tx1, tx2, tx3][:keep]

def test_multiple_accounts():
    idx = mkindex()

    NUM_ACCOUNTS = 20

    for i in range(NUM_ACCOUNTS)[1:]:
        acct = act(i)
        for j in range(i * 5):
            idx.add_transaction(acct, j, mktx(i, j))
        idx.db.commit()
        txs = list(idx.get_transactions(acct, offset=0))
        assert len(txs) == j + 1
        for j in range(i * 5):
            tx = mktx(i, j)
            assert tx == txs[j]
        for j in range(i * 5):
            tx = mktx(i, j)
            txs = list(idx.get_transactions(acct, offset=j))
            assert tx == txs[0]

    assert len(
        set(list(idx.get_accounts(account_from='')))) == NUM_ACCOUNTS - 1

def test_num_transactions():
    idx = mkindex()
    acct = act(4200000)
    assert idx.num_transactions(acct) == 0

    for j in range(50):
        idx.add_transaction(acct, j, mktx(j, j))
        assert idx.num_transactions(acct) == j + 1

    idx.delete_transactions(acct, offset=5)
    assert idx.num_transactions(acct) == 5
<commit_msg>test for append<commit_after>import sys
import os
import pytest
import tempfile
import pyethereum.indexdb
import pyethereum.utils
import pyethereum.db

tempdir = tempfile.mktemp()

def act(num):
    return pyethereum.utils.sha3(str(num)).encode('hex')[:40]

def mktx(a, b):
    return 'tx(%d,%d)' % (a, b)

@pytest.fixture(scope="module")
def mkindex():
    idx = pyethereum.indexdb.AccountTxIndex()
    idx.db = pyethereum.db.DB(tempfile.mktemp())
    return idx

def test_appending():
    idx = pyethereum.indexdb.Index('namespace')
    key = 'key'
    vals = ['v0', 'v1']
    for v in vals:
        idx.append(key, v)
    assert idx.num_values(key) == 2
    assert list(idx.get(key)) == vals

def test_adding():
    acct = act(10000)
    acct2 = act(10000)
    tx0 = mktx(0, 0)
    tx1 = mktx(0, 1)
    tx2 = mktx(0, 2)
    tx3 = mktx(0, 3)

    idx = mkindex()

    idx.add_transaction(acct, 0, tx0)
    idx.db.commit()
    txs = list(idx.get_transactions(acct, offset=0))
    assert txs == [tx0]

    idx.add_transaction(acct2, 0, tx0)
    idx.db.commit()
    txs = list(idx.get_transactions(acct2, offset=0))
    assert txs == [tx0]

    idx.add_transaction(acct, 1, tx1)
    idx.db.commit()
    txs = list(idx.get_transactions(acct, offset=0))
    assert txs == [tx0, tx1]

    idx.add_transaction(acct, 2, tx2)
    idx.db.commit()
    txs = list(idx.get_transactions(acct, offset=0))
    assert txs == [tx0, tx1, tx2]

    idx.add_transaction(acct, 3, tx3)
    idx.db.commit()
    txs = list(idx.get_transactions(acct, offset=0))
    assert txs == [tx0, tx1, tx2, tx3]

    txs = list(idx.get_transactions(acct, offset=2))
    assert txs == [tx2, tx3]

    # delete transaction
    for keep in reversed(range(4)):
        idx.delete_transactions(acct, offset=keep)
        idx.db.commit()
        txs = list(idx.get_transactions(acct, offset=0))
        assert txs == [tx0, tx1, tx2, tx3][:keep]

def test_multiple_accounts():
    idx = mkindex()

    NUM_ACCOUNTS = 20

    for i in range(NUM_ACCOUNTS)[1:]:
        acct = act(i)
        for j in range(i * 5):
            idx.add_transaction(acct, j, mktx(i, j))
        idx.db.commit()
        txs = list(idx.get_transactions(acct, offset=0))
        assert len(txs) == j + 1
        for j in range(i * 5):
            tx = mktx(i, j)
            assert tx == txs[j]
        for j in range(i * 5):
            tx = mktx(i, j)
            txs = list(idx.get_transactions(acct, offset=j))
            assert tx == txs[0]

    assert len(
        set(list(idx.get_accounts(account_from='')))) == NUM_ACCOUNTS - 1

def test_num_transactions():
    idx = mkindex()
    acct = act(4200000)
    assert idx.num_transactions(acct) == 0

    for j in range(50):
        idx.add_transaction(acct, j, mktx(j, j))
        assert idx.num_transactions(acct) == j + 1

    idx.delete_transactions(acct, offset=5)
    assert idx.num_transactions(acct) == 5
<|endoftext|>


<commit_before>from unittest import TestCase
import unittest
from equadratures.poly import Poly
from equadratures.sampling_methods.induced import Induced
from equadratures.parameter import Parameter
from equadratures.basis import Basis
import numpy as np
import time

class TestSamplingGeneration(TestCase):
    def test_sampling(self):
        d = 3
        order = 3
        param = Parameter(distribution='uniform', order=order, lower=-1.0, upper=1.0)
        myparameters = [param for _ in range(d)]
        mybasis2 = Basis('total-order')
        mypoly2 = Poly(myparameters, mybasis2, method='least-squares', sampling_args={'mesh':'induced', 'subsampling-algorithm':'qr', 'sampling-ratio':1.0})
        assert mypoly2._quadrature_points.shape == (mypoly2.basis.cardinality, d)

    def test_induced_jacobi_evaluation(self):
        dimension = 3
        parameters = [Parameter(1, "Uniform", upper=1, lower=-1)]*dimension
        basis = Basis("total-order")
        induced_sampling = Induced(parameters, basis)
        parameter = parameters[0]
        parameter.order = 3
        cdf_value = induced_sampling.induced_jacobi_evaluation(0, 0, 0, parameter)
        np.testing.assert_allclose(cdf_value, 0.5, atol=0.00001)
        cdf_value = induced_sampling.induced_jacobi_evaluation(0, 0, 1, parameter)
        assert cdf_value == 1
        cdf_value = induced_sampling.induced_jacobi_evaluation(0, 0, -1, parameter)
        assert cdf_value == 0
        cdf_value = induced_sampling.induced_jacobi_evaluation(0, 0, 0.6, parameter)
        np.testing.assert_allclose(cdf_value, 0.7462, atol=0.00005)
        cdf_value = induced_sampling.induced_jacobi_evaluation(0, 0, 0.999, parameter)
        np.testing.assert_allclose(cdf_value, 0.99652, atol=0.000005)

if __name__ == '__main__':
    unittest.main()
<commit_msg>remove test_induced print statement<commit_after>from unittest import TestCase
import unittest
from equadratures.poly import Poly
from equadratures.sampling_methods.induced import Induced
from equadratures.parameter import Parameter
from equadratures.basis import Basis
import numpy as np
# import time

class TestSamplingGeneration(TestCase):
    def test_sampling(self):
        d = 3
        order = 3
        param = Parameter(distribution='uniform', order=order, lower=-1.0, upper=1.0)
        myparameters = [param for _ in range(d)]
        mybasis2 = Basis('total-order')
        mypoly2 = Poly(myparameters, mybasis2, method='least-squares', sampling_args={'mesh':'induced', 'subsampling-algorithm':'qr', 'sampling-ratio':1.0})
        assert mypoly2._quadrature_points.shape == (mypoly2.basis.cardinality, d)

    def test_induced_jacobi_evaluation(self):
        dimension = 3
        parameters = [Parameter(1, "Uniform", upper=1, lower=-1)]*dimension
        basis = Basis("total-order")
        induced_sampling = Induced(parameters, basis)
        parameter = parameters[0]
        parameter.order = 3
        cdf_value = induced_sampling.induced_jacobi_evaluation(0, 0, 0, parameter)
        np.testing.assert_allclose(cdf_value, 0.5, atol=0.00001)
        cdf_value = induced_sampling.induced_jacobi_evaluation(0, 0, 1, parameter)
        assert cdf_value == 1
        cdf_value = induced_sampling.induced_jacobi_evaluation(0, 0, -1, parameter)
        assert cdf_value == 0
        cdf_value = induced_sampling.induced_jacobi_evaluation(0, 0, 0.6, parameter)
        np.testing.assert_allclose(cdf_value, 0.7462, atol=0.00005)
        cdf_value = induced_sampling.induced_jacobi_evaluation(0, 0, 0.999, parameter)
        np.testing.assert_allclose(cdf_value, 0.99652, atol=0.000005)

if __name__ == '__main__':
    unittest.main()
<|endoftext|>


<commit_before>from pecan.jsonify  import jsonify, encode
from pecan          import Pecan, expose
from webtest        import TestApp
from simplejson     import loads

def make_person():
    class Person(object):
        def __init__(self, first_name, last_name):
            self.first_name = first_name
            self.last_name = last_name

        @property
        def name(self):
            return '%s %s' % (self.first_name, self.last_name)
    return Person

def test_simple_rule():
    Person = make_person()

    # create a Person instance
    p = Person('Jonathan', 'LaCour')

    # register a generic JSON rule
    @jsonify.when_type(Person)
    def jsonify_person(obj):
        return dict(
            name=obj.name
        )

    # encode the object using our new rule
    result = loads(encode(p))
    assert result['name'] == 'Jonathan LaCour'
    assert len(result) == 1

class TestJsonify(object):

    def test_simple_jsonify(self):
        Person = make_person()

        # register a generic JSON rule
        @jsonify.when_type(Person)
        def jsonify_person(obj):
            return dict(
                name=obj.name
            )

        class RootController(object):
            @expose('json')
            def index(self):
                # create a Person instance
                p = Person('Jonathan', 'LaCour')
                return p

        app = TestApp(Pecan(RootController()))

        r = app.get('/')
        assert r.status_int == 200
        assert loads(r.body) == {'name':'Jonathan LaCour'}<commit_msg>the jsonify test was breaking because it imported from simplejson instead of json that should be installed via setup.py at build time.<commit_after>from pecan.jsonify  import jsonify, encode
from pecan          import Pecan, expose
from webtest        import TestApp
from json           import loads

def make_person():
    class Person(object):
        def __init__(self, first_name, last_name):
            self.first_name = first_name
            self.last_name = last_name

        @property
        def name(self):
            return '%s %s' % (self.first_name, self.last_name)
    return Person

def test_simple_rule():
    Person = make_person()

    # create a Person instance
    p = Person('Jonathan', 'LaCour')

    # register a generic JSON rule
    @jsonify.when_type(Person)
    def jsonify_person(obj):
        return dict(
            name=obj.name
        )

    # encode the object using our new rule
    result = loads(encode(p))
    assert result['name'] == 'Jonathan LaCour'
    assert len(result) == 1

class TestJsonify(object):

    def test_simple_jsonify(self):
        Person = make_person()

        # register a generic JSON rule
        @jsonify.when_type(Person)
        def jsonify_person(obj):
            return dict(
                name=obj.name
            )

        class RootController(object):
            @expose('json')
            def index(self):
                # create a Person instance
                p = Person('Jonathan', 'LaCour')
                return p

        app = TestApp(Pecan(RootController()))

        r = app.get('/')
        assert r.status_int == 200
        assert loads(r.body) == {'name':'Jonathan LaCour'}
<|endoftext|>