<commit_before>from __future__ import division

from PyQt4 import QtCore, QtGui

from vistrails.core.db.action import create_action
from vistrails.gui.modules.constant_configuration import ConstantWidgetMixin
from vistrails.gui.modules.module_configure import \
    StandardModuleConfigurationWidget

from .queries import QueryCondition, EqualString, EqualInt

def str_repr(s):
    if isinstance(s, unicode):
        s = (s.replace('\\', '\\\\')
              .replace("'", "\\'")
              .encode('ascii', 'backslashreplace'))
    else:
        s = (s.replace('\\', '\\\\')
              .replace("'", "\\'"))
    return "'%s'" % s

class Metadata(QtGui.QWidget):
    remove = QtCore.pyqtSignal()
    changed = QtCore.pyqtSignal()

    def __init__(self, name, value=None):
        QtGui.QWidget.__init__(self)
        layout = QtGui.QHBoxLayout()
        self.setLayout(layout)

        self.key = QtGui.QLineEdit()
        self.key.setText(name)
        layout.addWidget(self.key, 1)
        self.value = self.value_widget(value)
        layout.addWidget(self.value, 2)

        remove_button = QtGui.QPushButton("Remove port")
        remove_button.setSizePolicy(QtGui.QSizePolicy.Fixed,
                                    QtGui.QSizePolicy.Fixed)
        layout.addWidget(remove_button)

        self.connect(remove_button, QtCore.SIGNAL('clicked()'),
                     self.remove)
        self.connect(self.key, QtCore.SIGNAL('textEdited(const QString &)'),
                     self.changed)
        self.connect(self.value, QtCore.SIGNAL('textEdited(const QString &)'),
                     self.changed)

class StringMetadata(Metadata):
    @staticmethod
    def value_widget(value=None):
        return QtGui.QLineEdit(value)

    def to_string(self):
        return 'EqualString(%s, %s)' % (str_repr(self.key.text()),
                                        str_repr(self.value.text()))

class IntMetadata(Metadata):
    def value_widget(self, value=None):
        w = QtGui.QLineEdit()
        if value is not None:
            w.setText('%d' % value)
        w.setValidator(QtGui.QIntValidator(self))
        return w

    def to_string(self):
        try:
            i = int(self.value.text())
        except ValueError:
            i = 0
        return 'EqualInt(%s, %d)' % (str_repr(self.key.text()), i)

class SetMetadataWidget(StandardModuleConfigurationWidget):
    """
    Configuration widget allowing to set metadata on persisted modules.

    It is a visual editor for the strings functions set on the 'metadata' port,
    which have the form EqualString('mkey', 'mvalue') or EqualInt('mkey', 2).
    """
    def __init__(self, module, controller, parent=None):
        StandardModuleConfigurationWidget.__init__(self, module,
                                                   controller, parent)

        # Window title
        self.setWindowTitle("Metadata editor")

        central_layout = QtGui.QVBoxLayout()
        central_layout.setMargin(0)
        central_layout.setSpacing(0)
        self.setLayout(central_layout)

        self._scroll_area = QtGui.QScrollArea()
        inner_widget = QtGui.QWidget()
        self._list_layout = QtGui.QVBoxLayout()
        scroll_layout = QtGui.QVBoxLayout()
        scroll_layout.addLayout(self._list_layout)
        scroll_layout.addStretch()
        inner_widget.setLayout(scroll_layout)
        self._scroll_area.setVerticalScrollBarPolicy(
                QtCore.Qt.ScrollBarAlwaysOn)
        self._scroll_area.setWidget(inner_widget)
        self._scroll_area.setWidgetResizable(True)
        central_layout.addWidget(self._scroll_area)

        add_buttons = QtGui.QHBoxLayout()
        central_layout.addLayout(add_buttons)
        add_string = QtGui.QPushButton("Add a string")
        self.connect(add_string, QtCore.SIGNAL('clicked()'),
                     self.add_string)
        add_buttons.addWidget(add_string, 2)
        add_int = QtGui.QPushButton("Add an integer")
        self.connect(add_int, QtCore.SIGNAL('clicked()'),
                     self.add_int)
        add_buttons.addWidget(add_int, 1)

        self.createButtons()

        self.createEntries()

    def add_item(self, item):
        self._list_layout.addWidget(item)
        self.connect(item, QtCore.SIGNAL('remove()'),
                     lambda: item.deleteLater())
        self.connect(item, QtCore.SIGNAL('changed()'),
                     self.updateState)

    def add_string(self):
        self.add_item(StringMetadata(
                "string%d" % (self._list_layout.count() + 1)))
        self.updateState()

    def add_int(self):
        self.add_item(IntMetadata(
                "int%d" % (self._list_layout.count() + 1)))
        self.updateState()

    def createButtons(self):
        """ createButtons() -> None
        Create and connect signals to Ok & Cancel button

        """
        buttonLayout = QtGui.QHBoxLayout()
        buttonLayout.setMargin(5)
        self.saveButton = QtGui.QPushButton("&Save", self)
        self.saveButton.setFixedWidth(100)
        self.saveButton.setEnabled(False)
        buttonLayout.addWidget(self.saveButton)
        self.resetButton = QtGui.QPushButton("&Reset", self)
        self.resetButton.setFixedWidth(100)
        self.resetButton.setEnabled(False)
        buttonLayout.addWidget(self.resetButton)
        self.layout().addLayout(buttonLayout)
        self.connect(self.saveButton, QtCore.SIGNAL('clicked(bool)'),
                     self.saveTriggered)
        self.connect(self.resetButton, QtCore.SIGNAL('clicked(bool)'),
                     self.resetTriggered)

    def saveTriggered(self, checked = False):
        """ saveTriggered(checked: bool) -> None
        Update vistrail controller and module when the user click Ok

        """
        if self.updateVistrail():
            self.saveButton.setEnabled(False)
            self.resetButton.setEnabled(False)
            self.state_changed = False
            self.emit(QtCore.SIGNAL('stateChanged'))
            self.emit(QtCore.SIGNAL('doneConfigure'), self.module.id)

    def closeEvent(self, event):
        self.askToSaveChanges()
        event.accept()

    def updateVistrail(self):
        """ updateVistrail() -> None
        Update functions on the metadata port of the module
        """
        # Remove the keys that we loaded
        ops = [('delete', func) for func in self._loaded_keys]

        # Add the metadata in the list
        for i in xrange(self._list_layout.count()):
            widget = self._list_layout.itemAt(i).widget()
            ops.extend(self.controller.update_function_ops(
                    self.module, 'metadata',
                    [widget.to_string()]))

        # This code should really be in VistrailController
        self.controller.flush_delayed_actions()
        action = create_action(ops)
        self.controller.add_new_action(action,
                                       "Updated PersistedPath metadata")
        self.controller.perform_action(action)

        return True

    def getCurrentFunctions(self):
        for i in xrange(self.module.getNumFunctions()):
            func = self.module.functions[i]
            if func.name == 'metadata':
                yield func, func.params[0].strValue

    def createEntries(self):
        self._loaded_keys = set()
        for func, metadata in self.getCurrentFunctions():
            metadata = QueryCondition.translate_to_python(metadata)
            save = True
            if metadata is None:
                save = False
            elif isinstance(metadata, EqualString):
                self.add_item(StringMetadata(metadata.key, metadata.value))
            elif isinstance(metadata, EqualInt):
                self.add_item(IntMetadata(metadata.key, metadata.value))
            else:
                save = False

            if save:
                self._loaded_keys.add(func)

    def resetTriggered(self, checked = False):
        for i in xrange(self._list_layout.count()):
            self._list_layout.itemAt(i).widget().deleteLater()

        self.createEntries()

        self.saveButton.setEnabled(False)
        self.resetButton.setEnabled(False)
        self.state_changed = False
        self.emit(QtCore.SIGNAL('stateChanged'))

    def updateState(self):
        self.saveButton.setEnabled(True)
        self.resetButton.setEnabled(True)
        if not self.state_changed:
            self.state_changed = True
            self.emit(QtCore.SIGNAL('stateChanged'))

class MetadataConstantWidget(QtGui.QWidget, ConstantWidgetMixin):
    contentsChanged = QtCore.pyqtSignal(tuple)

    def __init__(self, param, parent=None):
        QtGui.QWidget.__init__(self, parent)
        ConstantWidgetMixin.__init__(self, param)

        self._key = QtGui.QLineEdit()
        self.connect(self._key, QtCore.SIGNAL("returnPressed()"),
                     self.update_parent)

        self._type = QtGui.QComboBox()
        self._type.addItems(['int', 'str'])
        self.connect(self._type, QtCore.SIGNAL("currentIndexChanged()"),
                     self.update_parent)

        self._value = QtGui.QLineEdit()
        self.connect(self._value, QtCore.SIGNAL("returnPressed()"),
                     self.update_parent)

        layout = QtGui.QHBoxLayout()
        layout.addWidget(self._key)
        layout.addWidget(self._type)
        layout.addWidget(self._value)
        self.setLayout(layout)

        if param.strValue:
            self.setContents(param.strValue)

    def contents(self):
        if self._type.currentText() == 'int':
            return 'EqualInt(%s, %s)' % (str_repr(self._key.text()),
                                         self._value.text())
        else:  # self._type.currentText() == 'str':
            return 'EqualString(%s, %s)' % (str_repr(self._key.text()),
                                            str_repr(self._value.text()))

    def setContents(self, value, silent=False):
        cond = QueryCondition.translate_to_python(value, text_query=False)
        self._key.setText(cond.key)
        if isinstance(cond, EqualInt):
            self._type.setCurrentIndex(0)
            self._value.setText('%d' % cond.value)
        elif isinstance(cond, EqualString):
            self._type.setCurrentIndex(1)
            self._value.setText(cond.value)
        if not silent:
            self.update_parent()
<commit_msg>Fix MetadataConstantWidget not saving on focus out<commit_after>from __future__ import division

from PyQt4 import QtCore, QtGui

from vistrails.core.db.action import create_action
from vistrails.gui.modules.constant_configuration import ConstantWidgetBase
from vistrails.gui.modules.module_configure import \
    StandardModuleConfigurationWidget

from .queries import QueryCondition, EqualString, EqualInt

def str_repr(s):
    if isinstance(s, unicode):
        s = (s.replace('\\', '\\\\')
              .replace("'", "\\'")
              .encode('ascii', 'backslashreplace'))
    else:
        s = (s.replace('\\', '\\\\')
              .replace("'", "\\'"))
    return "'%s'" % s

class Metadata(QtGui.QWidget):
    remove = QtCore.pyqtSignal()
    changed = QtCore.pyqtSignal()

    def __init__(self, name, value=None):
        QtGui.QWidget.__init__(self)
        layout = QtGui.QHBoxLayout()
        self.setLayout(layout)

        self.key = QtGui.QLineEdit()
        self.key.setText(name)
        layout.addWidget(self.key, 1)
        self.value = self.value_widget(value)
        layout.addWidget(self.value, 2)

        remove_button = QtGui.QPushButton("Remove port")
        remove_button.setSizePolicy(QtGui.QSizePolicy.Fixed,
                                    QtGui.QSizePolicy.Fixed)
        layout.addWidget(remove_button)

        self.connect(remove_button, QtCore.SIGNAL('clicked()'),
                     self.remove)
        self.connect(self.key, QtCore.SIGNAL('textEdited(const QString &)'),
                     self.changed)
        self.connect(self.value, QtCore.SIGNAL('textEdited(const QString &)'),
                     self.changed)

class StringMetadata(Metadata):
    @staticmethod
    def value_widget(value=None):
        return QtGui.QLineEdit(value)

    def to_string(self):
        return 'EqualString(%s, %s)' % (str_repr(self.key.text()),
                                        str_repr(self.value.text()))

class IntMetadata(Metadata):
    def value_widget(self, value=None):
        w = QtGui.QLineEdit()
        if value is not None:
            w.setText('%d' % value)
        w.setValidator(QtGui.QIntValidator(self))
        return w

    def to_string(self):
        try:
            i = int(self.value.text())
        except ValueError:
            i = 0
        return 'EqualInt(%s, %d)' % (str_repr(self.key.text()), i)

class SetMetadataWidget(StandardModuleConfigurationWidget):
    """
    Configuration widget allowing to set metadata on persisted modules.

    It is a visual editor for the strings functions set on the 'metadata' port,
    which have the form EqualString('mkey', 'mvalue') or EqualInt('mkey', 2).
    """
    def __init__(self, module, controller, parent=None):
        StandardModuleConfigurationWidget.__init__(self, module,
                                                   controller, parent)

        # Window title
        self.setWindowTitle("Metadata editor")

        central_layout = QtGui.QVBoxLayout()
        central_layout.setMargin(0)
        central_layout.setSpacing(0)
        self.setLayout(central_layout)

        self._scroll_area = QtGui.QScrollArea()
        inner_widget = QtGui.QWidget()
        self._list_layout = QtGui.QVBoxLayout()
        scroll_layout = QtGui.QVBoxLayout()
        scroll_layout.addLayout(self._list_layout)
        scroll_layout.addStretch()
        inner_widget.setLayout(scroll_layout)
        self._scroll_area.setVerticalScrollBarPolicy(
                QtCore.Qt.ScrollBarAlwaysOn)
        self._scroll_area.setWidget(inner_widget)
        self._scroll_area.setWidgetResizable(True)
        central_layout.addWidget(self._scroll_area)

        add_buttons = QtGui.QHBoxLayout()
        central_layout.addLayout(add_buttons)
        add_string = QtGui.QPushButton("Add a string")
        self.connect(add_string, QtCore.SIGNAL('clicked()'),
                     self.add_string)
        add_buttons.addWidget(add_string, 2)
        add_int = QtGui.QPushButton("Add an integer")
        self.connect(add_int, QtCore.SIGNAL('clicked()'),
                     self.add_int)
        add_buttons.addWidget(add_int, 1)

        self.createButtons()

        self.createEntries()

    def add_item(self, item):
        self._list_layout.addWidget(item)
        self.connect(item, QtCore.SIGNAL('remove()'),
                     lambda: item.deleteLater())
        self.connect(item, QtCore.SIGNAL('changed()'),
                     self.updateState)

    def add_string(self):
        self.add_item(StringMetadata(
                "string%d" % (self._list_layout.count() + 1)))
        self.updateState()

    def add_int(self):
        self.add_item(IntMetadata(
                "int%d" % (self._list_layout.count() + 1)))
        self.updateState()

    def createButtons(self):
        """ createButtons() -> None
        Create and connect signals to Ok & Cancel button

        """
        buttonLayout = QtGui.QHBoxLayout()
        buttonLayout.setMargin(5)
        self.saveButton = QtGui.QPushButton("&Save", self)
        self.saveButton.setFixedWidth(100)
        self.saveButton.setEnabled(False)
        buttonLayout.addWidget(self.saveButton)
        self.resetButton = QtGui.QPushButton("&Reset", self)
        self.resetButton.setFixedWidth(100)
        self.resetButton.setEnabled(False)
        buttonLayout.addWidget(self.resetButton)
        self.layout().addLayout(buttonLayout)
        self.connect(self.saveButton, QtCore.SIGNAL('clicked(bool)'),
                     self.saveTriggered)
        self.connect(self.resetButton, QtCore.SIGNAL('clicked(bool)'),
                     self.resetTriggered)

    def saveTriggered(self, checked = False):
        """ saveTriggered(checked: bool) -> None
        Update vistrail controller and module when the user click Ok

        """
        if self.updateVistrail():
            self.saveButton.setEnabled(False)
            self.resetButton.setEnabled(False)
            self.state_changed = False
            self.emit(QtCore.SIGNAL('stateChanged'))
            self.emit(QtCore.SIGNAL('doneConfigure'), self.module.id)

    def closeEvent(self, event):
        self.askToSaveChanges()
        event.accept()

    def updateVistrail(self):
        """ updateVistrail() -> None
        Update functions on the metadata port of the module
        """
        # Remove the keys that we loaded
        ops = [('delete', func) for func in self._loaded_keys]

        # Add the metadata in the list
        for i in xrange(self._list_layout.count()):
            widget = self._list_layout.itemAt(i).widget()
            ops.extend(self.controller.update_function_ops(
                    self.module, 'metadata',
                    [widget.to_string()]))

        # This code should really be in VistrailController
        self.controller.flush_delayed_actions()
        action = create_action(ops)
        self.controller.add_new_action(action,
                                       "Updated PersistedPath metadata")
        self.controller.perform_action(action)

        return True

    def getCurrentFunctions(self):
        for i in xrange(self.module.getNumFunctions()):
            func = self.module.functions[i]
            if func.name == 'metadata':
                yield func, func.params[0].strValue

    def createEntries(self):
        self._loaded_keys = set()
        for func, metadata in self.getCurrentFunctions():
            metadata = QueryCondition.translate_to_python(metadata)
            save = True
            if metadata is None:
                save = False
            elif isinstance(metadata, EqualString):
                self.add_item(StringMetadata(metadata.key, metadata.value))
            elif isinstance(metadata, EqualInt):
                self.add_item(IntMetadata(metadata.key, metadata.value))
            else:
                save = False

            if save:
                self._loaded_keys.add(func)

    def resetTriggered(self, checked = False):
        for i in xrange(self._list_layout.count()):
            self._list_layout.itemAt(i).widget().deleteLater()

        self.createEntries()

        self.saveButton.setEnabled(False)
        self.resetButton.setEnabled(False)
        self.state_changed = False
        self.emit(QtCore.SIGNAL('stateChanged'))

    def updateState(self):
        self.saveButton.setEnabled(True)
        self.resetButton.setEnabled(True)
        if not self.state_changed:
            self.state_changed = True
            self.emit(QtCore.SIGNAL('stateChanged'))

class MetadataConstantWidget(ConstantWidgetBase, QtGui.QWidget):
    contentsChanged = QtCore.pyqtSignal(tuple)

    def __init__(self, param, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self._key = QtGui.QLineEdit()
        self.connect(self._key, QtCore.SIGNAL("returnPressed()"),
                     self.update_parent)

        self._type = QtGui.QComboBox()
        self._type.addItems(['int', 'str'])
        self.connect(self._type, QtCore.SIGNAL("currentIndexChanged()"),
                     self.update_parent)

        self._value = QtGui.QLineEdit()
        self.connect(self._value, QtCore.SIGNAL("returnPressed()"),
                     self.update_parent)

        layout = QtGui.QHBoxLayout()
        layout.addWidget(self._key)
        layout.addWidget(self._type)
        layout.addWidget(self._value)
        self.setLayout(layout)

        ConstantWidgetBase.__init__(self, param)
        self._key.installEventFilter(self)
        self._type.installEventFilter(self)
        self._value.installEventFilter(self)

    def contents(self):
        if self._type.currentText() == 'int':
            return 'EqualInt(%s, %s)' % (str_repr(self._key.text()),
                                         self._value.text())
        else:  # self._type.currentText() == 'str':
            return 'EqualString(%s, %s)' % (str_repr(self._key.text()),
                                            str_repr(self._value.text()))

    def setContents(self, value, silent=False):
        cond = QueryCondition.translate_to_python(value, text_query=False)
        self._key.setText(cond.key)
        if isinstance(cond, EqualInt):
            self._type.setCurrentIndex(0)
            self._value.setText('%d' % cond.value)
        elif isinstance(cond, EqualString):
            self._type.setCurrentIndex(1)
            self._value.setText(cond.value)
        if not silent:
            self.update_parent()
<|endoftext|>


<commit_before>########
# Copyright (c) 2016 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from integration_tests.framework import docl

RIEMANN_CONFIGS_DIR = '/opt/riemann'

def reset_data_and_restart():
    docl.execute('rm -rf {0}'.format(RIEMANN_CONFIGS_DIR))
    docl.execute('mkdir -p {0}'.format(RIEMANN_CONFIGS_DIR))
    docl.execute('systemctl restart cloudify-riemann')
<commit_msg>CFY-6781 Fix riemann policies integration tests (#826)<commit_after>########
# Copyright (c) 2016 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from integration_tests.framework import docl

RIEMANN_CONFIGS_DIR = '/opt/riemann'

def reset_data_and_restart():
    docl.execute('rm -rf {0}'.format(RIEMANN_CONFIGS_DIR))
    docl.execute('mkdir -p {0}'.format(RIEMANN_CONFIGS_DIR))
    # This is how the dir is currently set up during the bootstrap
    docl.execute('chown -R riemann:mgmtworker {0}'.format(RIEMANN_CONFIGS_DIR))
    docl.execute('chmod 770 {0}'.format(RIEMANN_CONFIGS_DIR))
    docl.execute('systemctl restart cloudify-riemann')
<|endoftext|>


<commit_before>#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import unicode_literals
from django.test import TestCase, Client
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.contrib.auth.models import User
from django.core import mail
from django.test.utils import override_settings
import factory
from faker import Faker
from splinter import Browser

fake = Faker()

class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = User

    username = fake.username()
    email = fake.email()

# # # # # # # # # # # # # # # #
# Client Tests for Templates  #
# # # # # # # # # # # # # # # #

class HomepageClientTests(TestCase):

    # Test 1
    # Check that home page loads the correct template
    def test_home_template(self):
        response = Client().get('/')
        self.assertTemplateUsed(response, 'index.html')

# # # # # # # # # # # # # #
# Web Tests for Home Page #
# # # # # # # # # # # # # #

@override_settings(DEBUG=True)
class HomePageWebTests(StaticLiveServerTestCase):

    @classmethod
    def setUpClass(cls):
        super(HomePageWebTests, cls).setUpClass()
        cls.browser = Browser()

    @classmethod
    def tearDownClass(cls):
        cls.browser.quit()
        super(HomePageWebTests, cls).tearDownClass()

    def setUp(self):
        self.user1 = UserFactory()
        self.user1.set_password('abc')
        self.user1.save()

    def tearDown(self):
        User.objects.all().delete()

    def login_helper(self, username, password):
        self.browser.visit('%s%s' % (self.live_server_url, '/accounts/login/'))

        self.browser.fill('username', username)
        self.browser.fill('password', password)
        self.browser.find_by_value('Log in').first.click()

    # Test 2
    # Check for login link from anonymous get of homepage
    def test_anon_login(self):
        self.browser.visit('%s%s' % (self.live_server_url, '/'))
        login_link = self.browser.find_by_tag('a')[3]
        self.assertEqual(
            '%s%s' % (self.live_server_url, '/accounts/login/'),
            login_link['href']
        )

    # Test 3
    # Check for register link from anonymous get of homepage
    def test_anon_register(self):
        self.browser.visit('%s%s' % (self.live_server_url, '/'))
        register_link = self.browser.find_by_tag('a')[4]
        self.assertEqual(
            '%s%s' % (self.live_server_url, '/accounts/register/'),
            register_link['href']
        )

    # Test 4
    # Check for user login success
    def test_login_success(self):
        self.login_helper(self.user1.username, 'abc')

        self.assertEqual(
            self.browser.url,
            '%s%s' % (self.live_server_url, '/profile/')
        )
        logout_link = self.browser.find_by_tag('a')[4]
        self.assertEqual(
            '%s%s' % (self.live_server_url, '/accounts/logout/?next=/'),
            logout_link['href']
        )
        greeting = self.browser.find_by_tag('big')[0]
        self.assertEqual(
            '%s%s%s' % ('Well howdy there, ', self.user1.username, '.'),
            greeting.text
        )

    # Test 5
    # Check for user logout success
    def test_logout_success(self):
        self.login_helper(self.user1.username, 'abc')

        self.browser.find_by_tag('a')[4].click()

        self.assertEqual(
            self.browser.url,
            '%s%s' % (self.live_server_url, '/accounts/logout/')
        )

    # Test 6
    # Register brand new user
    def test_registration(self):
        self.browser.visit(
            '%s%s' % (self.live_server_url, '/accounts/register/')
        )

        self.browser.fill('username', 'joseph')
        self.browser.fill('email', 'joe@example.com')
        self.browser.fill('password1', '123')
        self.browser.fill('password2', '123')
        self.browser.find_by_value('Submit').first.click()

        self.assertEqual(
            self.browser.url,
            '%s%s' % (self.live_server_url, '/accounts/register/complete/')
        )

        link_end = mail.outbox[0].body.split('days:')[1].split()[0][18:]
        link = '%s%s' % (self.live_server_url, link_end)
        self.browser.evaluate_script('document.location="%s"' % link)
        self.assertEqual(
            self.browser.url,
            '%s%s' % (self.live_server_url, '/accounts/activate/complete/')
        )
        self.login_helper('joseph', '123')
        user_name = self.browser.find_by_tag('big')[0]
        self.assertEqual('Well howdy there, joseph.', user_name.text)
<commit_msg>Pass test for home page template loaded<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import unicode_literals
from django.test import TestCase, Client
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.contrib.auth.models import User
from django.core import mail
from django.test.utils import override_settings
import factory
from faker import Faker
from splinter import Browser

fake = Faker()

class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = User

    username = fake.username()
    email = fake.email()

# # # # # # # # # # # # # # # #
# Client Tests for Templates  #
# # # # # # # # # # # # # # # #

class HomepageClientTests(TestCase):

    # Test 1
    # Check that home page loads the correct template
    def test_home_template(self):
        response = Client().get('/')
        self.assertTemplateUsed(response, 'home.html')

# # # # # # # # # # # # # #
# Web Tests for Home Page #
# # # # # # # # # # # # # #

@override_settings(DEBUG=True)
class HomePageWebTests(StaticLiveServerTestCase):

    @classmethod
    def setUpClass(cls):
        super(HomePageWebTests, cls).setUpClass()
        cls.browser = Browser()

    @classmethod
    def tearDownClass(cls):
        cls.browser.quit()
        super(HomePageWebTests, cls).tearDownClass()

    def setUp(self):
        self.user1 = UserFactory()
        self.user1.set_password('abc')
        self.user1.save()

    def tearDown(self):
        User.objects.all().delete()

    def login_helper(self, username, password):
        self.browser.visit('%s%s' % (self.live_server_url, '/accounts/login/'))

        self.browser.fill('username', username)
        self.browser.fill('password', password)
        self.browser.find_by_value('Log in').first.click()

    # Test 2
    # Check for login link from anonymous get of homepage
    def test_anon_login(self):
        self.browser.visit('%s%s' % (self.live_server_url, '/'))
        login_link = self.browser.find_by_tag('a')[3]
        self.assertEqual(
            '%s%s' % (self.live_server_url, '/accounts/login/'),
            login_link['href']
        )

    # Test 3
    # Check for register link from anonymous get of homepage
    def test_anon_register(self):
        self.browser.visit('%s%s' % (self.live_server_url, '/'))
        register_link = self.browser.find_by_tag('a')[4]
        self.assertEqual(
            '%s%s' % (self.live_server_url, '/accounts/register/'),
            register_link['href']
        )

    # Test 4
    # Check for user login success
    def test_login_success(self):
        self.login_helper(self.user1.username, 'abc')

        self.assertEqual(
            self.browser.url,
            '%s%s' % (self.live_server_url, '/profile/')
        )
        logout_link = self.browser.find_by_tag('a')[4]
        self.assertEqual(
            '%s%s' % (self.live_server_url, '/accounts/logout/?next=/'),
            logout_link['href']
        )
        greeting = self.browser.find_by_tag('big')[0]
        self.assertEqual(
            '%s%s%s' % ('Well howdy there, ', self.user1.username, '.'),
            greeting.text
        )

    # Test 5
    # Check for user logout success
    def test_logout_success(self):
        self.login_helper(self.user1.username, 'abc')

        self.browser.find_by_tag('a')[4].click()

        self.assertEqual(
            self.browser.url,
            '%s%s' % (self.live_server_url, '/accounts/logout/')
        )

    # Test 6
    # Register brand new user
    def test_registration(self):
        self.browser.visit(
            '%s%s' % (self.live_server_url, '/accounts/register/')
        )

        self.browser.fill('username', 'joseph')
        self.browser.fill('email', 'joe@example.com')
        self.browser.fill('password1', '123')
        self.browser.fill('password2', '123')
        self.browser.find_by_value('Submit').first.click()

        self.assertEqual(
            self.browser.url,
            '%s%s' % (self.live_server_url, '/accounts/register/complete/')
        )

        link_end = mail.outbox[0].body.split('days:')[1].split()[0][18:]
        link = '%s%s' % (self.live_server_url, link_end)
        self.browser.evaluate_script('document.location="%s"' % link)
        self.assertEqual(
            self.browser.url,
            '%s%s' % (self.live_server_url, '/accounts/activate/complete/')
        )
        self.login_helper('joseph', '123')
        user_name = self.browser.find_by_tag('big')[0]
        self.assertEqual('Well howdy there, joseph.', user_name.text)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
#
# Copyright 2018-2019 Data61, CSIRO
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from stellargraph.mapper import ClusterNodeGenerator, ClusterNodeSequence
from stellargraph.core.graph import StellarGraph

import networkx as nx
import pandas as pd
import numpy as np
import pytest

def create_graph_features():
    G = nx.Graph()
    G.add_nodes_from(["a", "b", "c", "d"])
    G.add_edges_from([("a", "b"), ("b", "c"), ("a", "c"), ("b", "d")])
    G = G.to_undirected()
    return G, np.array([[1, 1], [1, 0], [0, 1], [0.5, 1]])

def create_stellargraph():
    Gnx, features = create_graph_features()
    nodes = Gnx.nodes()
    node_features = pd.DataFrame.from_dict(
        {n: f for n, f in zip(nodes, features)}, orient="index"
    )
    G = StellarGraph(Gnx, node_type_name="node", node_features=node_features)

    return G

def test_ClusterNodeSequence_init():

    G = create_stellargraph()

    nsg = ClusterNodeSequence(graph=G, clusters=[list(G.nodes())])
    assert len(nsg) == 1

    nsg = ClusterNodeSequence(graph=G, clusters=[["a"], ["b", "d"], ["c"]])
    assert len(nsg) == 3

    # If targets are given, so should node_ids that correspond to these targets
    with pytest.raises(ValueError):
        ClusterNodeSequence(
            graph=G, clusters=[list(G.nodes())], q=1, targets=np.array([[0, 1]])
        )

    # targets and node_id should have the same length.
    with pytest.raises(ValueError):
        ClusterNodeSequence(
            graph=G,
            clusters=[list(G.nodes())],
            q=1,
            targets=np.array([[0, 1], [1, 0]]),
            node_ids=["a"],
        )

    # len(clusters) is not exactly divisible by q
    with pytest.raises(ValueError):
        ClusterNodeSequence(graph=G, clusters=[list(G.nodes())], q=2)

def test_ClusterNodeSequence_getitem():

    G = create_stellargraph()

    nsg = ClusterNodeSequence(
        graph=G, clusters=[["a"], ["b"], ["c"], ["d"]], node_ids=["a", "b", "d"]
    )

    # 4 clusters with each cluster having a single node
    assert len(nsg) == 4

    for cluster in list(nsg):
        print(cluster)
        assert len(cluster) == 2
        # [features, target_node_indices, adj_cluster], cluster_targets
        assert len(cluster[0][0]) == 1
        assert len(cluster[0][1]) == 1
        assert cluster[0][2].shape == (
            1,
            1,
            1,
        )  # one node per cluster so adjacency matrix is 1x1
        assert cluster[1] is None  # no targets given

    # only 3 node_ids were specified
    assert len(nsg.node_order) == 3

    nodes = set()
    for node in nsg.node_order:
        nodes.add(node)

    assert len(nodes.intersection(["a", "b", "d"])) == 3

def test_ClusterNodeGenerator_init():

    G = create_stellargraph()

    with pytest.raises(ValueError):
        generator = ClusterNodeGenerator(G, k=0)

    # k must be integer
    with pytest.raises(TypeError):
        generator = ClusterNodeGenerator(G, k=0.5)

    with pytest.raises(ValueError):
        generator = ClusterNodeGenerator(G, q=0)

    # q must be integer
    with pytest.raises(TypeError):
        generator = ClusterNodeGenerator(G, q=1.0)

    # k is not exactly divisible by q
    with pytest.raises(ValueError):
        generator = ClusterNodeGenerator(G, k=5, q=2)

    # one cluster, k=len(clusters), not divisible by q
    with pytest.raises(ValueError):
        generator = ClusterNodeGenerator(G, clusters=[["a", "b", "c", "d"]], q=2)

    generator = ClusterNodeGenerator(G, clusters=[["a", "b", "c", "d"]], q=1)
    assert generator.k == 1
    assert generator.q == 1

    # two clusters, k=len(clusters).
    generator = ClusterNodeGenerator(G, clusters=[["a", "d"], ["b", "c"]], q=1)
    assert generator.k == 2
    assert generator.q == 1

    # lam has to be in the interval [0., 1.] and float
    with pytest.raises(TypeError):
        generator = ClusterNodeGenerator(G, k=1, q=1, lam=-1)

    with pytest.raises(TypeError):
        generator = ClusterNodeGenerator(G, k=1, q=1, lam=1)

    with pytest.raises(ValueError):
        generator = ClusterNodeGenerator(G, k=1, q=1, lam=2.5)

def test_ClusterNodeSquence():

    G = create_stellargraph()

    generator = ClusterNodeGenerator(G, k=1, q=1).flow(node_ids=["a", "b", "c", "d"])

    assert len(generator) == 1

    generator = ClusterNodeGenerator(G, k=4, q=1).flow(node_ids=["a", "b", "c", "d"])
    assert len(generator) == 4

    generator = ClusterNodeGenerator(G, k=4, q=1).flow(node_ids=["a", "b", "c", "d"])

    # ClusterNodeSequence returns the following:
    #      [features, target_node_indices, adj_cluster], cluster_targets
    for batch in generator:
        assert len(batch) == 2
        # The first dimension is the batch dimension necessary to make this work with Keras
        assert batch[0][0].shape == (1, 1, 2)
        assert batch[0][1].shape == (1, 1, 1)
        # one node so that adjacency matrix is 1x1
        assert batch[0][2].shape == (1, 1, 1)
        # no targets given
        assert batch[1] == None

    # Use 2 clusters
    generator = ClusterNodeGenerator(G, k=2, q=1).flow(node_ids=["a", "b", "c", "d"])
    assert len(generator) == 2

    # ClusterNodeSequence returns the following:
    #      [features, target_node_indices, adj_cluster], cluster_targets
    for batch in generator:
        assert len(batch) == 2
        # The first dimension is the batch dimension necessary to make this work with Keras
        assert batch[0][0].shape == (1, 2, 2)
        assert batch[0][1].shape == (1, 1, 2)
        # two nodes so that adjacency matrix is 2x2
        assert batch[0][2].shape == (1, 2, 2)
        # no targets given
        assert batch[1] is None
<commit_msg>Updated based on reviewer comments.<commit_after># -*- coding: utf-8 -*-
#
# Copyright 2018-2019 Data61, CSIRO
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from stellargraph.mapper import ClusterNodeGenerator, ClusterNodeSequence
from stellargraph.core.graph import StellarGraph

import networkx as nx
import pandas as pd
import numpy as np
import pytest

def create_graph_features():
    G = nx.Graph()
    G.add_nodes_from(["a", "b", "c", "d"])
    G.add_edges_from([("a", "b"), ("b", "c"), ("a", "c"), ("b", "d")])
    return G, np.array([[1, 1], [1, 0], [0, 1], [0.5, 1]])

def create_stellargraph():
    Gnx, features = create_graph_features()
    nodes = Gnx.nodes()
    node_features = pd.DataFrame.from_dict(
        {n: f for n, f in zip(nodes, features)}, orient="index"
    )
    G = StellarGraph(Gnx, node_type_name="node", node_features=node_features)

    return G

def test_ClusterNodeSequence_init():

    G = create_stellargraph()

    nsg = ClusterNodeSequence(graph=G, clusters=[list(G.nodes())])
    assert len(nsg) == 1

    nsg = ClusterNodeSequence(graph=G, clusters=[["a"], ["b", "d"], ["c"]])
    assert len(nsg) == 3

    # If targets are given, so should node_ids that correspond to these targets
    with pytest.raises(ValueError):
        ClusterNodeSequence(
            graph=G, clusters=[list(G.nodes())], q=1, targets=np.array([[0, 1]])
        )

    # targets and node_id should have the same length.
    with pytest.raises(ValueError):
        ClusterNodeSequence(
            graph=G,
            clusters=[list(G.nodes())],
            q=1,
            targets=np.array([[0, 1], [1, 0]]),
            node_ids=["a"],
        )

    # len(clusters) is not exactly divisible by q
    with pytest.raises(ValueError):
        ClusterNodeSequence(graph=G, clusters=[list(G.nodes())], q=2)

def test_ClusterNodeSequence_getitem():

    G = create_stellargraph()

    nsg = ClusterNodeSequence(
        graph=G, clusters=[["a"], ["b"], ["c"], ["d"]], node_ids=["a", "b", "d"]
    )

    # 4 clusters with each cluster having a single node
    assert len(nsg) == 4

    for cluster in list(nsg):
        print(cluster)
        assert len(cluster) == 2
        # [features, target_node_indices, adj_cluster], cluster_targets
        assert len(cluster[0][0]) == 1
        assert len(cluster[0][1]) == 1
        assert cluster[0][2].shape == (
            1,
            1,
            1,
        )  # one node per cluster so adjacency matrix is 1x1
        assert cluster[1] is None  # no targets given

    # only 3 node_ids were specified
    assert len(nsg.node_order) == 3

    nodes = set()
    for node in nsg.node_order:
        nodes.add(node)

    assert len(nodes.intersection(["a", "b", "d"])) == 3

def test_ClusterNodeGenerator_init():

    G = create_stellargraph()

    with pytest.raises(ValueError):
        generator = ClusterNodeGenerator(G, k=0)

    # k must be integer
    with pytest.raises(TypeError):
        generator = ClusterNodeGenerator(G, k=0.5)

    with pytest.raises(ValueError):
        generator = ClusterNodeGenerator(G, q=0)

    # q must be integer
    with pytest.raises(TypeError):
        generator = ClusterNodeGenerator(G, q=1.0)

    # k is not exactly divisible by q
    with pytest.raises(ValueError):
        generator = ClusterNodeGenerator(G, k=5, q=2)

    # one cluster, k=len(clusters), not divisible by q
    with pytest.raises(ValueError):
        generator = ClusterNodeGenerator(G, clusters=[["a", "b", "c", "d"]], q=2)

    generator = ClusterNodeGenerator(G, clusters=[["a", "b", "c", "d"]], q=1)
    assert generator.k == 1
    assert generator.q == 1

    # two clusters, k=len(clusters).
    generator = ClusterNodeGenerator(G, clusters=[["a", "d"], ["b", "c"]], q=1)
    assert generator.k == 2
    assert generator.q == 1

    # lam has to be in the interval [0., 1.] and float
    with pytest.raises(TypeError):
        generator = ClusterNodeGenerator(G, k=1, q=1, lam=-1)

    with pytest.raises(TypeError):
        generator = ClusterNodeGenerator(G, k=1, q=1, lam=1)

    with pytest.raises(ValueError):
        generator = ClusterNodeGenerator(G, k=1, q=1, lam=2.5)

def test_ClusterNodeSquence():

    G = create_stellargraph()

    generator = ClusterNodeGenerator(G, k=1, q=1).flow(node_ids=["a", "b", "c", "d"])

    assert len(generator) == 1

    generator = ClusterNodeGenerator(G, k=4, q=1).flow(node_ids=["a", "b", "c", "d"])
    assert len(generator) == 4

    generator = ClusterNodeGenerator(G, k=4, q=1).flow(node_ids=["a", "b", "c", "d"])

    # ClusterNodeSequence returns the following:
    #      [features, target_node_indices, adj_cluster], cluster_targets
    for batch in generator:
        assert len(batch) == 2
        # The first dimension is the batch dimension necessary to make this work with Keras
        assert batch[0][0].shape == (1, 1, 2)
        assert batch[0][1].shape == (1, 1, 1)
        # one node so that adjacency matrix is 1x1
        assert batch[0][2].shape == (1, 1, 1)
        # no targets given
        assert batch[1] == None

    # Use 2 clusters
    generator = ClusterNodeGenerator(G, k=2, q=1).flow(node_ids=["a", "b", "c", "d"])
    assert len(generator) == 2

    # ClusterNodeSequence returns the following:
    #      [features, target_node_indices, adj_cluster], cluster_targets
    for batch in generator:
        assert len(batch) == 2
        # The first dimension is the batch dimension necessary to make this work with Keras
        assert batch[0][0].shape == (1, 2, 2)
        assert batch[0][1].shape == (1, 1, 2)
        # two nodes so that adjacency matrix is 2x2
        assert batch[0][2].shape == (1, 2, 2)
        # no targets given
        assert batch[1] is None
<|endoftext|>


<commit_before>"""
34. DB-API Shortcuts

get_object_or_404 is a shortcut function to be used in view functions for
performing a get() lookup and raising a Http404 exception if a DoesNotExist
exception was rasied during the get() call.

get_list_or_404 is a shortcut function to be used in view functions for
performing a filter() lookup and raising a Http404 exception if a DoesNotExist
exception was rasied during the filter() call.
"""

from django.db import models
from django.http import Http404
from django.shortcuts import get_object_or_404, get_list_or_404

class Author(models.Model):
    name = models.CharField(maxlength=50)

    def __str__(self):
        return self.name

class ArticleManager(models.Manager):
    def get_query_set(self):
        return super(ArticleManager, self).get_query_set().filter(authors__name__icontains='sir')

class Article(models.Model):
    authors = models.ManyToManyField(Author)
    title = models.CharField(maxlength=50)
    objects = models.Manager()
    by_a_sir = ArticleManager()

    def __str__(self):
        return self.title

__test__ = {'API_TESTS':"""
# Create some Authors.
>>> a = Author.objects.create(name="Brave Sir Robin")
>>> a.save()
>>> a2 = Author.objects.create(name="Patsy")
>>> a2.save()

# No Articles yet, so we should get a Http404 error.
>>> get_object_or_404(Article, title="Foo")
Traceback (most recent call last):
...
Http404

# Create an Article.
>>> article = Article.objects.create(title="Run away!")
>>> article.authors = [a, a2]
>>> article.save()

# get_object_or_404 can be passed a Model to query.
>>> get_object_or_404(Article, title__contains="Run")
<Article: Run away!>

# We can also use the the Article manager through an Author object.
>>> get_object_or_404(a.article_set, title__contains="Run")
<Article: Run away!>

# No articles containing "Camelot".  This should raise a Http404 error.
>>> get_object_or_404(a.article_set, title__contains="Camelot")
Traceback (most recent call last):
...
Http404

# Custom managers can be used too.
>>> get_object_or_404(Article.by_a_sir, title="Run away!")
<Article: Run away!>

# get_list_or_404 can be used to get lists of objects
>>> get_list_or_404(a.article_set, title__icontains='Run')
[<Article: Run away!>]

# Http404 is returned if the list is empty
>>> get_list_or_404(a.article_set, title__icontains='Shrubbery')
Traceback (most recent call last):
...
Http404

# Custom managers can be used too.
>>> get_list_or_404(Article.by_a_sir, title__icontains="Run")
[<Article: Run away!>]

"""}
<commit_msg>Fixed tests that broke after [4756].<commit_after>"""
34. DB-API Shortcuts

get_object_or_404 is a shortcut function to be used in view functions for
performing a get() lookup and raising a Http404 exception if a DoesNotExist
exception was rasied during the get() call.

get_list_or_404 is a shortcut function to be used in view functions for
performing a filter() lookup and raising a Http404 exception if a DoesNotExist
exception was rasied during the filter() call.
"""

from django.db import models
from django.http import Http404
from django.shortcuts import get_object_or_404, get_list_or_404

class Author(models.Model):
    name = models.CharField(maxlength=50)

    def __str__(self):
        return self.name

class ArticleManager(models.Manager):
    def get_query_set(self):
        return super(ArticleManager, self).get_query_set().filter(authors__name__icontains='sir')

class Article(models.Model):
    authors = models.ManyToManyField(Author)
    title = models.CharField(maxlength=50)
    objects = models.Manager()
    by_a_sir = ArticleManager()

    def __str__(self):
        return self.title

__test__ = {'API_TESTS':"""
# Create some Authors.
>>> a = Author.objects.create(name="Brave Sir Robin")
>>> a.save()
>>> a2 = Author.objects.create(name="Patsy")
>>> a2.save()

# No Articles yet, so we should get a Http404 error.
>>> get_object_or_404(Article, title="Foo")
Traceback (most recent call last):
...
Http404: No Article matches the given query.

# Create an Article.
>>> article = Article.objects.create(title="Run away!")
>>> article.authors = [a, a2]
>>> article.save()

# get_object_or_404 can be passed a Model to query.
>>> get_object_or_404(Article, title__contains="Run")
<Article: Run away!>

# We can also use the the Article manager through an Author object.
>>> get_object_or_404(a.article_set, title__contains="Run")
<Article: Run away!>

# No articles containing "Camelot".  This should raise a Http404 error.
>>> get_object_or_404(a.article_set, title__contains="Camelot")
Traceback (most recent call last):
...
Http404: No Article matches the given query.

# Custom managers can be used too.
>>> get_object_or_404(Article.by_a_sir, title="Run away!")
<Article: Run away!>

# get_list_or_404 can be used to get lists of objects
>>> get_list_or_404(a.article_set, title__icontains='Run')
[<Article: Run away!>]

# Http404 is returned if the list is empty
>>> get_list_or_404(a.article_set, title__icontains='Shrubbery')
Traceback (most recent call last):
...
Http404: No Article matches the given query.

# Custom managers can be used too.
>>> get_list_or_404(Article.by_a_sir, title__icontains="Run")
[<Article: Run away!>]

"""}
<|endoftext|>


<commit_before>from django import template

from wagtail.wagtailimages.models import Filter, Rendition

register = template.Library()

@register.tag(name="image")
def image(parser, token):
    args = token.split_contents()

    if len(args) == 3:
        # token is of the form {% image self.photo max-320x200 %}
        tag_name, image_var, filter_spec = args
        return ImageNode(image_var, filter_spec)

    elif len(args) == 5:
        # token is of the form {% image self.photo max-320x200 as img %}
        tag_name, image_var, filter_spec, as_token, out_var = args

        if as_token != 'as':
            raise template.TemplateSyntaxError("'image' tag should be of the form {%% image self.photo max-320x200 %%} or {%% image self.photo max-320x200 as img %%}")

        return ImageNode(image_var, filter_spec, out_var)

    else:
        raise template.TemplateSyntaxError("'image' tag should be of the form {%% image self.photo max-320x200 %%} or {%% image self.photo max-320x200 as img %%}")

class ImageNode(template.Node):
    def __init__(self, image_var_name, filter_spec, output_var_name=None):
        self.image_var = template.Variable(image_var_name)
        self.filter, created = Filter.objects.get_or_create(spec=filter_spec)
        self.output_var_name = output_var_name

    def render(self, context):
        try:
            image = self.image_var.resolve(context)
        except template.VariableDoesNotExist:
            return ''

        if not image:
            return ''

        try:
            rendition = image.get_rendition(self.filter)
        except IOError:
            # It's fairly routine for people to pull down remote databases to their
            # local dev versions without retrieving the corresponding image files.
            # In such a case, we would get an IOError at the point where we try to
            # create the resized version of a non-existent image. Since this is a
            # bit catastrophic for a missing image, we'll substitute a dummy
            # Rendition object so that we just output a broken link instead.
            rendition = Rendition(image=image, width=0, height=0)
            rendition.file.name = 'not-found'

        if self.output_var_name:
            # return the rendition object in the given variable
            context[self.output_var_name] = rendition
            return ''
        else:
            # render the rendition's image tag now
            return rendition.img_tag()
<commit_msg>use custom Rendition model for file-not-found images where relevant<commit_after>from django import template

from wagtail.wagtailimages.models import Filter

register = template.Library()

@register.tag(name="image")
def image(parser, token):
    args = token.split_contents()

    if len(args) == 3:
        # token is of the form {% image self.photo max-320x200 %}
        tag_name, image_var, filter_spec = args
        return ImageNode(image_var, filter_spec)

    elif len(args) == 5:
        # token is of the form {% image self.photo max-320x200 as img %}
        tag_name, image_var, filter_spec, as_token, out_var = args

        if as_token != 'as':
            raise template.TemplateSyntaxError("'image' tag should be of the form {%% image self.photo max-320x200 %%} or {%% image self.photo max-320x200 as img %%}")

        return ImageNode(image_var, filter_spec, out_var)

    else:
        raise template.TemplateSyntaxError("'image' tag should be of the form {%% image self.photo max-320x200 %%} or {%% image self.photo max-320x200 as img %%}")

class ImageNode(template.Node):
    def __init__(self, image_var_name, filter_spec, output_var_name=None):
        self.image_var = template.Variable(image_var_name)
        self.filter, created = Filter.objects.get_or_create(spec=filter_spec)
        self.output_var_name = output_var_name

    def render(self, context):
        try:
            image = self.image_var.resolve(context)
        except template.VariableDoesNotExist:
            return ''

        if not image:
            return ''

        try:
            rendition = image.get_rendition(self.filter)
        except IOError:
            # It's fairly routine for people to pull down remote databases to their
            # local dev versions without retrieving the corresponding image files.
            # In such a case, we would get an IOError at the point where we try to
            # create the resized version of a non-existent image. Since this is a
            # bit catastrophic for a missing image, we'll substitute a dummy
            # Rendition object so that we just output a broken link instead.
            Rendition = image.renditions.model  # pick up any custom Image / Rendition classes that may be in use
            rendition = Rendition(image=image, width=0, height=0)
            rendition.file.name = 'not-found'

        if self.output_var_name:
            # return the rendition object in the given variable
            context[self.output_var_name] = rendition
            return ''
        else:
            # render the rendition's image tag now
            return rendition.img_tag()
<|endoftext|>


<commit_before>import mock
from punch.vcs_use_cases import release as rel

def test_pre_start_release():
    repo = mock.Mock()
    use_case = rel.VCSReleaseUseCase(repo)

    use_case.pre_start_release("release_name")

    assert repo.pre_start_release.called
    assert repo.pre_start_release.called_with("release_name")

def test_pre_start_release_can_be_called_without_release_name():
    repo = mock.Mock()
    use_case = rel.VCSReleaseUseCase(repo)

    use_case.pre_start_release()

    assert repo.pre_start_release.called
    assert repo.pre_start_release.called_with()

def test_start_release():
    repo = mock.Mock()
    use_case = rel.VCSReleaseUseCase(repo)

    use_case.start_release("release_name")

    assert repo.start_release.called
    assert repo.start_release.called_with("release_name")

def test_finish_release():
    repo = mock.Mock()
    use_case = rel.VCSReleaseUseCase(repo)

    use_case.finish_release("release_name", "custom_message")

    assert repo.finish_release.called
    assert repo.finish_release.called_with("release_name", "custom_message")

def test_post_finish_release():
    repo = mock.Mock()
    use_case = rel.VCSReleaseUseCase(repo)

    use_case.post_finish_release("release_name")

    assert repo.post_finish_release.called
    assert repo.post_finish_release.called_with("release_name")

def test_run():
    repo = mock.Mock()
    use_case = rel.VCSReleaseUseCase(repo)

    use_case.run("release_name", "custom_message")
    assert repo.pre_start_release.called_with("release_name")
    assert repo.start_release.called_with("release_name")
    assert repo.finish_release.called_with("release_name", "custom_message")
    assert repo.post_finish_release.called_with("release_name")
<commit_msg>Fixed wrong UseCase invocation of repo<commit_after>import mock
from punch.vcs_use_cases import release as rel

def test_pre_start_release():
    repo = mock.Mock()
    use_case = rel.VCSReleaseUseCase(repo)

    use_case.pre_start_release()

    assert repo.pre_start_release.called
    assert repo.pre_start_release.called_with()

def test_pre_start_release_can_be_called_without_release_name():
    repo = mock.Mock()
    use_case = rel.VCSReleaseUseCase(repo)

    use_case.pre_start_release()

    assert repo.pre_start_release.called
    assert repo.pre_start_release.called_with()

def test_start_release():
    repo = mock.Mock()
    use_case = rel.VCSReleaseUseCase(repo)

    use_case.start_release()

    assert repo.start_release.called
    assert repo.start_release.called_with()

def test_finish_release():
    repo = mock.Mock()
    use_case = rel.VCSReleaseUseCase(repo)

    use_case.finish_release()

    assert repo.finish_release.called
    assert repo.finish_release.called_with()

def test_post_finish_release():
    repo = mock.Mock()
    use_case = rel.VCSReleaseUseCase(repo)

    use_case.post_finish_release()

    assert repo.post_finish_release.called
    assert repo.post_finish_release.called_with()

def test_run():
    repo = mock.Mock()
    use_case = rel.VCSReleaseUseCase(repo)

    use_case.run()
    assert repo.pre_start_release.called_with()
    assert repo.start_release.called_with()
    assert repo.finish_release.called_with()
    assert repo.post_finish_release.called_with()
<|endoftext|>


<commit_before>from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from time import sleep
import requests
import os
from webparticipation.apps.utils.views import undashify_user

messages = settings.MESSAGES

@csrf_exempt
def rapidpro_receptor(request):
    if request.method == 'POST':
        request_params = request.POST.dict()
        send_received_confirmation_to_rapidpro(request_params)
        broadcast_rapidpro_response(request_params)
        return HttpResponse('OK')

def send_received_confirmation_to_rapidpro(request_params):
    requests.post(os.environ.get('RAPIDPRO_RECEIVED_PATH'), data={
        'from': request_params['from'],
        'text': request_params['text']
    })

def broadcast_rapidpro_response(request_params):
    settings.RAPIDPRO_DISPATCHER.send(
        sender=request_params['to'],
        param_id=request_params['id'],
        param_channel=request_params['channel'],
        param_from=request_params['from'],
        param_to=request_params['to'],
        param_text=request_params['text'])

def get_messages_for_user(uuid):
    global messages
    while not len(messages):
        sleep(10)
    return filter_messages(uuid)

def filter_messages(uuid):
    global messages
    undashified_uuid = undashify_user(uuid)
    filtered_messages = filter(lambda msg: msg['msg_to'] == undashified_uuid, messages)
    messages = filter(lambda msg: msg['msg_to'] != undashified_uuid, messages)
    print uuid, messages
    return filtered_messages

def rapidpro_dispatcher_callback(sender, **kwargs):
    global messages
    messages.append({
        'msg_id': kwargs['param_id'],
        'msg_channel': kwargs['param_channel'],
        'msg_from': kwargs['param_from'],
        'msg_to': kwargs['param_to'],
        'msg_text': kwargs['param_text']
    })
<commit_msg>[steve] - revert interval to half second<commit_after>from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from time import sleep
import requests
import os
from webparticipation.apps.utils.views import undashify_user

messages = settings.MESSAGES

@csrf_exempt
def rapidpro_receptor(request):
    if request.method == 'POST':
        request_params = request.POST.dict()
        send_received_confirmation_to_rapidpro(request_params)
        broadcast_rapidpro_response(request_params)
        return HttpResponse('OK')

def send_received_confirmation_to_rapidpro(request_params):
    requests.post(os.environ.get('RAPIDPRO_RECEIVED_PATH'), data={
        'from': request_params['from'],
        'text': request_params['text']
    })

def broadcast_rapidpro_response(request_params):
    settings.RAPIDPRO_DISPATCHER.send(
        sender=request_params['to'],
        param_id=request_params['id'],
        param_channel=request_params['channel'],
        param_from=request_params['from'],
        param_to=request_params['to'],
        param_text=request_params['text'])

def get_messages_for_user(uuid):
    global messages
    while not len(messages):
        sleep(.5)
    return filter_messages(uuid)

def filter_messages(uuid):
    global messages
    undashified_uuid = undashify_user(uuid)
    filtered_messages = filter(lambda msg: msg['msg_to'] == undashified_uuid, messages)
    messages = filter(lambda msg: msg['msg_to'] != undashified_uuid, messages)
    print uuid, messages
    return filtered_messages

def rapidpro_dispatcher_callback(sender, **kwargs):
    global messages
    messages.append({
        'msg_id': kwargs['param_id'],
        'msg_channel': kwargs['param_channel'],
        'msg_from': kwargs['param_from'],
        'msg_to': kwargs['param_to'],
        'msg_text': kwargs['param_text']
    })
<|endoftext|>


<commit_before>import sys
import zipfile
import py
import pytest

ast = pytest.importorskip("ast")
if sys.platform.startswith("java"):
    # XXX should be xfail
    pytest.skip("assert rewrite does currently not work on jython")

from _pytest.assertion import util
from _pytest.assertion.rewrite import rewrite_asserts

def setup_module(mod):
    mod._old_reprcompare = util._reprcompare
    py.code._reprcompare = None

def teardown_module(mod):
    util._reprcompare = mod._old_reprcompare
    del mod._old_reprcompare

def rewrite(src):
    tree = ast.parse(src)
    rewrite_asserts(tree)
    return tree

def getmsg(f, extra_ns=None, must_pass=False):
    """Rewrite the assertions in f, run it, and get the failure message."""
    src = '\n'.join(py.code.Code(f).source().lines)
    mod = rewrite(src)
    code = compile(mod, "<test>", "exec")
    ns = {}
    if extra_ns is not None:
        ns.update(extra_ns)
    py.builtin.exec_(code, ns)
    func = ns[f.__name__]
    try:
        func()
    except AssertionError:
        if must_pass:
            pytest.fail("shouldn't have raised")
        s = str(sys.exc_info()[1])
        if not s.startswith("assert"):
            return "AssertionError: " + s
        return s
    else:
        if not must_pass:
            pytest.fail("function didn't raise at all")

class TestAssertionRewrite:

    def test_place_initial_imports(self):
        s = """'Doc string'\nother = stuff"""
        m = rewrite(s)
        assert isinstance(m.body[0], ast.Expr)
        assert isinstance(m.body[0].value, ast.Str)
        for imp in m.body[1:3]:
            assert isinstance(imp, ast.Import)
            assert imp.lineno == 2
            assert imp.col_offset == 0
        assert isinstance(m.body[3], ast.Assign)
        s = """from __future__ import with_statement\nother_stuff"""
        m = rewrite(s)
        assert isinstance(m.body[0], ast.ImportFrom)
        for imp in m.body[1:3]:
            assert isinstance(imp, ast.Import)
            assert imp.lineno == 2
            assert imp.col_offset == 0
        assert isinstance(m.body[3], ast.Expr)
        s = """'doc string'\nfrom __future__ import with_statement\nother"""
        m = rewrite(s)
        assert isinstance(m.body[0], ast.Expr)
        assert isinstance(m.body[0].value, ast.Str)
        assert isinstance(m.body[1], ast.ImportFrom)
        for imp in m.body[2:4]:
            assert isinstance(imp, ast.Import)
            assert imp.lineno == 3
            assert imp.col_offset == 0
        assert isinstance(m.body[4], ast.Expr)
        s = """from . import relative\nother_stuff"""
        m = rewrite(s)
        for imp in m.body[0:2]:
            assert isinstance(imp, ast.Import)
            assert imp.lineno == 1
            assert imp.col_offset == 0
        assert isinstance(m.body[3], ast.Expr)

    def test_dont_rewrite(self):
        s = """'PYTEST_DONT_REWRITE'\nassert 14"""
        m = rewrite(s)
        assert len(m.body) == 2
        assert isinstance(m.body[0].value, ast.Str)
        assert isinstance(m.body[1], ast.Assert)
        assert m.body[1].msg is None

    def test_name(self):
        def f():
            assert False
        assert getmsg(f) == "assert False"
        def f():
            f = False
            assert f
        assert getmsg(f) == "assert False"
        def f():
            assert a_global
        assert getmsg(f, {"a_global" : False}) == "assert a_global"

    def test_assert_already_has_message(self):
        def f():
            assert False, "something bad!"
        assert getmsg(f) == "AssertionError: something bad!"

    def test_boolop(self):
        def f():
            f = g = False
            assert f and g
        assert getmsg(f) == "assert (False)"
        def f():
            f = True
            g = False
            assert f and g
        assert getmsg(f) == "assert (True and False)"
        def f():
            f = False
            g = True
            assert f and g
        assert getmsg(f) == "assert (False)"
        def f():
            f = g = False
            assert f or g
        assert getmsg(f) == "assert (False or False)"
        def f():
            f = g = False
            assert not f and not g
        getmsg(f, must_pass=True)
        def x():
            return False
        def f():
            assert x() and x()
        assert getmsg(f, {"x" : x}) == "assert (x())"
        def f():
            assert False or x()
        assert getmsg(f, {"x" : x}) == "assert (False or x())"
        def f():
            assert 1 in {} and 2 in {}
        assert getmsg(f) == "assert (1 in {})"
        def f():
            x = 1
            y = 2
            assert x in {1 : None} and y in {}
        assert getmsg(f) == "assert (1 in {1: None} and 2 in {})"
        def f():
            f = True
            g = False
            assert f or g
        getmsg(f, must_pass=True)
        def f():
            f = g = h = lambda: True
            assert f() and g() and h()
        getmsg(f, must_pass=True)

    def test_short_circut_evaluation(self):
        def f():
            assert True or explode
        getmsg(f, must_pass=True)
        def f():
            x = 1
            assert x == 1 or x == 2
        getmsg(f, must_pass=True)

    def test_unary_op(self):
        def f():
            x = True
            assert not x
        assert getmsg(f) == "assert not True"
        def f():
            x = 0
            assert ~x + 1
        assert getmsg(f) == "assert (~0 + 1)"
        def f():
            x = 3
            assert -x + x
        assert getmsg(f) == "assert (-3 + 3)"
        def f():
            x = 0
            assert +x + x
        assert getmsg(f) == "assert (+0 + 0)"

    def test_binary_op(self):
        def f():
            x = 1
            y = -1
            assert x + y
        assert getmsg(f) == "assert (1 + -1)"
        def f():
            x = range(10)
            assert not 5 % 4
        assert getmsg(f) == "assert not (5 % 4)"

    def test_call(self):
        def g(a=42, *args, **kwargs):
            return False
        ns = {"g" : g}
        def f():
            assert g()
        assert getmsg(f, ns) == """assert g()"""
        def f():
            assert g(1)
        assert getmsg(f, ns) == """assert g(1)"""
        def f():
            assert g(1, 2)
        assert getmsg(f, ns) == """assert g(1, 2)"""
        def f():
            assert g(1, g=42)
        assert getmsg(f, ns) == """assert g(1, g=42)"""
        def f():
            assert g(1, 3, g=23)
        assert getmsg(f, ns) == """assert g(1, 3, g=23)"""
        def f():
            seq = [1, 2, 3]
            assert g(*seq)
        assert getmsg(f, ns) == """assert g(*[1, 2, 3])"""
        def f():
            x = "a"
            assert g(**{x : 2})
        assert getmsg(f, ns) == """assert g(**{'a': 2})"""

    def test_attribute(self):
        class X(object):
            g = 3
        ns = {"X" : X, "x" : X()}
        def f():
            assert not x.g
        assert getmsg(f, ns) == """assert not 3
 +  where 3 = x.g"""
        def f():
            x.a = False
            assert x.a
        assert getmsg(f, ns) == """assert x.a"""

    def test_comparisons(self):
        def f():
            a, b = range(2)
            assert b < a
        assert getmsg(f) == """assert 1 < 0"""
        def f():
            a, b, c = range(3)
            assert a > b > c
        assert getmsg(f) == """assert 0 > 1"""
        def f():
            a, b, c = range(3)
            assert a < b > c
        assert getmsg(f) == """assert 1 > 2"""
        def f():
            a, b, c = range(3)
            assert a < b <= c
        getmsg(f, must_pass=True)
        def f():
            a, b, c = range(3)
            assert a < b
            assert b < c
        getmsg(f, must_pass=True)

    def test_len(self):
        def f():
            l = list(range(10))
            assert len(l) == 11
        assert getmsg(f).startswith("""assert 10 == 11
 +  where 10 = len([""")

    def test_custom_reprcompare(self, monkeypatch):
        def my_reprcompare(op, left, right):
            return "42"
        monkeypatch.setattr(util, "_reprcompare", my_reprcompare)
        def f():
            assert 42 < 3
        assert getmsg(f) == "assert 42"
        def my_reprcompare(op, left, right):
            return "%s %s %s" % (left, op, right)
        monkeypatch.setattr(util, "_reprcompare", my_reprcompare)
        def f():
            assert 1 < 3 < 5 <= 4 < 7
        assert getmsg(f) == "assert 5 <= 4"

    def test_assert_raising_nonzero_in_comparison(self):
        def f():
            class A(object):
                def __nonzero__(self):
                    raise ValueError(42)
                def __lt__(self, other):
                    return A()
                def __repr__(self):
                    return "<MY42 object>"
            def myany(x):
                return False
            assert myany(A() < 0)
        assert "<MY42 object> < 0" in getmsg(f)

    def test_formatchar(self):
        def f():
            assert "%test" == "test"
        assert getmsg(f).startswith("assert '%test' == 'test'")

class TestRewriteOnImport:

    def test_pycache_is_a_file(self, testdir):
        testdir.tmpdir.join("__pycache__").write("Hello")
        testdir.makepyfile("""
def test_rewritten():
    assert "@py_builtins" in globals()""")
        assert testdir.runpytest().ret == 0

    def test_zipfile(self, testdir):
        z = testdir.tmpdir.join("myzip.zip")
        z_fn = str(z)
        f = zipfile.ZipFile(z_fn, "w")
        try:
            f.writestr("test_gum/__init__.py", "")
            f.writestr("test_gum/test_lizard.py", "")
        finally:
            f.close()
        z.chmod(256)
        testdir.makepyfile("""
import sys
sys.path.append(%r)
import test_gum.test_lizard""" % (z_fn,))
        assert testdir.runpytest().ret == 0

    def test_readonly(self, testdir):
        sub = testdir.mkdir("testing")
        sub.join("test_readonly.py").write(
        py.builtin._totext("""
def test_rewritten():
    assert "@py_builtins" in globals()
""").encode("utf-8"), "wb")
        sub.chmod(320)
        assert testdir.runpytest().ret == 0

    def test_dont_write_bytecode(self, testdir, monkeypatch):
        testdir.makepyfile("""
import os
def test_no_bytecode():
    assert "__pycache__" in __cached__
    assert not os.path.exists(__cached__)
    assert not os.path.exists(os.path.dirname(__cached__))""")
        monkeypatch.setenv("PYTHONDONTWRITEBYTECODE", "1")
        assert testdir.runpytest().ret == 0

    def test_pyc_vs_pyo(self, testdir, monkeypatch):
        testdir.makepyfile("""
import pytest
def test_optimized():
    "hello"
    assert test_optimized.__doc__ is None""")
        p = py.path.local.make_numbered_dir(prefix="runpytest-", keep=None,
                                            rootdir=testdir.tmpdir)
        tmp = "--basetemp=%s" % p
        monkeypatch.setenv("PYTHONOPTIMIZE", "2")
        assert testdir.runpybin("py.test", tmp).ret == 0
        monkeypatch.undo()
        assert testdir.runpybin("py.test", tmp).ret == 1

    def test_package(self, testdir):
        pkg = testdir.tmpdir.join("pkg")
        pkg.mkdir()
        pkg.join("__init__.py").ensure()
        pkg.join("test_blah.py").write("""
def test_rewritten():
    assert "@py_builtins" in globals()""")
        assert testdir.runpytest().ret == 0

    def test_translate_newlines(self, testdir):
        content = "def test_rewritten():\r\n assert '@py_builtins' in globals()"
        b = content.encode("utf-8")
        testdir.tmpdir.join("test_newlines.py").write(b, "wb")
        assert testdir.runpytest().ret == 0
<commit_msg>skip test for pyo on pypy since pypy doesnt do pyo<commit_after>import sys
import zipfile
import py
import pytest

ast = pytest.importorskip("ast")
if sys.platform.startswith("java"):
    # XXX should be xfail
    pytest.skip("assert rewrite does currently not work on jython")

from _pytest.assertion import util
from _pytest.assertion.rewrite import rewrite_asserts

def setup_module(mod):
    mod._old_reprcompare = util._reprcompare
    py.code._reprcompare = None

def teardown_module(mod):
    util._reprcompare = mod._old_reprcompare
    del mod._old_reprcompare

def rewrite(src):
    tree = ast.parse(src)
    rewrite_asserts(tree)
    return tree

def getmsg(f, extra_ns=None, must_pass=False):
    """Rewrite the assertions in f, run it, and get the failure message."""
    src = '\n'.join(py.code.Code(f).source().lines)
    mod = rewrite(src)
    code = compile(mod, "<test>", "exec")
    ns = {}
    if extra_ns is not None:
        ns.update(extra_ns)
    py.builtin.exec_(code, ns)
    func = ns[f.__name__]
    try:
        func()
    except AssertionError:
        if must_pass:
            pytest.fail("shouldn't have raised")
        s = str(sys.exc_info()[1])
        if not s.startswith("assert"):
            return "AssertionError: " + s
        return s
    else:
        if not must_pass:
            pytest.fail("function didn't raise at all")

class TestAssertionRewrite:

    def test_place_initial_imports(self):
        s = """'Doc string'\nother = stuff"""
        m = rewrite(s)
        assert isinstance(m.body[0], ast.Expr)
        assert isinstance(m.body[0].value, ast.Str)
        for imp in m.body[1:3]:
            assert isinstance(imp, ast.Import)
            assert imp.lineno == 2
            assert imp.col_offset == 0
        assert isinstance(m.body[3], ast.Assign)
        s = """from __future__ import with_statement\nother_stuff"""
        m = rewrite(s)
        assert isinstance(m.body[0], ast.ImportFrom)
        for imp in m.body[1:3]:
            assert isinstance(imp, ast.Import)
            assert imp.lineno == 2
            assert imp.col_offset == 0
        assert isinstance(m.body[3], ast.Expr)
        s = """'doc string'\nfrom __future__ import with_statement\nother"""
        m = rewrite(s)
        assert isinstance(m.body[0], ast.Expr)
        assert isinstance(m.body[0].value, ast.Str)
        assert isinstance(m.body[1], ast.ImportFrom)
        for imp in m.body[2:4]:
            assert isinstance(imp, ast.Import)
            assert imp.lineno == 3
            assert imp.col_offset == 0
        assert isinstance(m.body[4], ast.Expr)
        s = """from . import relative\nother_stuff"""
        m = rewrite(s)
        for imp in m.body[0:2]:
            assert isinstance(imp, ast.Import)
            assert imp.lineno == 1
            assert imp.col_offset == 0
        assert isinstance(m.body[3], ast.Expr)

    def test_dont_rewrite(self):
        s = """'PYTEST_DONT_REWRITE'\nassert 14"""
        m = rewrite(s)
        assert len(m.body) == 2
        assert isinstance(m.body[0].value, ast.Str)
        assert isinstance(m.body[1], ast.Assert)
        assert m.body[1].msg is None

    def test_name(self):
        def f():
            assert False
        assert getmsg(f) == "assert False"
        def f():
            f = False
            assert f
        assert getmsg(f) == "assert False"
        def f():
            assert a_global
        assert getmsg(f, {"a_global" : False}) == "assert a_global"

    def test_assert_already_has_message(self):
        def f():
            assert False, "something bad!"
        assert getmsg(f) == "AssertionError: something bad!"

    def test_boolop(self):
        def f():
            f = g = False
            assert f and g
        assert getmsg(f) == "assert (False)"
        def f():
            f = True
            g = False
            assert f and g
        assert getmsg(f) == "assert (True and False)"
        def f():
            f = False
            g = True
            assert f and g
        assert getmsg(f) == "assert (False)"
        def f():
            f = g = False
            assert f or g
        assert getmsg(f) == "assert (False or False)"
        def f():
            f = g = False
            assert not f and not g
        getmsg(f, must_pass=True)
        def x():
            return False
        def f():
            assert x() and x()
        assert getmsg(f, {"x" : x}) == "assert (x())"
        def f():
            assert False or x()
        assert getmsg(f, {"x" : x}) == "assert (False or x())"
        def f():
            assert 1 in {} and 2 in {}
        assert getmsg(f) == "assert (1 in {})"
        def f():
            x = 1
            y = 2
            assert x in {1 : None} and y in {}
        assert getmsg(f) == "assert (1 in {1: None} and 2 in {})"
        def f():
            f = True
            g = False
            assert f or g
        getmsg(f, must_pass=True)
        def f():
            f = g = h = lambda: True
            assert f() and g() and h()
        getmsg(f, must_pass=True)

    def test_short_circut_evaluation(self):
        def f():
            assert True or explode
        getmsg(f, must_pass=True)
        def f():
            x = 1
            assert x == 1 or x == 2
        getmsg(f, must_pass=True)

    def test_unary_op(self):
        def f():
            x = True
            assert not x
        assert getmsg(f) == "assert not True"
        def f():
            x = 0
            assert ~x + 1
        assert getmsg(f) == "assert (~0 + 1)"
        def f():
            x = 3
            assert -x + x
        assert getmsg(f) == "assert (-3 + 3)"
        def f():
            x = 0
            assert +x + x
        assert getmsg(f) == "assert (+0 + 0)"

    def test_binary_op(self):
        def f():
            x = 1
            y = -1
            assert x + y
        assert getmsg(f) == "assert (1 + -1)"
        def f():
            x = range(10)
            assert not 5 % 4
        assert getmsg(f) == "assert not (5 % 4)"

    def test_call(self):
        def g(a=42, *args, **kwargs):
            return False
        ns = {"g" : g}
        def f():
            assert g()
        assert getmsg(f, ns) == """assert g()"""
        def f():
            assert g(1)
        assert getmsg(f, ns) == """assert g(1)"""
        def f():
            assert g(1, 2)
        assert getmsg(f, ns) == """assert g(1, 2)"""
        def f():
            assert g(1, g=42)
        assert getmsg(f, ns) == """assert g(1, g=42)"""
        def f():
            assert g(1, 3, g=23)
        assert getmsg(f, ns) == """assert g(1, 3, g=23)"""
        def f():
            seq = [1, 2, 3]
            assert g(*seq)
        assert getmsg(f, ns) == """assert g(*[1, 2, 3])"""
        def f():
            x = "a"
            assert g(**{x : 2})
        assert getmsg(f, ns) == """assert g(**{'a': 2})"""

    def test_attribute(self):
        class X(object):
            g = 3
        ns = {"X" : X, "x" : X()}
        def f():
            assert not x.g
        assert getmsg(f, ns) == """assert not 3
 +  where 3 = x.g"""
        def f():
            x.a = False
            assert x.a
        assert getmsg(f, ns) == """assert x.a"""

    def test_comparisons(self):
        def f():
            a, b = range(2)
            assert b < a
        assert getmsg(f) == """assert 1 < 0"""
        def f():
            a, b, c = range(3)
            assert a > b > c
        assert getmsg(f) == """assert 0 > 1"""
        def f():
            a, b, c = range(3)
            assert a < b > c
        assert getmsg(f) == """assert 1 > 2"""
        def f():
            a, b, c = range(3)
            assert a < b <= c
        getmsg(f, must_pass=True)
        def f():
            a, b, c = range(3)
            assert a < b
            assert b < c
        getmsg(f, must_pass=True)

    def test_len(self):
        def f():
            l = list(range(10))
            assert len(l) == 11
        assert getmsg(f).startswith("""assert 10 == 11
 +  where 10 = len([""")

    def test_custom_reprcompare(self, monkeypatch):
        def my_reprcompare(op, left, right):
            return "42"
        monkeypatch.setattr(util, "_reprcompare", my_reprcompare)
        def f():
            assert 42 < 3
        assert getmsg(f) == "assert 42"
        def my_reprcompare(op, left, right):
            return "%s %s %s" % (left, op, right)
        monkeypatch.setattr(util, "_reprcompare", my_reprcompare)
        def f():
            assert 1 < 3 < 5 <= 4 < 7
        assert getmsg(f) == "assert 5 <= 4"

    def test_assert_raising_nonzero_in_comparison(self):
        def f():
            class A(object):
                def __nonzero__(self):
                    raise ValueError(42)
                def __lt__(self, other):
                    return A()
                def __repr__(self):
                    return "<MY42 object>"
            def myany(x):
                return False
            assert myany(A() < 0)
        assert "<MY42 object> < 0" in getmsg(f)

    def test_formatchar(self):
        def f():
            assert "%test" == "test"
        assert getmsg(f).startswith("assert '%test' == 'test'")

class TestRewriteOnImport:

    def test_pycache_is_a_file(self, testdir):
        testdir.tmpdir.join("__pycache__").write("Hello")
        testdir.makepyfile("""
def test_rewritten():
    assert "@py_builtins" in globals()""")
        assert testdir.runpytest().ret == 0

    def test_zipfile(self, testdir):
        z = testdir.tmpdir.join("myzip.zip")
        z_fn = str(z)
        f = zipfile.ZipFile(z_fn, "w")
        try:
            f.writestr("test_gum/__init__.py", "")
            f.writestr("test_gum/test_lizard.py", "")
        finally:
            f.close()
        z.chmod(256)
        testdir.makepyfile("""
import sys
sys.path.append(%r)
import test_gum.test_lizard""" % (z_fn,))
        assert testdir.runpytest().ret == 0

    def test_readonly(self, testdir):
        sub = testdir.mkdir("testing")
        sub.join("test_readonly.py").write(
        py.builtin._totext("""
def test_rewritten():
    assert "@py_builtins" in globals()
""").encode("utf-8"), "wb")
        sub.chmod(320)
        assert testdir.runpytest().ret == 0

    def test_dont_write_bytecode(self, testdir, monkeypatch):
        testdir.makepyfile("""
import os
def test_no_bytecode():
    assert "__pycache__" in __cached__
    assert not os.path.exists(__cached__)
    assert not os.path.exists(os.path.dirname(__cached__))""")
        monkeypatch.setenv("PYTHONDONTWRITEBYTECODE", "1")
        assert testdir.runpytest().ret == 0

    @pytest.mark.skipif('"__pypy__" in sys.modules')
    def test_pyc_vs_pyo(self, testdir, monkeypatch):
        testdir.makepyfile("""
import pytest
def test_optimized():
    "hello"
    assert test_optimized.__doc__ is None""")
        p = py.path.local.make_numbered_dir(prefix="runpytest-", keep=None,
                                            rootdir=testdir.tmpdir)
        tmp = "--basetemp=%s" % p
        monkeypatch.setenv("PYTHONOPTIMIZE", "2")
        assert testdir.runpybin("py.test", tmp).ret == 0
        monkeypatch.undo()
        assert testdir.runpybin("py.test", tmp).ret == 1

    def test_package(self, testdir):
        pkg = testdir.tmpdir.join("pkg")
        pkg.mkdir()
        pkg.join("__init__.py").ensure()
        pkg.join("test_blah.py").write("""
def test_rewritten():
    assert "@py_builtins" in globals()""")
        assert testdir.runpytest().ret == 0

    def test_translate_newlines(self, testdir):
        content = "def test_rewritten():\r\n assert '@py_builtins' in globals()"
        b = content.encode("utf-8")
        testdir.tmpdir.join("test_newlines.py").write(b, "wb")
        assert testdir.runpytest().ret == 0
<|endoftext|>


<commit_before>def writeCoordinates(file, x, y, z):
    file.write("(" + str(x) + "," + str(y) + "," + str(z) + ") ")

def createTex(x, y, z, output='3d-manhattan-bar-plot.tex'):
    template = open('template.tpl', 'r').read()
    make3dhistogram(x, y, z, 0.0, 'data')
    data = open('data', 'r').read()
    file = open(output, 'wb')
    template = template.replace('[PLACE_PLOT_HERE]', data)
    template = template.replace('[XMAX]', str(len(x)-1))
    template = template.replace('[YMAX]', str(len(y)-1))
    file.write(template)

def make3dhistogram(x, y, z, zmin, output):
    file = open(output, 'wb')
    i = 0
    for j in range(len(y)):
        writeCoordinates(file, x[i], y[j], zmin)
        writeCoordinates(file, x[i], y[j], zmin)
    file.write("\n\n")
    for i in range(len(x)-1):
        writeCoordinates(file, x[i], y[0], zmin)
        for j in range(len(y)-1):
            writeCoordinates(file, x[i], y[j], z[i][j])
            writeCoordinates(file, x[i], y[j+1], z[i][j])
        writeCoordinates(file, x[i], y[len(y)-1], zmin)
        writeCoordinates(file, x[i+1], y[0], zmin)
        file.write("\n\n")
        for j in range(len(y)-1):
            writeCoordinates(file, x[i+1], y[j], z[i][j])
            writeCoordinates(file, x[i+1], y[j+1], z[i][j])
        writeCoordinates(file, x[i+1], y[len(y)-1], zmin)
        file.write("\n\n")

    i = len(x)-1
    for j in range(len(y)):
        writeCoordinates(file, x[i], y[j], zmin)
        writeCoordinates(file, x[i], y[j], zmin)

if __name__ == "__main__":
    x = [0,1,2,3,4]
    y = [0,1,2,3,4] # <- size of y
    z = [[2,3,1,0], [0,6,0,0], [1,0,0,4], [0,0,0,0]]
    createTex(x,y,z)
<commit_msg>added comment<commit_after>def writeCoordinates(file, x, y, z):
    file.write("(" + str(x) + "," + str(y) + "," + str(z) + ") ")

def createTex(x, y, z, output='3d-manhattan-bar-plot.tex'):
    template = open('template.tpl', 'r').read()
    make3dhistogram(x, y, z, 0.0, 'data')
    data = open('data', 'r').read()
    file = open(output, 'wb')
    template = template.replace('[PLACE_PLOT_HERE]', data)
    template = template.replace('[XMAX]', str(len(x)-1))
    template = template.replace('[YMAX]', str(len(y)-1))
    file.write(template)

def make3dhistogram(x, y, z, zmin, output):
    file = open(output, 'wb')
    i = 0
    for j in range(len(y)):
        writeCoordinates(file, x[i], y[j], zmin)
        writeCoordinates(file, x[i], y[j], zmin)
    file.write("\n\n")
    for i in range(len(x)-1):
        writeCoordinates(file, x[i], y[0], zmin)
        for j in range(len(y)-1):
            writeCoordinates(file, x[i], y[j], z[i][j])
            writeCoordinates(file, x[i], y[j+1], z[i][j])
        writeCoordinates(file, x[i], y[len(y)-1], zmin)
        writeCoordinates(file, x[i+1], y[0], zmin)
        file.write("\n\n")
        for j in range(len(y)-1):
            writeCoordinates(file, x[i+1], y[j], z[i][j])
            writeCoordinates(file, x[i+1], y[j+1], z[i][j])
        writeCoordinates(file, x[i+1], y[len(y)-1], zmin)
        file.write("\n\n")

    i = len(x)-1
    for j in range(len(y)):
        writeCoordinates(file, x[i], y[j], zmin)
        writeCoordinates(file, x[i], y[j], zmin)

if __name__ == "__main__":
    x = [0,1,2,3,4] # Whats that good for? Can it be replaced by range(xMax+1)?
    y = [0,1,2,3,4] # Whats that good for? Can it be replaced by range(yMax+1)?
    z = [[2,3,1,0], [0,6,0,0], [1,0,0,4], [0,0,0,0]]
    createTex(x,y,z)
<|endoftext|>


<commit_before>from .. utils import TranspileTestCase, UnaryOperationTestCase, BinaryOperationTestCase, InplaceOperationTestCase

class FloatTests(TranspileTestCase):
    def test_setattr(self):
        self.assertCodeExecution("""
            x = 3.14159
            try:
                x.attr = 42
            except AttributeError as err:
                print(err)
            """)

    def test_getattr(self):
        self.assertCodeExecution("""
            x = 3.14159
            try:
                print(x.attr)
            except AttributeError as err:
                print(err)
            """)

    def test_repr(self):
        self.assertCodeExecution("""
            x = 350000000000000000.0
            print(x)
            x = 3500.0
            print(x)
            x = 35.0
            print(x)
            x = 3.5
            print(x)
            x = 0.35
            print(x)
            x = 0.035
            print(x)
            x = 0.0035
            print(x)
            x = 0.00035
            print(x)
            x = 0.000035
            print(x)
            x = 0.0000035
            print(x)
            x = 0.00000000000000035
            print(x)

            x = 0.0
            print(x)
            x = float('-0.0')
            print(x)
            x = float('nan')
            print(x)
            x = float('inf')
            print(x)
            x = float('-inf')
            print(x)
            """)

    def test_negative_zero_constant(self):
        self.assertCodeExecution("""
            x = -0.0
            y = 0.0
            print(x, y)
            """)

    def test_is_integer(self):
        self.assertCodeExecution("""
            x = 0.0
            print(x.is_integer())
            x = 3.14
            print(x.is_integer())
            x = -1.0
            print(x.is_integer())
            x = -62.5
            print(x.is_integer())
            x = float('nan')
            print(x.is_integer())
            x = float('inf')
            print(x.is_integer())
            x = float('-inf')
            print(x.is_integer())
            """)

    def test_hex(self):
        numbers = [
            0e0, -0e0, 10000152587890625e-16, -566e85,
            -87336362425182547697e-280, 4.9406564584124654e-324,
            'nan', 'inf', '-inf'
        ]
        template = """
            x = float('{}')
            print(x.hex())
            """
        code = '\n'.join(template.format(number) for number in numbers)
        self.assertCodeExecution(code)

class UnaryFloatOperationTests(UnaryOperationTestCase, TranspileTestCase):
    data_type = 'float'

    not_implemented = [
    ]

class BinaryFloatOperationTests(BinaryOperationTestCase, TranspileTestCase):
    data_type = 'float'

    not_implemented = [
        'test_modulo_complex',

        'test_multiply_bytearray',
        'test_multiply_bytes',
        'test_multiply_class',
        'test_multiply_complex',
        'test_multiply_NotImplemented',
        'test_multiply_range',

        'test_power_complex',
        'test_power_float',

        'test_subscr_bool',
        'test_subscr_bytearray',
        'test_subscr_bytes',
        'test_subscr_class',
        'test_subscr_complex',
        'test_subscr_dict',
        'test_subscr_float',
        'test_subscr_frozenset',
        'test_subscr_int',
        'test_subscr_list',
        'test_subscr_None',
        'test_subscr_NotImplemented',
        'test_subscr_range',
        'test_subscr_set',
        'test_subscr_slice',
        'test_subscr_str',
        'test_subscr_tuple',

        'test_true_divide_complex',
    ]

class InplaceFloatOperationTests(InplaceOperationTestCase, TranspileTestCase):
    data_type = 'float'

    not_implemented = [
        'test_multiply_bytearray',
        'test_multiply_bytes',
        'test_multiply_class',
        'test_multiply_complex',
        'test_multiply_frozenset',
        'test_multiply_list',
        'test_multiply_NotImplemented',
        'test_multiply_range',
        'test_multiply_str',
        'test_multiply_tuple',

        'test_power_complex',
        'test_power_float',

        'test_true_divide_complex',
    ]
<commit_msg>Fixed error-unexpected success<commit_after>from .. utils import TranspileTestCase, UnaryOperationTestCase, BinaryOperationTestCase, InplaceOperationTestCase

class FloatTests(TranspileTestCase):
    def test_setattr(self):
        self.assertCodeExecution("""
            x = 3.14159
            try:
                x.attr = 42
            except AttributeError as err:
                print(err)
            """)

    def test_getattr(self):
        self.assertCodeExecution("""
            x = 3.14159
            try:
                print(x.attr)
            except AttributeError as err:
                print(err)
            """)

    def test_repr(self):
        self.assertCodeExecution("""
            x = 350000000000000000.0
            print(x)
            x = 3500.0
            print(x)
            x = 35.0
            print(x)
            x = 3.5
            print(x)
            x = 0.35
            print(x)
            x = 0.035
            print(x)
            x = 0.0035
            print(x)
            x = 0.00035
            print(x)
            x = 0.000035
            print(x)
            x = 0.0000035
            print(x)
            x = 0.00000000000000035
            print(x)

            x = 0.0
            print(x)
            x = float('-0.0')
            print(x)
            x = float('nan')
            print(x)
            x = float('inf')
            print(x)
            x = float('-inf')
            print(x)
            """)

    def test_negative_zero_constant(self):
        self.assertCodeExecution("""
            x = -0.0
            y = 0.0
            print(x, y)
            """)

    def test_is_integer(self):
        self.assertCodeExecution("""
            x = 0.0
            print(x.is_integer())
            x = 3.14
            print(x.is_integer())
            x = -1.0
            print(x.is_integer())
            x = -62.5
            print(x.is_integer())
            x = float('nan')
            print(x.is_integer())
            x = float('inf')
            print(x.is_integer())
            x = float('-inf')
            print(x.is_integer())
            """)

    def test_hex(self):
        numbers = [
            0e0, -0e0, 10000152587890625e-16, -566e85,
            -87336362425182547697e-280, 4.9406564584124654e-324,
            'nan', 'inf', '-inf'
        ]
        template = """
            x = float('{}')
            print(x.hex())
            """
        code = '\n'.join(template.format(number) for number in numbers)
        self.assertCodeExecution(code)

class UnaryFloatOperationTests(UnaryOperationTestCase, TranspileTestCase):
    data_type = 'float'

    not_implemented = [
    ]

class BinaryFloatOperationTests(BinaryOperationTestCase, TranspileTestCase):
    data_type = 'float'

    not_implemented = [
        'test_modulo_complex',

        'test_multiply_bytearray',
        'test_multiply_bytes',
        'test_multiply_class',
        'test_multiply_complex',
        'test_multiply_NotImplemented',
        'test_multiply_range',

        'test_power_complex',
        'test_power_float',

        'test_subscr_bool',
        'test_subscr_bytearray',
        'test_subscr_bytes',
        'test_subscr_class',
        'test_subscr_complex',
        'test_subscr_dict',
        'test_subscr_float',
        'test_subscr_frozenset',
        'test_subscr_int',
        'test_subscr_list',
        'test_subscr_None',
        'test_subscr_NotImplemented',
        'test_subscr_range',
        'test_subscr_set',
        'test_subscr_slice',
        'test_subscr_str',
        'test_subscr_tuple',

        'test_true_divide_complex',
    ]

class InplaceFloatOperationTests(InplaceOperationTestCase, TranspileTestCase):
    data_type = 'float'

    not_implemented = [
        'test_multiply_bytearray',
        'test_multiply_bytes',
        'test_multiply_class',
        'test_multiply_complex',
        'test_multiply_list',
        'test_multiply_NotImplemented',
        'test_multiply_range',
        'test_multiply_str',
        'test_multiply_tuple',

        'test_power_complex',
        'test_power_float',

        'test_true_divide_complex',
    ]
<|endoftext|>