Add time information to test logs

Add time information to test logs

--- tests/logging.py
+++ tests/logging.py
@@ -1,4 +1,5 @@
 import os
+from datetime import datetime

 def save_logs(groomer, test_description):
@@ -6,6 +7,9 @@
     test_log_path = 'tests/test_logs/{}.log'.format(test_description)
     with open(test_log_path, 'w+') as test_log:
         test_log.write(divider.format('TEST LOG'))
+        test_log.write(str(datetime.now().time()) + '\n')
+        test_log.write(test_description + '\n')
+        test_log.write('-' * 20 + '\n')
         with open(groomer.logger.log_path, 'r') as logfile:
             log = logfile.read()
             test_log.write(log)

<|original_code|>
import os

def save_logs(groomer, test_description):
    divider = ('=' * 10 + '{}' + '=' * 10 + '\n')
    test_log_path = 'tests/test_logs/{}.log'.format(test_description)
    with open(test_log_path, 'w+') as test_log:
        test_log.write(divider.format('TEST LOG'))
        with open(groomer.logger.log_path, 'r') as logfile:
            log = logfile.read()
            test_log.write(log)
        if os.path.exists(groomer.logger.log_debug_err):
            test_log.write(divider.format('ERR LOG'))
            with open(groomer.logger.log_debug_err, 'r') as debug_err:
                err = debug_err.read()
                test_log.write(err)
        if os.path.exists(groomer.logger.log_debug_out):
            test_log.write(divider.format('OUT LOG'))
            with open(groomer.logger.log_debug_out, 'r') as debug_out:
                out = debug_out.read()
                test_log.write(out)

<|edits_diff|>
--- tests/logging.py
+++ tests/logging.py
@@ -1,4 +1,5 @@
 import os
+from datetime import datetime

 def save_logs(groomer, test_description):
<|current_version|>
import os
from datetime import datetime

def save_logs(groomer, test_description):
    divider = ('=' * 10 + '{}' + '=' * 10 + '\n')
    test_log_path = 'tests/test_logs/{}.log'.format(test_description)
    with open(test_log_path, 'w+') as test_log:
        test_log.write(divider.format('TEST LOG'))
        with open(groomer.logger.log_path, 'r') as logfile:
            log = logfile.read()
            test_log.write(log)
        if os.path.exists(groomer.logger.log_debug_err):
            test_log.write(divider.format('ERR LOG'))
            with open(groomer.logger.log_debug_err, 'r') as debug_err:
                err = debug_err.read()
                test_log.write(err)
        if os.path.exists(groomer.logger.log_debug_out):
            test_log.write(divider.format('OUT LOG'))
            with open(groomer.logger.log_debug_out, 'r') as debug_out:
                out = debug_out.read()
                test_log.write(out)

<|next_version|>
import os
from datetime import datetime

def save_logs(groomer, test_description):
    divider = ('=' * 10 + '{}' + '=' * 10 + '\n')
    test_log_path = 'tests/test_logs/{}.log'.format(test_description)
    with open(test_log_path, 'w+') as test_log:
        test_log.write(divider.format('TEST LOG'))
        test_log.write(str(datetime.now().time()) + '\n')
        test_log.write(test_description + '\n')
        test_log.write('-' * 20 + '\n')
        with open(groomer.logger.log_path, 'r') as logfile:
            log = logfile.read()
            test_log.write(log)
        if os.path.exists(groomer.logger.log_debug_err):
            test_log.write(divider.format('ERR LOG'))
            with open(groomer.logger.log_debug_err, 'r') as debug_err:
                err = debug_err.read()
                test_log.write(err)
        if os.path.exists(groomer.logger.log_debug_out):
            test_log.write(divider.format('OUT LOG'))
            with open(groomer.logger.log_debug_out, 'r') as debug_out:
                out = debug_out.read()
                test_log.write(out)


Add a check if the target output directories exist

--- tests/cyclus_tools.py
+++ tests/cyclus_tools.py
@@ -1,4 +1,6 @@
 #! /usr/bin/env python
+
+import os

 from tools import check_cmd

@@ -8,6 +10,10 @@

     for sim_input, sim_output in sim_files:
         holdsrtn = [1]  # needed because nose does not send() to test generator
+        # make sure the output target directory exists
+        if not os.path.exists(sim_output):
+            os.makedirs(sim_output)
+
         cmd = [cyclus, "-o", sim_output, "--input-file", sim_input]
         check_cmd(cmd, cwd, holdsrtn)
         rtn = holdsrtn[0]

<|original_code|>
#! /usr/bin/env python

from tools import check_cmd

def run_cyclus(cyclus, cwd, sim_files):
    """Runs cyclus with various inputs and creates output databases
       """

    for sim_input, sim_output in sim_files:
        holdsrtn = [1]  # needed because nose does not send() to test generator
        cmd = [cyclus, "-o", sim_output, "--input-file", sim_input]
        check_cmd(cmd, cwd, holdsrtn)
        rtn = holdsrtn[0]
        if rtn != 0:
            return  # don"t execute further commands

<|edits_diff|>
--- tests/cyclus_tools.py
+++ tests/cyclus_tools.py
@@ -1,4 +1,6 @@
 #! /usr/bin/env python
+
+import os

 from tools import check_cmd

<|current_version|>
#! /usr/bin/env python

import os

from tools import check_cmd

def run_cyclus(cyclus, cwd, sim_files):
    """Runs cyclus with various inputs and creates output databases
       """

    for sim_input, sim_output in sim_files:
        holdsrtn = [1]  # needed because nose does not send() to test generator
        cmd = [cyclus, "-o", sim_output, "--input-file", sim_input]
        check_cmd(cmd, cwd, holdsrtn)
        rtn = holdsrtn[0]
        if rtn != 0:
            return  # don"t execute further commands

<|next_version|>
#! /usr/bin/env python

import os

from tools import check_cmd

def run_cyclus(cyclus, cwd, sim_files):
    """Runs cyclus with various inputs and creates output databases
       """

    for sim_input, sim_output in sim_files:
        holdsrtn = [1]  # needed because nose does not send() to test generator
        # make sure the output target directory exists
        if not os.path.exists(sim_output):
            os.makedirs(sim_output)

        cmd = [cyclus, "-o", sim_output, "--input-file", sim_input]
        check_cmd(cmd, cwd, holdsrtn)
        rtn = holdsrtn[0]
        if rtn != 0:
            return  # don"t execute further commands


Clean up more in tests

Clean up more in tests

--- tests/sanity_tests.py
+++ tests/sanity_tests.py
@@ -17,6 +17,8 @@
         moov_atom = [atom for atom in root.children if atom.type() == 'moov']
         self.assertEqual(len(moov_atom), 1, 'There should be 1 moov atom.')

+        mp4file.close()
+
     def test_lossless_write(self):
         mp4filename = os.path.join(TESTDATA, 'loop_circle.mp4')
         infile = open(mp4filename, 'rb')
@@ -30,5 +32,7 @@

         self.assertTrue(filecmp.cmp(infile.name, outfile.name))

+        os.remove(outfile.name)
+
 if __name__ == '__main__':
     unittest.main()

<|original_code|>
import filecmp
import os
import tempfile
import unittest

import isomedia

TESTDATA = os.path.join(os.path.dirname(__file__), 'testdata')

class TestSanity(unittest.TestCase):
    def test_sanity(self):
        mp4filename = os.path.join(TESTDATA, 'loop_circle.mp4')
        mp4file = open(mp4filename, 'rb')
        isofile = isomedia.load(mp4file)

        root = isofile.root
        moov_atom = [atom for atom in root.children if atom.type() == 'moov']
        self.assertEqual(len(moov_atom), 1, 'There should be 1 moov atom.')

    def test_lossless_write(self):
        mp4filename = os.path.join(TESTDATA, 'loop_circle.mp4')
        infile = open(mp4filename, 'rb')
        isofile = isomedia.load(infile)

        outfile = tempfile.NamedTemporaryFile(delete=False)
        isofile.write(outfile)

        infile.close()
        outfile.close()

        self.assertTrue(filecmp.cmp(infile.name, outfile.name))

if __name__ == '__main__':
    unittest.main()

<|edits_diff|>
--- tests/sanity_tests.py
+++ tests/sanity_tests.py
@@ -17,6 +17,8 @@
         moov_atom = [atom for atom in root.children if atom.type() == 'moov']
         self.assertEqual(len(moov_atom), 1, 'There should be 1 moov atom.')

+        mp4file.close()
+
     def test_lossless_write(self):
         mp4filename = os.path.join(TESTDATA, 'loop_circle.mp4')
         infile = open(mp4filename, 'rb')
<|current_version|>
import filecmp
import os
import tempfile
import unittest

import isomedia

TESTDATA = os.path.join(os.path.dirname(__file__), 'testdata')

class TestSanity(unittest.TestCase):
    def test_sanity(self):
        mp4filename = os.path.join(TESTDATA, 'loop_circle.mp4')
        mp4file = open(mp4filename, 'rb')
        isofile = isomedia.load(mp4file)

        root = isofile.root
        moov_atom = [atom for atom in root.children if atom.type() == 'moov']
        self.assertEqual(len(moov_atom), 1, 'There should be 1 moov atom.')

        mp4file.close()

    def test_lossless_write(self):
        mp4filename = os.path.join(TESTDATA, 'loop_circle.mp4')
        infile = open(mp4filename, 'rb')
        isofile = isomedia.load(infile)

        outfile = tempfile.NamedTemporaryFile(delete=False)
        isofile.write(outfile)

        infile.close()
        outfile.close()

        self.assertTrue(filecmp.cmp(infile.name, outfile.name))

if __name__ == '__main__':
    unittest.main()

<|next_version|>
import filecmp
import os
import tempfile
import unittest

import isomedia

TESTDATA = os.path.join(os.path.dirname(__file__), 'testdata')

class TestSanity(unittest.TestCase):
    def test_sanity(self):
        mp4filename = os.path.join(TESTDATA, 'loop_circle.mp4')
        mp4file = open(mp4filename, 'rb')
        isofile = isomedia.load(mp4file)

        root = isofile.root
        moov_atom = [atom for atom in root.children if atom.type() == 'moov']
        self.assertEqual(len(moov_atom), 1, 'There should be 1 moov atom.')

        mp4file.close()

    def test_lossless_write(self):
        mp4filename = os.path.join(TESTDATA, 'loop_circle.mp4')
        infile = open(mp4filename, 'rb')
        isofile = isomedia.load(infile)

        outfile = tempfile.NamedTemporaryFile(delete=False)
        isofile.write(outfile)

        infile.close()
        outfile.close()

        self.assertTrue(filecmp.cmp(infile.name, outfile.name))

        os.remove(outfile.name)

if __name__ == '__main__':
    unittest.main()


Discard the '_method' parameter on HTTP POST

--- respite/middleware.py
+++ respite/middleware.py
@@ -1,3 +1,5 @@
+import re
+
 from django.http import QueryDict

 class HttpMethodOverrideMiddleware:
@@ -13,6 +15,9 @@
                 request.META.get('HTTP_X_HTTP_METHOD_OVERRIDE') or
                 request.POST.get('_method')
             ).upper()
+
+        if '_method' in request.POST:
+            request._raw_post_data = re.sub(r'_method=(PUT|PATCH|DELETE)&?', '', request.raw_post_data)

 class HttpPutMiddleware:
     """

<|original_code|>
from django.http import QueryDict

class HttpMethodOverrideMiddleware:
    """
    Facilitate for overriding the HTTP method with the X-HTTP-Method-Override
    header or a '_method' HTTP POST parameter.
    """

    def process_request(self, request):
        if request.META.has_key('HTTP_X_HTTP_METHOD_OVERRIDE') \
        or request.POST.has_key('_method'):
            request.method = (
                request.META.get('HTTP_X_HTTP_METHOD_OVERRIDE') or
                request.POST.get('_method')
            ).upper()

class HttpPutMiddleware:
    """
    Facilitate for HTTP PUT in the same way Django facilitates for HTTP GET
    and HTTP POST; populate a QueryDict instance with the request body in request.PUT.
    """

    def process_request(self, request):
        if request.method == 'PUT':
            request.PUT = QueryDict(request.raw_post_data)

class HttpPatchMiddleware:
    """
    Facilitate for HTTP PATCH in the same way Django facilitates for HTTP GET
    and HTTP POST; populate a QueryDict instance with the request body in request.PATCH.
    """

    def process_request(self, request):
        if request.method == 'PATCH':
            request.PATCH = QueryDict(request.raw_post_data)

<|edits_diff|>
--- respite/middleware.py
+++ respite/middleware.py
@@ -1,3 +1,5 @@
+import re
+
 from django.http import QueryDict

 class HttpMethodOverrideMiddleware:
<|current_version|>
import re

from django.http import QueryDict

class HttpMethodOverrideMiddleware:
    """
    Facilitate for overriding the HTTP method with the X-HTTP-Method-Override
    header or a '_method' HTTP POST parameter.
    """

    def process_request(self, request):
        if request.META.has_key('HTTP_X_HTTP_METHOD_OVERRIDE') \
        or request.POST.has_key('_method'):
            request.method = (
                request.META.get('HTTP_X_HTTP_METHOD_OVERRIDE') or
                request.POST.get('_method')
            ).upper()

class HttpPutMiddleware:
    """
    Facilitate for HTTP PUT in the same way Django facilitates for HTTP GET
    and HTTP POST; populate a QueryDict instance with the request body in request.PUT.
    """

    def process_request(self, request):
        if request.method == 'PUT':
            request.PUT = QueryDict(request.raw_post_data)

class HttpPatchMiddleware:
    """
    Facilitate for HTTP PATCH in the same way Django facilitates for HTTP GET
    and HTTP POST; populate a QueryDict instance with the request body in request.PATCH.
    """

    def process_request(self, request):
        if request.method == 'PATCH':
            request.PATCH = QueryDict(request.raw_post_data)

<|next_version|>
import re

from django.http import QueryDict

class HttpMethodOverrideMiddleware:
    """
    Facilitate for overriding the HTTP method with the X-HTTP-Method-Override
    header or a '_method' HTTP POST parameter.
    """

    def process_request(self, request):
        if request.META.has_key('HTTP_X_HTTP_METHOD_OVERRIDE') \
        or request.POST.has_key('_method'):
            request.method = (
                request.META.get('HTTP_X_HTTP_METHOD_OVERRIDE') or
                request.POST.get('_method')
            ).upper()

        if '_method' in request.POST:
            request._raw_post_data = re.sub(r'_method=(PUT|PATCH|DELETE)&?', '', request.raw_post_data)

class HttpPutMiddleware:
    """
    Facilitate for HTTP PUT in the same way Django facilitates for HTTP GET
    and HTTP POST; populate a QueryDict instance with the request body in request.PUT.
    """

    def process_request(self, request):
        if request.method == 'PUT':
            request.PUT = QueryDict(request.raw_post_data)

class HttpPatchMiddleware:
    """
    Facilitate for HTTP PATCH in the same way Django facilitates for HTTP GET
    and HTTP POST; populate a QueryDict instance with the request body in request.PATCH.
    """

    def process_request(self, request):
        if request.method == 'PATCH':
            request.PATCH = QueryDict(request.raw_post_data)


Return a list of all photo objects which have been updated

--- quickphotos/utils.py
+++ quickphotos/utils.py
@@ -4,6 +4,8 @@

 def update_photos(photos):
+    obj_list = []
+
     for i in photos:
         image = i.images['standard_resolution']

@@ -16,3 +18,7 @@
             'caption': i.caption or '',
             'link': i.link,
         })
+
+        obj_list.append(obj)
+
+    return obj_list

<|original_code|>
from django.utils.timezone import make_aware, utc

from .models import Photo

def update_photos(photos):
    for i in photos:
        image = i.images['standard_resolution']

        obj, created = Photo.objects.update_or_create(photo_id=i.id, defaults={
            'user': i.user.username,
            'image': image.url,
            'image_width': image.width,
            'image_height': image.height,
            'created': make_aware(i.created_time, utc),
            'caption': i.caption or '',
            'link': i.link,
        })

<|edits_diff|>
--- quickphotos/utils.py
+++ quickphotos/utils.py
@@ -4,6 +4,8 @@

 def update_photos(photos):
+    obj_list = []
+
     for i in photos:
         image = i.images['standard_resolution']

<|current_version|>
from django.utils.timezone import make_aware, utc

from .models import Photo

def update_photos(photos):
    obj_list = []

    for i in photos:
        image = i.images['standard_resolution']

        obj, created = Photo.objects.update_or_create(photo_id=i.id, defaults={
            'user': i.user.username,
            'image': image.url,
            'image_width': image.width,
            'image_height': image.height,
            'created': make_aware(i.created_time, utc),
            'caption': i.caption or '',
            'link': i.link,
        })

<|next_version|>
from django.utils.timezone import make_aware, utc

from .models import Photo

def update_photos(photos):
    obj_list = []

    for i in photos:
        image = i.images['standard_resolution']

        obj, created = Photo.objects.update_or_create(photo_id=i.id, defaults={
            'user': i.user.username,
            'image': image.url,
            'image_width': image.width,
            'image_height': image.height,
            'created': make_aware(i.created_time, utc),
            'caption': i.caption or '',
            'link': i.link,
        })

        obj_list.append(obj)

    return obj_list


Add missing packages for install: algorithms, testing.

git-svn-id: 24f545668198cdd163a527378499f2123e59bf9f@527 ead46cd0-7350-4e37-8683-fc4c6f79bf00

--- nipype/setup.py
+++ nipype/setup.py
@@ -3,10 +3,12 @@
     config = Configuration('nipype', parent_package, top_path)

     # List all packages to be loaded here
+    config.add_subpackage('algorithms')
     config.add_subpackage('interfaces')
     config.add_subpackage('pipeline')
     config.add_subpackage('utils')
     config.add_subpackage('externals')
+    config.add_subpackage('testing')

     # List all data directories to be loaded here
     return config

<|original_code|>
def configuration(parent_package='',top_path=None):
    from numpy.distutils.misc_util import Configuration
    config = Configuration('nipype', parent_package, top_path)

    # List all packages to be loaded here
    config.add_subpackage('interfaces')
    config.add_subpackage('pipeline')
    config.add_subpackage('utils')
    config.add_subpackage('externals')

    # List all data directories to be loaded here
    return config

if __name__ == '__main__':
    from numpy.distutils.core import setup
    setup(**configuration(top_path='').todict())

<|edits_diff|>
--- nipype/setup.py
+++ nipype/setup.py
@@ -3,6 +3,7 @@
     config = Configuration('nipype', parent_package, top_path)

     # List all packages to be loaded here
+    config.add_subpackage('algorithms')
     config.add_subpackage('interfaces')
     config.add_subpackage('pipeline')
     config.add_subpackage('utils')
<|current_version|>
def configuration(parent_package='',top_path=None):
    from numpy.distutils.misc_util import Configuration
    config = Configuration('nipype', parent_package, top_path)

    # List all packages to be loaded here
    config.add_subpackage('algorithms')
    config.add_subpackage('interfaces')
    config.add_subpackage('pipeline')
    config.add_subpackage('utils')
    config.add_subpackage('externals')

    # List all data directories to be loaded here
    return config

if __name__ == '__main__':
    from numpy.distutils.core import setup
    setup(**configuration(top_path='').todict())

<|next_version|>
def configuration(parent_package='',top_path=None):
    from numpy.distutils.misc_util import Configuration
    config = Configuration('nipype', parent_package, top_path)

    # List all packages to be loaded here
    config.add_subpackage('algorithms')
    config.add_subpackage('interfaces')
    config.add_subpackage('pipeline')
    config.add_subpackage('utils')
    config.add_subpackage('externals')
    config.add_subpackage('testing')

    # List all data directories to be loaded here
    return config

if __name__ == '__main__':
    from numpy.distutils.core import setup
    setup(**configuration(top_path='').todict())


Allow overriding the config with app settings yaml in the worker process.

--- dad/worker/__init__.py
+++ dad/worker/__init__.py
@@ -1,8 +1,16 @@
+import os
+
+import yaml
 import click

 from flask import Flask, current_app
 app = Flask(__name__)
 app.config.from_object('dad.worker.settings')
+
+if os.environ.get('APP_SETTINGS_YAML'):
+    config = yaml.safe_load(open(os.environ['APP_SETTINGS_YAML']))
+    app.config.update(config)
+

 import dad.worker.server  # noqa

<|original_code|>
import click

from flask import Flask, current_app
app = Flask(__name__)
app.config.from_object('dad.worker.settings')

import dad.worker.server  # noqa

@click.command()
@click.option('--port', '-p', default=6010)
def run(port):
    with app.app_context():
        dad.worker.server.register(current_app)
    app.run(port=port)

<|edits_diff|>
--- dad/worker/__init__.py
+++ dad/worker/__init__.py
@@ -1,3 +1,6 @@
+import os
+
+import yaml
 import click

 from flask import Flask, current_app
<|current_version|>
import os

import yaml
import click

from flask import Flask, current_app
app = Flask(__name__)
app.config.from_object('dad.worker.settings')

import dad.worker.server  # noqa

@click.command()
@click.option('--port', '-p', default=6010)
def run(port):
    with app.app_context():
        dad.worker.server.register(current_app)
    app.run(port=port)

<|next_version|>
import os

import yaml
import click

from flask import Flask, current_app
app = Flask(__name__)
app.config.from_object('dad.worker.settings')

if os.environ.get('APP_SETTINGS_YAML'):
    config = yaml.safe_load(open(os.environ['APP_SETTINGS_YAML']))
    app.config.update(config)

import dad.worker.server  # noqa

@click.command()
@click.option('--port', '-p', default=6010)
def run(port):
    with app.app_context():
        dad.worker.server.register(current_app)
    app.run(port=port)


Stop printing logs while running dashboard tests in catapult.

Some of the dashboard tests invoke functions which log errors,
but these are not interesting or indicative of actual errors when
running the test.

By setting the logging level in run_tests.py, this makes it so
no log messages are printed when run_tests.py is run, so the
output is a bit cleaner.

Review URL: https://codereview.chromium.org/1180363002

--- dashboard/run_tests.py
+++ dashboard/run_tests.py
@@ -4,6 +4,7 @@

 import argparse
 import dev_appserver
+import logging
 import os
 import sys
 import unittest
@@ -34,6 +35,7 @@
       'tests', nargs='*', help='Fully-qualified names of tests to run.')
   args = parser.parse_args()
   runner = unittest.TextTestRunner(verbosity=1)
+  logging.basicConfig(level=logging.CRITICAL)
   result = runner.run(_GetTests(args))
   if result.wasSuccessful():
     sys.exit(0)

<|original_code|>
#!/usr/bin/python

"""Runs the unit test suite for perf dashboard."""

import argparse
import dev_appserver
import os
import sys
import unittest

_DASHBOARD_PARENT = os.path.join(os.path.dirname(__file__))
_DASHBOARD = os.path.join(_DASHBOARD_PARENT, 'dashboard')

def _GetTests(args):
  loader = unittest.TestLoader()
  if args.tests:
    return loader.loadTestsFromNames(args.tests)
  return loader.discover(_DASHBOARD, pattern='*_test.py')

def _FixPath():
  dev_appserver.fix_sys_path()
  sys.path.append(os.path.dirname(__file__))
  # The __init__.py in the dashboard package should add third party
  # libraries to the path.
  import dashboard  # pylint: disable=unused-variable

def main():
  _FixPath()
  parser = argparse.ArgumentParser(description='Run the test suite.')
  parser.add_argument(
      'tests', nargs='*', help='Fully-qualified names of tests to run.')
  args = parser.parse_args()
  runner = unittest.TextTestRunner(verbosity=1)
  result = runner.run(_GetTests(args))
  if result.wasSuccessful():
    sys.exit(0)
  else:
    sys.exit(1)

if __name__ == '__main__':
  main()

<|edits_diff|>
--- dashboard/run_tests.py
+++ dashboard/run_tests.py
@@ -4,6 +4,7 @@

 import argparse
 import dev_appserver
+import logging
 import os
 import sys
 import unittest
<|current_version|>
#!/usr/bin/python

"""Runs the unit test suite for perf dashboard."""

import argparse
import dev_appserver
import logging
import os
import sys
import unittest

_DASHBOARD_PARENT = os.path.join(os.path.dirname(__file__))
_DASHBOARD = os.path.join(_DASHBOARD_PARENT, 'dashboard')

def _GetTests(args):
  loader = unittest.TestLoader()
  if args.tests:
    return loader.loadTestsFromNames(args.tests)
  return loader.discover(_DASHBOARD, pattern='*_test.py')

def _FixPath():
  dev_appserver.fix_sys_path()
  sys.path.append(os.path.dirname(__file__))
  # The __init__.py in the dashboard package should add third party
  # libraries to the path.
  import dashboard  # pylint: disable=unused-variable

def main():
  _FixPath()
  parser = argparse.ArgumentParser(description='Run the test suite.')
  parser.add_argument(
      'tests', nargs='*', help='Fully-qualified names of tests to run.')
  args = parser.parse_args()
  runner = unittest.TextTestRunner(verbosity=1)
  result = runner.run(_GetTests(args))
  if result.wasSuccessful():
    sys.exit(0)
  else:
    sys.exit(1)

if __name__ == '__main__':
  main()

<|next_version|>
#!/usr/bin/python

"""Runs the unit test suite for perf dashboard."""

import argparse
import dev_appserver
import logging
import os
import sys
import unittest

_DASHBOARD_PARENT = os.path.join(os.path.dirname(__file__))
_DASHBOARD = os.path.join(_DASHBOARD_PARENT, 'dashboard')

def _GetTests(args):
  loader = unittest.TestLoader()
  if args.tests:
    return loader.loadTestsFromNames(args.tests)
  return loader.discover(_DASHBOARD, pattern='*_test.py')

def _FixPath():
  dev_appserver.fix_sys_path()
  sys.path.append(os.path.dirname(__file__))
  # The __init__.py in the dashboard package should add third party
  # libraries to the path.
  import dashboard  # pylint: disable=unused-variable

def main():
  _FixPath()
  parser = argparse.ArgumentParser(description='Run the test suite.')
  parser.add_argument(
      'tests', nargs='*', help='Fully-qualified names of tests to run.')
  args = parser.parse_args()
  runner = unittest.TextTestRunner(verbosity=1)
  logging.basicConfig(level=logging.CRITICAL)
  result = runner.run(_GetTests(args))
  if result.wasSuccessful():
    sys.exit(0)
  else:
    sys.exit(1)

if __name__ == '__main__':
  main()


Refactor migrations after generating to ensure custom user model compatibility.

--- generate_migrations.py
+++ generate_migrations.py
@@ -17,6 +17,8 @@
 # missing or badly-configured settings.
 from django.core import management

+from refactor_migrations import refactor
+

 def generate_migrations(initial):
   management.call_command('syncdb', interactive=False)
@@ -24,6 +26,8 @@
     management.call_command('schemamigration', 'djoauth2', initial=True)
   else:
     management.call_command('schemamigration', 'djoauth2', auto=True)
+  refactor('./djoauth2/migrations/')
+

 def test_migrations():
   management.call_command('syncdb', interactive=False)

<|original_code|>
#!/usr/bin/env python
# coding: utf-8
import sys
from argparse import ArgumentParser
from os.path import abspath
from os.path import dirname

# Modify the path so that our djoauth2 app is in it.
parent_dir = dirname(abspath(__file__))
sys.path.insert(0, parent_dir)

# Load Django-related settings; necessary for tests to run and for Django
# imports to work.
import local_settings

# Now, imports from Django will work properly without raising errors related to
# missing or badly-configured settings.
from django.core import management

def generate_migrations(initial):
  management.call_command('syncdb', interactive=False)
  if initial:
    management.call_command('schemamigration', 'djoauth2', initial=True)
  else:
    management.call_command('schemamigration', 'djoauth2', auto=True)

def test_migrations():
  management.call_command('syncdb', interactive=False)
  management.call_command('migrate', 'djoauth2')

if __name__ == '__main__':
  parser = ArgumentParser()

  parser.add_argument('--initial-migration',
                      action='store_true',
                      default=False,
                      dest='initial')

  parser.add_argument('--test-migrations',
                      action='store_true',
                      default=False,
                      dest='test_migrations')

  args = parser.parse_args()

  if args.test_migrations:
    test_migrations()
  else:
    generate_migrations(args.initial)

<|edits_diff|>
--- generate_migrations.py
+++ generate_migrations.py
@@ -16,6 +16,8 @@
 # Now, imports from Django will work properly without raising errors related to
 # missing or badly-configured settings.
 from django.core import management
+
+from refactor_migrations import refactor

 def generate_migrations(initial):
<|current_version|>
#!/usr/bin/env python
# coding: utf-8
import sys
from argparse import ArgumentParser
from os.path import abspath
from os.path import dirname

# Modify the path so that our djoauth2 app is in it.
parent_dir = dirname(abspath(__file__))
sys.path.insert(0, parent_dir)

# Load Django-related settings; necessary for tests to run and for Django
# imports to work.
import local_settings

# Now, imports from Django will work properly without raising errors related to
# missing or badly-configured settings.
from django.core import management

from refactor_migrations import refactor

def generate_migrations(initial):
  management.call_command('syncdb', interactive=False)
  if initial:
    management.call_command('schemamigration', 'djoauth2', initial=True)
  else:
    management.call_command('schemamigration', 'djoauth2', auto=True)

def test_migrations():
  management.call_command('syncdb', interactive=False)
  management.call_command('migrate', 'djoauth2')

if __name__ == '__main__':
  parser = ArgumentParser()

  parser.add_argument('--initial-migration',
                      action='store_true',
                      default=False,
                      dest='initial')

  parser.add_argument('--test-migrations',
                      action='store_true',
                      default=False,
                      dest='test_migrations')

  args = parser.parse_args()

  if args.test_migrations:
    test_migrations()
  else:
    generate_migrations(args.initial)

<|next_version|>
#!/usr/bin/env python
# coding: utf-8
import sys
from argparse import ArgumentParser
from os.path import abspath
from os.path import dirname

# Modify the path so that our djoauth2 app is in it.
parent_dir = dirname(abspath(__file__))
sys.path.insert(0, parent_dir)

# Load Django-related settings; necessary for tests to run and for Django
# imports to work.
import local_settings

# Now, imports from Django will work properly without raising errors related to
# missing or badly-configured settings.
from django.core import management

from refactor_migrations import refactor

def generate_migrations(initial):
  management.call_command('syncdb', interactive=False)
  if initial:
    management.call_command('schemamigration', 'djoauth2', initial=True)
  else:
    management.call_command('schemamigration', 'djoauth2', auto=True)
  refactor('./djoauth2/migrations/')

def test_migrations():
  management.call_command('syncdb', interactive=False)
  management.call_command('migrate', 'djoauth2')

if __name__ == '__main__':
  parser = ArgumentParser()

  parser.add_argument('--initial-migration',
                      action='store_true',
                      default=False,
                      dest='initial')

  parser.add_argument('--test-migrations',
                      action='store_true',
                      default=False,
                      dest='test_migrations')

  args = parser.parse_args()

  if args.test_migrations:
    test_migrations()
  else:
    generate_migrations(args.initial)


Fix problem with South migrations.

Fix problem with South migrations.

--- begood_sites/fields.py
+++ begood_sites/fields.py
@@ -9,12 +9,16 @@
         'blank': False,
         }
     defaults.update(kwargs)
+    if 'to' in defaults:
+      del defaults['to']
     super(MultiSiteField, self).__init__(Site, **defaults)

 class SingleSiteField(models.ForeignKey):

   def __init__(self, **kwargs):
+    if 'to' in kwargs:
+      del kwargs['to']
     super(SingleSiteField, self).__init__(Site, **kwargs)

<|original_code|>
from django.db import models
from django.contrib.sites.models import Site

class MultiSiteField(models.ManyToManyField):

  def __init__(self, **kwargs):
    defaults = {
        'blank': False,
        }
    defaults.update(kwargs)
    super(MultiSiteField, self).__init__(Site, **defaults)

class SingleSiteField(models.ForeignKey):

  def __init__(self, **kwargs):
    super(SingleSiteField, self).__init__(Site, **kwargs)

# Make sure South migrations work
try:
  from south.modelsinspector import add_introspection_rules
  add_introspection_rules([], ["^begood_sites\.fields\.MultiSiteField"])
  add_introspection_rules([], ["^begood_sites\.fields\.SingleSiteField"])
except:
  pass

<|edits_diff|>
--- begood_sites/fields.py
+++ begood_sites/fields.py
@@ -9,6 +9,8 @@
         'blank': False,
         }
     defaults.update(kwargs)
+    if 'to' in defaults:
+      del defaults['to']
     super(MultiSiteField, self).__init__(Site, **defaults)

<|current_version|>
from django.db import models
from django.contrib.sites.models import Site

class MultiSiteField(models.ManyToManyField):

  def __init__(self, **kwargs):
    defaults = {
        'blank': False,
        }
    defaults.update(kwargs)
    if 'to' in defaults:
      del defaults['to']
    super(MultiSiteField, self).__init__(Site, **defaults)

class SingleSiteField(models.ForeignKey):

  def __init__(self, **kwargs):
    super(SingleSiteField, self).__init__(Site, **kwargs)

# Make sure South migrations work
try:
  from south.modelsinspector import add_introspection_rules
  add_introspection_rules([], ["^begood_sites\.fields\.MultiSiteField"])
  add_introspection_rules([], ["^begood_sites\.fields\.SingleSiteField"])
except:
  pass

<|next_version|>
from django.db import models
from django.contrib.sites.models import Site

class MultiSiteField(models.ManyToManyField):

  def __init__(self, **kwargs):
    defaults = {
        'blank': False,
        }
    defaults.update(kwargs)
    if 'to' in defaults:
      del defaults['to']
    super(MultiSiteField, self).__init__(Site, **defaults)

class SingleSiteField(models.ForeignKey):

  def __init__(self, **kwargs):
    if 'to' in kwargs:
      del kwargs['to']
    super(SingleSiteField, self).__init__(Site, **kwargs)

# Make sure South migrations work
try:
  from south.modelsinspector import add_introspection_rules
  add_introspection_rules([], ["^begood_sites\.fields\.MultiSiteField"])
  add_introspection_rules([], ["^begood_sites\.fields\.SingleSiteField"])
except:
  pass


Add missing returns to the array API sorting functions

--- numpy/_array_api/_sorting_functions.py
+++ numpy/_array_api/_sorting_functions.py
@@ -6,6 +6,7 @@
     res = argsort(x, axis=axis, kind=kind)
     if descending:
         res = flip(res, axis=axis)
+    return res

 def sort(x, /, *, axis=-1, descending=False, stable=True):
     from .. import sort
@@ -15,3 +16,4 @@
     res = sort(x, axis=axis, kind=kind)
     if descending:
         res = flip(res, axis=axis)
+    return res

<|original_code|>
def argsort(x, /, *, axis=-1, descending=False, stable=True):
    from .. import argsort
    from .. import flip
    # Note: this keyword argument is different, and the default is different.
    kind = 'stable' if stable else 'quicksort'
    res = argsort(x, axis=axis, kind=kind)
    if descending:
        res = flip(res, axis=axis)

def sort(x, /, *, axis=-1, descending=False, stable=True):
    from .. import sort
    from .. import flip
    # Note: this keyword argument is different, and the default is different.
    kind = 'stable' if stable else 'quicksort'
    res = sort(x, axis=axis, kind=kind)
    if descending:
        res = flip(res, axis=axis)

<|edits_diff|>
--- numpy/_array_api/_sorting_functions.py
+++ numpy/_array_api/_sorting_functions.py
@@ -6,6 +6,7 @@
     res = argsort(x, axis=axis, kind=kind)
     if descending:
         res = flip(res, axis=axis)
+    return res

 def sort(x, /, *, axis=-1, descending=False, stable=True):
     from .. import sort
<|current_version|>
def argsort(x, /, *, axis=-1, descending=False, stable=True):
    from .. import argsort
    from .. import flip
    # Note: this keyword argument is different, and the default is different.
    kind = 'stable' if stable else 'quicksort'
    res = argsort(x, axis=axis, kind=kind)
    if descending:
        res = flip(res, axis=axis)
    return res

def sort(x, /, *, axis=-1, descending=False, stable=True):
    from .. import sort
    from .. import flip
    # Note: this keyword argument is different, and the default is different.
    kind = 'stable' if stable else 'quicksort'
    res = sort(x, axis=axis, kind=kind)
    if descending:
        res = flip(res, axis=axis)

<|next_version|>
def argsort(x, /, *, axis=-1, descending=False, stable=True):
    from .. import argsort
    from .. import flip
    # Note: this keyword argument is different, and the default is different.
    kind = 'stable' if stable else 'quicksort'
    res = argsort(x, axis=axis, kind=kind)
    if descending:
        res = flip(res, axis=axis)
    return res

def sort(x, /, *, axis=-1, descending=False, stable=True):
    from .. import sort
    from .. import flip
    # Note: this keyword argument is different, and the default is different.
    kind = 'stable' if stable else 'quicksort'
    res = sort(x, axis=axis, kind=kind)
    if descending:
        res = flip(res, axis=axis)
    return res


Update file for pep8 compliance

Update file for pep8 compliance

--- tests/test_accounts.py
+++ tests/test_accounts.py
@@ -4,6 +4,7 @@

 from tools import create_mock_json
 from twilio.rest.resources import Account
+

 class AccountTest(unittest.TestCase):

@@ -19,6 +20,7 @@
         records = account.usage_records.list()
         self.assertEquals(len(records), 2)

+
     @patch("twilio.rest.resources.base.make_twilio_request")
     def test_usage_triggers_subresource(self, request):
         resp = create_mock_json("tests/resources/usage_triggers_list.json")

<|original_code|>
import unittest

from mock import Mock, patch

from tools import create_mock_json
from twilio.rest.resources import Account

class AccountTest(unittest.TestCase):

    @patch("twilio.rest.resources.base.make_twilio_request")
    def test_usage_records_subresource(self, request):
        resp = create_mock_json("tests/resources/usage_records_list.json")
        request.return_value = resp

        mock = Mock()
        mock.uri = "/base"
        account = Account(mock, 'AC123')
        account.load_subresources()
        records = account.usage_records.list()
        self.assertEquals(len(records), 2)

    @patch("twilio.rest.resources.base.make_twilio_request")
    def test_usage_triggers_subresource(self, request):
        resp = create_mock_json("tests/resources/usage_triggers_list.json")
        request.return_value = resp

        mock = Mock()
        mock.uri = "/base"
        account = Account(mock, 'AC123')
        account.load_subresources()
        triggers = account.usage_triggers.list()
        self.assertEquals(len(triggers), 2)

<|edits_diff|>
--- tests/test_accounts.py
+++ tests/test_accounts.py
@@ -4,6 +4,7 @@

 from tools import create_mock_json
 from twilio.rest.resources import Account
+

 class AccountTest(unittest.TestCase):

<|current_version|>
import unittest

from mock import Mock, patch

from tools import create_mock_json
from twilio.rest.resources import Account

class AccountTest(unittest.TestCase):

    @patch("twilio.rest.resources.base.make_twilio_request")
    def test_usage_records_subresource(self, request):
        resp = create_mock_json("tests/resources/usage_records_list.json")
        request.return_value = resp

        mock = Mock()
        mock.uri = "/base"
        account = Account(mock, 'AC123')
        account.load_subresources()
        records = account.usage_records.list()
        self.assertEquals(len(records), 2)

    @patch("twilio.rest.resources.base.make_twilio_request")
    def test_usage_triggers_subresource(self, request):
        resp = create_mock_json("tests/resources/usage_triggers_list.json")
        request.return_value = resp

        mock = Mock()
        mock.uri = "/base"
        account = Account(mock, 'AC123')
        account.load_subresources()
        triggers = account.usage_triggers.list()
        self.assertEquals(len(triggers), 2)

<|next_version|>
import unittest

from mock import Mock, patch

from tools import create_mock_json
from twilio.rest.resources import Account

class AccountTest(unittest.TestCase):

    @patch("twilio.rest.resources.base.make_twilio_request")
    def test_usage_records_subresource(self, request):
        resp = create_mock_json("tests/resources/usage_records_list.json")
        request.return_value = resp

        mock = Mock()
        mock.uri = "/base"
        account = Account(mock, 'AC123')
        account.load_subresources()
        records = account.usage_records.list()
        self.assertEquals(len(records), 2)

    @patch("twilio.rest.resources.base.make_twilio_request")
    def test_usage_triggers_subresource(self, request):
        resp = create_mock_json("tests/resources/usage_triggers_list.json")
        request.return_value = resp

        mock = Mock()
        mock.uri = "/base"
        account = Account(mock, 'AC123')
        account.load_subresources()
        triggers = account.usage_triggers.list()
        self.assertEquals(len(triggers), 2)


Add support for specifying branch name to svg badges

--- frigg/projects/urls.py
+++ frigg/projects/urls.py
@@ -6,6 +6,10 @@
     url(r'^projects/approve/$', views.approve_projects, name='approve_projects_overview'),
     url(r'^projects/approve/(?P<project_id>\d+)/$', views.approve_projects, name='approve_project'),
     url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+).svg$', views.build_badge, name='build_badge'),
+    url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/(?P<branch>[^/]+).svg$', views.build_badge,
+        name='build_branch_badge'),
     url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/coverage.svg$', views.coverage_badge,
         name='coverage_badge'),
+    url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/(?P<branch>[^/]+)/coverage.svg$', views.coverage_badge,
+        name='coverage_branch_badge'),
 ]

<|original_code|>
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^projects/approve/$', views.approve_projects, name='approve_projects_overview'),
    url(r'^projects/approve/(?P<project_id>\d+)/$', views.approve_projects, name='approve_project'),
    url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+).svg$', views.build_badge, name='build_badge'),
    url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/coverage.svg$', views.coverage_badge,
        name='coverage_badge'),
]

<|edits_diff|>
--- frigg/projects/urls.py
+++ frigg/projects/urls.py
@@ -6,6 +6,8 @@
     url(r'^projects/approve/$', views.approve_projects, name='approve_projects_overview'),
     url(r'^projects/approve/(?P<project_id>\d+)/$', views.approve_projects, name='approve_project'),
     url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+).svg$', views.build_badge, name='build_badge'),
+    url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/(?P<branch>[^/]+).svg$', views.build_badge,
+        name='build_branch_badge'),
     url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/coverage.svg$', views.coverage_badge,
         name='coverage_badge'),
 ]
<|current_version|>
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^projects/approve/$', views.approve_projects, name='approve_projects_overview'),
    url(r'^projects/approve/(?P<project_id>\d+)/$', views.approve_projects, name='approve_project'),
    url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+).svg$', views.build_badge, name='build_badge'),
    url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/(?P<branch>[^/]+).svg$', views.build_badge,
        name='build_branch_badge'),
    url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/coverage.svg$', views.coverage_badge,
        name='coverage_badge'),
]

<|next_version|>
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^projects/approve/$', views.approve_projects, name='approve_projects_overview'),
    url(r'^projects/approve/(?P<project_id>\d+)/$', views.approve_projects, name='approve_project'),
    url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+).svg$', views.build_badge, name='build_badge'),
    url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/(?P<branch>[^/]+).svg$', views.build_badge,
        name='build_branch_badge'),
    url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/coverage.svg$', views.coverage_badge,
        name='coverage_badge'),
    url(r'^(?P<owner>[^/]+)/(?P<name>[^/]+)/(?P<branch>[^/]+)/coverage.svg$', views.coverage_badge,
        name='coverage_branch_badge'),
]


Add docstring for main module

Add docstring for main module

--- quilt/__init__.py
+++ quilt/__init__.py
@@ -19,5 +19,8 @@
 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 # 02110-1301 USA

+""" A python implementation of quilt """
+
 __version_info__ = ("0", "1", "dev1")
 __version__ = '.'.join(__version_info__)
+

<|original_code|>
# vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:

# python-quilt - A Python implementation of the quilt patch system
#
# Copyright (C) 2012  Björn Ricks <bjoern.ricks@googlemail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.

# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA

__version_info__ = ("0", "1", "dev1")
__version__ = '.'.join(__version_info__)

<|edits_diff|>
--- quilt/__init__.py
+++ quilt/__init__.py
@@ -19,5 +19,7 @@
 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 # 02110-1301 USA

+""" A python implementation of quilt """
+
 __version_info__ = ("0", "1", "dev1")
 __version__ = '.'.join(__version_info__)
<|current_version|>
# vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:

# python-quilt - A Python implementation of the quilt patch system
#
# Copyright (C) 2012  Björn Ricks <bjoern.ricks@googlemail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.

# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA

""" A python implementation of quilt """

__version_info__ = ("0", "1", "dev1")
__version__ = '.'.join(__version_info__)

<|next_version|>
# vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:

# python-quilt - A Python implementation of the quilt patch system
#
# Copyright (C) 2012  Björn Ricks <bjoern.ricks@googlemail.com>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.

# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.

# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA

""" A python implementation of quilt """

__version_info__ = ("0", "1", "dev1")
__version__ = '.'.join(__version_info__)


Add zipcode filter for MFPs.

Add zipcode filter for MFPs.

--- homeful/views.py
+++ homeful/views.py
@@ -24,6 +24,8 @@
         if fmr['area'] == u'Seattle-Bellevue, WA HUD Metro FMR Area':
             seattle_fmr = fmr

+    mfps = filterByZipcode(zipcode, mfps)
+
     context['mfps'] = mfps
     context['rooms'] = rooms

@@ -33,3 +35,8 @@
     context['price_range'] = "$" + "{0:.2f}".format(price_range_min) + " - $" + "{0:.2f}".format(price_range_max)

     return render(request, 'homeful/content1.html', context)
+
+def filterByZipcode(zipcode, mfps):
+    def myfilter(mfp):
+        return mfp['zipcode'] == zipcode
+    return filter(myfilter, mfps)

<|original_code|>
from django.shortcuts import render
import logging
from homeful.hud_helper import getSeattleFairMarketRents, getSeattleMultiFamilyProperties

logger = logging.getLogger(__name__)

def index(request):
    context = {}
    return render(request, 'homeful/index.html', context)

def list(request):
    zipcode = request.GET['zipcode']
    rooms = request.GET['rooms']
    price = request.GET['price']
    context = {}

    fmrs = getSeattleFairMarketRents()
    mfps = getSeattleMultiFamilyProperties()

    # modify FMRs and MFPs based on request HERE

    seattle_fmr = dict()
    for fmr in fmrs:
        if fmr['area'] == u'Seattle-Bellevue, WA HUD Metro FMR Area':
            seattle_fmr = fmr

    context['mfps'] = mfps
    context['rooms'] = rooms

    estimated_price = seattle_fmr[rooms + 'br']
    price_range_max = estimated_price + (estimated_price*.12)
    price_range_min = estimated_price - (estimated_price*.12)
    context['price_range'] = "$" + "{0:.2f}".format(price_range_min) + " - $" + "{0:.2f}".format(price_range_max)

    return render(request, 'homeful/content1.html', context)

<|edits_diff|>
--- homeful/views.py
+++ homeful/views.py
@@ -24,6 +24,8 @@
         if fmr['area'] == u'Seattle-Bellevue, WA HUD Metro FMR Area':
             seattle_fmr = fmr

+    mfps = filterByZipcode(zipcode, mfps)
+
     context['mfps'] = mfps
     context['rooms'] = rooms

<|current_version|>
from django.shortcuts import render
import logging
from homeful.hud_helper import getSeattleFairMarketRents, getSeattleMultiFamilyProperties

logger = logging.getLogger(__name__)

def index(request):
    context = {}
    return render(request, 'homeful/index.html', context)

def list(request):
    zipcode = request.GET['zipcode']
    rooms = request.GET['rooms']
    price = request.GET['price']
    context = {}

    fmrs = getSeattleFairMarketRents()
    mfps = getSeattleMultiFamilyProperties()

    # modify FMRs and MFPs based on request HERE

    seattle_fmr = dict()
    for fmr in fmrs:
        if fmr['area'] == u'Seattle-Bellevue, WA HUD Metro FMR Area':
            seattle_fmr = fmr

    mfps = filterByZipcode(zipcode, mfps)

    context['mfps'] = mfps
    context['rooms'] = rooms

    estimated_price = seattle_fmr[rooms + 'br']
    price_range_max = estimated_price + (estimated_price*.12)
    price_range_min = estimated_price - (estimated_price*.12)
    context['price_range'] = "$" + "{0:.2f}".format(price_range_min) + " - $" + "{0:.2f}".format(price_range_max)

    return render(request, 'homeful/content1.html', context)

<|next_version|>
from django.shortcuts import render
import logging
from homeful.hud_helper import getSeattleFairMarketRents, getSeattleMultiFamilyProperties

logger = logging.getLogger(__name__)

def index(request):
    context = {}
    return render(request, 'homeful/index.html', context)

def list(request):
    zipcode = request.GET['zipcode']
    rooms = request.GET['rooms']
    price = request.GET['price']
    context = {}

    fmrs = getSeattleFairMarketRents()
    mfps = getSeattleMultiFamilyProperties()

    # modify FMRs and MFPs based on request HERE

    seattle_fmr = dict()
    for fmr in fmrs:
        if fmr['area'] == u'Seattle-Bellevue, WA HUD Metro FMR Area':
            seattle_fmr = fmr

    mfps = filterByZipcode(zipcode, mfps)

    context['mfps'] = mfps
    context['rooms'] = rooms

    estimated_price = seattle_fmr[rooms + 'br']
    price_range_max = estimated_price + (estimated_price*.12)
    price_range_min = estimated_price - (estimated_price*.12)
    context['price_range'] = "$" + "{0:.2f}".format(price_range_min) + " - $" + "{0:.2f}".format(price_range_max)

    return render(request, 'homeful/content1.html', context)

def filterByZipcode(zipcode, mfps):
    def myfilter(mfp):
        return mfp['zipcode'] == zipcode
    return filter(myfilter, mfps)


Add some pretty to the unit tests

Add some pretty to the unit tests

--- tests/runtests.py
+++ tests/runtests.py
@@ -10,18 +10,32 @@

 TEST_DIR = os.path.dirname(os.path.normpath(os.path.abspath(__file__)))

+PNUM = 50
+
 def run_integration_tests():
+    print '~' * PNUM
+    print 'Setting up Salt daemons to execute tests'
+    print '~' * PNUM
     with TestDaemon():
         moduleloader = saltunittest.TestLoader()
         moduletests = moduleloader.discover(os.path.join(TEST_DIR, 'integration', 'modules'), '*.py')
+        print '~' * PNUM
+        print 'Starting Module Tets'
+        print '~' * PNUM
         saltunittest.TextTestRunner(verbosity=1).run(moduletests)
         clientloader = saltunittest.TestLoader()
         clienttests = clientloader.discover(os.path.join(TEST_DIR, 'integration', 'client'), '*.py')
+        print '~' * PNUM
+        print 'Starting Client tests'
+        print '~' * PNUM
         saltunittest.TextTestRunner(verbosity=1).run(clienttests)

 def run_unit_tests():
     loader = saltunittest.TestLoader()
     tests = loader.discover(os.path.join(TEST_DIR, 'unit', 'templates'), '*.py')
+    print '~' * PNUM
+    print 'Starting Unit Tests'
+    print '~' * PNUM
     saltunittest.TextTestRunner(verbosity=1).run(tests)

<|original_code|>
#!/usr/bin/env python
'''
Discover all instances of unittest.TestCase in this directory.
'''
# Import python libs
import os
# Import salt libs
import saltunittest
from integration import TestDaemon

TEST_DIR = os.path.dirname(os.path.normpath(os.path.abspath(__file__)))

def run_integration_tests():
    with TestDaemon():
        moduleloader = saltunittest.TestLoader()
        moduletests = moduleloader.discover(os.path.join(TEST_DIR, 'integration', 'modules'), '*.py')
        saltunittest.TextTestRunner(verbosity=1).run(moduletests)
        clientloader = saltunittest.TestLoader()
        clienttests = clientloader.discover(os.path.join(TEST_DIR, 'integration', 'client'), '*.py')
        saltunittest.TextTestRunner(verbosity=1).run(clienttests)

def run_unit_tests():
    loader = saltunittest.TestLoader()
    tests = loader.discover(os.path.join(TEST_DIR, 'unit', 'templates'), '*.py')
    saltunittest.TextTestRunner(verbosity=1).run(tests)

if __name__ == "__main__":
    run_integration_tests()
    run_unit_tests()

<|edits_diff|>
--- tests/runtests.py
+++ tests/runtests.py
@@ -10,13 +10,24 @@

 TEST_DIR = os.path.dirname(os.path.normpath(os.path.abspath(__file__)))

+PNUM = 50
+
 def run_integration_tests():
+    print '~' * PNUM
+    print 'Setting up Salt daemons to execute tests'
+    print '~' * PNUM
     with TestDaemon():
         moduleloader = saltunittest.TestLoader()
         moduletests = moduleloader.discover(os.path.join(TEST_DIR, 'integration', 'modules'), '*.py')
+        print '~' * PNUM
+        print 'Starting Module Tets'
+        print '~' * PNUM
         saltunittest.TextTestRunner(verbosity=1).run(moduletests)
         clientloader = saltunittest.TestLoader()
         clienttests = clientloader.discover(os.path.join(TEST_DIR, 'integration', 'client'), '*.py')
+        print '~' * PNUM
+        print 'Starting Client tests'
+        print '~' * PNUM
         saltunittest.TextTestRunner(verbosity=1).run(clienttests)

 def run_unit_tests():
<|current_version|>
#!/usr/bin/env python
'''
Discover all instances of unittest.TestCase in this directory.
'''
# Import python libs
import os
# Import salt libs
import saltunittest
from integration import TestDaemon

TEST_DIR = os.path.dirname(os.path.normpath(os.path.abspath(__file__)))

PNUM = 50

def run_integration_tests():
    print '~' * PNUM
    print 'Setting up Salt daemons to execute tests'
    print '~' * PNUM
    with TestDaemon():
        moduleloader = saltunittest.TestLoader()
        moduletests = moduleloader.discover(os.path.join(TEST_DIR, 'integration', 'modules'), '*.py')
        print '~' * PNUM
        print 'Starting Module Tets'
        print '~' * PNUM
        saltunittest.TextTestRunner(verbosity=1).run(moduletests)
        clientloader = saltunittest.TestLoader()
        clienttests = clientloader.discover(os.path.join(TEST_DIR, 'integration', 'client'), '*.py')
        print '~' * PNUM
        print 'Starting Client tests'
        print '~' * PNUM
        saltunittest.TextTestRunner(verbosity=1).run(clienttests)

def run_unit_tests():
    loader = saltunittest.TestLoader()
    tests = loader.discover(os.path.join(TEST_DIR, 'unit', 'templates'), '*.py')
    saltunittest.TextTestRunner(verbosity=1).run(tests)

if __name__ == "__main__":
    run_integration_tests()
    run_unit_tests()

<|next_version|>
#!/usr/bin/env python
'''
Discover all instances of unittest.TestCase in this directory.
'''
# Import python libs
import os
# Import salt libs
import saltunittest
from integration import TestDaemon

TEST_DIR = os.path.dirname(os.path.normpath(os.path.abspath(__file__)))

PNUM = 50

def run_integration_tests():
    print '~' * PNUM
    print 'Setting up Salt daemons to execute tests'
    print '~' * PNUM
    with TestDaemon():
        moduleloader = saltunittest.TestLoader()
        moduletests = moduleloader.discover(os.path.join(TEST_DIR, 'integration', 'modules'), '*.py')
        print '~' * PNUM
        print 'Starting Module Tets'
        print '~' * PNUM
        saltunittest.TextTestRunner(verbosity=1).run(moduletests)
        clientloader = saltunittest.TestLoader()
        clienttests = clientloader.discover(os.path.join(TEST_DIR, 'integration', 'client'), '*.py')
        print '~' * PNUM
        print 'Starting Client tests'
        print '~' * PNUM
        saltunittest.TextTestRunner(verbosity=1).run(clienttests)

def run_unit_tests():
    loader = saltunittest.TestLoader()
    tests = loader.discover(os.path.join(TEST_DIR, 'unit', 'templates'), '*.py')
    print '~' * PNUM
    print 'Starting Unit Tests'
    print '~' * PNUM
    saltunittest.TextTestRunner(verbosity=1).run(tests)

if __name__ == "__main__":
    run_integration_tests()
    run_unit_tests()


Add missing libraries to the install_requires list (we import from them, so they really should be declared.

--- setup.py
+++ setup.py
@@ -11,13 +11,16 @@
 install_requires = [
     'Django',
     'ddsc-logging',
+    'ddsc-core',
     'ddsc-opendap',
     'ddsc-site',
     'dikedata-api',
     'django-cors-headers',
     'django-extensions',
+    'django-haystack >= 2.0',
     'django-nose',
     'gunicorn',
+    'lizard-security',
     'lizard-auth-client',
     'lizard-ui >= 4.0b5',
     'lxml >= 3.0',

<|original_code|>
from setuptools import setup

version = '0.5.dev0'

long_description = '\n\n'.join([
    open('README.rst').read(),
    open('CREDITS.rst').read(),
    open('CHANGES.rst').read(),
    ])

install_requires = [
    'Django',
    'ddsc-logging',
    'ddsc-opendap',
    'ddsc-site',
    'dikedata-api',
    'django-cors-headers',
    'django-extensions',
    'django-nose',
    'gunicorn',
    'lizard-auth-client',
    'lizard-ui >= 4.0b5',
    'lxml >= 3.0',
    'pyproj',
    'python-magic',
    'python-memcached',
    'raven',
    'tslib',
    'werkzeug',
    ],

setup(name='ddsc-api',
      version=version,
      description="TODO",
      long_description=long_description,
      # Get strings from http://www.python.org/pypi?%3Aaction=list_classifiers
      classifiers=['Programming Language :: Python',
                   'Framework :: Django',
                   ],
      keywords=[],
      author='Reinout van Rees',
      author_email='reinout.vanrees@nelen-schuurmans.nl',
      url='',
      license='MIT',
      packages=['ddsc_api'],
      include_package_data=True,
      zip_safe=False,
      install_requires=install_requires,
      entry_points={
          'console_scripts': [
          ]},
      )

<|edits_diff|>
--- setup.py
+++ setup.py
@@ -11,11 +11,13 @@
 install_requires = [
     'Django',
     'ddsc-logging',
+    'ddsc-core',
     'ddsc-opendap',
     'ddsc-site',
     'dikedata-api',
     'django-cors-headers',
     'django-extensions',
+    'django-haystack >= 2.0',
     'django-nose',
     'gunicorn',
     'lizard-auth-client',
<|current_version|>
from setuptools import setup

version = '0.5.dev0'

long_description = '\n\n'.join([
    open('README.rst').read(),
    open('CREDITS.rst').read(),
    open('CHANGES.rst').read(),
    ])

install_requires = [
    'Django',
    'ddsc-logging',
    'ddsc-core',
    'ddsc-opendap',
    'ddsc-site',
    'dikedata-api',
    'django-cors-headers',
    'django-extensions',
    'django-haystack >= 2.0',
    'django-nose',
    'gunicorn',
    'lizard-auth-client',
    'lizard-ui >= 4.0b5',
    'lxml >= 3.0',
    'pyproj',
    'python-magic',
    'python-memcached',
    'raven',
    'tslib',
    'werkzeug',
    ],

setup(name='ddsc-api',
      version=version,
      description="TODO",
      long_description=long_description,
      # Get strings from http://www.python.org/pypi?%3Aaction=list_classifiers
      classifiers=['Programming Language :: Python',
                   'Framework :: Django',
                   ],
      keywords=[],
      author='Reinout van Rees',
      author_email='reinout.vanrees@nelen-schuurmans.nl',
      url='',
      license='MIT',
      packages=['ddsc_api'],
      include_package_data=True,
      zip_safe=False,
      install_requires=install_requires,
      entry_points={
          'console_scripts': [
          ]},
      )

<|next_version|>
from setuptools import setup

version = '0.5.dev0'

long_description = '\n\n'.join([
    open('README.rst').read(),
    open('CREDITS.rst').read(),
    open('CHANGES.rst').read(),
    ])

install_requires = [
    'Django',
    'ddsc-logging',
    'ddsc-core',
    'ddsc-opendap',
    'ddsc-site',
    'dikedata-api',
    'django-cors-headers',
    'django-extensions',
    'django-haystack >= 2.0',
    'django-nose',
    'gunicorn',
    'lizard-security',
    'lizard-auth-client',
    'lizard-ui >= 4.0b5',
    'lxml >= 3.0',
    'pyproj',
    'python-magic',
    'python-memcached',
    'raven',
    'tslib',
    'werkzeug',
    ],

setup(name='ddsc-api',
      version=version,
      description="TODO",
      long_description=long_description,
      # Get strings from http://www.python.org/pypi?%3Aaction=list_classifiers
      classifiers=['Programming Language :: Python',
                   'Framework :: Django',
                   ],
      keywords=[],
      author='Reinout van Rees',
      author_email='reinout.vanrees@nelen-schuurmans.nl',
      url='',
      license='MIT',
      packages=['ddsc_api'],
      include_package_data=True,
      zip_safe=False,
      install_requires=install_requires,
      entry_points={
          'console_scripts': [
          ]},
      )


Add long description (from README.md)

Add long description (from README.md)

--- setup.py
+++ setup.py
@@ -1,10 +1,17 @@
 #!/usr/bin/env python

+import os
 from setuptools import setup
+
+def get_long_description():
+    filename = os.path.join(os.path.dirname(__file__), 'README.md')
+    with open(filename) as f:
+        return f.read()

 setup(name='pyannotate',
       version='1.0.5',
       description="PyAnnotate: Auto-generate PEP-484 annotations",
+      long_description=get_long_description(),
       author='Dropbox',
       author_email='guido@dropbox.com',
       url='https://github.com/dropbox/pyannotate',

<|original_code|>
#!/usr/bin/env python

from setuptools import setup

setup(name='pyannotate',
      version='1.0.5',
      description="PyAnnotate: Auto-generate PEP-484 annotations",
      author='Dropbox',
      author_email='guido@dropbox.com',
      url='https://github.com/dropbox/pyannotate',
      license='Apache 2.0',
      platforms=['POSIX'],
      packages=['pyannotate_runtime', 'pyannotate_tools',
                'pyannotate_tools.annotations', 'pyannotate_tools.fixes'],
      entry_points={'console_scripts': ['pyannotate=pyannotate_tools.annotations.__main__:main']},
      classifiers=[
          'Development Status :: 3 - Alpha',
          'Environment :: Console',
          'Intended Audience :: Developers',
          'License :: OSI Approved :: Apache Software License',
          'Operating System :: POSIX',
          'Programming Language :: Python :: 2',
          'Programming Language :: Python :: 2.7',
          'Programming Language :: Python :: 3',
          'Programming Language :: Python :: 3.4',
          'Programming Language :: Python :: 3.5',
          'Programming Language :: Python :: 3.6',
          'Programming Language :: Python :: 3.7',
          'Topic :: Software Development',
          ],
      install_requires = ['six',
                          'mypy_extensions',
                          'typing >= 3.5.3; python_version < "3.5"'
                          ],
      )

<|edits_diff|>
--- setup.py
+++ setup.py
@@ -1,6 +1,12 @@
 #!/usr/bin/env python

+import os
 from setuptools import setup
+
+def get_long_description():
+    filename = os.path.join(os.path.dirname(__file__), 'README.md')
+    with open(filename) as f:
+        return f.read()

 setup(name='pyannotate',
       version='1.0.5',
<|current_version|>
#!/usr/bin/env python

import os
from setuptools import setup

def get_long_description():
    filename = os.path.join(os.path.dirname(__file__), 'README.md')
    with open(filename) as f:
        return f.read()

setup(name='pyannotate',
      version='1.0.5',
      description="PyAnnotate: Auto-generate PEP-484 annotations",
      author='Dropbox',
      author_email='guido@dropbox.com',
      url='https://github.com/dropbox/pyannotate',
      license='Apache 2.0',
      platforms=['POSIX'],
      packages=['pyannotate_runtime', 'pyannotate_tools',
                'pyannotate_tools.annotations', 'pyannotate_tools.fixes'],
      entry_points={'console_scripts': ['pyannotate=pyannotate_tools.annotations.__main__:main']},
      classifiers=[
          'Development Status :: 3 - Alpha',
          'Environment :: Console',
          'Intended Audience :: Developers',
          'License :: OSI Approved :: Apache Software License',
          'Operating System :: POSIX',
          'Programming Language :: Python :: 2',
          'Programming Language :: Python :: 2.7',
          'Programming Language :: Python :: 3',
          'Programming Language :: Python :: 3.4',
          'Programming Language :: Python :: 3.5',
          'Programming Language :: Python :: 3.6',
          'Programming Language :: Python :: 3.7',
          'Topic :: Software Development',
          ],
      install_requires = ['six',
                          'mypy_extensions',
                          'typing >= 3.5.3; python_version < "3.5"'
                          ],
      )

<|next_version|>
#!/usr/bin/env python

import os
from setuptools import setup

def get_long_description():
    filename = os.path.join(os.path.dirname(__file__), 'README.md')
    with open(filename) as f:
        return f.read()

setup(name='pyannotate',
      version='1.0.5',
      description="PyAnnotate: Auto-generate PEP-484 annotations",
      long_description=get_long_description(),
      author='Dropbox',
      author_email='guido@dropbox.com',
      url='https://github.com/dropbox/pyannotate',
      license='Apache 2.0',
      platforms=['POSIX'],
      packages=['pyannotate_runtime', 'pyannotate_tools',
                'pyannotate_tools.annotations', 'pyannotate_tools.fixes'],
      entry_points={'console_scripts': ['pyannotate=pyannotate_tools.annotations.__main__:main']},
      classifiers=[
          'Development Status :: 3 - Alpha',
          'Environment :: Console',
          'Intended Audience :: Developers',
          'License :: OSI Approved :: Apache Software License',
          'Operating System :: POSIX',
          'Programming Language :: Python :: 2',
          'Programming Language :: Python :: 2.7',
          'Programming Language :: Python :: 3',
          'Programming Language :: Python :: 3.4',
          'Programming Language :: Python :: 3.5',
          'Programming Language :: Python :: 3.6',
          'Programming Language :: Python :: 3.7',
          'Topic :: Software Development',
          ],
      install_requires = ['six',
                          'mypy_extensions',
                          'typing >= 3.5.3; python_version < "3.5"'
                          ],
      )


Change frontpage keyword to "-reddit.com".

--- reddit_adzerk/adzerkads.py
+++ reddit_adzerk/adzerkads.py
@@ -3,6 +3,7 @@
 from pylons import c, g

 from r2.lib.pages import Ads as BaseAds
+from r2.models.subreddit import DefaultSR

 class Ads(BaseAds):
@@ -11,6 +12,11 @@

         url_key = "adzerk_https_url" if c.secure else "adzerk_url"
         site_name = getattr(c.site, "analytics_name", c.site.name)
+
+        # adzerk reporting is easier when not using a space in the tag
+        if isinstance(c.site, DefaultSR):
+            site_name = "-reddit.com"
+
         self.ad_url = g.config[url_key].format(
             subreddit=quote(site_name.lower()),
             origin=c.request_origin,

<|original_code|>
from urllib import quote

from pylons import c, g

from r2.lib.pages import Ads as BaseAds

class Ads(BaseAds):
    def __init__(self):
        BaseAds.__init__(self)

        url_key = "adzerk_https_url" if c.secure else "adzerk_url"
        site_name = getattr(c.site, "analytics_name", c.site.name)
        self.ad_url = g.config[url_key].format(
            subreddit=quote(site_name.lower()),
            origin=c.request_origin,
        )
        self.frame_id = "ad_main"

<|edits_diff|>
--- reddit_adzerk/adzerkads.py
+++ reddit_adzerk/adzerkads.py
@@ -3,6 +3,7 @@
 from pylons import c, g

 from r2.lib.pages import Ads as BaseAds
+from r2.models.subreddit import DefaultSR

 class Ads(BaseAds):
<|current_version|>
from urllib import quote

from pylons import c, g

from r2.lib.pages import Ads as BaseAds
from r2.models.subreddit import DefaultSR

class Ads(BaseAds):
    def __init__(self):
        BaseAds.__init__(self)

        url_key = "adzerk_https_url" if c.secure else "adzerk_url"
        site_name = getattr(c.site, "analytics_name", c.site.name)
        self.ad_url = g.config[url_key].format(
            subreddit=quote(site_name.lower()),
            origin=c.request_origin,
        )
        self.frame_id = "ad_main"

<|next_version|>
from urllib import quote

from pylons import c, g

from r2.lib.pages import Ads as BaseAds
from r2.models.subreddit import DefaultSR

class Ads(BaseAds):
    def __init__(self):
        BaseAds.__init__(self)

        url_key = "adzerk_https_url" if c.secure else "adzerk_url"
        site_name = getattr(c.site, "analytics_name", c.site.name)

        # adzerk reporting is easier when not using a space in the tag
        if isinstance(c.site, DefaultSR):
            site_name = "-reddit.com"

        self.ad_url = g.config[url_key].format(
            subreddit=quote(site_name.lower()),
            origin=c.request_origin,
        )
        self.frame_id = "ad_main"


Add plot handling to test

Add plot handling to test

--- test_octave_kernel.py
+++ test_octave_kernel.py
@@ -11,6 +11,11 @@

     code_hello_world = "disp('hello, world')"

+    code_display_data = [
+        {'code': '%plot -f png\nplot([1,2,3])', 'mime': 'image/png'},
+        {'code': '%plot -f svg\nplot([1,2,3])', 'mime': 'image/svg+xml'}
+    ]
+
     completion_samples = [
         {
             'text': 'one',
@@ -20,5 +25,6 @@

     code_page_something = "ones?"

+
 if __name__ == '__main__':
     unittest.main()

<|original_code|>
"""Example use of jupyter_kernel_test, with tests for IPython."""

import unittest
import jupyter_kernel_test as jkt

class OctaveKernelTests(jkt.KernelTests):
    kernel_name = "octave"

    language_name = "octave"

    code_hello_world = "disp('hello, world')"

    completion_samples = [
        {
            'text': 'one',
            'matches': {'ones', 'onenormest'},
        },
    ]

    code_page_something = "ones?"

if __name__ == '__main__':
    unittest.main()

<|edits_diff|>
--- test_octave_kernel.py
+++ test_octave_kernel.py
@@ -11,6 +11,11 @@

     code_hello_world = "disp('hello, world')"

+    code_display_data = [
+        {'code': '%plot -f png\nplot([1,2,3])', 'mime': 'image/png'},
+        {'code': '%plot -f svg\nplot([1,2,3])', 'mime': 'image/svg+xml'}
+    ]
+
     completion_samples = [
         {
             'text': 'one',
<|current_version|>
"""Example use of jupyter_kernel_test, with tests for IPython."""

import unittest
import jupyter_kernel_test as jkt

class OctaveKernelTests(jkt.KernelTests):
    kernel_name = "octave"

    language_name = "octave"

    code_hello_world = "disp('hello, world')"

    code_display_data = [
        {'code': '%plot -f png\nplot([1,2,3])', 'mime': 'image/png'},
        {'code': '%plot -f svg\nplot([1,2,3])', 'mime': 'image/svg+xml'}
    ]

    completion_samples = [
        {
            'text': 'one',
            'matches': {'ones', 'onenormest'},
        },
    ]

    code_page_something = "ones?"

if __name__ == '__main__':
    unittest.main()

<|next_version|>
"""Example use of jupyter_kernel_test, with tests for IPython."""

import unittest
import jupyter_kernel_test as jkt

class OctaveKernelTests(jkt.KernelTests):
    kernel_name = "octave"

    language_name = "octave"

    code_hello_world = "disp('hello, world')"

    code_display_data = [
        {'code': '%plot -f png\nplot([1,2,3])', 'mime': 'image/png'},
        {'code': '%plot -f svg\nplot([1,2,3])', 'mime': 'image/svg+xml'}
    ]

    completion_samples = [
        {
            'text': 'one',
            'matches': {'ones', 'onenormest'},
        },
    ]

    code_page_something = "ones?"

if __name__ == '__main__':
    unittest.main()


Add missing env variables for testing.

Add missing env variables for testing.

--- manage.py
+++ manage.py
@@ -8,7 +8,9 @@
     if 'test' in sys.argv:
         # For now, fake setting the environment for testing.
         os.environ['DJANGO_SETTINGS_MODULE'] = 'conductor.settings.test'
+        os.environ['CORS_ORIGIN_WHITELIST'] = 'localhost:4200'
         os.environ['SECRET_KEY'] = 'asecrettoeverybody'
+        os.environ['STATIC_URL'] = '/static/'

     from django.core.management import execute_from_command_line

<|original_code|>
#!/usr/bin/env python
import os
import sys

if __name__ == '__main__':
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'conductor.settings.development')

    if 'test' in sys.argv:
        # For now, fake setting the environment for testing.
        os.environ['DJANGO_SETTINGS_MODULE'] = 'conductor.settings.test'
        os.environ['SECRET_KEY'] = 'asecrettoeverybody'

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)

<|edits_diff|>
--- manage.py
+++ manage.py
@@ -8,6 +8,7 @@
     if 'test' in sys.argv:
         # For now, fake setting the environment for testing.
         os.environ['DJANGO_SETTINGS_MODULE'] = 'conductor.settings.test'
+        os.environ['CORS_ORIGIN_WHITELIST'] = 'localhost:4200'
         os.environ['SECRET_KEY'] = 'asecrettoeverybody'

     from django.core.management import execute_from_command_line
<|current_version|>
#!/usr/bin/env python
import os
import sys

if __name__ == '__main__':
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'conductor.settings.development')

    if 'test' in sys.argv:
        # For now, fake setting the environment for testing.
        os.environ['DJANGO_SETTINGS_MODULE'] = 'conductor.settings.test'
        os.environ['CORS_ORIGIN_WHITELIST'] = 'localhost:4200'
        os.environ['SECRET_KEY'] = 'asecrettoeverybody'

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)

<|next_version|>
#!/usr/bin/env python
import os
import sys

if __name__ == '__main__':
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'conductor.settings.development')

    if 'test' in sys.argv:
        # For now, fake setting the environment for testing.
        os.environ['DJANGO_SETTINGS_MODULE'] = 'conductor.settings.test'
        os.environ['CORS_ORIGIN_WHITELIST'] = 'localhost:4200'
        os.environ['SECRET_KEY'] = 'asecrettoeverybody'
        os.environ['STATIC_URL'] = '/static/'

    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)


Fix some test breakages with Hypothesis.

--- test/conftest.py
+++ test/conftest.py
@@ -4,8 +4,13 @@
 import json
 import sys

+from hypothesis.strategies import text
+
 if sys.version_info[0] == 2:
     from codecs import open
+
+# We need to grab one text example from hypothesis to prime its cache.
+text().example()

 # This pair of generator expressions are pretty lame, but building lists is a
 # bad idea as I plan to have a substantial number of tests here.

<|original_code|>
# -*- coding: utf-8 -*-
import pytest
import os
import json
import sys

if sys.version_info[0] == 2:
    from codecs import open

# This pair of generator expressions are pretty lame, but building lists is a
# bad idea as I plan to have a substantial number of tests here.
story_directories = (
    os.path.join('test/test_fixtures', d) for d in os.listdir('test/test_fixtures')
)
story_files = (
    os.path.join(storydir, name) for storydir in story_directories
                                 for name in os.listdir(storydir)
                                 if 'raw-data' not in storydir
)
raw_story_files = (
    os.path.join('test/test_fixtures/raw-data', name)
    for name in os.listdir('test/test_fixtures/raw-data')
)

@pytest.fixture(scope='class', params=story_files)
def story(request):
    """
    Provides a detailed HPACK story to test with.
    """
    with open(request.param, 'r', encoding='utf-8') as f:
        return json.load(f)

@pytest.fixture(scope='class', params=raw_story_files)
def raw_story(request):
    """
    Provides a detailed HPACK story to test the encoder with.
    """
    with open(request.param, 'r', encoding='utf-8') as f:
        return json.load(f)

<|edits_diff|>
--- test/conftest.py
+++ test/conftest.py
@@ -3,6 +3,8 @@
 import os
 import json
 import sys
+
+from hypothesis.strategies import text

 if sys.version_info[0] == 2:
     from codecs import open
<|current_version|>
# -*- coding: utf-8 -*-
import pytest
import os
import json
import sys

from hypothesis.strategies import text

if sys.version_info[0] == 2:
    from codecs import open

# This pair of generator expressions are pretty lame, but building lists is a
# bad idea as I plan to have a substantial number of tests here.
story_directories = (
    os.path.join('test/test_fixtures', d) for d in os.listdir('test/test_fixtures')
)
story_files = (
    os.path.join(storydir, name) for storydir in story_directories
                                 for name in os.listdir(storydir)
                                 if 'raw-data' not in storydir
)
raw_story_files = (
    os.path.join('test/test_fixtures/raw-data', name)
    for name in os.listdir('test/test_fixtures/raw-data')
)

@pytest.fixture(scope='class', params=story_files)
def story(request):
    """
    Provides a detailed HPACK story to test with.
    """
    with open(request.param, 'r', encoding='utf-8') as f:
        return json.load(f)

@pytest.fixture(scope='class', params=raw_story_files)
def raw_story(request):
    """
    Provides a detailed HPACK story to test the encoder with.
    """
    with open(request.param, 'r', encoding='utf-8') as f:
        return json.load(f)

<|next_version|>
# -*- coding: utf-8 -*-
import pytest
import os
import json
import sys

from hypothesis.strategies import text

if sys.version_info[0] == 2:
    from codecs import open

# We need to grab one text example from hypothesis to prime its cache.
text().example()

# This pair of generator expressions are pretty lame, but building lists is a
# bad idea as I plan to have a substantial number of tests here.
story_directories = (
    os.path.join('test/test_fixtures', d) for d in os.listdir('test/test_fixtures')
)
story_files = (
    os.path.join(storydir, name) for storydir in story_directories
                                 for name in os.listdir(storydir)
                                 if 'raw-data' not in storydir
)
raw_story_files = (
    os.path.join('test/test_fixtures/raw-data', name)
    for name in os.listdir('test/test_fixtures/raw-data')
)

@pytest.fixture(scope='class', params=story_files)
def story(request):
    """
    Provides a detailed HPACK story to test with.
    """
    with open(request.param, 'r', encoding='utf-8') as f:
        return json.load(f)

@pytest.fixture(scope='class', params=raw_story_files)
def raw_story(request):
    """
    Provides a detailed HPACK story to test the encoder with.
    """
    with open(request.param, 'r', encoding='utf-8') as f:
        return json.load(f)


Fix Django Debug Toolbar installation for new DjDT version

--- {{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/urls.py
+++ {{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/urls.py
@@ -12,7 +12,9 @@

 # This is only needed when using runserver.
 if settings.DEBUG:
+    import debug_toolbar
     urlpatterns = [
         url(r'^media/(?P<path>.*)$', django.views.static.serve,
             {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
+        url(r'^__debug__/', include(debug_toolbar.urls)),
     ] + staticfiles_urlpatterns() + urlpatterns

<|original_code|>
from django.conf.urls import *  # NOQA
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from django.conf import settings
import django.views.static

admin.autodiscover()

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
]

# This is only needed when using runserver.
if settings.DEBUG:
    urlpatterns = [
        url(r'^media/(?P<path>.*)$', django.views.static.serve,
            {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
    ] + staticfiles_urlpatterns() + urlpatterns

<|edits_diff|>
--- {{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/urls.py
+++ {{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/urls.py
@@ -12,6 +12,7 @@

 # This is only needed when using runserver.
 if settings.DEBUG:
+    import debug_toolbar
     urlpatterns = [
         url(r'^media/(?P<path>.*)$', django.views.static.serve,
             {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
<|current_version|>
from django.conf.urls import *  # NOQA
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from django.conf import settings
import django.views.static

admin.autodiscover()

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
]

# This is only needed when using runserver.
if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
        url(r'^media/(?P<path>.*)$', django.views.static.serve,
            {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
    ] + staticfiles_urlpatterns() + urlpatterns

<|next_version|>
from django.conf.urls import *  # NOQA
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.contrib import admin
from django.conf import settings
import django.views.static

admin.autodiscover()

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
]

# This is only needed when using runserver.
if settings.DEBUG:
    import debug_toolbar
    urlpatterns = [
        url(r'^media/(?P<path>.*)$', django.views.static.serve,
            {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
        url(r'^__debug__/', include(debug_toolbar.urls)),
    ] + staticfiles_urlpatterns() + urlpatterns


Make this test a bit harder.

Make this test a bit harder.

--- tests/test_flask_get.py
+++ tests/test_flask_get.py
@@ -1,3 +1,4 @@
+import json
 import unittest

 from flask import Flask
@@ -32,3 +33,6 @@

         response = self.client.get('/docs')
         self.assertEqual(response.status_code, 200)
+
+        data = json.loads(response.data)
+        self.assertIn('endpoints', data)

<|original_code|>
import unittest

from flask import Flask
from flask.ext.autodoc import Autodoc

class TestAutodocWithFlask(unittest.TestCase):
    def setUp(self):
        self.app = Flask(__name__)
        self.autodoc = Autodoc(self.app)

        @self.app.route('/')
        @self.autodoc.doc()
        def index():
            """Returns a hello world message"""
            return 'Hello World!'

        self.client = self.app.test_client()

    def test_html(self):
        @self.app.route('/docs')
        def html_docs():
            return self.autodoc.html()

        response = self.client.get('/docs')
        self.assertEqual(response.status_code, 200)

    def test_json(self):
        @self.app.route('/docs')
        def json_docs():
            return self.autodoc.json()

        response = self.client.get('/docs')
        self.assertEqual(response.status_code, 200)

<|edits_diff|>
--- tests/test_flask_get.py
+++ tests/test_flask_get.py
@@ -1,3 +1,4 @@
+import json
 import unittest

 from flask import Flask
<|current_version|>
import json
import unittest

from flask import Flask
from flask.ext.autodoc import Autodoc

class TestAutodocWithFlask(unittest.TestCase):
    def setUp(self):
        self.app = Flask(__name__)
        self.autodoc = Autodoc(self.app)

        @self.app.route('/')
        @self.autodoc.doc()
        def index():
            """Returns a hello world message"""
            return 'Hello World!'

        self.client = self.app.test_client()

    def test_html(self):
        @self.app.route('/docs')
        def html_docs():
            return self.autodoc.html()

        response = self.client.get('/docs')
        self.assertEqual(response.status_code, 200)

    def test_json(self):
        @self.app.route('/docs')
        def json_docs():
            return self.autodoc.json()

        response = self.client.get('/docs')
        self.assertEqual(response.status_code, 200)

<|next_version|>
import json
import unittest

from flask import Flask
from flask.ext.autodoc import Autodoc

class TestAutodocWithFlask(unittest.TestCase):
    def setUp(self):
        self.app = Flask(__name__)
        self.autodoc = Autodoc(self.app)

        @self.app.route('/')
        @self.autodoc.doc()
        def index():
            """Returns a hello world message"""
            return 'Hello World!'

        self.client = self.app.test_client()

    def test_html(self):
        @self.app.route('/docs')
        def html_docs():
            return self.autodoc.html()

        response = self.client.get('/docs')
        self.assertEqual(response.status_code, 200)

    def test_json(self):
        @self.app.route('/docs')
        def json_docs():
            return self.autodoc.json()

        response = self.client.get('/docs')
        self.assertEqual(response.status_code, 200)

        data = json.loads(response.data)
        self.assertIn('endpoints', data)


Set up the app registry when running tests on django 1.7

(cherry picked from commit 7b3c994758254f16e8f47bf0f13b363d98082f20)
Signed-off-by: Antoine Catton <4589f2e060cef08c47d868a06754605a848a1006@fusionbox.com>

--- testproject/__init__.py
+++ testproject/__init__.py
@@ -3,10 +3,14 @@
 import sys
 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.testproject.settings")

+import django
 from django.test.utils import get_runner
 from django.conf import settings

 def runtests():
+    if hasattr(django, 'setup'):
+        # django >= 1.7
+        django.setup()
     # Stolen from django/core/management/commands/test.py
     TestRunner = get_runner(settings)
     test_runner = TestRunner(verbosity=1, interactive=True)

<|original_code|>
#!/usr/bin/env python
import os
import sys
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.testproject.settings")

from django.test.utils import get_runner
from django.conf import settings

def runtests():
    # Stolen from django/core/management/commands/test.py
    TestRunner = get_runner(settings)
    test_runner = TestRunner(verbosity=1, interactive=True)
    failures = test_runner.run_tests(['argonauts'])
    sys.exit(bool(failures))

<|edits_diff|>
--- testproject/__init__.py
+++ testproject/__init__.py
@@ -3,6 +3,7 @@
 import sys
 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.testproject.settings")

+import django
 from django.test.utils import get_runner
 from django.conf import settings

<|current_version|>
#!/usr/bin/env python
import os
import sys
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.testproject.settings")

import django
from django.test.utils import get_runner
from django.conf import settings

def runtests():
    # Stolen from django/core/management/commands/test.py
    TestRunner = get_runner(settings)
    test_runner = TestRunner(verbosity=1, interactive=True)
    failures = test_runner.run_tests(['argonauts'])
    sys.exit(bool(failures))

<|next_version|>
#!/usr/bin/env python
import os
import sys
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.testproject.settings")

import django
from django.test.utils import get_runner
from django.conf import settings

def runtests():
    if hasattr(django, 'setup'):
        # django >= 1.7
        django.setup()
    # Stolen from django/core/management/commands/test.py
    TestRunner = get_runner(settings)
    test_runner = TestRunner(verbosity=1, interactive=True)
    failures = test_runner.run_tests(['argonauts'])
    sys.exit(bool(failures))


Set the exit code when running tests correctly

--- manage.py
+++ manage.py
@@ -1,5 +1,6 @@
 #!/usr/bin/env python
 import os
+import sys
 import unittest
 from flask.ext.script import Manager, Server
 from app import app
@@ -19,6 +20,8 @@
     test_dir = os.path.join(parent_dir, 'tests')
     tests = unittest.TestLoader().discover(test_dir)
     results = unittest.TextTestRunner(verbosity=2).run(tests)
+    ret = not results.wasSuccessful()
+    sys.exit(ret)

 if __name__ == '__main__':

<|original_code|>
#!/usr/bin/env python
import os
import unittest
from flask.ext.script import Manager, Server
from app import app

manager = Manager(app)

server = Server(host='0.0.0.0', use_debugger=True)
manager.add_command("runserver", server)

@manager.command
def test():
    """Runs all the tests"""
    parent_dir = os.path.dirname(os.path.abspath(__file__))
    test_dir = os.path.join(parent_dir, 'tests')
    tests = unittest.TestLoader().discover(test_dir)
    results = unittest.TextTestRunner(verbosity=2).run(tests)

if __name__ == '__main__':
    manager.run()

<|edits_diff|>
--- manage.py
+++ manage.py
@@ -1,5 +1,6 @@
 #!/usr/bin/env python
 import os
+import sys
 import unittest
 from flask.ext.script import Manager, Server
 from app import app
<|current_version|>
#!/usr/bin/env python
import os
import sys
import unittest
from flask.ext.script import Manager, Server
from app import app

manager = Manager(app)

server = Server(host='0.0.0.0', use_debugger=True)
manager.add_command("runserver", server)

@manager.command
def test():
    """Runs all the tests"""
    parent_dir = os.path.dirname(os.path.abspath(__file__))
    test_dir = os.path.join(parent_dir, 'tests')
    tests = unittest.TestLoader().discover(test_dir)
    results = unittest.TextTestRunner(verbosity=2).run(tests)

if __name__ == '__main__':
    manager.run()

<|next_version|>
#!/usr/bin/env python
import os
import sys
import unittest
from flask.ext.script import Manager, Server
from app import app

manager = Manager(app)

server = Server(host='0.0.0.0', use_debugger=True)
manager.add_command("runserver", server)

@manager.command
def test():
    """Runs all the tests"""
    parent_dir = os.path.dirname(os.path.abspath(__file__))
    test_dir = os.path.join(parent_dir, 'tests')
    tests = unittest.TestLoader().discover(test_dir)
    results = unittest.TextTestRunner(verbosity=2).run(tests)
    ret = not results.wasSuccessful()
    sys.exit(ret)

if __name__ == '__main__':
    manager.run()


TST: Remove doct from the equation in attrs tests.

--- databroker/tests/test_core.py
+++ databroker/tests/test_core.py
@@ -1,9 +1,12 @@
 from __future__ import absolute_import, division, print_function
+import copy

 from databroker.core import Header

 def test_header_dict_conformance(db):
+    db.prepare_hook = lambda name, doc: copy.deepcopy(doc)
+
     # TODO update this if / when we add conformance testing to
     # validate attrs in Header
     target = {'start': {'uid': 'start'},

<|original_code|>
from __future__ import absolute_import, division, print_function

from databroker.core import Header

def test_header_dict_conformance(db):
    # TODO update this if / when we add conformance testing to
    # validate attrs in Header
    target = {'start': {'uid': 'start'},
              'stop': {'uid': 'stop', 'start_uid': 'start'}}

    h = Header(db, **target)
    # hack the descriptor lookup/cache mechanism
    target['descriptors'] = [{'uid': 'desc', 'start_uid': 'start'}]
    h._cache['desc'] = [{'uid': 'desc', 'start_uid': 'start'}]

    assert len(h) == len(target)
    assert set(h) == set(target)
    assert set(h.keys()) == set(target.keys())

    for k, v in h.items():
        assert v == target[k]
        assert v == h[k]

    # this is a dumb test
    assert len(list(h.values())) == len(h)

    n, d = h.to_name_dict_pair()
    assert n == 'header'
    assert d == target

<|edits_diff|>
--- databroker/tests/test_core.py
+++ databroker/tests/test_core.py
@@ -1,4 +1,5 @@
 from __future__ import absolute_import, division, print_function
+import copy

 from databroker.core import Header

<|current_version|>
from __future__ import absolute_import, division, print_function
import copy

from databroker.core import Header

def test_header_dict_conformance(db):
    # TODO update this if / when we add conformance testing to
    # validate attrs in Header
    target = {'start': {'uid': 'start'},
              'stop': {'uid': 'stop', 'start_uid': 'start'}}

    h = Header(db, **target)
    # hack the descriptor lookup/cache mechanism
    target['descriptors'] = [{'uid': 'desc', 'start_uid': 'start'}]
    h._cache['desc'] = [{'uid': 'desc', 'start_uid': 'start'}]

    assert len(h) == len(target)
    assert set(h) == set(target)
    assert set(h.keys()) == set(target.keys())

    for k, v in h.items():
        assert v == target[k]
        assert v == h[k]

    # this is a dumb test
    assert len(list(h.values())) == len(h)

    n, d = h.to_name_dict_pair()
    assert n == 'header'
    assert d == target

<|next_version|>
from __future__ import absolute_import, division, print_function
import copy

from databroker.core import Header

def test_header_dict_conformance(db):
    db.prepare_hook = lambda name, doc: copy.deepcopy(doc)

    # TODO update this if / when we add conformance testing to
    # validate attrs in Header
    target = {'start': {'uid': 'start'},
              'stop': {'uid': 'stop', 'start_uid': 'start'}}

    h = Header(db, **target)
    # hack the descriptor lookup/cache mechanism
    target['descriptors'] = [{'uid': 'desc', 'start_uid': 'start'}]
    h._cache['desc'] = [{'uid': 'desc', 'start_uid': 'start'}]

    assert len(h) == len(target)
    assert set(h) == set(target)
    assert set(h.keys()) == set(target.keys())

    for k, v in h.items():
        assert v == target[k]
        assert v == h[k]

    # this is a dumb test
    assert len(list(h.values())) == len(h)

    n, d = h.to_name_dict_pair()
    assert n == 'header'
    assert d == target