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

from datetime import datetime
from collections import namedtuple

from bson.errors import InvalidId
from bson.objectid import ObjectId

from marshmallow import (
        Schema, fields, validates, ValidationError
)
from flask_restful import Resource

from flask import current_app, request, session

from model import (
        get_article, vote_article,
        get_begin_day, get_before_day, get_after_day,
        get_entries_by_day,
        get_entries_next, get_entries_pre, get_entries_by_spider,
        get_spiders,
)

Spider = namedtuple('Spider', ['id', 'source'])

class ObjectIdField(fields.Field):

    def _serialize(self, value, attr, obj, **kwargs):
        return str(value)

    def _deserialize(self, value, attr, data, **kwargs):
        try:
            return ObjectId(value)
        except InvalidId:
            raise ValidationError(f'invalid ObjectId {value}')

class Vote(Resource):

    def post(self):

        class VoteRequestSchema(Schema):
            aid = ObjectIdField(required=True)

            def __init__(self, strict=True, **kwargs):
                super().__init__(strict=strict, **kwargs)

        if 'uid' not in session:
            return {'message': 'no uid'}, 401

        schema = VoteRequestSchema()
        try:
            vote_request = schema.load(request.get_json()).data
        except ValidationError as err:
            return {'message': err.messages}, 400
        except Exception:
            return {'message': 'invalid request'}, 400

        aid = vote_request['aid']
        a = get_article(aid)

        if not a:
            return {'message': 'article not existed'}, 400

        vote_article(a)
        return {'aid': str(aid)}, 200

class Day(Resource):

    def get(self):

        class DayRequestSchema(Schema):
            day = fields.Date(required=True)

            def __init__(self, strict=True, **kwargs):
                super().__init__(strict=strict, **kwargs)

            @validates('day')
            def validate_day(self, day):
                day_begin = get_begin_day()
                if not day_begin <= day <= datetime.utcnow().date():
                    raise ValidationError('invalid day value')

        schema = DayRequestSchema()
        try:
            day_request = schema.load(request.args).data
        except ValidationError as err:
            return {'message': err.messages}, 400
        except Exception:
            return {'message': 'invalid request'}, 400

        day_entry = day_request['day']
        day_before = get_before_day(day_entry)
        if day_before is not None:
            day_before = day_before.strftime('%Y-%m-%d')
        day_after = get_after_day(day_entry)
        if day_after is not None:
            day_after = day_after.strftime('%Y-%m-%d')
        entries = get_entries_by_day(day_entry)
        return {
                'day_before': day_before,
                'day_after': day_after,
                'data': entries,
        }

class Categories(Resource):

    def get(self):
        return {'data': list(current_app.config['ARTICLE_CATEGORIES'])}

class Spiders(Resource):

    def get(self):
        spiders = get_spiders()
        entries = [
            Spider(spid, name)
            for spid, name in spiders.items()
        ]
        return {'entries': entries}

class Entries(Resource):

    def get(self):

        class EntryRequestScheme(Schema):
            spid = ObjectIdField(required=True)
            aid = ObjectIdField()
            q = fields.String()

            def __init__(self, strict=True, **kwargs):
                super().__init__(strict=strict, **kwargs)

            @validates('q')
            def validate_q(self, q):
                if q not in ('p', 'n'):
                    raise ValidationError('invalid q value')

        schema = EntryRequestScheme()
        try:
            entry_request = schema.load(request.args).data
        except ValidationError as err:
            return {'message': err.messages}, 400
        except Exception:
            return {'message': 'invalid request argument'}, 400

        spid = entry_request.get('spid')
        aid = entry_request.get('aid', None)
        q = entry_request.get('q', 'n')
        if aid is None:
            entries = get_entries_by_spider(spid)
        elif q == 'p':
            entries = get_entries_pre(spid, aid)
        elif q == 'n':
            entries = get_entries_next(spid, aid)

        if not entries:
            return {'message': 'no articles found'}, 400

        spid = str(spid)
        spiders = get_spiders()
        return {'spider': Spider(spid, spiders[spid]), 'entries': entries}
<commit_msg>format<commit_after># -*- coding: utf-8 -*-

from datetime import datetime
from collections import namedtuple

from bson.errors import InvalidId
from bson.objectid import ObjectId

from marshmallow import (
        Schema, fields, validates, ValidationError
)
from flask_restful import Resource

from flask import current_app, request, session

from model import (
        get_article, vote_article,
        get_begin_day, get_before_day, get_after_day,
        get_entries_by_day,
        get_entries_next, get_entries_pre, get_entries_by_spider,
        get_spiders,
)

Spider = namedtuple('Spider', ['id', 'source'])

class ObjectIdField(fields.Field):

    def _serialize(self, value, attr, obj, **kwargs):
        return str(value)

    def _deserialize(self, value, attr, data, **kwargs):
        try:
            return ObjectId(value)
        except InvalidId:
            raise ValidationError(f'invalid ObjectId {value}')

class Day(Resource):

    def get(self):

        class DayRequestSchema(Schema):
            day = fields.Date(required=True)

            def __init__(self, strict=True, **kwargs):
                super().__init__(strict=strict, **kwargs)

            @validates('day')
            def validate_day(self, day):
                day_begin = get_begin_day()
                if not day_begin <= day <= datetime.utcnow().date():
                    raise ValidationError('invalid day value')

        schema = DayRequestSchema()
        try:
            day_request = schema.load(request.args).data
        except ValidationError as err:
            return {'message': err.messages}, 400
        except Exception:
            return {'message': 'invalid request'}, 400

        day_entry = day_request['day']
        day_before = get_before_day(day_entry)
        if day_before is not None:
            day_before = day_before.strftime('%Y-%m-%d')
        day_after = get_after_day(day_entry)
        if day_after is not None:
            day_after = day_after.strftime('%Y-%m-%d')
        entries = get_entries_by_day(day_entry)
        return {
                'day_before': day_before,
                'day_after': day_after,
                'data': entries,
        }

class Categories(Resource):

    def get(self):
        return {'data': list(current_app.config['ARTICLE_CATEGORIES'])}

class Spiders(Resource):

    def get(self):
        spiders = get_spiders()
        entries = [
            Spider(spid, name)
            for spid, name in spiders.items()
        ]
        return {'entries': entries}

class Entries(Resource):

    def get(self):

        class EntryRequestScheme(Schema):
            spid = ObjectIdField(required=True)
            aid = ObjectIdField()
            q = fields.String()

            def __init__(self, strict=True, **kwargs):
                super().__init__(strict=strict, **kwargs)

            @validates('q')
            def validate_q(self, q):
                if q not in ('p', 'n'):
                    raise ValidationError('invalid q value')

        schema = EntryRequestScheme()
        try:
            entry_request = schema.load(request.args).data
        except ValidationError as err:
            return {'message': err.messages}, 400
        except Exception:
            return {'message': 'invalid request argument'}, 400

        spid = entry_request.get('spid')
        aid = entry_request.get('aid', None)
        q = entry_request.get('q', 'n')
        if aid is None:
            entries = get_entries_by_spider(spid)
        elif q == 'p':
            entries = get_entries_pre(spid, aid)
        elif q == 'n':
            entries = get_entries_next(spid, aid)

        if not entries:
            return {'message': 'no articles found'}, 400

        spid = str(spid)
        spiders = get_spiders()
        return {'spider': Spider(spid, spiders[spid]), 'entries': entries}

class Vote(Resource):

    def post(self):

        class VoteRequestSchema(Schema):
            aid = ObjectIdField(required=True)

            def __init__(self, strict=True, **kwargs):
                super().__init__(strict=strict, **kwargs)

        if 'uid' not in session:
            return {'message': 'no uid'}, 401

        schema = VoteRequestSchema()
        try:
            vote_request = schema.load(request.get_json()).data
        except ValidationError as err:
            return {'message': err.messages}, 400
        except Exception:
            return {'message': 'invalid request'}, 400

        aid = vote_request['aid']
        a = get_article(aid)

        if not a:
            return {'message': 'article not existed'}, 400

        vote_article(a)
        return {'aid': str(aid)}, 200
<|endoftext|>


<commit_before>"""
    Tests for the NURBS-Python package
    Released under The MIT License. See LICENSE file for details.
    Copyright (c) 2018 Onur Rauf Bingol

    Tests visualization modules. Requires "pytest" to run.
"""
import os
import pytest
from geomdl import BSpline, NURBS
from geomdl.visualization import VisMPL

SAMPLE_SIZE = 25

@pytest.fixture
def bspline_curve3d():
    """ Creates a B-Spline 3-dimensional curve instance """
    # Create a curve instance
    curve = BSpline.Curve()

    # Set curve degree
    curve.degree = 4

    # Set control points
    curve.ctrlpts = [[5.0, 15.0, 0.0], [10.0, 25.0, 5.0], [20.0, 20.0, 10.0], [15.0, -5.0, 15.0], [7.5, 10.0, 20.0],
                     [12.5, 15.0, 25.0], [15.0, 0.0, 30.0], [5.0, -10.0, 35.0], [10.0, 15.0, 40.0], [5.0, 15.0, 30.0]]

    # Set knot vector
    curve.knotvector = [0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.3, 0.5, 0.7, 0.9, 1.0, 1.0, 1.0, 1.0, 1.0]

    # Set sample size
    curve.sample_size = SAMPLE_SIZE

    # Return the instance
    return curve

@pytest.fixture
def bspline_surface():
    """ Creates a B-Spline surface instance """
    # Create a surface instance
    surf = BSpline.Surface()

    # Set degrees
    surf.degree_u = 3
    surf.degree_v = 3

    # Set control points
    surf.ctrlpts_size_u = 6
    surf.ctrlpts_size_v = 6
    surf.ctrlpts = [[-25.0, -25.0, -10.0], [-25.0, -15.0, -5.0], [-25.0, -5.0, 0.0], [-25.0, 5.0, 0.0],
                    [-25.0, 15.0, -5.0], [-25.0, 25.0, -10.0], [-15.0, -25.0, -8.0], [-15.0, -15.0, -4.0],
                    [-15.0, -5.0, -4.0], [-15.0, 5.0, -4.0], [-15.0, 15.0, -4.0], [-15.0, 25.0, -8.0],
                    [-5.0, -25.0, -5.0], [-5.0, -15.0, -3.0], [-5.0, -5.0, -8.0], [-5.0, 5.0, -8.0],
                    [-5.0, 15.0, -3.0], [-5.0, 25.0, -5.0], [5.0, -25.0, -3.0], [5.0, -15.0, -2.0],
                    [5.0, -5.0, -8.0], [5.0, 5.0, -8.0], [5.0, 15.0, -2.0], [5.0, 25.0, -3.0],
                    [15.0, -25.0, -8.0], [15.0, -15.0, -4.0], [15.0, -5.0, -4.0], [15.0, 5.0, -4.0],
                    [15.0, 15.0, -4.0], [15.0, 25.0, -8.0], [25.0, -25.0, -10.0], [25.0, -15.0, -5.0],
                    [25.0, -5.0, 2.0], [25.0, 5.0, 2.0], [25.0, 15.0, -5.0], [25.0, 25.0, -10.0]]

    # Set knot vectors
    surf.knotvector_u = [0.0, 0.0, 0.0, 0.0, 0.33, 0.66, 1.0, 1.0, 1.0, 1.0]
    surf.knotvector_v = [0.0, 0.0, 0.0, 0.0, 0.33, 0.66, 1.0, 1.0, 1.0, 1.0]

    # Set sample size
    surf.sample_size = SAMPLE_SIZE

    # Return the instance
    return surf

# Test if plotting a 3-dimensional curve without a window is possible
def test_curve3d_fig_nowindow(bspline_curve3d):
    conf = VisMPL.VisConfig()
    vis = VisMPL.VisCurve3D(config=conf)
    bspline_curve3d.vis = vis
    bspline_curve3d.render(plot=False)

    assert os.path.isfile(conf.figure_image_filename)
    assert os.path.getsize(conf.figure_image_filename) > 0

    # Clean up temporary file if exists
    if os.path.isfile(conf.figure_image_filename):
        os.remove(conf.figure_image_filename)

# Test if using a different file name is possible
def test_curve3d_fig_save(bspline_curve3d):
    fname = "test-curve.png"
    conf = VisMPL.VisConfig()
    vis = VisMPL.VisCurve3D(config=conf)
    bspline_curve3d.vis = vis
    bspline_curve3d.render(filename=fname, plot=False)

    assert os.path.isfile(fname)
    assert os.path.getsize(fname) > 0

    # Clean up temporary file if exists
    if os.path.isfile(fname):
        os.remove(fname)

# Test if plotting a surface without a window is possible
def test_surf_fig_nowindow(bspline_surface):
    conf = VisMPL.VisConfig()
    vis = VisMPL.VisSurface(config=conf)
    bspline_surface.vis = vis
    bspline_surface.render(plot=False)

    assert os.path.isfile(conf.figure_image_filename)
    assert os.path.getsize(conf.figure_image_filename) > 0

    # Clean up temporary file if exists
    if os.path.isfile(conf.figure_image_filename):
        os.remove(conf.figure_image_filename)

# Test if using a different file name is possible
def test_surf_fig_save(bspline_surface):
    fname = "test-surface.png"
    conf = VisMPL.VisConfig()
    vis = VisMPL.VisSurface(config=conf)
    bspline_surface.vis = vis
    bspline_surface.render(filename=fname, plot=False)

    assert os.path.isfile(fname)
    assert os.path.getsize(fname) > 0

    # Clean up temporary file if exists
    if os.path.isfile(fname):
        os.remove(fname)
<commit_msg>Add multi-curve and multi-surface visualization tests<commit_after>"""
    Tests for the NURBS-Python package
    Released under The MIT License. See LICENSE file for details.
    Copyright (c) 2018 Onur Rauf Bingol

    Tests visualization modules. Requires "pytest" to run.
"""
import os
import pytest
from geomdl import BSpline, NURBS
from geomdl.visualization import VisMPL

SAMPLE_SIZE = 25

@pytest.fixture
def bspline_curve3d():
    """ Creates a B-Spline 3-dimensional curve instance """
    # Create a curve instance
    curve = BSpline.Curve()

    # Set curve degree
    curve.degree = 4

    # Set control points
    curve.ctrlpts = [[5.0, 15.0, 0.0], [10.0, 25.0, 5.0], [20.0, 20.0, 10.0], [15.0, -5.0, 15.0], [7.5, 10.0, 20.0],
                     [12.5, 15.0, 25.0], [15.0, 0.0, 30.0], [5.0, -10.0, 35.0], [10.0, 15.0, 40.0], [5.0, 15.0, 30.0]]

    # Set knot vector
    curve.knotvector = [0.0, 0.0, 0.0, 0.0, 0.0, 0.1, 0.3, 0.5, 0.7, 0.9, 1.0, 1.0, 1.0, 1.0, 1.0]

    # Set sample size
    curve.sample_size = SAMPLE_SIZE

    # Return the instance
    return curve

@pytest.fixture
def bspline_surface():
    """ Creates a B-Spline surface instance """
    # Create a surface instance
    surf = BSpline.Surface()

    # Set degrees
    surf.degree_u = 3
    surf.degree_v = 3

    # Set control points
    surf.ctrlpts_size_u = 6
    surf.ctrlpts_size_v = 6
    surf.ctrlpts = [[-25.0, -25.0, -10.0], [-25.0, -15.0, -5.0], [-25.0, -5.0, 0.0], [-25.0, 5.0, 0.0],
                    [-25.0, 15.0, -5.0], [-25.0, 25.0, -10.0], [-15.0, -25.0, -8.0], [-15.0, -15.0, -4.0],
                    [-15.0, -5.0, -4.0], [-15.0, 5.0, -4.0], [-15.0, 15.0, -4.0], [-15.0, 25.0, -8.0],
                    [-5.0, -25.0, -5.0], [-5.0, -15.0, -3.0], [-5.0, -5.0, -8.0], [-5.0, 5.0, -8.0],
                    [-5.0, 15.0, -3.0], [-5.0, 25.0, -5.0], [5.0, -25.0, -3.0], [5.0, -15.0, -2.0],
                    [5.0, -5.0, -8.0], [5.0, 5.0, -8.0], [5.0, 15.0, -2.0], [5.0, 25.0, -3.0],
                    [15.0, -25.0, -8.0], [15.0, -15.0, -4.0], [15.0, -5.0, -4.0], [15.0, 5.0, -4.0],
                    [15.0, 15.0, -4.0], [15.0, 25.0, -8.0], [25.0, -25.0, -10.0], [25.0, -15.0, -5.0],
                    [25.0, -5.0, 2.0], [25.0, 5.0, 2.0], [25.0, 15.0, -5.0], [25.0, 25.0, -10.0]]

    # Set knot vectors
    surf.knotvector_u = [0.0, 0.0, 0.0, 0.0, 0.33, 0.66, 1.0, 1.0, 1.0, 1.0]
    surf.knotvector_v = [0.0, 0.0, 0.0, 0.0, 0.33, 0.66, 1.0, 1.0, 1.0, 1.0]

    # Set sample size
    surf.sample_size = SAMPLE_SIZE

    # Return the instance
    return surf

# Test if plotting a 3-dimensional curve without a window is possible
def test_curve3d_fig_nowindow(bspline_curve3d):
    conf = VisMPL.VisConfig()
    vis = VisMPL.VisCurve3D(config=conf)
    bspline_curve3d.vis = vis
    bspline_curve3d.render(plot=False)

    assert os.path.isfile(conf.figure_image_filename)
    assert os.path.getsize(conf.figure_image_filename) > 0

    # Clean up temporary file if exists
    if os.path.isfile(conf.figure_image_filename):
        os.remove(conf.figure_image_filename)

# Test if using a different file name is possible
def test_curve3d_fig_save(bspline_curve3d):
    fname = "test-curve.png"
    conf = VisMPL.VisConfig()
    vis = VisMPL.VisCurve3D(config=conf)
    bspline_curve3d.vis = vis
    bspline_curve3d.render(filename=fname, plot=False)

    assert os.path.isfile(fname)
    assert os.path.getsize(fname) > 0

    # Clean up temporary file if exists
    if os.path.isfile(fname):
        os.remove(fname)

# Test if plotting a 3-dimensional multi-curve without a window is possible
def test_curve3d_multi_fig_nowindow(bspline_curve3d):
    multi = bspline_curve3d.decompose()
    conf = VisMPL.VisConfig()
    vis = VisMPL.VisCurve3D(config=conf)
    multi.vis = vis
    multi.render(plot=False)

    assert os.path.isfile(conf.figure_image_filename)
    assert os.path.getsize(conf.figure_image_filename) > 0

    # Clean up temporary file if exists
    if os.path.isfile(conf.figure_image_filename):
        os.remove(conf.figure_image_filename)

# Test if using a different file name is possible
def test_curve3d_multi_fig_save(bspline_curve3d):
    fname = "test-multi_curve.png"
    multi = bspline_curve3d.decompose()
    conf = VisMPL.VisConfig()
    vis = VisMPL.VisCurve3D(config=conf)
    multi.vis = vis
    multi.render(filename=fname, plot=False)

    assert os.path.isfile(fname)
    assert os.path.getsize(fname) > 0

    # Clean up temporary file if exists
    if os.path.isfile(fname):
        os.remove(fname)

# Test if plotting a surface without a window is possible
def test_surf_fig_nowindow(bspline_surface):
    conf = VisMPL.VisConfig()
    vis = VisMPL.VisSurface(config=conf)
    bspline_surface.vis = vis
    bspline_surface.render(plot=False)

    assert os.path.isfile(conf.figure_image_filename)
    assert os.path.getsize(conf.figure_image_filename) > 0

    # Clean up temporary file if exists
    if os.path.isfile(conf.figure_image_filename):
        os.remove(conf.figure_image_filename)

# Test if using a different file name is possible
def test_surf_fig_save(bspline_surface):
    fname = "test-surface.png"
    conf = VisMPL.VisConfig()
    vis = VisMPL.VisSurface(config=conf)
    bspline_surface.vis = vis
    bspline_surface.render(filename=fname, plot=False)

    assert os.path.isfile(fname)
    assert os.path.getsize(fname) > 0

    # Clean up temporary file if exists
    if os.path.isfile(fname):
        os.remove(fname)

# Test if plotting a multi-surface without a window is possible
def test_surf_multi_fig_nowindow(bspline_surface):
    multi = bspline_surface.decompose()
    conf = VisMPL.VisConfig()
    vis = VisMPL.VisSurface(config=conf)
    multi.vis = vis
    multi.render(plot=False)

    assert os.path.isfile(conf.figure_image_filename)
    assert os.path.getsize(conf.figure_image_filename) > 0

    # Clean up temporary file if exists
    if os.path.isfile(conf.figure_image_filename):
        os.remove(conf.figure_image_filename)

# Test if using a different file name is possible
def test_surf_multi_fig_save(bspline_surface):
    fname = "test-multi_surface.png"
    multi = bspline_surface.decompose()
    conf = VisMPL.VisConfig()
    vis = VisMPL.VisSurface(config=conf)
    multi.vis = vis
    multi.render(filename=fname, plot=False)

    assert os.path.isfile(fname)
    assert os.path.getsize(fname) > 0

    # Clean up temporary file if exists
    if os.path.isfile(fname):
        os.remove(fname)
<|endoftext|>


<commit_before><commit_msg>nova função para split<commit_after><|endoftext|>


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

"""Test PySlip map-relative images.

Usage: test_maprel_image.py [-h] [-t (OSM|GMT)]
"""

import wx

import pyslip

######
# Various constants
######

DefaultAppSize = (600, 400)

DefaultTileDirectory = 'tiles'
MinTileLevel = 0
InitViewLevel = 2
InitViewPosition = (158.0, -20.0)

arrow = 'graphics/arrow_right.png'

ImageMapData = [(158, -17, arrow, {'offset_x': 0, 'offset_y': 0}),
                (158, -18, arrow, {'offset_x': 0, 'offset_y': 0}),
                (158, -19, arrow, {'offset_x': 0, 'offset_y': 0}),
                (158, -20, arrow, {'offset_x': 0, 'offset_y': 0}),
                (158, -21, arrow, {'offset_x': 0, 'offset_y': 0}),
                (158, -22, arrow, {'offset_x': 0, 'offset_y': 0}),
                (158, -23, arrow, {'offset_x': 0, 'offset_y': 0})
               ]

PolygonMapData = [(((158,-17),(158,-23)),
                      {'width': 1, 'colour': 'black', 'filled': False})
                 ]

################################################################################
# The main application frame
################################################################################

class TestFrame(wx.Frame):
    def __init__(self, tile_dir=None):
        wx.Frame.__init__(self, None, size=DefaultAppSize,
                          title=('PySlip %s - map-relative image test'
                                 % pyslip.__version__))
        self.SetMinSize(DefaultAppSize)
        self.panel = wx.Panel(self, wx.ID_ANY)
        self.panel.SetBackgroundColour(wx.WHITE)
        self.panel.ClearBackground()

        # create the tile source object
        self.tile_src = Tiles(tile_dir)

        # build the GUI
        box = wx.BoxSizer(wx.HORIZONTAL)
        self.panel.SetSizer(box)
        self.pyslip = pyslip.PySlip(self.panel, tile_src=self.tile_src,
                                    min_level=MinTileLevel)
        box.Add(self.pyslip, proportion=1, border=1, flag=wx.EXPAND)
        self.panel.SetSizerAndFit(box)
        self.panel.Layout()
        self.Centre()
        self.Show(True)

        # set initial view position
        self.pyslip.GotoLevelAndPosition(InitViewLevel, InitViewPosition)

        # add test layers
        self.poly_layer = self.pyslip.AddPolygonLayer(PolygonMapData)
        self.image_layer = self.pyslip.AddImageLayer(ImageMapData,
                                                     map_rel=True,
                                                     placement='ce',
                                                     name='<image_map_layer>')

################################################################################

if __name__ == '__main__':
    import sys
    import getopt
    import traceback

    # print some usage information
    def usage(msg=None):
        if msg:
            print(msg+'\n')
        print(__doc__)        # module docstring used

    # our own handler for uncaught exceptions
    def excepthook(type, value, tb):
        msg = '\n' + '=' * 80
        msg += '\nUncaught exception:\n'
        msg += ''.join(traceback.format_exception(type, value, tb))
        msg += '=' * 80 + '\n'
        print msg
        sys.exit(1)
    sys.excepthook = excepthook

    # decide which tiles to use, default is GMT
    argv = sys.argv[1:]

    try:
        (opts, args) = getopt.getopt(argv, 'ht:', ['help', 'tiles='])
    except getopt.error:
        usage()
        sys.exit(1)

    tile_source = 'GMT'
    for (opt, param) in opts:
        if opt in ['-h', '--help']:
            usage()
            sys.exit(0)
        elif opt in ('-t', '--tiles'):
            tile_source = param
    tile_source = tile_source.lower()
    print('tile_source=%s' % str(tile_source))

    # set up the appropriate tile source
    if tile_source == 'gmt':
        from gmt_local_tiles import GMTTiles as Tiles
        print('Using GMT tiles')
        tile_dir = 'gmt_tiles'
    elif tile_source == 'osm':
        from osm_tiles import OSMTiles as Tiles
        print('Using OSM tiles')
        tile_dir = 'osm_tiles'
    else:
        usage('Bad tile source: %s' % tile_source)
        sys.exit(3)

    # start wxPython app
    app = wx.App()
    TestFrame(tile_dir=tile_dir).Show()
    app.MainLoop()

<commit_msg>Removed unwanted print statements<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Test PySlip map-relative images.

Usage: test_maprel_image.py [-h] [-t (OSM|GMT)]
"""

import wx

import pyslip

######
# Various constants
######

DefaultAppSize = (600, 400)

DefaultTileDirectory = 'tiles'
MinTileLevel = 0
InitViewLevel = 2
InitViewPosition = (158.0, -20.0)

arrow = 'graphics/arrow_right.png'

ImageMapData = [(158, -17, arrow, {'offset_x': 0, 'offset_y': 0}),
                (158, -18, arrow, {'offset_x': 0, 'offset_y': 0}),
                (158, -19, arrow, {'offset_x': 0, 'offset_y': 0}),
                (158, -20, arrow, {'offset_x': 0, 'offset_y': 0}),
                (158, -21, arrow, {'offset_x': 0, 'offset_y': 0}),
                (158, -22, arrow, {'offset_x': 0, 'offset_y': 0}),
                (158, -23, arrow, {'offset_x': 0, 'offset_y': 0})
               ]

PolygonMapData = [(((158,-17),(158,-23)),
                      {'width': 1, 'colour': 'black', 'filled': False})
                 ]

################################################################################
# The main application frame
################################################################################

class TestFrame(wx.Frame):
    def __init__(self, tile_dir=None):
        wx.Frame.__init__(self, None, size=DefaultAppSize,
                          title=('PySlip %s - map-relative image test'
                                 % pyslip.__version__))
        self.SetMinSize(DefaultAppSize)
        self.panel = wx.Panel(self, wx.ID_ANY)
        self.panel.SetBackgroundColour(wx.WHITE)
        self.panel.ClearBackground()

        # create the tile source object
        self.tile_src = Tiles(tile_dir)

        # build the GUI
        box = wx.BoxSizer(wx.HORIZONTAL)
        self.panel.SetSizer(box)
        self.pyslip = pyslip.PySlip(self.panel, tile_src=self.tile_src,
                                    min_level=MinTileLevel)
        box.Add(self.pyslip, proportion=1, border=1, flag=wx.EXPAND)
        self.panel.SetSizerAndFit(box)
        self.panel.Layout()
        self.Centre()
        self.Show(True)

        # set initial view position
        self.pyslip.GotoLevelAndPosition(InitViewLevel, InitViewPosition)

        # add test layers
        self.poly_layer = self.pyslip.AddPolygonLayer(PolygonMapData)
        self.image_layer = self.pyslip.AddImageLayer(ImageMapData,
                                                     map_rel=True,
                                                     placement='ce',
                                                     name='<image_map_layer>')

################################################################################

if __name__ == '__main__':
    import sys
    import getopt
    import traceback

    # print some usage information
    def usage(msg=None):
        if msg:
            print(msg+'\n')
        print(__doc__)        # module docstring used

    # our own handler for uncaught exceptions
    def excepthook(type, value, tb):
        msg = '\n' + '=' * 80
        msg += '\nUncaught exception:\n'
        msg += ''.join(traceback.format_exception(type, value, tb))
        msg += '=' * 80 + '\n'
        print msg
        sys.exit(1)
    sys.excepthook = excepthook

    # decide which tiles to use, default is GMT
    argv = sys.argv[1:]

    try:
        (opts, args) = getopt.getopt(argv, 'ht:', ['help', 'tiles='])
    except getopt.error:
        usage()
        sys.exit(1)

    tile_source = 'GMT'
    for (opt, param) in opts:
        if opt in ['-h', '--help']:
            usage()
            sys.exit(0)
        elif opt in ('-t', '--tiles'):
            tile_source = param
    tile_source = tile_source.lower()

    # set up the appropriate tile source
    if tile_source == 'gmt':
        from gmt_local_tiles import GMTTiles as Tiles
        tile_dir = 'gmt_tiles'
    elif tile_source == 'osm':
        from osm_tiles import OSMTiles as Tiles
        tile_dir = 'osm_tiles'
    else:
        usage('Bad tile source: %s' % tile_source)
        sys.exit(3)

    # start wxPython app
    app = wx.App()
    TestFrame(tile_dir=tile_dir).Show()
    app.MainLoop()

<|endoftext|>


<commit_before>import os

from django.core.management.commands.loaddata import Command
from django.db import connections, DEFAULT_DB_ALIAS
from django.db.backends.creation import TEST_DATABASE_PREFIX
from django.db.backends.mysql import creation as mysql

import django_nose

# Monkey-patch loaddata to ignore foreign key checks.
_old_handle = Command.handle
def _new_handle(self, *fixture_labels, **options):
    using = options.get('database', DEFAULT_DB_ALIAS)
    commit = options.get('commit', True)
    connection = connections[using]

    cursor = connection.cursor()
    cursor.execute('SET foreign_key_checks = 0')

    _old_handle(self, *fixture_labels, **options)

    cursor = connection.cursor()
    cursor.execute('SET foreign_key_checks = 1')

    if commit:
        connection.close()
Command.handle = _new_handle

# XXX: hard-coded to mysql.
class SkipDatabaseCreation(mysql.DatabaseCreation):

    def _create_test_db(self, verbosity, autoclobber):
        ### Oh yes, let's copy from django/db/backends/creation.py
        suffix = self.sql_table_creation_suffix()

        if self.connection.settings_dict['TEST_NAME']:
            test_database_name = self.connection.settings_dict['TEST_NAME']
        else:
            test_database_name = TEST_DATABASE_PREFIX + self.connection.settings_dict['NAME']
        qn = self.connection.ops.quote_name

        # Create the test database and connect to it. We need to autocommit
        # if the database supports it because PostgreSQL doesn't allow
        # CREATE/DROP DATABASE statements within transactions.
        cursor = self.connection.cursor()
        self.set_autocommit()

        ### That's enough copying.

        # If we couldn't create the test db, assume it already exists.
        try:
            cursor.execute("CREATE DATABASE %s %s" %
                           (qn(test_database_name), suffix))
        except Exception, e:
            print '...Skipping setup of %s!' % test_database_name
            print '...Try FORCE_DB=true if you need fresh databases.'
            return test_database_name

        # Drop the db we just created, then do the normal setup.
        cursor.execute("DROP DATABASE %s" % qn(test_database_name))
        return super(SkipDatabaseCreation, self)._create_test_db(
            verbosity, autoclobber)

class RadicalTestSuiteRunner(django_nose.NoseTestSuiteRunner):
    """
    This is a test runner that monkeypatches connection.creation to skip database
    creation if it appears that the db already exists.  Your tests will run much
    faster.

    To force the normal database creation, define the environment variable
    ``FORCE_DB``.  It doesn't really matter what the value is, we just check to
    see if it's there.
    """

    def setup_databases(self):
        if not os.getenv('FORCE_DB'):
            for alias in connections:
                connection = connections[alias]
                connection.creation.__class__ = SkipDatabaseCreation
        return super(RadicalTestSuiteRunner, self).setup_databases()

    def teardown_databases(self, old_config):
        if os.getenv('FORCE_DB'):
            super(RadicalTestSuiteRunner, self).teardown_databases(old_config)
<commit_msg>Allow use of test_settings.py<commit_after>import os

from django.conf import settings
from django.core.management.commands.loaddata import Command
from django.db import connections, DEFAULT_DB_ALIAS
from django.db.backends.creation import TEST_DATABASE_PREFIX
from django.db.backends.mysql import creation as mysql

import django_nose

# Monkey-patch loaddata to ignore foreign key checks.
_old_handle = Command.handle
def _new_handle(self, *fixture_labels, **options):
    using = options.get('database', DEFAULT_DB_ALIAS)
    commit = options.get('commit', True)
    connection = connections[using]

    cursor = connection.cursor()
    cursor.execute('SET foreign_key_checks = 0')

    _old_handle(self, *fixture_labels, **options)

    cursor = connection.cursor()
    cursor.execute('SET foreign_key_checks = 1')

    if commit:
        connection.close()
Command.handle = _new_handle

# XXX: hard-coded to mysql.
class SkipDatabaseCreation(mysql.DatabaseCreation):

    def _create_test_db(self, verbosity, autoclobber):
        ### Oh yes, let's copy from django/db/backends/creation.py
        suffix = self.sql_table_creation_suffix()

        if self.connection.settings_dict['TEST_NAME']:
            test_database_name = self.connection.settings_dict['TEST_NAME']
        else:
            test_database_name = TEST_DATABASE_PREFIX + self.connection.settings_dict['NAME']
        qn = self.connection.ops.quote_name

        # Create the test database and connect to it. We need to autocommit
        # if the database supports it because PostgreSQL doesn't allow
        # CREATE/DROP DATABASE statements within transactions.
        cursor = self.connection.cursor()
        self.set_autocommit()

        ### That's enough copying.

        # If we couldn't create the test db, assume it already exists.
        try:
            cursor.execute("CREATE DATABASE %s %s" %
                           (qn(test_database_name), suffix))
        except Exception, e:
            print '...Skipping setup of %s!' % test_database_name
            print '...Try FORCE_DB=true if you need fresh databases.'
            return test_database_name

        # Drop the db we just created, then do the normal setup.
        cursor.execute("DROP DATABASE %s" % qn(test_database_name))
        return super(SkipDatabaseCreation, self)._create_test_db(
            verbosity, autoclobber)

class RadicalTestSuiteRunner(django_nose.NoseTestSuiteRunner):
    """
    This is a test runner that monkeypatches connection.creation to skip
    database creation if it appears that the db already exists.  Your tests
    will run much faster.

    To force the normal database creation, define the environment variable
    ``FORCE_DB``.  It doesn't really matter what the value is, we just check to
    see if it's there.
    """

    def setup_databases(self):
        if not os.getenv('FORCE_DB'):
            for alias in connections:
                connection = connections[alias]
                connection.creation.__class__ = SkipDatabaseCreation
        return super(RadicalTestSuiteRunner, self).setup_databases()

    def teardown_databases(self, old_config):
        if os.getenv('FORCE_DB'):
            super(RadicalTestSuiteRunner, self).teardown_databases(old_config)

    def setup_test_environment(self, **kwargs):
        super(RadicalTestSuiteRunner, self).setup_test_environment(**kwargs)

        # If we have a settings_test.py let's roll it into our settings.
        try:
            import settings_test
            settings.__dict__.update(settings_test.__dict__)
        except ImportError:
            pass

<|endoftext|>


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

import pytest, json
from pyglet.resource import ResourceNotFoundException
from glooey.themes import ResourceLoader

@pytest.mark.parametrize("theme", ["golden", "kenney"])
def test_assets_installed(theme):
    assets = ResourceLoader(theme)

    # Make sure that the test errors on a resource that doesn't exist.
    with pytest.raises(ResourceNotFoundException):
        assets.location('nonexistent')

    # Load the list of assets that should be included for this theme.
    with open(f'{theme}_assets.json') as fp:
        manifest = json.load(fp)

    # If all these paths exist, we shouldn't get any exceptions asking for
    # their locations:
    for path in manifest:
        assets.location(path)
<commit_msg>Fix the asset test.<commit_after>#!/usr/bin/env python3

import pytest, json
from pathlib import Path
from pyglet.resource import ResourceNotFoundException
from glooey.themes import ResourceLoader

@pytest.mark.parametrize("theme", ["golden", "kenney"])
def test_assets_installed(theme):
    assets = ResourceLoader(theme)

    # Make sure that the test errors on a resource that doesn't exist.
    with pytest.raises(ResourceNotFoundException):
        assets.location('nonexistent')

    # Load the list of assets that should be included for this theme.
    manifest_json = Path(__file__).parent / f'{theme}_assets.json'
    with manifest_json.open() as fp:
        manifest = json.load(fp)

    # If all these paths exist, we shouldn't get any exceptions asking for
    # their locations:
    for path in manifest:
        assets.location(path)
<|endoftext|>


<commit_before>#!/usr/bin/env python
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""
A top level harness to run all unit-tests in a specific engine build.
"""

import argparse
import glob
import os
import re
import subprocess
import sys

buildroot_dir = os.path.abspath(os.path.join(os.path.realpath(__file__), '..', '..', '..'))
out_dir = os.path.join(buildroot_dir, 'out')
golden_dir = os.path.join(buildroot_dir, 'flutter', 'testing', 'resources')
fonts_dir = os.path.join(buildroot_dir, 'flutter', 'third_party', 'txt', 'third_party', 'fonts')
roboto_font_path = os.path.join(fonts_dir, 'Roboto-Regular.ttf')
dart_tests_dir = os.path.join(buildroot_dir, 'flutter', 'testing', 'dart',)

time_sensitve_test_flag = '--gtest_filter=-*TimeSensitiveTest*'

def IsMac():
  return sys.platform == 'darwin'

def IsLinux():
  return sys.platform.startswith('linux')

def IsWindows():
  return sys.platform.startswith(('cygwin', 'win'))

def ExecutableSuffix():
  return '.exe' if IsWindows() else ''

def FindExecutablePath(path):
  if os.path.exists(path):
    return path

  if IsWindows():
    exe_path = path + '.exe'
    if os.path.exists(exe_path):
      return exe_path

    bat_path = path + '.bat'
    if os.path.exists(bat_path):
      return bat_path

  raise Exception('Executable %s does not exist!' % path)

def RunEngineExecutable(build_dir, executable_name, filter, flags=[], cwd=buildroot_dir):
  if filter is not None and executable_name not in filter:
    print 'Skipping %s due to filter.' % executable_name
    return

  executable = FindExecutablePath(os.path.join(build_dir, executable_name))

  print 'Running %s in %s' % (executable_name, cwd)
  test_command = [ executable ] + flags
  print ' '.join(test_command)
  subprocess.check_call(test_command, cwd=cwd)

def RunCCTests(build_dir, filter):
  print "Running Engine Unit-tests."

  shuffle_flags = [
    "--gtest_shuffle",
    "--gtest_repeat=2",
  ]

  RunEngineExecutable(build_dir, 'client_wrapper_glfw_unittests', filter, shuffle_flags)

  RunEngineExecutable(build_dir, 'client_wrapper_unittests', filter, shuffle_flags)

  # https://github.com/flutter/flutter/issues/36294
  if not IsWindows():
    RunEngineExecutable(build_dir, 'embedder_unittests', filter, shuffle_flags)
  else:
    RunEngineExecutable(build_dir, 'flutter_windows_unittests', filter, shuffle_flags)

    RunEngineExecutable(build_dir, 'client_wrapper_windows_unittests', filter, shuffle_flags)

  flow_flags = ['--gtest_filter=-PerformanceOverlayLayer.Gold']
  if IsLinux():
    flow_flags = [
      '--golden-dir=%s' % golden_dir,
      '--font-file=%s' % roboto_font_path,
    ]
  RunEngineExecutable(build_dir, 'flow_unittests', filter, flow_flags + shuffle_flags)

  RunEngineExecutable(build_dir, 'fml_unittests', filter, [ time_sensitve_test_flag ] + shuffle_flags)

  RunEngineExecutable(build_dir, 'runtime_unittests', filter, shuffle_flags)

  # https://github.com/flutter/flutter/issues/36295
  if not IsWindows():
    RunEngineExecutable(build_dir, 'shell_unittests', filter, shuffle_flags)

  RunEngineExecutable(build_dir, 'ui_unittests', filter, shuffle_flags)

  # These unit-tests are Objective-C and can only run on Darwin.
  if IsMac():
    RunEngineExecutable(build_dir, 'flutter_channels_unittests', filter, shuffle_flags)

  # https://github.com/flutter/flutter/issues/36296
  if IsLinux():
    RunEngineExecutable(build_dir, 'txt_unittests', filter, shuffle_flags)

def RunEngineBenchmarks(build_dir, filter):
  print "Running Engine Benchmarks."

  RunEngineExecutable(build_dir, 'shell_benchmarks', filter)

  RunEngineExecutable(build_dir, 'fml_benchmarks', filter)

  if IsLinux():
    RunEngineExecutable(build_dir, 'txt_benchmarks', filter)

def SnapshotTest(build_dir, dart_file, kernel_file_output, verbose_dart_snapshot):
  print "Generating snapshot for test %s" % dart_file

  dart = os.path.join(build_dir, 'dart-sdk', 'bin', 'dart')
  frontend_server = os.path.join(build_dir, 'gen', 'frontend_server.dart.snapshot')
  flutter_patched_sdk = os.path.join(build_dir, 'flutter_patched_sdk')
  test_packages = os.path.join(dart_tests_dir, '.packages')

  assert os.path.exists(dart)
  assert os.path.exists(frontend_server)
  assert os.path.exists(flutter_patched_sdk)
  assert os.path.exists(test_packages)

  snapshot_command = [
    dart,
    frontend_server,
    '--sdk-root',
    flutter_patched_sdk,
    '--incremental',
    '--strong',
    '--target=flutter',
    '--packages',
    test_packages,
    '--output-dill',
    kernel_file_output,
    dart_file
  ]

  if verbose_dart_snapshot:
    subprocess.check_call(snapshot_command, cwd=buildroot_dir)
  else:
    with open(os.devnull,"w") as out_file:
      subprocess.check_call(snapshot_command, cwd=buildroot_dir, stdout=out_file)
  assert os.path.exists(kernel_file_output)

def RunDartTest(build_dir, dart_file, verbose_dart_snapshot, multithreaded):
  kernel_file_name = os.path.basename(dart_file) + '.kernel.dill'
  kernel_file_output = os.path.join(out_dir, kernel_file_name)

  SnapshotTest(build_dir, dart_file, kernel_file_output, verbose_dart_snapshot)

  command_args = [
    '--disable-observatory',
    '--use-test-fonts',
    kernel_file_output
  ]

  if multithreaded:
    threading = 'multithreaded'
    command_args.insert(0, '--force-multithreading')
  else:
    threading = 'single-threaded'

  print "Running test '%s' using 'flutter_tester' (%s)" % (kernel_file_name, threading)
  RunEngineExecutable(build_dir, 'flutter_tester', None, command_args)

def RunPubGet(build_dir, directory):
  print "Running 'pub get' in the tests directory %s" % dart_tests_dir

  pub_get_command = [
    os.path.join(build_dir, 'dart-sdk', 'bin', 'pub'),
    'get'
  ]
  subprocess.check_call(pub_get_command, cwd=directory)

def EnsureDebugUnoptSkyPackagesAreBuilt():
  variant_out_dir = os.path.join(out_dir, 'host_debug_unopt')

  ninja_command = [
    'autoninja',
    '-C',
    variant_out_dir,
    'flutter/sky/packages'
  ]

  # Attempt running Ninja if the out directory exists.
  # We don't want to blow away any custom GN args the caller may have already set.
  if os.path.exists(variant_out_dir):
    subprocess.check_call(ninja_command, cwd=buildroot_dir)
    return

  gn_command = [
    os.path.join(buildroot_dir, 'flutter', 'tools', 'gn'),
    '--runtime-mode',
    'debug',
    '--unopt',
    '--no-lto',
  ]

  subprocess.check_call(gn_command, cwd=buildroot_dir)
  subprocess.check_call(ninja_command, cwd=buildroot_dir)

def EnsureJavaTestsAreBuilt(android_out_dir):
  ninja_command = [
    'autoninja',
    '-C',
    android_out_dir,
    'flutter/shell/platform/android:robolectric_tests'
  ]

  # Attempt running Ninja if the out directory exists.
  # We don't want to blow away any custom GN args the caller may have already set.
  if os.path.exists(android_out_dir):
    subprocess.check_call(ninja_command, cwd=buildroot_dir)
    return

  # Otherwise prepare the directory first, then build the test.
  gn_command = [
    os.path.join(buildroot_dir, 'flutter', 'tools', 'gn'),
    '--android',
    '--unoptimized',
    '--runtime-mode=debug',
    '--no-lto',
  ]
  subprocess.check_call(gn_command, cwd=buildroot_dir)
  subprocess.check_call(ninja_command, cwd=buildroot_dir)

def AssertExpectedJavaVersion():
  EXPECTED_VERSION = '1.8'
  # `java -version` is output to stderr. https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4380614
  version_output = subprocess.check_output(['java', '-version'], stderr=subprocess.STDOUT)
  match = bool(re.compile('version "%s' % EXPECTED_VERSION).search(version_output))
  message = "JUnit tests need to be run with Java %s. Check the `java -version` on your PATH." % EXPECTED_VERSION
  assert match, message

def RunJavaTests(filter, android_variant='android_debug_unopt'):
  AssertExpectedJavaVersion()
  android_out_dir = os.path.join(out_dir, android_variant)
  EnsureJavaTestsAreBuilt(android_out_dir)

  robolectric_dir = os.path.join(buildroot_dir, 'third_party', 'robolectric', 'lib')
  classpath = map(str, [
    os.path.join(buildroot_dir, 'third_party', 'android_tools', 'sdk', 'platforms', 'android-29', 'android.jar'),
    os.path.join(robolectric_dir, '*'), # Wildcard for all jars in the directory
    os.path.join(android_out_dir, 'flutter.jar'),
    os.path.join(android_out_dir, 'robolectric_tests.jar')
  ])

  test_class = filter if filter else 'io.flutter.FlutterTestSuite'
  command = [
    'java',
    '-Drobolectric.offline=true',
    '-Drobolectric.dependency.dir=' + robolectric_dir,
    '-classpath', ':'.join(classpath),
    '-Drobolectric.logging=stdout',
    'org.junit.runner.JUnitCore',
    test_class
  ]

  return subprocess.check_call(command)

def RunDartTests(build_dir, filter, verbose_dart_snapshot):
  # This one is a bit messy. The pubspec.yaml at flutter/testing/dart/pubspec.yaml
  # has dependencies that are hardcoded to point to the sky packages at host_debug_unopt/
  # Before running Dart tests, make sure to run just that target (NOT the whole engine)
  EnsureDebugUnoptSkyPackagesAreBuilt();

  # Now that we have the Sky packages at the hardcoded location, run `pub get`.
  RunEngineExecutable(build_dir, os.path.join('dart-sdk', 'bin', 'pub'), None, flags=['get'], cwd=dart_tests_dir)

  dart_tests = glob.glob('%s/*.dart' % dart_tests_dir)

  for dart_test_file in dart_tests:
    if filter is not None and os.path.basename(dart_test_file) not in filter:
      print "Skipping %s due to filter." % dart_test_file
    else:
      print "Testing dart file %s" % dart_test_file
      RunDartTest(build_dir, dart_test_file, verbose_dart_snapshot, True)
      RunDartTest(build_dir, dart_test_file, verbose_dart_snapshot, False)

def main():
  parser = argparse.ArgumentParser();

  parser.add_argument('--variant', dest='variant', action='store',
      default='host_debug_unopt', help='The engine build variant to run the tests for.');
  parser.add_argument('--type', type=str, default='all')
  parser.add_argument('--engine-filter', type=str, default='',
      help='A list of engine test executables to run.')
  parser.add_argument('--dart-filter', type=str, default='',
      help='A list of Dart test scripts to run.')
  parser.add_argument('--java-filter', type=str, default='',
      help='A single Java test class to run.')
  parser.add_argument('--android-variant', dest='android_variant', action='store',
      default='android_debug_unopt',
      help='The engine build variant to run java tests for')
  parser.add_argument('--verbose-dart-snapshot', dest='verbose_dart_snapshot', action='store_true',
      default=False, help='Show extra dart snapshot logging.')

  args = parser.parse_args()

  if args.type == 'all':
    types = ['engine', 'dart', 'benchmarks', 'java']
  else:
    types = args.type.split(',')

  build_dir = os.path.join(out_dir, args.variant)
  if args.type != 'java':
    assert os.path.exists(build_dir), 'Build variant directory %s does not exist!' % build_dir

  engine_filter = args.engine_filter.split(',') if args.engine_filter else None
  if 'engine' in types:
    RunCCTests(build_dir, engine_filter)

  if 'dart' in types:
    assert not IsWindows(), "Dart tests can't be run on windows. https://github.com/flutter/flutter/issues/36301."
    dart_filter = args.dart_filter.split(',') if args.dart_filter else None
    RunDartTests(build_dir, dart_filter, args.verbose_dart_snapshot)

  if 'java' in types:
    assert not IsWindows(), "Android engine files can't be compiled on Windows."
    java_filter = args.java_filter
    if ',' in java_filter or '*' in java_filter:
      print('Can only filter JUnit4 tests by single entire class name, eg "io.flutter.SmokeTest". Ignoring filter=' + java_filter)
      java_filter = None
    RunJavaTests(java_filter, args.android_variant)

  # https://github.com/flutter/flutter/issues/36300
  if 'benchmarks' in types and not IsWindows():
    RunEngineBenchmarks(build_dir, engine_filter)

if __name__ == '__main__':
  sys.exit(main())
<commit_msg>use check_output instead of check_call so that exceptions show the output. (#13478)<commit_after>#!/usr/bin/env python
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""
A top level harness to run all unit-tests in a specific engine build.
"""

import argparse
import glob
import os
import re
import subprocess
import sys

buildroot_dir = os.path.abspath(os.path.join(os.path.realpath(__file__), '..', '..', '..'))
out_dir = os.path.join(buildroot_dir, 'out')
golden_dir = os.path.join(buildroot_dir, 'flutter', 'testing', 'resources')
fonts_dir = os.path.join(buildroot_dir, 'flutter', 'third_party', 'txt', 'third_party', 'fonts')
roboto_font_path = os.path.join(fonts_dir, 'Roboto-Regular.ttf')
dart_tests_dir = os.path.join(buildroot_dir, 'flutter', 'testing', 'dart',)

time_sensitve_test_flag = '--gtest_filter=-*TimeSensitiveTest*'

def IsMac():
  return sys.platform == 'darwin'

def IsLinux():
  return sys.platform.startswith('linux')

def IsWindows():
  return sys.platform.startswith(('cygwin', 'win'))

def ExecutableSuffix():
  return '.exe' if IsWindows() else ''

def FindExecutablePath(path):
  if os.path.exists(path):
    return path

  if IsWindows():
    exe_path = path + '.exe'
    if os.path.exists(exe_path):
      return exe_path

    bat_path = path + '.bat'
    if os.path.exists(bat_path):
      return bat_path

  raise Exception('Executable %s does not exist!' % path)

def RunEngineExecutable(build_dir, executable_name, filter, flags=[], cwd=buildroot_dir):
  if filter is not None and executable_name not in filter:
    print 'Skipping %s due to filter.' % executable_name
    return

  executable = FindExecutablePath(os.path.join(build_dir, executable_name))

  print 'Running %s in %s' % (executable_name, cwd)
  test_command = [ executable ] + flags
  print ' '.join(test_command)
  subprocess.check_output(test_command, cwd=cwd)

def RunCCTests(build_dir, filter):
  print "Running Engine Unit-tests."

  shuffle_flags = [
    "--gtest_shuffle",
    "--gtest_repeat=2",
  ]

  RunEngineExecutable(build_dir, 'client_wrapper_glfw_unittests', filter, shuffle_flags)

  RunEngineExecutable(build_dir, 'client_wrapper_unittests', filter, shuffle_flags)

  # https://github.com/flutter/flutter/issues/36294
  if not IsWindows():
    RunEngineExecutable(build_dir, 'embedder_unittests', filter, shuffle_flags)
  else:
    RunEngineExecutable(build_dir, 'flutter_windows_unittests', filter, shuffle_flags)

    RunEngineExecutable(build_dir, 'client_wrapper_windows_unittests', filter, shuffle_flags)

  flow_flags = ['--gtest_filter=-PerformanceOverlayLayer.Gold']
  if IsLinux():
    flow_flags = [
      '--golden-dir=%s' % golden_dir,
      '--font-file=%s' % roboto_font_path,
    ]
  RunEngineExecutable(build_dir, 'flow_unittests', filter, flow_flags + shuffle_flags)

  RunEngineExecutable(build_dir, 'fml_unittests', filter, [ time_sensitve_test_flag ] + shuffle_flags)

  RunEngineExecutable(build_dir, 'runtime_unittests', filter, shuffle_flags)

  # https://github.com/flutter/flutter/issues/36295
  if not IsWindows():
    RunEngineExecutable(build_dir, 'shell_unittests', filter, shuffle_flags)

  RunEngineExecutable(build_dir, 'ui_unittests', filter, shuffle_flags)

  # These unit-tests are Objective-C and can only run on Darwin.
  if IsMac():
    RunEngineExecutable(build_dir, 'flutter_channels_unittests', filter, shuffle_flags)

  # https://github.com/flutter/flutter/issues/36296
  if IsLinux():
    RunEngineExecutable(build_dir, 'txt_unittests', filter, shuffle_flags)

def RunEngineBenchmarks(build_dir, filter):
  print "Running Engine Benchmarks."

  RunEngineExecutable(build_dir, 'shell_benchmarks', filter)

  RunEngineExecutable(build_dir, 'fml_benchmarks', filter)

  if IsLinux():
    RunEngineExecutable(build_dir, 'txt_benchmarks', filter)

def SnapshotTest(build_dir, dart_file, kernel_file_output, verbose_dart_snapshot):
  print "Generating snapshot for test %s" % dart_file

  dart = os.path.join(build_dir, 'dart-sdk', 'bin', 'dart')
  frontend_server = os.path.join(build_dir, 'gen', 'frontend_server.dart.snapshot')
  flutter_patched_sdk = os.path.join(build_dir, 'flutter_patched_sdk')
  test_packages = os.path.join(dart_tests_dir, '.packages')

  assert os.path.exists(dart)
  assert os.path.exists(frontend_server)
  assert os.path.exists(flutter_patched_sdk)
  assert os.path.exists(test_packages)

  snapshot_command = [
    dart,
    frontend_server,
    '--sdk-root',
    flutter_patched_sdk,
    '--incremental',
    '--strong',
    '--target=flutter',
    '--packages',
    test_packages,
    '--output-dill',
    kernel_file_output,
    dart_file
  ]

  if verbose_dart_snapshot:
    subprocess.check_output(snapshot_command, cwd=buildroot_dir)
  else:
    with open(os.devnull,"w") as out_file:
      subprocess.check_output(snapshot_command, cwd=buildroot_dir, stdout=out_file)
  assert os.path.exists(kernel_file_output)

def RunDartTest(build_dir, dart_file, verbose_dart_snapshot, multithreaded):
  kernel_file_name = os.path.basename(dart_file) + '.kernel.dill'
  kernel_file_output = os.path.join(out_dir, kernel_file_name)

  SnapshotTest(build_dir, dart_file, kernel_file_output, verbose_dart_snapshot)

  command_args = [
    '--disable-observatory',
    '--use-test-fonts',
    kernel_file_output
  ]

  if multithreaded:
    threading = 'multithreaded'
    command_args.insert(0, '--force-multithreading')
  else:
    threading = 'single-threaded'

  print "Running test '%s' using 'flutter_tester' (%s)" % (kernel_file_name, threading)
  RunEngineExecutable(build_dir, 'flutter_tester', None, command_args)

def RunPubGet(build_dir, directory):
  print "Running 'pub get' in the tests directory %s" % dart_tests_dir

  pub_get_command = [
    os.path.join(build_dir, 'dart-sdk', 'bin', 'pub'),
    'get'
  ]
  subprocess.check_output(pub_get_command, cwd=directory)

def EnsureDebugUnoptSkyPackagesAreBuilt():
  variant_out_dir = os.path.join(out_dir, 'host_debug_unopt')

  ninja_command = [
    'autoninja',
    '-C',
    variant_out_dir,
    'flutter/sky/packages'
  ]

  # Attempt running Ninja if the out directory exists.
  # We don't want to blow away any custom GN args the caller may have already set.
  if os.path.exists(variant_out_dir):
    subprocess.check_output(ninja_command, cwd=buildroot_dir)
    return

  gn_command = [
    os.path.join(buildroot_dir, 'flutter', 'tools', 'gn'),
    '--runtime-mode',
    'debug',
    '--unopt',
    '--no-lto',
  ]

  subprocess.check_output(gn_command, cwd=buildroot_dir)
  subprocess.check_output(ninja_command, cwd=buildroot_dir)

def EnsureJavaTestsAreBuilt(android_out_dir):
  ninja_command = [
    'autoninja',
    '-C',
    android_out_dir,
    'flutter/shell/platform/android:robolectric_tests'
  ]

  # Attempt running Ninja if the out directory exists.
  # We don't want to blow away any custom GN args the caller may have already set.
  if os.path.exists(android_out_dir):
    subprocess.check_output(ninja_command, cwd=buildroot_dir)
    return

  # Otherwise prepare the directory first, then build the test.
  gn_command = [
    os.path.join(buildroot_dir, 'flutter', 'tools', 'gn'),
    '--android',
    '--unoptimized',
    '--runtime-mode=debug',
    '--no-lto',
  ]
  subprocess.check_output(gn_command, cwd=buildroot_dir)
  subprocess.check_output(ninja_command, cwd=buildroot_dir)

def AssertExpectedJavaVersion():
  EXPECTED_VERSION = '1.8'
  # `java -version` is output to stderr. https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4380614
  version_output = subprocess.check_output(['java', '-version'], stderr=subprocess.STDOUT)
  match = bool(re.compile('version "%s' % EXPECTED_VERSION).search(version_output))
  message = "JUnit tests need to be run with Java %s. Check the `java -version` on your PATH." % EXPECTED_VERSION
  assert match, message

def RunJavaTests(filter, android_variant='android_debug_unopt'):
  AssertExpectedJavaVersion()
  android_out_dir = os.path.join(out_dir, android_variant)
  EnsureJavaTestsAreBuilt(android_out_dir)

  robolectric_dir = os.path.join(buildroot_dir, 'third_party', 'robolectric', 'lib')
  classpath = map(str, [
    os.path.join(buildroot_dir, 'third_party', 'android_tools', 'sdk', 'platforms', 'android-29', 'android.jar'),
    os.path.join(robolectric_dir, '*'), # Wildcard for all jars in the directory
    os.path.join(android_out_dir, 'flutter.jar'),
    os.path.join(android_out_dir, 'robolectric_tests.jar')
  ])

  test_class = filter if filter else 'io.flutter.FlutterTestSuite'
  command = [
    'java',
    '-Drobolectric.offline=true',
    '-Drobolectric.dependency.dir=' + robolectric_dir,
    '-classpath', ':'.join(classpath),
    '-Drobolectric.logging=stdout',
    'org.junit.runner.JUnitCore',
    test_class
  ]

  return subprocess.check_output(command)

def RunDartTests(build_dir, filter, verbose_dart_snapshot):
  # This one is a bit messy. The pubspec.yaml at flutter/testing/dart/pubspec.yaml
  # has dependencies that are hardcoded to point to the sky packages at host_debug_unopt/
  # Before running Dart tests, make sure to run just that target (NOT the whole engine)
  EnsureDebugUnoptSkyPackagesAreBuilt();

  # Now that we have the Sky packages at the hardcoded location, run `pub get`.
  RunEngineExecutable(build_dir, os.path.join('dart-sdk', 'bin', 'pub'), None, flags=['get'], cwd=dart_tests_dir)

  dart_tests = glob.glob('%s/*.dart' % dart_tests_dir)

  for dart_test_file in dart_tests:
    if filter is not None and os.path.basename(dart_test_file) not in filter:
      print "Skipping %s due to filter." % dart_test_file
    else:
      print "Testing dart file %s" % dart_test_file
      RunDartTest(build_dir, dart_test_file, verbose_dart_snapshot, True)
      RunDartTest(build_dir, dart_test_file, verbose_dart_snapshot, False)

def main():
  parser = argparse.ArgumentParser();

  parser.add_argument('--variant', dest='variant', action='store',
      default='host_debug_unopt', help='The engine build variant to run the tests for.');
  parser.add_argument('--type', type=str, default='all')
  parser.add_argument('--engine-filter', type=str, default='',
      help='A list of engine test executables to run.')
  parser.add_argument('--dart-filter', type=str, default='',
      help='A list of Dart test scripts to run.')
  parser.add_argument('--java-filter', type=str, default='',
      help='A single Java test class to run.')
  parser.add_argument('--android-variant', dest='android_variant', action='store',
      default='android_debug_unopt',
      help='The engine build variant to run java tests for')
  parser.add_argument('--verbose-dart-snapshot', dest='verbose_dart_snapshot', action='store_true',
      default=False, help='Show extra dart snapshot logging.')

  args = parser.parse_args()

  if args.type == 'all':
    types = ['engine', 'dart', 'benchmarks', 'java']
  else:
    types = args.type.split(',')

  build_dir = os.path.join(out_dir, args.variant)
  if args.type != 'java':
    assert os.path.exists(build_dir), 'Build variant directory %s does not exist!' % build_dir

  engine_filter = args.engine_filter.split(',') if args.engine_filter else None
  if 'engine' in types:
    RunCCTests(build_dir, engine_filter)

  if 'dart' in types:
    assert not IsWindows(), "Dart tests can't be run on windows. https://github.com/flutter/flutter/issues/36301."
    dart_filter = args.dart_filter.split(',') if args.dart_filter else None
    RunDartTests(build_dir, dart_filter, args.verbose_dart_snapshot)

  if 'java' in types:
    assert not IsWindows(), "Android engine files can't be compiled on Windows."
    java_filter = args.java_filter
    if ',' in java_filter or '*' in java_filter:
      print('Can only filter JUnit4 tests by single entire class name, eg "io.flutter.SmokeTest". Ignoring filter=' + java_filter)
      java_filter = None
    RunJavaTests(java_filter, args.android_variant)

  # https://github.com/flutter/flutter/issues/36300
  if 'benchmarks' in types and not IsWindows():
    RunEngineBenchmarks(build_dir, engine_filter)

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


<commit_before># Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

"""
Unit Tests for periodic_task decorator and PeriodicTasks class.
"""

import datetime

from openstack.common.fixture import config
from openstack.common import periodic_task
from openstack.common import test
from openstack.common import timeutils
from testtools import matchers

class AnException(Exception):
    pass

class AService(periodic_task.PeriodicTasks):

    def __init__(self):
        self.called = {}

    @periodic_task.periodic_task
    def doit(self, context):
        self.called['doit'] = True

    @periodic_task.periodic_task
    def crashit(self, context):
        self.called['urg'] = True
        raise AnException('urg')

    @periodic_task.periodic_task(spacing=10)
    def doit_with_kwargs_odd(self, context):
        self.called['ticks'] = True

class PeriodicTasksTestCase(test.BaseTestCase):
    """Test cases for PeriodicTasks."""

    def test_is_called(self):
        serv = AService()
        serv.run_periodic_tasks(None)
        self.assertTrue(serv.called['doit'])
        self.assertTrue(len(serv.called) == 2)

    def test_called_twice(self):
        serv = AService()
        serv.run_periodic_tasks(None)
        serv.run_periodic_tasks(None)
        # expect doit_with_kwargs to be called twice
        # and doit_with_kwargs_odd to be called once.
        self.assertTrue(len(serv.called) == 3)

    def test_raises(self):
        serv = AService()
        self.assertRaises(AnException,
                          serv.run_periodic_tasks,
                          None, raise_on_error=True)

class ManagerMetaTestCase(test.BaseTestCase):
    """Tests for the meta class which manages the creation of periodic tasks.
    """

    def test_meta(self):
        class Manager(periodic_task.PeriodicTasks):

            @periodic_task.periodic_task
            def foo(self):
                return 'foo'

            @periodic_task.periodic_task(spacing=4)
            def bar(self):
                return 'bar'

            @periodic_task.periodic_task(enabled=False)
            def baz(self):
                return 'baz'

        m = Manager()
        self.assertThat(m._periodic_tasks, matchers.HasLength(2))
        self.assertEqual(None, m._periodic_spacing['foo'])
        self.assertEqual(4, m._periodic_spacing['bar'])
        self.assertThat(
            m._periodic_spacing, matchers.Not(matchers.Contains('baz')))

class ManagerTestCase(test.BaseTestCase):
    """Tests the periodic tasks portion of the manager class."""
    def setUp(self):
        super(ManagerTestCase, self).setUp()
        self.config = self.useFixture(config.Config()).config

    def test_periodic_tasks_with_idle(self):
        class Manager(periodic_task.PeriodicTasks):

            @periodic_task.periodic_task(spacing=200)
            def bar(self):
                return 'bar'

        m = Manager()
        self.assertThat(m._periodic_tasks, matchers.HasLength(1))
        self.assertEqual(200, m._periodic_spacing['bar'])

        # Now a single pass of the periodic tasks
        idle = m.run_periodic_tasks(None)
        self.assertAlmostEqual(60, idle, 1)

    def test_periodic_tasks_constant(self):
        class Manager(periodic_task.PeriodicTasks):

            @periodic_task.periodic_task(spacing=0)
            def bar(self):
                return 'bar'

        m = Manager()
        idle = m.run_periodic_tasks(None)
        self.assertAlmostEqual(60, idle, 1)

    def test_periodic_tasks_idle_calculation(self):
        fake_time = datetime.datetime(3000, 1, 1)
        timeutils.set_time_override(fake_time)

        class Manager(periodic_task.PeriodicTasks):

            @periodic_task.periodic_task(spacing=10)
            def bar(self, context):
                return 'bar'

        m = Manager()

        # Ensure initial values are correct
        self.assertEqual(1, len(m._periodic_tasks))
        task_name, task = m._periodic_tasks[0]

        # Test task values
        self.assertEqual('bar', task_name)
        self.assertEqual(10, task._periodic_spacing)
        self.assertEqual(True, task._periodic_enabled)
        self.assertEqual(False, task._periodic_external_ok)
        self.assertEqual(False, task._periodic_immediate)
        self.assertNotEqual(None, task._periodic_last_run)

        # Test the manager's representation of those values
        self.assertEqual(10, m._periodic_spacing[task_name])
        self.assertNotEqual(None, m._periodic_last_run[task_name])

        timeutils.advance_time_delta(datetime.timedelta(seconds=5))
        m.run_periodic_tasks(None)

        timeutils.advance_time_delta(datetime.timedelta(seconds=5))
        idle = m.run_periodic_tasks(None)
        self.assertAlmostEqual(10, idle, 1)

    def test_periodic_tasks_immediate_runs_now(self):
        fake_time = datetime.datetime(3000, 1, 1)
        timeutils.set_time_override(fake_time)

        class Manager(periodic_task.PeriodicTasks):

            @periodic_task.periodic_task(spacing=10, run_immediately=True)
            def bar(self, context):
                return 'bar'

        m = Manager()

        # Ensure initial values are correct
        self.assertEqual(1, len(m._periodic_tasks))
        task_name, task = m._periodic_tasks[0]

        # Test task values
        self.assertEqual('bar', task_name)
        self.assertEqual(10, task._periodic_spacing)
        self.assertEqual(True, task._periodic_enabled)
        self.assertEqual(False, task._periodic_external_ok)
        self.assertEqual(True, task._periodic_immediate)
        self.assertEqual(None, task._periodic_last_run)

        # Test the manager's representation of those values
        self.assertEqual(10, m._periodic_spacing[task_name])
        self.assertEqual(None, m._periodic_last_run[task_name])

        idle = m.run_periodic_tasks(None)
        self.assertEqual(datetime.datetime(3000, 1, 1, 0, 0),
                         m._periodic_last_run[task_name])
        self.assertAlmostEqual(10, idle, 1)

        timeutils.advance_time_delta(datetime.timedelta(seconds=5))
        idle = m.run_periodic_tasks(None)
        self.assertAlmostEqual(5, idle, 1)

    def test_periodic_tasks_disabled(self):
        class Manager(periodic_task.PeriodicTasks):

            @periodic_task.periodic_task(spacing=-1)
            def bar(self):
                return 'bar'

        m = Manager()
        idle = m.run_periodic_tasks(None)
        self.assertAlmostEqual(60, idle, 1)

    def test_external_running_here(self):
        self.config(run_external_periodic_tasks=True)

        class Manager(periodic_task.PeriodicTasks):

            @periodic_task.periodic_task(spacing=200, external_process_ok=True)
            def bar(self):
                return 'bar'

        m = Manager()
        self.assertThat(m._periodic_tasks, matchers.HasLength(1))

    def test_external_running_elsewhere(self):
        self.config(run_external_periodic_tasks=False)

        class Manager(periodic_task.PeriodicTasks):

            @periodic_task.periodic_task(spacing=200, external_process_ok=True)
            def bar(self):
                return 'bar'

        m = Manager()
        self.assertEqual([], m._periodic_tasks)
<commit_msg>Utilizes assertIsNone and assertIsNotNone<commit_after># Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

"""
Unit Tests for periodic_task decorator and PeriodicTasks class.
"""

import datetime

from openstack.common.fixture import config
from openstack.common import periodic_task
from openstack.common import test
from openstack.common import timeutils
from testtools import matchers

class AnException(Exception):
    pass

class AService(periodic_task.PeriodicTasks):

    def __init__(self):
        self.called = {}

    @periodic_task.periodic_task
    def doit(self, context):
        self.called['doit'] = True

    @periodic_task.periodic_task
    def crashit(self, context):
        self.called['urg'] = True
        raise AnException('urg')

    @periodic_task.periodic_task(spacing=10)
    def doit_with_kwargs_odd(self, context):
        self.called['ticks'] = True

class PeriodicTasksTestCase(test.BaseTestCase):
    """Test cases for PeriodicTasks."""

    def test_is_called(self):
        serv = AService()
        serv.run_periodic_tasks(None)
        self.assertTrue(serv.called['doit'])
        self.assertTrue(len(serv.called) == 2)

    def test_called_twice(self):
        serv = AService()
        serv.run_periodic_tasks(None)
        serv.run_periodic_tasks(None)
        # expect doit_with_kwargs to be called twice
        # and doit_with_kwargs_odd to be called once.
        self.assertTrue(len(serv.called) == 3)

    def test_raises(self):
        serv = AService()
        self.assertRaises(AnException,
                          serv.run_periodic_tasks,
                          None, raise_on_error=True)

class ManagerMetaTestCase(test.BaseTestCase):
    """Tests for the meta class which manages the creation of periodic tasks.
    """

    def test_meta(self):
        class Manager(periodic_task.PeriodicTasks):

            @periodic_task.periodic_task
            def foo(self):
                return 'foo'

            @periodic_task.periodic_task(spacing=4)
            def bar(self):
                return 'bar'

            @periodic_task.periodic_task(enabled=False)
            def baz(self):
                return 'baz'

        m = Manager()
        self.assertThat(m._periodic_tasks, matchers.HasLength(2))
        self.assertIsNone(m._periodic_spacing['foo'])
        self.assertEqual(4, m._periodic_spacing['bar'])
        self.assertThat(
            m._periodic_spacing, matchers.Not(matchers.Contains('baz')))

class ManagerTestCase(test.BaseTestCase):
    """Tests the periodic tasks portion of the manager class."""
    def setUp(self):
        super(ManagerTestCase, self).setUp()
        self.config = self.useFixture(config.Config()).config

    def test_periodic_tasks_with_idle(self):
        class Manager(periodic_task.PeriodicTasks):

            @periodic_task.periodic_task(spacing=200)
            def bar(self):
                return 'bar'

        m = Manager()
        self.assertThat(m._periodic_tasks, matchers.HasLength(1))
        self.assertEqual(200, m._periodic_spacing['bar'])

        # Now a single pass of the periodic tasks
        idle = m.run_periodic_tasks(None)
        self.assertAlmostEqual(60, idle, 1)

    def test_periodic_tasks_constant(self):
        class Manager(periodic_task.PeriodicTasks):

            @periodic_task.periodic_task(spacing=0)
            def bar(self):
                return 'bar'

        m = Manager()
        idle = m.run_periodic_tasks(None)
        self.assertAlmostEqual(60, idle, 1)

    def test_periodic_tasks_idle_calculation(self):
        fake_time = datetime.datetime(3000, 1, 1)
        timeutils.set_time_override(fake_time)

        class Manager(periodic_task.PeriodicTasks):

            @periodic_task.periodic_task(spacing=10)
            def bar(self, context):
                return 'bar'

        m = Manager()

        # Ensure initial values are correct
        self.assertEqual(1, len(m._periodic_tasks))
        task_name, task = m._periodic_tasks[0]

        # Test task values
        self.assertEqual('bar', task_name)
        self.assertEqual(10, task._periodic_spacing)
        self.assertEqual(True, task._periodic_enabled)
        self.assertEqual(False, task._periodic_external_ok)
        self.assertEqual(False, task._periodic_immediate)
        self.assertIsNotNone(task._periodic_last_run)

        # Test the manager's representation of those values
        self.assertEqual(10, m._periodic_spacing[task_name])
        self.assertIsNotNone(m._periodic_last_run[task_name])

        timeutils.advance_time_delta(datetime.timedelta(seconds=5))
        m.run_periodic_tasks(None)

        timeutils.advance_time_delta(datetime.timedelta(seconds=5))
        idle = m.run_periodic_tasks(None)
        self.assertAlmostEqual(10, idle, 1)

    def test_periodic_tasks_immediate_runs_now(self):
        fake_time = datetime.datetime(3000, 1, 1)
        timeutils.set_time_override(fake_time)

        class Manager(periodic_task.PeriodicTasks):

            @periodic_task.periodic_task(spacing=10, run_immediately=True)
            def bar(self, context):
                return 'bar'

        m = Manager()

        # Ensure initial values are correct
        self.assertEqual(1, len(m._periodic_tasks))
        task_name, task = m._periodic_tasks[0]

        # Test task values
        self.assertEqual('bar', task_name)
        self.assertEqual(10, task._periodic_spacing)
        self.assertEqual(True, task._periodic_enabled)
        self.assertEqual(False, task._periodic_external_ok)
        self.assertEqual(True, task._periodic_immediate)
        self.assertIsNone(task._periodic_last_run)

        # Test the manager's representation of those values
        self.assertEqual(10, m._periodic_spacing[task_name])
        self.assertIsNone(m._periodic_last_run[task_name])

        idle = m.run_periodic_tasks(None)
        self.assertEqual(datetime.datetime(3000, 1, 1, 0, 0),
                         m._periodic_last_run[task_name])
        self.assertAlmostEqual(10, idle, 1)

        timeutils.advance_time_delta(datetime.timedelta(seconds=5))
        idle = m.run_periodic_tasks(None)
        self.assertAlmostEqual(5, idle, 1)

    def test_periodic_tasks_disabled(self):
        class Manager(periodic_task.PeriodicTasks):

            @periodic_task.periodic_task(spacing=-1)
            def bar(self):
                return 'bar'

        m = Manager()
        idle = m.run_periodic_tasks(None)
        self.assertAlmostEqual(60, idle, 1)

    def test_external_running_here(self):
        self.config(run_external_periodic_tasks=True)

        class Manager(periodic_task.PeriodicTasks):

            @periodic_task.periodic_task(spacing=200, external_process_ok=True)
            def bar(self):
                return 'bar'

        m = Manager()
        self.assertThat(m._periodic_tasks, matchers.HasLength(1))

    def test_external_running_elsewhere(self):
        self.config(run_external_periodic_tasks=False)

        class Manager(periodic_task.PeriodicTasks):

            @periodic_task.periodic_task(spacing=200, external_process_ok=True)
            def bar(self):
                return 'bar'

        m = Manager()
        self.assertEqual([], m._periodic_tasks)
<|endoftext|>