<commit_before># -*- coding: utf-8 -*-
from distutils.version import LooseVersion

import django
import pytest
import six
from django import get_version
from django.core.exceptions import ValidationError
from django.db import migrations, models, IntegrityError
from django.db.migrations.writer import MigrationWriter
from django.test import TestCase, TransactionTestCase
from django.utils.encoding import force_bytes

import django_extensions  # noqa
from django_extensions.db.fields import AutoSlugField

from .testapp.models import (
    ChildSluggedTestModel, CustomFuncPrecedenceSluggedTestModel, CustomFuncSluggedTestModel,
    FKSluggedTestModel, FKSluggedTestModelCallable, FunctionSluggedTestModel,
    ModelMethodSluggedTestModel, SluggedTestModel, SluggedTestNoOverwriteOnAddModel,
    OverridedFindUniqueModel, SluggedWithConstraintsTestModel,
)

@pytest.mark.usefixtures("admin_user")
class AutoSlugFieldTest(TestCase):
    def tearDown(self):
        super(AutoSlugFieldTest, self).tearDown()

        SluggedTestModel.objects.all().delete()
        CustomFuncSluggedTestModel.objects.all().delete()
        CustomFuncPrecedenceSluggedTestModel.objects.all().delete()

    def test_auto_create_slug(self):
        m = SluggedTestModel(title='foo')
        m.save()
        self.assertEqual(m.slug, 'foo')

    def test_auto_create_next_slug(self):
        m = SluggedTestModel(title='foo')
        m.save()

        m = SluggedTestModel(title='foo')
        m.save()
        self.assertEqual(m.slug, 'foo-2')

    def test_auto_create_slug_with_number(self):
        m = SluggedTestModel(title='foo 2012')
        m.save()
        self.assertEqual(m.slug, 'foo-2012')

    def test_auto_update_slug_with_number(self):
        m = SluggedTestModel(title='foo 2012')
        m.save()
        m.save()
        self.assertEqual(m.slug, 'foo-2012')

    def test_update_slug(self):
        m = SluggedTestModel(title='foo')
        m.save()
        self.assertEqual(m.slug, 'foo')

        # update m instance without using `save'
        SluggedTestModel.objects.filter(pk=m.pk).update(slug='foo-2012')
        # update m instance with new data from the db
        m = SluggedTestModel.objects.get(pk=m.pk)
        self.assertEqual(m.slug, 'foo-2012')

        m.save()
        self.assertEqual(m.title, 'foo')
        self.assertEqual(m.slug, 'foo-2012')

        # Check slug is not overwrite
        m.title = 'bar'
        m.save()
        self.assertEqual(m.title, 'bar')
        self.assertEqual(m.slug, 'foo-2012')

    def test_simple_slug_source(self):
        m = SluggedTestModel(title='-foo')
        m.save()
        self.assertEqual(m.slug, 'foo')

        n = SluggedTestModel(title='-foo')
        n.save()
        self.assertEqual(n.slug, 'foo-2')

        n.save()
        self.assertEqual(n.slug, 'foo-2')

    def test_empty_slug_source(self):
        # regression test

        m = SluggedTestModel(title='')
        m.save()
        self.assertEqual(m.slug, '-2')

        n = SluggedTestModel(title='')
        n.save()
        self.assertEqual(n.slug, '-3')

        n.save()
        self.assertEqual(n.slug, '-3')

    def test_callable_method_slug_source(self):
        m = ModelMethodSluggedTestModel(title='-foo')
        m.save()
        self.assertEqual(m.slug, 'the-title-is-foo')

        n = ModelMethodSluggedTestModel(title='-foo')
        n.save()
        self.assertEqual(n.slug, 'the-title-is-foo-2')

        n.save()
        self.assertEqual(n.slug, 'the-title-is-foo-2')

    def test_callable_function_slug_source(self):
        m = FunctionSluggedTestModel(title='-foo')
        m.save()
        self.assertEqual(m.slug, 'the-title-is-foo')

        n = FunctionSluggedTestModel(title='-foo')
        n.save()
        self.assertEqual(n.slug, 'the-title-is-foo-2')

        n.save()
        self.assertEqual(n.slug, 'the-title-is-foo-2')

    def test_inheritance_creates_next_slug(self):
        m = SluggedTestModel(title='foo')
        m.save()

        n = ChildSluggedTestModel(title='foo')
        n.save()
        self.assertEqual(n.slug, 'foo-2')

        o = SluggedTestModel(title='foo')
        o.save()
        self.assertEqual(o.slug, 'foo-3')

    def test_foreign_key_populate_from_field(self):
        m_fk = SluggedTestModel(title='foo')
        m_fk.save()
        m = FKSluggedTestModel(related_field=m_fk)
        m.save()
        self.assertEqual(m.slug, 'foo')

    def test_foreign_key_populate_from_callable(self):
        m_fk = ModelMethodSluggedTestModel(title='foo')
        m_fk.save()
        m = FKSluggedTestModelCallable(related_field=m_fk)
        m.save()
        self.assertEqual(m.slug, 'the-title-is-foo')

    def test_copy_model_generates_new_slug(self):
        m = SluggedTestModel(title='foo')
        m.save()
        self.assertEqual(m.slug, 'foo')

        m.pk = None
        m.save()
        self.assertEqual(m.slug, 'foo-2')

    def test_copy_model_generates_new_slug_no_overwrite_on_add(self):
        m = SluggedTestNoOverwriteOnAddModel(title='foo')
        m.save()
        self.assertEqual(m.slug, 'foo')

        m.pk = None
        m.slug = None
        m.save()
        self.assertEqual(m.slug, 'foo-2')

    def test_populate_from_does_not_allow_bytes(self):
        if six.PY3:
            with pytest.raises(TypeError):
                AutoSlugField(populate_from=b'bytes')

            with pytest.raises(TypeError):
                AutoSlugField(populate_from=[b'bytes'])

    def test_populate_from_must_allow_string_or_list_str_or_tuple_str(self):
        AutoSlugField(populate_from='str')
        AutoSlugField(populate_from=['str'])
        AutoSlugField(populate_from=('str', ))

    def test_slug_argument_priority(self):
        m = SluggedTestModel(slug='slug', title='title')
        m.save()
        self.assertEqual(m.slug, 'title')

    def test_slug_argument_priority_no_overwrite_on_add(self):
        m = SluggedTestNoOverwriteOnAddModel(slug='slug', title='title')
        m.save()
        self.assertEqual(m.slug, 'slug')

    def test_overrided_find_unique_autoslug_field(self):
        m = OverridedFindUniqueModel(title='foo')
        slug_field = m._meta.fields[2]
        self.assertFalse(hasattr(slug_field, 'overrided'))
        m.save()
        slug_field = m._meta.fields[2]
        self.assertTrue(slug_field.overrided)

    def test_slugify_func(self):
        to_upper = lambda c: c.upper()
        to_lower = lambda c: c.lower()

        content_n_func_n_expected = (
            ('test', to_upper, 'TEST'),
            ('', to_upper, ''),
            ('TEST', to_lower, 'test'),
        )

        for content, slugify_function, expected in content_n_func_n_expected:
            self.assertEqual(
                AutoSlugField.slugify_func(content, slugify_function),
                expected
            )

    def test_use_custom_slug_function(self):
        m = CustomFuncSluggedTestModel(title='test')
        m.save()
        self.assertEqual(m.slug, 'TEST')

    def test_precedence_custom_slug_function(self):
        m = CustomFuncPrecedenceSluggedTestModel(title='test')
        m.save()
        self.assertEqual(m.slug, 'TEST')
        self.assertTrue(hasattr(m._meta.get_field('slug'), 'slugify_function'))
        self.assertEqual(m._meta.get_field('slug').slugify_function('TEST'), 'test')

class MigrationTest(TestCase):
    def safe_exec(self, string, value=None):
        dct = {}
        try:
            exec(force_bytes(string), globals(), dct)
        except Exception as e:
            if value:
                self.fail("Could not exec %r (from value %r): %s" % (string.strip(), value, e))
            else:
                self.fail("Could not exec %r: %s" % (string.strip(), e))
        return dct

    def test_17_migration(self):
        """
        Tests making migrations with Django's migration framework
        """

        fields = {
            'autoslugfield': AutoSlugField(populate_from='otherfield'),
        }

        migration = type(str("Migration"), (migrations.Migration,), {
            "operations": [
                migrations.CreateModel(
                    "MyModel",
                    tuple(fields.items()),
                    {'populate_from': 'otherfield'},
                    (models.Model,)
                ),
            ],
        })
        writer = MigrationWriter(migration)
        output = writer.as_string()
        # It should NOT be unicode.
        if django.VERSION < (1, 11):
            self.assertIsInstance(output, six.binary_type, "Migration as_string returned unicode")
        else:
            # As of Django 1.11 MigrationWriter.as_string returns unicode not bytes
            self.assertIsInstance(output, six.text_type, "Migration as_string returned bytes")
        # We don't test the output formatting - that's too fragile.
        # Just make sure it runs for now, and that things look alright.
        result = self.safe_exec(output)
        self.assertIn("Migration", result)

    def test_stable_deconstruct(self):
        slug_field = SluggedTestModel._meta.get_field('slug')
        construction_values = slug_field.deconstruct()
        m = SluggedTestModel(title='foo')
        m.save()
        self.assertEqual(slug_field.deconstruct(), construction_values)

@pytest.mark.skipif(
    LooseVersion(get_version()) < LooseVersion('2.2.0'),
    reason="This test works only on Django greater than 2.2.0",
)
class AutoFieldTransactionTest(TransactionTestCase):

    def test_fail_to_create_by_constraints(self):
        m = SluggedWithConstraintsTestModel(title='foo', category='self-introduction')
        m.save()
        self.assertEqual(m.slug, 'foo')

        with self.assertRaises((IntegrityError, ValidationError)):
            m = SluggedWithConstraintsTestModel(title='foo', category='self-introduction')
            m.save()
<commit_msg>Use django.VERSION<commit_after># -*- coding: utf-8 -*-
import django
import pytest
import six
from django.core.exceptions import ValidationError
from django.db import migrations, models, IntegrityError
from django.db.migrations.writer import MigrationWriter
from django.test import TestCase, TransactionTestCase
from django.utils.encoding import force_bytes

import django_extensions  # noqa
from django_extensions.db.fields import AutoSlugField

from .testapp.models import (
    ChildSluggedTestModel, CustomFuncPrecedenceSluggedTestModel, CustomFuncSluggedTestModel,
    FKSluggedTestModel, FKSluggedTestModelCallable, FunctionSluggedTestModel,
    ModelMethodSluggedTestModel, SluggedTestModel, SluggedTestNoOverwriteOnAddModel,
    OverridedFindUniqueModel, SluggedWithConstraintsTestModel,
)

@pytest.mark.usefixtures("admin_user")
class AutoSlugFieldTest(TestCase):
    def tearDown(self):
        super(AutoSlugFieldTest, self).tearDown()

        SluggedTestModel.objects.all().delete()
        CustomFuncSluggedTestModel.objects.all().delete()
        CustomFuncPrecedenceSluggedTestModel.objects.all().delete()

    def test_auto_create_slug(self):
        m = SluggedTestModel(title='foo')
        m.save()
        self.assertEqual(m.slug, 'foo')

    def test_auto_create_next_slug(self):
        m = SluggedTestModel(title='foo')
        m.save()

        m = SluggedTestModel(title='foo')
        m.save()
        self.assertEqual(m.slug, 'foo-2')

    def test_auto_create_slug_with_number(self):
        m = SluggedTestModel(title='foo 2012')
        m.save()
        self.assertEqual(m.slug, 'foo-2012')

    def test_auto_update_slug_with_number(self):
        m = SluggedTestModel(title='foo 2012')
        m.save()
        m.save()
        self.assertEqual(m.slug, 'foo-2012')

    def test_update_slug(self):
        m = SluggedTestModel(title='foo')
        m.save()
        self.assertEqual(m.slug, 'foo')

        # update m instance without using `save'
        SluggedTestModel.objects.filter(pk=m.pk).update(slug='foo-2012')
        # update m instance with new data from the db
        m = SluggedTestModel.objects.get(pk=m.pk)
        self.assertEqual(m.slug, 'foo-2012')

        m.save()
        self.assertEqual(m.title, 'foo')
        self.assertEqual(m.slug, 'foo-2012')

        # Check slug is not overwrite
        m.title = 'bar'
        m.save()
        self.assertEqual(m.title, 'bar')
        self.assertEqual(m.slug, 'foo-2012')

    def test_simple_slug_source(self):
        m = SluggedTestModel(title='-foo')
        m.save()
        self.assertEqual(m.slug, 'foo')

        n = SluggedTestModel(title='-foo')
        n.save()
        self.assertEqual(n.slug, 'foo-2')

        n.save()
        self.assertEqual(n.slug, 'foo-2')

    def test_empty_slug_source(self):
        # regression test

        m = SluggedTestModel(title='')
        m.save()
        self.assertEqual(m.slug, '-2')

        n = SluggedTestModel(title='')
        n.save()
        self.assertEqual(n.slug, '-3')

        n.save()
        self.assertEqual(n.slug, '-3')

    def test_callable_method_slug_source(self):
        m = ModelMethodSluggedTestModel(title='-foo')
        m.save()
        self.assertEqual(m.slug, 'the-title-is-foo')

        n = ModelMethodSluggedTestModel(title='-foo')
        n.save()
        self.assertEqual(n.slug, 'the-title-is-foo-2')

        n.save()
        self.assertEqual(n.slug, 'the-title-is-foo-2')

    def test_callable_function_slug_source(self):
        m = FunctionSluggedTestModel(title='-foo')
        m.save()
        self.assertEqual(m.slug, 'the-title-is-foo')

        n = FunctionSluggedTestModel(title='-foo')
        n.save()
        self.assertEqual(n.slug, 'the-title-is-foo-2')

        n.save()
        self.assertEqual(n.slug, 'the-title-is-foo-2')

    def test_inheritance_creates_next_slug(self):
        m = SluggedTestModel(title='foo')
        m.save()

        n = ChildSluggedTestModel(title='foo')
        n.save()
        self.assertEqual(n.slug, 'foo-2')

        o = SluggedTestModel(title='foo')
        o.save()
        self.assertEqual(o.slug, 'foo-3')

    def test_foreign_key_populate_from_field(self):
        m_fk = SluggedTestModel(title='foo')
        m_fk.save()
        m = FKSluggedTestModel(related_field=m_fk)
        m.save()
        self.assertEqual(m.slug, 'foo')

    def test_foreign_key_populate_from_callable(self):
        m_fk = ModelMethodSluggedTestModel(title='foo')
        m_fk.save()
        m = FKSluggedTestModelCallable(related_field=m_fk)
        m.save()
        self.assertEqual(m.slug, 'the-title-is-foo')

    def test_copy_model_generates_new_slug(self):
        m = SluggedTestModel(title='foo')
        m.save()
        self.assertEqual(m.slug, 'foo')

        m.pk = None
        m.save()
        self.assertEqual(m.slug, 'foo-2')

    def test_copy_model_generates_new_slug_no_overwrite_on_add(self):
        m = SluggedTestNoOverwriteOnAddModel(title='foo')
        m.save()
        self.assertEqual(m.slug, 'foo')

        m.pk = None
        m.slug = None
        m.save()
        self.assertEqual(m.slug, 'foo-2')

    def test_populate_from_does_not_allow_bytes(self):
        if six.PY3:
            with pytest.raises(TypeError):
                AutoSlugField(populate_from=b'bytes')

            with pytest.raises(TypeError):
                AutoSlugField(populate_from=[b'bytes'])

    def test_populate_from_must_allow_string_or_list_str_or_tuple_str(self):
        AutoSlugField(populate_from='str')
        AutoSlugField(populate_from=['str'])
        AutoSlugField(populate_from=('str', ))

    def test_slug_argument_priority(self):
        m = SluggedTestModel(slug='slug', title='title')
        m.save()
        self.assertEqual(m.slug, 'title')

    def test_slug_argument_priority_no_overwrite_on_add(self):
        m = SluggedTestNoOverwriteOnAddModel(slug='slug', title='title')
        m.save()
        self.assertEqual(m.slug, 'slug')

    def test_overrided_find_unique_autoslug_field(self):
        m = OverridedFindUniqueModel(title='foo')
        slug_field = m._meta.fields[2]
        self.assertFalse(hasattr(slug_field, 'overrided'))
        m.save()
        slug_field = m._meta.fields[2]
        self.assertTrue(slug_field.overrided)

    def test_slugify_func(self):
        to_upper = lambda c: c.upper()
        to_lower = lambda c: c.lower()

        content_n_func_n_expected = (
            ('test', to_upper, 'TEST'),
            ('', to_upper, ''),
            ('TEST', to_lower, 'test'),
        )

        for content, slugify_function, expected in content_n_func_n_expected:
            self.assertEqual(
                AutoSlugField.slugify_func(content, slugify_function),
                expected
            )

    def test_use_custom_slug_function(self):
        m = CustomFuncSluggedTestModel(title='test')
        m.save()
        self.assertEqual(m.slug, 'TEST')

    def test_precedence_custom_slug_function(self):
        m = CustomFuncPrecedenceSluggedTestModel(title='test')
        m.save()
        self.assertEqual(m.slug, 'TEST')
        self.assertTrue(hasattr(m._meta.get_field('slug'), 'slugify_function'))
        self.assertEqual(m._meta.get_field('slug').slugify_function('TEST'), 'test')

class MigrationTest(TestCase):
    def safe_exec(self, string, value=None):
        dct = {}
        try:
            exec(force_bytes(string), globals(), dct)
        except Exception as e:
            if value:
                self.fail("Could not exec %r (from value %r): %s" % (string.strip(), value, e))
            else:
                self.fail("Could not exec %r: %s" % (string.strip(), e))
        return dct

    def test_17_migration(self):
        """
        Tests making migrations with Django's migration framework
        """

        fields = {
            'autoslugfield': AutoSlugField(populate_from='otherfield'),
        }

        migration = type(str("Migration"), (migrations.Migration,), {
            "operations": [
                migrations.CreateModel(
                    "MyModel",
                    tuple(fields.items()),
                    {'populate_from': 'otherfield'},
                    (models.Model,)
                ),
            ],
        })
        writer = MigrationWriter(migration)
        output = writer.as_string()
        # It should NOT be unicode.
        if django.VERSION < (1, 11):
            self.assertIsInstance(output, six.binary_type, "Migration as_string returned unicode")
        else:
            # As of Django 1.11 MigrationWriter.as_string returns unicode not bytes
            self.assertIsInstance(output, six.text_type, "Migration as_string returned bytes")
        # We don't test the output formatting - that's too fragile.
        # Just make sure it runs for now, and that things look alright.
        result = self.safe_exec(output)
        self.assertIn("Migration", result)

    def test_stable_deconstruct(self):
        slug_field = SluggedTestModel._meta.get_field('slug')
        construction_values = slug_field.deconstruct()
        m = SluggedTestModel(title='foo')
        m.save()
        self.assertEqual(slug_field.deconstruct(), construction_values)

@pytest.mark.skipif(django.VERSION < (2, 2), reason="This test works only on Django greater than 2.2.0")
class AutoFieldTransactionTest(TransactionTestCase):

    def test_fail_to_create_by_constraints(self):
        m = SluggedWithConstraintsTestModel(title='foo', category='self-introduction')
        m.save()
        self.assertEqual(m.slug, 'foo')

        with self.assertRaises((IntegrityError, ValidationError)):
            m = SluggedWithConstraintsTestModel(title='foo', category='self-introduction')
            m.save()
<|endoftext|>


<commit_before>"""
  Cloud connected autonomous RC car.

  Copyright 2016 Visible Energy Inc. All Rights Reserved.
"""
__license__ = """
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.
"""
import time
import json
import serial
import string
import sys
import Queue
import threading
import subprocess

import streamer
import utils
from keras.models import model_from_json

class States:
  """ Vehicle states """
  IDLE=1
  RUNNING=2
  PAUSE=3
  STOPPED=0

class Modes:
  """ Vehicle running modes """
  AUTO=1        # fully autonomous
  TRAINING=2    # RC controlled to capture training video
  REMOTE=3      # controlled remotely through Cometa JSON/RPC

# --- Module constansts
THETA_CENTER = 90
MOTOR_NEUTRAL = 90
# filename to fetch telemetry from -- updated atomically by the controller loop at 30 Hz
TELEMFNAME = '/tmpfs/meta.txt'

# filename where to store the last frame -- used by the application loop and as parameter for the CNN prediction
FRAMEFNAME = '/tmpfs/frame.yuv'

def setup_arduino(config, logger):
  """ Arduino radio receiver and servos controller setup. """
  try:
    # set serial non-blocking
    port = serial.Serial(config['arduino']['serial'], config['arduino']['speed'], timeout=0.0, xonxoff=False, rtscts=False, dsrdtr=False)
    port.flushInput()
    port.flushOutput()
  except Exception as e:
    logger("Arduino setup: %s" % e)
    return None
  # wait the board to start
  while port.inWaiting() == 0:
    time.sleep(0.1)
  return port

class RCVehicle(object):
  """
  Vehicle controller class
    config - configuration object from config.json
    log - system logger
  """
  # current state and mode
  state = None
  mode = None

  # running options flags
  capture = False     # capturing video and telemetry for CNN training
  streaming = False   # streaming video to cloud server

  # current servo and motor values
  steering = None
  throttle = None

  # Arduino serial port
  arport = None

  # Mailbox for asynchronous commands
  mbox = Queue.Queue()

  # GPS readings
  readings={}

  # System logger
  log = None

  def __init__(self, config, logger):
    self.state=States.IDLE
    self.steering=THETA_CENTER
    self.throttle=MOTOR_NEUTRAL
    self.serial=config['serial']

    # Set the system log
    self.log=logger
    self.verbose=config['app_params']['verbose']

    # CNN predicting model
    self.cnn_model = None

    self.arport=setup_arduino(config, self.log)
    while self.arport == None:
      self.log("Fatal error setting up Arduino board. Cannot proceed without properly connecting to the control board.")
      time.sleep(5)
      self.arport=setup_arduino(config, self.log)
    # TODO: remember to create a board heartbeat thread

    # Global lock
    self.glock = threading.Lock()

    # Start the main loop
    self.loop_t = threading.Thread(target=self.control_loop)
    self.loop_t.daemon = True   # force to exit on SIGINT

    self.telemetry_period=config['app_params']['telemetry_period']
    return

  def load_model(self, modelpath):
    """ Load a CNN model """
    try:
      self.model = model_from_json(open(modelpath + ".json").read())
      self.model.load_weights(modelpath + ".h5")
    except Exception, e:
      self.log("Failed to load CNN model %s. (%s)" % (modelpath,str(e)) )
      return

    self.log("Loaded CNN model %s." % modelpath)
    return

  def state2run(self):
    """ State transition to RUNNING """
    if self.state == States.RUNNING:
      return
    self.steering=THETA_CENTER
    self.throttle=MOTOR_NEUTRAL
    self.state=States.RUNNING
    self.log("State RUNNING")
    return

  def state2stopped(self):
    """ State transition to PAUSE """
    if self.state == States.STOPPED:
      return
    self.steering=THETA_CENTER
    self.throttle=MOTOR_NEUTRAL
    self.state=States.STOPPED
    self.output_arduino(self.steering, self.throttle)
    self.log("State STOPPED")
    return

  def state2idle(self):
    """ State transition to IDLE """
    if self.state == States.IDLE:
      return
    self.steering=THETA_CENTER
    self.throttle=MOTOR_NEUTRAL
    self.state=States.IDLE
    self.output_arduino(self.steering, self.throttle)
    self.log("State IDLE")
    return

  def mode2auto(self):
    """ Mode transition to AUTO """
    if self.mode == Modes.AUTO:
      return
    # TODO: start the video fast video streamer

    self.mode=Modes.AUTO
    self.arport.flushInput()
    self.arport.flushOutput()
    self.log("Mode AUTO")
    return

  def mode2training(self):
    """ Mode transition to TRAINING """
    if self.mode == Modes.TRAINING:
      return
    # TODO: start the video streamer with telemetry annotations
    self.mode=Modes.TRAINING
    self.arport.flushInput()
    self.arport.flushOutput()
    self.log("Mode TRAINING")
    return

  def mode2remote(self):
    """ Mode transition to REMOTE """
    if self.mode == Modes.REMOTE:
      return

    self.arport.flushInput()
    self.arport.flushOutput()
    self.steering=THETA_CENTER
    self.throttle=MOTOR_NEUTRAL
    self.mode=Modes.REMOTE
    self.log("Mode REMOTE")
    return

  def start(self):
    """ Initial start """
    self.mode2training()
    self.state2run()
    self.loop_t.start()
    return

  def telemetry(self):
    ret = {}
    ret['type'] = 1
    ret['time'] = str(int(time.time() * 1000))
    ret['device'] = self.serial
    ret['state'] = self.state
    ret['mode'] = self.mode
    ret['steering'] = self.steering
    ret['throttle'] = self.throttle
    ret['GPS'] = {}
    try:
      ret['GPS']['lat'] = int(self.readings['lat'] * 10E4) / 10E4
      ret['GPS']['lon'] = int(self.readings['lon'] * 10E4) / 10E4
    except:
      # leave GPS empty
      pass
    return ret

  def input_arduino(self):
    """ Read a line composed of throttle and steering values received from the RC. """
    inputLine = ''
    if self.arport.inWaiting():
      ch = self.arport.read(1)
      while ch != b'\x0A':
        inputLine += ch
        ch = self.arport.read(1)
      try:
        # print inputLine.decode('ISO-8859-1')
        t_in, s_in = inputLine.split()
        # return the steering and throttle values from the receiver
        return int(s_in), int(t_in)
      except:
        pass
    # return current values after a reading error
    return self.steering, self.throttle

  def output_arduino(self, steering, throttle):
    """ Write steering and throttle PWM values in the [0,180] range to the controller. """
    # set steering to neutral if within an interval around 90
    steering = 90 if 88 < steering < 92 else steering
    # send a new steering PWM setting to the controller
    if self.mode == Modes.TRAINING:
      if steering != self.steering:
        self.steering = steering   # update global
        self.arport.write(('S %d\n' % self.steering).encode('ascii'))
    else:
        self.arport.write(('S %d\n' % self.steering).encode('ascii'))

    # send a new throttle PWM setting to the controller
    if self.mode == Modes.TRAINING:
      if throttle != self.throttle:
        self.throttle = throttle   # update global
        self.arport.write(('M %d\n' % self.throttle).encode('ascii'))
    else:
      self.arport.write(('M %d\n' % self.throttle).encode('ascii'))
    return

  # ---------------------------------------
  #
  def control_loop(self):
    """ Controller main loop """
    last_update=0
    steering_in=self.steering
    throttle_in=self.throttle
    mv = '/bin/mv /tmpfs/meta.tmp ' + TELEMFNAME

    while True:
      now = time.time()
      #
      # ------------------------------------------------------------
      #
      if self.state == States.RUNNING and self.mode == Modes.TRAINING:
        # get inputs from RC receiver in the [0,180] range
        try:
          if self.arport.inWaiting():
            steering_in, throttle_in = self.input_arduino()
        except Exception, e:
          self.log("input_arduino: %s" % str(e))
          continue
        # set steering to neutral if within an interval around 90
        steering_in = 90 if 87 <= steering_in < 92 else steering_in
        if self.verbose: print steering_in, throttle_in

        if self.steering == steering_in and self.throttle == throttle_in:
          # like it or not we need to sleep to avoid to hog the CPU in a spin loop
          time.sleep(0.01)
          continue

        # update telemetry file 30 times per second
        if 0.03337 < now - last_update:
          s = "%03d %03d" %  (steering_in, throttle_in)
          # create metadata file for embedding steering and throttle values in the video stream
          try:
            f = open('/tmpfs/meta.tmp', 'w', 0)
            f.write(s)
            f.close()
            # use mv that is a system call and not preempted (atomic)
            subprocess.check_call(mv, shell=True)
          except Exception, e:
            self.log("writing file: %s" % str(e))
            pass
        last_update = now
        # set new values for throttle and steering servos
        self.output_arduino(steering_in, throttle_in)
      #
      # ------------------------------------------------------------
      #
      elif self.state == States.RUNNING and self.mode == Modes.AUTO:
        # predict steering and trhottle and set the values at a rate depending on preditiction speed
        start_t = time.time()
        Y = utils.read_uyvy(FRAMEFNAME)
        p = model.predict(Y)
        print "execution time:", time.time() - start_t
        self.steering = np.argmax(p[:, :15],  1)[0]
        self.throttle = np.argmax(p[:, 15:], 1)[0]
        self.steering = utils.bucket2steering(self.steering)
        self.throttle = utils.bucket2throttle(self.throttle)
        print self.steering, self.throttle
        # clip the prediction for testing
        if self.throttle > 110:
          self.throttle = 110
        if self.throttle < 80:
          self.throttle = 80
        self.output_arduino(self.steering, self.throttle)
      #
      # ------------------------------------------------------------
      #
      elif self.state == States.RUNNING and self.mode == Modes.REMOTE:
        self.output_arduino(self.steering, self.throttle)
        time.sleep(0.2)
      #
      # ------------------------------------------------------------
      #
      elif self.state == States.IDLE:
        time.sleep(0.1)
      #
      # ------------------------------------------------------------
      #
      else:
        time.sleep(1)
<commit_msg>added autonomous mode from predicted steering and throttle using CNN<commit_after>"""
  Cloud connected autonomous RC car.

  Copyright 2016 Visible Energy Inc. All Rights Reserved.
"""
__license__ = """
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.
"""
import time
import json
import serial
import string
import sys
import Queue
import threading
import subprocess

import streamer
import utils
from keras.models import model_from_json

class States:
  """ Vehicle states """
  IDLE=1
  RUNNING=2
  PAUSE=3
  STOPPED=0

class Modes:
  """ Vehicle running modes """
  AUTO=1        # fully autonomous
  TRAINING=2    # RC controlled to capture training video
  REMOTE=3      # controlled remotely through Cometa JSON/RPC

# --- Module constansts
THETA_CENTER = 90
MOTOR_NEUTRAL = 90
# filename to fetch telemetry from -- updated atomically by the controller loop at 30 Hz
TELEMFNAME = '/tmpfs/meta.txt'

# filename where to store the last frame -- used by the application loop and as parameter for the CNN prediction
FRAMEFNAME = '/tmpfs/frame.yuv'

def setup_arduino(config, logger):
  """ Arduino radio receiver and servos controller setup. """
  try:
    # set serial non-blocking
    port = serial.Serial(config['arduino']['serial'], config['arduino']['speed'], timeout=0.0, xonxoff=False, rtscts=False, dsrdtr=False)
    port.flushInput()
    port.flushOutput()
  except Exception as e:
    logger("Arduino setup: %s" % e)
    return None
  # wait the board to start
  while port.inWaiting() == 0:
    time.sleep(0.1)
  return port

class RCVehicle(object):
  """
  Vehicle controller class
    config - configuration object from config.json
    log - system logger
  """
  # current state and mode
  state = None
  mode = None

  # running options flags
  capture = False     # capturing video and telemetry for CNN training
  streaming = False   # streaming video to cloud server

  # current servo and motor values
  steering = None
  throttle = None

  # Arduino serial port
  arport = None

  # Mailbox for asynchronous commands
  mbox = Queue.Queue()

  # GPS readings
  readings={}

  # System logger
  log = None

  def __init__(self, config, logger):
    self.state=States.IDLE
    self.steering=THETA_CENTER
    self.throttle=MOTOR_NEUTRAL
    self.serial=config['serial']

    # Set the system log
    self.log=logger
    self.verbose=config['app_params']['verbose']

    # CNN predicting model
    self.cnn_model = None

    self.arport=setup_arduino(config, self.log)
    while self.arport == None:
      self.log("Fatal error setting up Arduino board. Cannot proceed without properly connecting to the control board.")
      time.sleep(5)
      self.arport=setup_arduino(config, self.log)
    # TODO: remember to create a board heartbeat thread

    # Global lock
    self.glock = threading.Lock()

    # Start the main loop
    self.loop_t = threading.Thread(target=self.control_loop)
    self.loop_t.daemon = True   # force to exit on SIGINT

    self.telemetry_period=config['app_params']['telemetry_period']
    return

  def load_model(self, modelpath):
    """ Load a CNN model """
    try:
      self.model = model_from_json(open(modelpath + ".json").read())
      self.model.load_weights(modelpath + ".h5")
    except Exception, e:
      self.log("Failed to load CNN model %s. (%s)" % (modelpath,str(e)) )
      return

    self.log("Loaded CNN model %s." % modelpath)
    return

  def state2run(self):
    """ State transition to RUNNING """
    if self.state == States.RUNNING:
      return
    self.steering=THETA_CENTER
    self.throttle=MOTOR_NEUTRAL
    self.state=States.RUNNING
    self.log("State RUNNING")
    return

  def state2stopped(self):
    """ State transition to PAUSE """
    if self.state == States.STOPPED:
      return
    self.steering=THETA_CENTER
    self.throttle=MOTOR_NEUTRAL
    self.state=States.STOPPED
    self.output_arduino(self.steering, self.throttle)
    self.log("State STOPPED")
    return

  def state2idle(self):
    """ State transition to IDLE """
    if self.state == States.IDLE:
      return
    self.steering=THETA_CENTER
    self.throttle=MOTOR_NEUTRAL
    self.state=States.IDLE
    self.output_arduino(self.steering, self.throttle)
    self.log("State IDLE")
    return

  def mode2auto(self):
    """ Mode transition to AUTO """
    if self.mode == Modes.AUTO:
      return
    # TODO: start the video fast video streamer

    self.mode=Modes.AUTO
    self.arport.flushInput()
    self.arport.flushOutput()
    self.log("Mode AUTO")
    return

  def mode2training(self):
    """ Mode transition to TRAINING """
    if self.mode == Modes.TRAINING:
      return
    # TODO: start the video streamer with telemetry annotations
    self.mode=Modes.TRAINING
    self.arport.flushInput()
    self.arport.flushOutput()
    self.log("Mode TRAINING")
    return

  def mode2remote(self):
    """ Mode transition to REMOTE """
    if self.mode == Modes.REMOTE:
      return

    self.arport.flushInput()
    self.arport.flushOutput()
    self.steering=THETA_CENTER
    self.throttle=MOTOR_NEUTRAL
    self.mode=Modes.REMOTE
    self.log("Mode REMOTE")
    return

  def start(self):
    """ Initial start """
    self.mode2training()
    self.state2run()
    self.loop_t.start()
    return

  def telemetry(self):
    ret = {}
    ret['type'] = 1
    ret['time'] = str(int(time.time() * 1000))
    ret['device'] = self.serial
    ret['state'] = self.state
    ret['mode'] = self.mode
    ret['steering'] = self.steering
    ret['throttle'] = self.throttle
    ret['GPS'] = {}
    try:
      ret['GPS']['lat'] = int(self.readings['lat'] * 10E4) / 10E4
      ret['GPS']['lon'] = int(self.readings['lon'] * 10E4) / 10E4
    except:
      # leave GPS empty
      pass
    return ret

  def input_arduino(self):
    """ Read a line composed of throttle and steering values received from the RC. """
    inputLine = ''
    if self.arport.inWaiting():
      ch = self.arport.read(1)
      while ch != b'\x0A':
        inputLine += ch
        ch = self.arport.read(1)
      try:
        # print inputLine.decode('ISO-8859-1')
        t_in, s_in = inputLine.split()
        # return the steering and throttle values from the receiver
        return int(s_in), int(t_in)
      except:
        pass
    # return current values after a reading error
    return self.steering, self.throttle

  def output_arduino(self, steering, throttle):
    """ Write steering and throttle PWM values in the [0,180] range to the controller. """
    # set steering to neutral if within an interval around 90
    steering = 90 if 88 < steering < 92 else steering
    # send a new steering PWM setting to the controller
    if self.mode == Modes.TRAINING:
      if steering != self.steering:
        self.steering = steering   # update global
        self.arport.write(('S %d\n' % self.steering).encode('ascii'))
    else:
        self.arport.write(('S %d\n' % self.steering).encode('ascii'))

    # send a new throttle PWM setting to the controller
    if self.mode == Modes.TRAINING:
      if throttle != self.throttle:
        self.throttle = throttle   # update global
        self.arport.write(('M %d\n' % self.throttle).encode('ascii'))
    else:
      self.arport.write(('M %d\n' % self.throttle).encode('ascii'))
    return

  # ---------------------------------------
  #
  def control_loop(self):
    """ Controller main loop """
    last_update=0
    steering_in=self.steering
    throttle_in=self.throttle
    mv = '/bin/mv /tmpfs/meta.tmp ' + TELEMFNAME

    while True:
      now = time.time()
      #
      # ------------------------------------------------------------
      #
      if self.state == States.RUNNING and self.mode == Modes.TRAINING:
        # get inputs from RC receiver in the [0,180] range
        try:
          if self.arport.inWaiting():
            steering_in, throttle_in = self.input_arduino()
        except Exception, e:
          self.log("input_arduino: %s" % str(e))
          continue
        # set steering to neutral if within an interval around 90
        steering_in = 90 if 87 <= steering_in < 92 else steering_in
        if self.verbose: print steering_in, throttle_in

        if self.steering == steering_in and self.throttle == throttle_in:
          # like it or not we need to sleep to avoid to hog the CPU in a spin loop
          time.sleep(0.01)
          continue

        # update telemetry file 30 times per second
        if 0.03337 < now - last_update:
          s = "%03d %03d" %  (steering_in, throttle_in)
          # create metadata file for embedding steering and throttle values in the video stream
          try:
            f = open('/tmpfs/meta.tmp', 'w', 0)
            f.write(s)
            f.close()
            # use mv that is a system call and not preempted (atomic)
            subprocess.check_call(mv, shell=True)
          except Exception, e:
            self.log("writing file: %s" % str(e))
            pass
        last_update = now
        # set new values for throttle and steering servos
        self.output_arduino(steering_in, throttle_in)
      #
      # ------------------------------------------------------------
      #
      elif self.state == States.RUNNING and self.mode == Modes.AUTO:
        # predict steering and trhottle and set the values at a rate depending on preditiction speed
        start_t = time.time()
        Y = utils.read_uyvy(FRAMEFNAME)
        p = self.model.predict(Y)
        print "execution time:", time.time() - start_t
        self.steering = np.argmax(p[:, :15],  1)[0]
        self.throttle = np.argmax(p[:, 15:], 1)[0]
        self.steering = utils.bucket2steering(self.steering)
        self.throttle = utils.bucket2throttle(self.throttle)
        print self.steering, self.throttle
        # clip the prediction for testing
        if self.throttle > 110:
          self.throttle = 110
        if self.throttle < 80:
          self.throttle = 80
        self.output_arduino(self.steering, self.throttle)
      #
      # ------------------------------------------------------------
      #
      elif self.state == States.RUNNING and self.mode == Modes.REMOTE:
        self.output_arduino(self.steering, self.throttle)
        time.sleep(0.2)
      #
      # ------------------------------------------------------------
      #
      elif self.state == States.IDLE:
        time.sleep(0.1)
      #
      # ------------------------------------------------------------
      #
      else:
        time.sleep(1)
<|endoftext|>


<commit_before>import os
import glob
from pkg_resources import resource_filename

from foyer import Forcefield

def get_ff_path():
    return [resource_filename('foyer', 'forcefields')]

def get_forcefield_paths(forcefield_name=None):
    for dir_path in get_ff_path():
        file_pattern = os.path.join(dir_path, 'xml/*.xml')
        file_paths = [file_path for file_path in glob.glob(file_pattern)]
    return file_paths

def get_forcefield(name=None):
    if name is None:
        raise ValueError('Need a force field name')
    file_paths = get_forcefield_paths()
    try:
        ff_path = next(val for val in file_paths if name in val)
    except StopIteration:
        raise ValueError('Could not find force field with name {}'
                ' in path {}'.format(name, get_ff_path()))
    return Forcefield(ff_path)

load_OPLSAA = get_forcefield(name='oplsaa')
load_TRAPPE_UA = get_forcefield(name='trappe-ua')
<commit_msg>Make discrete functions for each force field<commit_after>import os
import glob
from pkg_resources import resource_filename

from foyer import Forcefield

def get_ff_path():
    return [resource_filename('foyer', 'forcefields')]

def get_forcefield_paths(forcefield_name=None):
    for dir_path in get_ff_path():
        file_pattern = os.path.join(dir_path, 'xml/*.xml')
        file_paths = [file_path for file_path in glob.glob(file_pattern)]
    return file_paths

def get_forcefield(name=None):
    if name is None:
        raise ValueError('Need a force field name')
    file_paths = get_forcefield_paths()
    try:
        ff_path = next(val for val in file_paths if name in val)
    except StopIteration:
        raise ValueError('Could not find force field with name {}'
                ' in path {}'.format(name, get_ff_path()))
    return Forcefield(ff_path)

def load_OPLSAA():
    return get_forcefield(name='oplsaa')

def load_TRAPPE_UA():
    return get_forcefield(name='trappe-ua')

load_OPLSAA = load_OPLSAA
load_TRAPPE_UA = load_TRAPPE_UA
<|endoftext|>


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

import pysh.pysh_interpreter as interp
from pysh.instructions import boolean, char, code, common, numbers, string, input_output
from pysh.instructions import registered_instructions as ri

print("Setting up Pysh interpreter...")
i = interp.Pysh_Interpreter()

print("Testing boolean_and")
prog = [True, False, ri.get_instruction_by_name('boolean_and')]
result = i.run_push(prog)
assert i.state.total_state_size() == 1,                     "State has %r items. Should be 1." % i.state.total_state_size()
assert len(i.state.stacks['_boolean']) == 1,                i.state.stacks['_boolean']
assert i.state.stacks['_boolean'].top_item() == False,      i.state.stacks['_boolean'].top_item()

prog = [True, True, ri.get_instruction_by_name('boolean_and')]
result = i.run_push(prog)
assert i.state.total_state_size() == 1,                     "State has %r items. Should be 1." % i.state.total_state_size()
assert len(i.state.stacks['_boolean']) == 1                 i.state.stacks['_boolean']
assert i.state.stacks['_boolean'].top_item() == True        i.state.stacks['_boolean'].top_item()

print("Testing boolean_or")
prog = [True, False, ri.get_instruction_by_name('boolean_or')]
result = i.run_push(prog)
assert i.state.total_state_size() == 1,                     "State has %r items. Should be 1." % i.state.total_state_size()
assert len(i.state.stacks['_boolean']) == 1                 i.state.stacks['_boolean']
assert i.state.stacks['_boolean'].top_item() == True        i.state.stacks['_boolean'].top_item()

prog = [False, False, ri.get_instruction_by_name('boolean_or')]
result = i.run_push(prog)
assert i.state.total_state_size() == 1,                     "State has %r items. Should be 1." % i.state.total_state_size()
assert len(i.state.stacks['_boolean']) == 1                 i.state.stacks['_boolean']
assert i.state.stacks['_boolean'].top_item() == False       i.state.stacks['_boolean'].top_item()

print("Testing boolean_not")
prog = [True, ri.get_instruction_by_name('boolean_not')]
result = i.run_push(prog)
assert i.state.total_state_size() == 1,                     "State has %r items. Should be 1." % i.state.total_state_size()
assert len(i.state.stacks['_boolean']) == 1                 i.state.stacks['_boolean']
assert i.state.stacks['_boolean'].top_item() == False       i.state.stacks['_boolean'].top_item()

prog = [False, ri.get_instruction_by_name('boolean_not')]
result = i.run_push(prog)
assert i.state.total_state_size() == 1,                     "State has %r items. Should be 1." % i.state.total_state_size()
assert len(i.state.stacks['_boolean']) == 1                 i.state.stacks['_boolean']
assert i.state.stacks['_boolean'].top_item() == True        i.state.stacks['_boolean'].top_item()<commit_msg>Formatting test<commit_after>from __future__ import absolute_import, division, print_function, unicode_literals

import pysh.pysh_interpreter as interp
from pysh.instructions import boolean, char, code, common, numbers, string, input_output
from pysh.instructions import registered_instructions as ri

print("Setting up Pysh interpreter...")
i = interp.Pysh_Interpreter()

print("Testing boolean_and")
prog = [True, False, ri.get_instruction_by_name('boolean_and')]
result = i.run_push(prog)
assert i.state.total_state_size() == 1,
       "State has %r items. Should be 1." % i.state.total_state_size()
assert len(i.state.stacks['_boolean']) == 1,
       i.state.stacks['_boolean']
assert i.state.stacks['_boolean'].top_item() == False,
       i.state.stacks['_boolean'].top_item()

prog = [True, True, ri.get_instruction_by_name('boolean_and')]
result = i.run_push(prog)
assert i.state.total_state_size() == 1,                     "State has %r items. Should be 1." % i.state.total_state_size()
assert len(i.state.stacks['_boolean']) == 1                 i.state.stacks['_boolean']
assert i.state.stacks['_boolean'].top_item() == True        i.state.stacks['_boolean'].top_item()

print("Testing boolean_or")
prog = [True, False, ri.get_instruction_by_name('boolean_or')]
result = i.run_push(prog)
assert i.state.total_state_size() == 1,                     "State has %r items. Should be 1." % i.state.total_state_size()
assert len(i.state.stacks['_boolean']) == 1                 i.state.stacks['_boolean']
assert i.state.stacks['_boolean'].top_item() == True        i.state.stacks['_boolean'].top_item()

prog = [False, False, ri.get_instruction_by_name('boolean_or')]
result = i.run_push(prog)
assert i.state.total_state_size() == 1,                     "State has %r items. Should be 1." % i.state.total_state_size()
assert len(i.state.stacks['_boolean']) == 1                 i.state.stacks['_boolean']
assert i.state.stacks['_boolean'].top_item() == False       i.state.stacks['_boolean'].top_item()

print("Testing boolean_not")
prog = [True, ri.get_instruction_by_name('boolean_not')]
result = i.run_push(prog)
assert i.state.total_state_size() == 1,                     "State has %r items. Should be 1." % i.state.total_state_size()
assert len(i.state.stacks['_boolean']) == 1                 i.state.stacks['_boolean']
assert i.state.stacks['_boolean'].top_item() == False       i.state.stacks['_boolean'].top_item()

prog = [False, ri.get_instruction_by_name('boolean_not')]
result = i.run_push(prog)
assert i.state.total_state_size() == 1,                     "State has %r items. Should be 1." % i.state.total_state_size()
assert len(i.state.stacks['_boolean']) == 1                 i.state.stacks['_boolean']
assert i.state.stacks['_boolean'].top_item() == True        i.state.stacks['_boolean'].top_item()<|endoftext|>


<commit_before>import unittest

import graphene
from graphene import ObjectType, Argument, List, String

from graphene_custom_directives import CustomDirectiveMeta, CustomDirectivesMiddleware

__author__ = 'ekampf'

class QueryRoot(ObjectType):
    list_value = List(String, value=Argument(List(String)))

    @graphene.resolve_only_args
    def resolve_list_value(self, value=None):
        return value

schema = graphene.Schema(query=QueryRoot, directives=CustomDirectiveMeta.get_all_directives())

class TestNumberDirectives(unittest.TestCase):

    def testShuffle(self):
        result = self.__execute('{ listValue(value: ["1", "2", "3"]) @shuffle }')
        self.assertEqual(set(result.data['listValue']), {"1", "2", "3"})
        self.assertNotEqual(result.data['listValue'], ["1", "2", "3"])

        result = self.__execute('{ listValue(value: []) @shuffle }')
        self.assertFalse(bool(result.data['listValue']))

    def testSample(self):
        result = self.__execute('{ listValue(value: ["1", "2", "3"]) @sample(k: 1) }')
        self.assertEqual(len(result.data['listValue']), 1)
        self.assertIn(result.data['listValue'][0], ["1", "2", "3"])

    def __execute(self, query):
        result = schema.execute(query, middleware=[CustomDirectivesMiddleware()])
        self.assertFalse(bool(result.errors))
        return result
<commit_msg>List tests fix<commit_after>import unittest

import graphene
from graphene import ObjectType, Argument, List, String, Int

from graphene_custom_directives import CustomDirectiveMeta, CustomDirectivesMiddleware

__author__ = 'ekampf'

class QueryRoot(ObjectType):
    list_value = List(Int, value=Argument(List(Int)))

    @graphene.resolve_only_args
    def resolve_list_value(self, value=None):
        return value

schema = graphene.Schema(query=QueryRoot, directives=CustomDirectiveMeta.get_all_directives())

class TestListDirectives(unittest.TestCase):

    def testShuffle(self):
        result = self.__execute('{ listValue(value: [1, 2, 3]) @shuffle }')
        self.assertEqual(set(result.data['listValue']), {1, 2, 3})
        self.assertNotEqual(result.data['listValue'], [1, 2, 3])

        result = self.__execute('{ listValue(value: []) @shuffle }')
        self.assertFalse(bool(result.data['listValue']))

    def testSample(self):
        result = self.__execute('{ listValue(value: [1, 2, 3]) @sample(k: 1) }')
        self.assertEqual(len(result.data['listValue']), 1)
        self.assertIn(result.data['listValue'][0], [1, 2, 3])

    def __execute(self, query):
        result = schema.execute(query, middleware=[CustomDirectivesMiddleware()])
        self.assertFalse(bool(result.errors))
        return result
<|endoftext|>


<commit_before>from __future__ import print_function

import unittest
import sys

import wrapt

def global_function_1(*args, **kwargs):
    return args, kwargs

def global_function_2(*args, **kwargs):
    return args, kwargs

def global_function_3(*args, **kwargs):
    return args, kwargs

def global_function_4(*args, **kwargs):
    return args, kwargs

class Class_1(object):
    def method(self, *args, **kwargs):
        return args, kwargs

class Class_2(object):
    @classmethod
    def method(cls, *args, **kwargs):
        return args, kwargs

class Class_3(object):
    @staticmethod
    def method(*args, **kwargs):
        return args, kwargs

class TestMonkeyPatching(unittest.TestCase):

    def test_function_wrapper(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        @wrapt.function_wrapper
        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(instance, None)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        @wrapper
        def function(*args, **kwargs):
            return args, kwargs

        result = function(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_function_wrapper_instance_method(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        _self = self

        class wrapper(object):
            @wrapt.function_wrapper
            def __call__(self, wrapped, instance, args, kwargs):
                _self.assertEqual(type(self), wrapper)
                called.append((args, kwargs))
                _self.assertEqual(instance, None)
                _self.assertEqual(args, _args)
                _self.assertEqual(kwargs, _kwargs)
                return wrapped(*args, **kwargs)

        @wrapper()
        def function(*args, **kwargs):
            return args, kwargs

        result = function(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_function_wrapper_class_method(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        class wrapper(object):
            @wrapt.function_wrapper
            @classmethod
            def __call__(cls, wrapped, instance, args, kwargs):
                self.assertEqual(cls, wrapper)
                called.append((args, kwargs))
                self.assertEqual(instance, None)
                self.assertEqual(args, _args)
                self.assertEqual(kwargs, _kwargs)
                return wrapped(*args, **kwargs)

        @wrapper()
        def function(*args, **kwargs):
            return args, kwargs

        result = function(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_wrap_function_module_name(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(instance, None)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        wrapt.wrap_function_wrapper(__name__, 'global_function_1', wrapper)

        result = global_function_1(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_wrap_function_module(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(instance, None)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        module = sys.modules[__name__]

        wrapt.wrap_function_wrapper(module, 'global_function_2', wrapper)

        result = global_function_2(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_wrap_instance_method_module_name(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        _instance = Class_1()

        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(instance, _instance)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        wrapt.wrap_function_wrapper(__name__, 'Class_1.method',
                wrapper)

        result = _instance.method(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_wrap_class_method_module_name(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(instance, Class_2)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        wrapt.wrap_function_wrapper(__name__, 'Class_2.method',
                wrapper)

        result = Class_2.method(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_wrap_static_method_module_name(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(instance, None)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        wrapt.wrap_function_wrapper(__name__, 'Class_3.method',
                wrapper)

        result = Class_3.method(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_patch_function_module_name(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        @wrapt.patch_function_wrapper(__name__, 'global_function_3')
        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(instance, None)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        result = global_function_3(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_patch_function_module(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        module = sys.modules[__name__]

        @wrapt.patch_function_wrapper(module, 'global_function_4')
        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(instance, None)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        result = global_function_4(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def _test_transient_function_wrapper(self, *args, **kwargs):
        return args, kwargs

    def test_transient_function_wrapper(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        @wrapt.transient_function_wrapper(__name__,
                'TestMonkeyPatching._test_transient_function_wrapper')
        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(wrapped, self._test_transient_function_wrapper)
            self.assertEqual(instance, self)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        @wrapper
        def function(*args, **kwargs):
            return self._test_transient_function_wrapper(*args, **kwargs)

        result = function(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_transient_function_wrapper_instance_method(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        _self = self

        class wrapper(object):
            @wrapt.transient_function_wrapper(__name__,
                    'TestMonkeyPatching._test_transient_function_wrapper')
            def __call__(self, wrapped, instance, args, kwargs):
                called.append((args, kwargs))
                _self.assertEqual(wrapped, _self._test_transient_function_wrapper)
                _self.assertEqual(instance, _self)
                _self.assertEqual(args, _args)
                _self.assertEqual(kwargs, _kwargs)
                return wrapped(*args, **kwargs)

        @wrapper()
        def function(*args, **kwargs):
            return self._test_transient_function_wrapper(*args, **kwargs)

        result = function(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

class TestExplicitMonkeyPatching(unittest.TestCase):

    def test_patch_instance_method_class(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        @wrapt.function_wrapper
        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(instance, _instance)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        class Class(object):
            def function(self, *args, **kwargs):
                return args, kwargs

        Class.function = wrapper(Class.function)

        _instance = Class()

        result = _instance.function(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_patch_instance_method_dict(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        @wrapt.function_wrapper
        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(instance, _instance)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        class Class(object):
            def function(self, *args, **kwargs):
                return args, kwargs

        Class.function = wrapper(vars(Class)['function'])

        _instance = Class()

        result = _instance.function(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_patch_instance_method_instance(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        @wrapt.function_wrapper
        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(instance, _instance)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        class Class(object):
            def function(self, *args, **kwargs):
                return args, kwargs

        _instance = Class()

        _instance.function = wrapper(_instance.function)

        result = _instance.function(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_patch_instance_method_extracted(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        @wrapt.function_wrapper
        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(instance, _instance)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        class Class(object):
            def function(self, *args, **kwargs):
                return args, kwargs

        _instance = Class()

        function = wrapper(_instance.function)

        result = function(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

if __name__ == '__main__':
    unittest.main()
<commit_msg>Add test for wrapping an inherited classmethod.<commit_after>from __future__ import print_function

import unittest
import sys

import wrapt

def global_function_1(*args, **kwargs):
    return args, kwargs

def global_function_2(*args, **kwargs):
    return args, kwargs

def global_function_3(*args, **kwargs):
    return args, kwargs

def global_function_4(*args, **kwargs):
    return args, kwargs

class Class_1(object):
    def method(self, *args, **kwargs):
        return args, kwargs

class Class_2(object):
    @classmethod
    def method(cls, *args, **kwargs):
        return cls, args, kwargs

class Class_2_1(Class_2):
    pass

class Class_2_2(Class_2_1):
    pass

class Class_3(object):
    @staticmethod
    def method(*args, **kwargs):
        return args, kwargs

class TestMonkeyPatching(unittest.TestCase):

    def test_function_wrapper(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        @wrapt.function_wrapper
        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(instance, None)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        @wrapper
        def function(*args, **kwargs):
            return args, kwargs

        result = function(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_function_wrapper_instance_method(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        _self = self

        class wrapper(object):
            @wrapt.function_wrapper
            def __call__(self, wrapped, instance, args, kwargs):
                _self.assertEqual(type(self), wrapper)
                called.append((args, kwargs))
                _self.assertEqual(instance, None)
                _self.assertEqual(args, _args)
                _self.assertEqual(kwargs, _kwargs)
                return wrapped(*args, **kwargs)

        @wrapper()
        def function(*args, **kwargs):
            return args, kwargs

        result = function(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_function_wrapper_class_method(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        class wrapper(object):
            @wrapt.function_wrapper
            @classmethod
            def __call__(cls, wrapped, instance, args, kwargs):
                self.assertEqual(cls, wrapper)
                called.append((args, kwargs))
                self.assertEqual(instance, None)
                self.assertEqual(args, _args)
                self.assertEqual(kwargs, _kwargs)
                return wrapped(*args, **kwargs)

        @wrapper()
        def function(*args, **kwargs):
            return args, kwargs

        result = function(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_wrap_function_module_name(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(instance, None)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        wrapt.wrap_function_wrapper(__name__, 'global_function_1', wrapper)

        result = global_function_1(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_wrap_function_module(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(instance, None)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        module = sys.modules[__name__]

        wrapt.wrap_function_wrapper(module, 'global_function_2', wrapper)

        result = global_function_2(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_wrap_instance_method_module_name(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        _instance = Class_1()

        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(instance, _instance)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        wrapt.wrap_function_wrapper(__name__, 'Class_1.method',
                wrapper)

        result = _instance.method(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_wrap_class_method_module_name(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(instance, Class_2)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        wrapt.wrap_function_wrapper(__name__, 'Class_2.method',
                wrapper)

        result = Class_2.method(*_args, **_kwargs)

        self.assertEqual(result, (Class_2, _args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_wrap_class_method_inherited(self):
        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        wrapt.wrap_function_wrapper(__name__, 'Class_2_1.method',
                wrapper)

        result = Class_2_1.method(*_args, **_kwargs)
        self.assertEqual(result, (Class_2_1, _args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

        called.pop()

        result = Class_2_2.method(*_args, **_kwargs)
        self.assertEqual(result, (Class_2_2, _args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_wrap_static_method_module_name(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(instance, None)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        wrapt.wrap_function_wrapper(__name__, 'Class_3.method',
                wrapper)

        result = Class_3.method(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_patch_function_module_name(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        @wrapt.patch_function_wrapper(__name__, 'global_function_3')
        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(instance, None)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        result = global_function_3(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_patch_function_module(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        module = sys.modules[__name__]

        @wrapt.patch_function_wrapper(module, 'global_function_4')
        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(instance, None)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        result = global_function_4(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def _test_transient_function_wrapper(self, *args, **kwargs):
        return args, kwargs

    def test_transient_function_wrapper(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        @wrapt.transient_function_wrapper(__name__,
                'TestMonkeyPatching._test_transient_function_wrapper')
        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(wrapped, self._test_transient_function_wrapper)
            self.assertEqual(instance, self)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        @wrapper
        def function(*args, **kwargs):
            return self._test_transient_function_wrapper(*args, **kwargs)

        result = function(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_transient_function_wrapper_instance_method(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        _self = self

        class wrapper(object):
            @wrapt.transient_function_wrapper(__name__,
                    'TestMonkeyPatching._test_transient_function_wrapper')
            def __call__(self, wrapped, instance, args, kwargs):
                called.append((args, kwargs))
                _self.assertEqual(wrapped, _self._test_transient_function_wrapper)
                _self.assertEqual(instance, _self)
                _self.assertEqual(args, _args)
                _self.assertEqual(kwargs, _kwargs)
                return wrapped(*args, **kwargs)

        @wrapper()
        def function(*args, **kwargs):
            return self._test_transient_function_wrapper(*args, **kwargs)

        result = function(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

class TestExplicitMonkeyPatching(unittest.TestCase):

    def test_patch_instance_method_class(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        @wrapt.function_wrapper
        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(instance, _instance)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        class Class(object):
            def function(self, *args, **kwargs):
                return args, kwargs

        Class.function = wrapper(Class.function)

        _instance = Class()

        result = _instance.function(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_patch_instance_method_dict(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        @wrapt.function_wrapper
        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(instance, _instance)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        class Class(object):
            def function(self, *args, **kwargs):
                return args, kwargs

        Class.function = wrapper(vars(Class)['function'])

        _instance = Class()

        result = _instance.function(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_patch_instance_method_instance(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        @wrapt.function_wrapper
        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(instance, _instance)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        class Class(object):
            def function(self, *args, **kwargs):
                return args, kwargs

        _instance = Class()

        _instance.function = wrapper(_instance.function)

        result = _instance.function(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

    def test_patch_instance_method_extracted(self):

        _args = (1, 2)
        _kwargs = {'one': 1, 'two': 2}

        called = []

        @wrapt.function_wrapper
        def wrapper(wrapped, instance, args, kwargs):
            called.append((args, kwargs))
            self.assertEqual(instance, _instance)
            self.assertEqual(args, _args)
            self.assertEqual(kwargs, _kwargs)
            return wrapped(*args, **kwargs)

        class Class(object):
            def function(self, *args, **kwargs):
                return args, kwargs

        _instance = Class()

        function = wrapper(_instance.function)

        result = function(*_args, **_kwargs)

        self.assertEqual(result, (_args, _kwargs))
        self.assertEqual(called[0], (_args, _kwargs))

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


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

# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.

import os

try:
    import unittest2 as unittest
except ImportError:
    import unittest

from fake_webapp import EXAMPLE_APP
from splinter.request_handler.request_handler import RequestHandler
from splinter.request_handler.status_code import HttpResponseError
from tests import TESTS_ROOT

class RequestHandlerTestCase(unittest.TestCase):

    def setUp(self):
        self.request = RequestHandler()
        self.request.connect(EXAMPLE_APP)

    def test_should_receive_an_url_and_get_a_success_response(self):
        self.assertTrue(self.request.status_code.is_success())

    def test_should_start_a_request_with_localhost(self):
        self.assertEqual("localhost", self.request.host)

    def test_should_start_a_request_with_port_5000(self):
        self.assertEqual(5000, self.request.port)

    def test_should_visit_alert_page_and_get_a_success_response(self):
        request = RequestHandler()
        request.connect(EXAMPLE_APP + "alert")
        self.assertTrue(request.status_code.is_success())

    def test_should_compare_app_index_with_404_and_get_false(self):
        self.assertFalse(self.request.status_code == 404)

    def test_is_success_should_be_false_when_url_does_not_exists(self):
        request = RequestHandler()
        request.connect(EXAMPLE_APP + "page-that-doesnt-exists")
        self.assertFalse(request.status_code.is_success())

    def test_should_get_an_absent_url_and_raise_an_exception(self):
        with self.assertRaises(HttpResponseError):
            request = RequestHandler()
            request.connect(EXAMPLE_APP + "page-that-doesnt-exists")
            request.ensure_success_response()

    def test_should_get_an_exception_and_format_it(self):
        request = RequestHandler()
        request.connect(EXAMPLE_APP + "page-that-doesnt-exists")
        try:
            request.ensure_success_response()
        except HttpResponseError as e:
            exception = e.msg
        self.assertEqual("404 - Not Found", exception)

    def test_should_be_able_to_represent_exception_as_string(self):
        "HttpResponseError exception should be representable as string"
        error = HttpResponseError(404, "Not Found")
        self.assertEqual("404 - Not Found", str(error))

    def test_should_not_connect_to_non_http_protocols(self):
        mockfile_path = "file://%s" % os.path.join(TESTS_ROOT, "mockfile.txt")
        request = RequestHandler()
        request.connect(mockfile_path)
        self.assertTrue(request.status_code.is_success())

    def test_should_connect_to_pages_with_query_string(self):
        request = RequestHandler()
        url = EXAMPLE_APP + "query?model"
        request.connect(url)
        self.assertTrue(request.status_code.is_success())

    def test_should_set_user_agent(self):
        request = RequestHandler()
        url = EXAMPLE_APP + 'useragent'
        request.connect(url)
        self.assertEqual('python/splinter', request.response.read())
<commit_msg>Test that https is handled even if we do not have a proper https server<commit_after># -*- coding: utf-8 -*-

# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.

import os

try:
    import unittest2 as unittest
except ImportError:
    import unittest

from ssl import SSLError

from fake_webapp import EXAMPLE_APP
from splinter.request_handler.request_handler import RequestHandler
from splinter.request_handler.status_code import HttpResponseError
from tests import TESTS_ROOT

class RequestHandlerTestCase(unittest.TestCase):

    def setUp(self):
        self.request = RequestHandler()
        self.request.connect(EXAMPLE_APP)

    def test_should_receive_an_url_and_get_a_success_response(self):
        self.assertTrue(self.request.status_code.is_success())

    def test_should_start_a_request_with_localhost(self):
        self.assertEqual("localhost", self.request.host)

    def test_should_start_a_request_with_port_5000(self):
        self.assertEqual(5000, self.request.port)

    def test_should_visit_alert_page_and_get_a_success_response(self):
        request = RequestHandler()
        request.connect(EXAMPLE_APP + "alert")
        self.assertTrue(request.status_code.is_success())

    def test_should_compare_app_index_with_404_and_get_false(self):
        self.assertFalse(self.request.status_code == 404)

    def test_is_success_should_be_false_when_url_does_not_exists(self):
        request = RequestHandler()
        request.connect(EXAMPLE_APP + "page-that-doesnt-exists")
        self.assertFalse(request.status_code.is_success())

    def test_should_get_an_absent_url_and_raise_an_exception(self):
        with self.assertRaises(HttpResponseError):
            request = RequestHandler()
            request.connect(EXAMPLE_APP + "page-that-doesnt-exists")
            request.ensure_success_response()

    def test_should_get_an_exception_and_format_it(self):
        request = RequestHandler()
        request.connect(EXAMPLE_APP + "page-that-doesnt-exists")
        try:
            request.ensure_success_response()
        except HttpResponseError as e:
            exception = e.msg
        self.assertEqual("404 - Not Found", exception)

    def test_should_be_able_to_represent_exception_as_string(self):
        "HttpResponseError exception should be representable as string"
        error = HttpResponseError(404, "Not Found")
        self.assertEqual("404 - Not Found", str(error))

    def test_should_not_connect_to_non_http_protocols(self):
        mockfile_path = "file://%s" % os.path.join(TESTS_ROOT, "mockfile.txt")
        request = RequestHandler()
        request.connect(mockfile_path)
        self.assertTrue(request.status_code.is_success())

    def test_should_connect_to_pages_with_query_string(self):
        request = RequestHandler()
        url = EXAMPLE_APP + "query?model"
        request.connect(url)
        self.assertTrue(request.status_code.is_success())

    def test_should_connect_to_https_protocols(self):
        # We do not run an HTTPS server, but we know we handle https
        # if we get an SSLError accessing a non-HTTPS site.
        with self.assertRaises(SSLError):
            request = RequestHandler()
            url = EXAMPLE_APP.replace('http', 'https')
            request.connect(url)
            self.assertEqual(request.scheme, 'https')

    def test_should_set_user_agent(self):
        request = RequestHandler()
        url = EXAMPLE_APP + 'useragent'
        request.connect(url)
        self.assertEqual('python/splinter', request.response.read())
<|endoftext|>