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

"""
test_pypepa
----------------------------------

Tests for `pypepa` module.
"""

import unittest
import logging

from pypepa import pypepa
Action = pypepa.Action

simple_components = """
P = (a,1.0).P1;
P1 = (b, 1.0).P;

Q = (a,1.0).Q1;
Q1 = (b, 1.0).Q;
"""

simple_choice_component = """
P = (a, 1.0).P1 + (b, 1.0).P2;
P1 = (c, 1.0).P;
P2 = (d, 1.0).P;
"""

class TestModelBase(unittest.TestCase):
    """A simple couple of definitions with a system equation involving no
       cooperation. This also acts as a good base class to inherit from for
       testing a model. One needs only to override the model definition and
       the expected answers.
    """
    def setUp(self):
        self.model_source = simple_components + "\nP || Q"
        # It would be nice to actually test the parsing but that doesn't
        # seem to be possible.
        self.model = pypepa.parse_model(self.model_source)
        self.expected_used_process_names = set(["P", "P1", "Q", "Q1"])
        self.expected_defined_process_names = set(["P", "P1", "Q", "Q1"])

        self.expected_actions_dictionary = dict()
        self.expected_actions_dictionary["P"] = [ Action("a", 1.0, "P1") ]
        self.expected_actions_dictionary["P1" ] = [ Action ("b", 1.0, "P") ]
        self.expected_actions_dictionary["Q" ] = [ Action("a", 1.0, "Q1") ]
        self.expected_actions_dictionary["Q1" ] = [ Action("b", 1.0, "Q") ]

        self.expected_initial_state = [ "P", "Q" ]
        self.expected_state_space_size = 4

    def test_used_names(self):
        used_names = self.model.used_process_names()
        self.assertEqual(used_names, self.expected_used_process_names)

    def test_defined_names(self):
        defined_names = self.model.defined_process_names()
        self.assertEqual(defined_names, self.expected_defined_process_names)

    # TODO: Somehow test the correct parsing of coopertions (system equation)

    def test_actions(self):
        actual_actions = self.model.get_process_actions()
        self.assertEqual(actual_actions, self.expected_actions_dictionary)

    def test_initial_state(self):
        initial_state = self.model.get_initial_state()
        self.assertEqual(initial_state.local_states, self.expected_initial_state)

    def test_state_space_size(self):
        state_space = pypepa.build_state_space(self.model)
        self.assertEqual(len(state_space), self.expected_state_space_size)

class TestSimpleSingleCoop(TestModelBase):
    def setUp(self):
        # This model has most of the same results as the base test case
        # So I'll just call super here rather than copy and paste, but in
        # general it shouldn't be necessary to call super here.
        super(TestSimpleSingleCoop, self).setUp()
        self.model_source = simple_components + "\nP <a> Q"
        self.model = pypepa.parse_model(self.model_source)

class TestSimpleDoubleCoop(TestModelBase):
    def setUp(self):
        # Similar to the above case we're only using super here because we can
        # and so many of th expected results are the same.
        super(TestSimpleDoubleCoop, self).setUp()
        self.model_source = simple_components + "\nP <a, b> Q"
        self.model = pypepa.parse_model(self.model_source)
        self.expected_state_space_size = 2

class TestSimpleAlias(TestModelBase):
    def setUp(self):
        # Similar to the above case we're only using super here because we can
        # and so many of th expected results are the same.
        super(TestSimpleAlias, self).setUp()
        self.model_source = "A = P;\n" + simple_components + "\nP || Q"
        self.model = pypepa.parse_model(self.model_source)

        self.expected_defined_process_names.add("A")

        self.expected_actions_dictionary["A"] = self.expected_actions_dictionary["P"]

    # Note, if you expect everything to fail, you can decorate the class with
    # unittest.expectedFailure, however I prefer this as if you decorate the
    # entire class, then it is essentially the same as skipping the tests, that
    # is no report is given saying how many expected failures there were.
    @unittest.expectedFailure
    def test_actions(self):
        super(TestSimpleAlias, self).test_actions()

    @unittest.expectedFailure
    def test_state_space_size(self):
        super(TestSimpleAlias, self).test_state_space_size()

class TestSimpleChoice(TestModelBase):
    def setUp(self):
        self.model_source = simple_choice_component + "\nP"
        self.model = pypepa.parse_model(self.model_source)

        self.expected_used_process_names = set(["P", "P1", "P2"])
        self.expected_defined_process_names = self.expected_used_process_names

        self.expected_actions_dictionary = dict()
        self.expected_actions_dictionary["P"] = [ Action("a", 1.0, "P1"),
                                                  Action("b", 1.0, "P2") ]
        self.expected_actions_dictionary["P1" ] = [ Action("c", 1.0, "P") ]
        self.expected_actions_dictionary["P2" ] = [ Action("d", 1.0, "P") ]

        self.expected_initial_state = [ "P" ]
        self.expected_state_space_size = 3

class TestChoiceAlias(TestModelBase):
    def setUp(self):
        self.model_source = """P = P1 + P2;
                               P1 = (a, 1.0).P3;
                               P2 = (b, 1.0).P3;
                               P3 = (c, 1.0).P;
                               P
                            """
        self.model = pypepa.parse_model(self.model_source)

        self.expected_used_process_names = set(["P", "P1", "P2", "P3"])
        self.expected_defined_process_names = self.expected_used_process_names

        self.expected_actions_dictionary = dict()
        self.expected_actions_dictionary["P"] = [ Action("a", 1.0, "P3"),
                                                  Action("b", 1.0, "P3") ]
        self.expected_actions_dictionary["P1" ] = [ Action("a", 1.0, "P3") ]
        self.expected_actions_dictionary["P2" ] = [ Action("b", 1.0, "P3") ]
        self.expected_actions_dictionary["P3" ] = [ Action("c", 1.0, "P") ]

        self.expected_initial_state = [ "P" ]
        self.expected_state_space_size = 4

    @unittest.expectedFailure
    def test_actions(self):
        super(TestChoiceAlias, self).test_actions()

    @unittest.expectedFailure
    def test_state_space_size(self):
        super(TestChoiceAlias, self).test_state_space_size()

class TestPypepa(unittest.TestCase):
    """A simple test only because I'm not sure how to generically test the
       parsing of the system equation. Once I figure that out I can move this
       into TestModelBase
    """
    def test_cooperation_parser(self):
        model_source = simple_components + "\n P <a> P"
        model = pypepa.parse_model(model_source)
        self.assertEqual(model.system_equation.cooperation_set, ["a"])
        model_source = simple_components + "\nP || Q"
        model = pypepa.parse_model(model_source)
        self.assertEqual(model.system_equation.cooperation_set, [])
        model_source = simple_components + "\nP <a,b>Q"
        model = pypepa.parse_model(model_source)
        self.assertEqual(model.system_equation.cooperation_set, ["a", "b"])

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    unittest.main()
<commit_msg>A temporary test added to test the generation of the generator matrix. It's temporary as I have not integrated it with the all tests on a model approach yet. I will do once this feature is working for the first model.<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
test_pypepa
----------------------------------

Tests for `pypepa` module.
"""

import unittest
import logging

import numpy

from pypepa import pypepa
Action = pypepa.Action

simple_components = """
P = (a,1.0).P1;
P1 = (b, 1.0).P;

Q = (a,1.0).Q1;
Q1 = (b, 1.0).Q;
"""

simple_choice_component = """
P = (a, 1.0).P1 + (b, 1.0).P2;
P1 = (c, 1.0).P;
P2 = (d, 1.0).P;
"""

class TestModelBase(unittest.TestCase):
    """A simple couple of definitions with a system equation involving no
       cooperation. This also acts as a good base class to inherit from for
       testing a model. One needs only to override the model definition and
       the expected answers.
    """
    def setUp(self):
        self.model_source = simple_components + "\nP || Q"
        # It would be nice to actually test the parsing but that doesn't
        # seem to be possible.
        self.model = pypepa.parse_model(self.model_source)
        self.expected_used_process_names = set(["P", "P1", "Q", "Q1"])
        self.expected_defined_process_names = set(["P", "P1", "Q", "Q1"])

        self.expected_actions_dictionary = dict()
        self.expected_actions_dictionary["P"] = [ Action("a", 1.0, "P1") ]
        self.expected_actions_dictionary["P1" ] = [ Action ("b", 1.0, "P") ]
        self.expected_actions_dictionary["Q" ] = [ Action("a", 1.0, "Q1") ]
        self.expected_actions_dictionary["Q1" ] = [ Action("b", 1.0, "Q") ]

        self.expected_initial_state = [ "P", "Q" ]
        self.expected_state_space_size = 4

    def test_used_names(self):
        used_names = self.model.used_process_names()
        self.assertEqual(used_names, self.expected_used_process_names)

    def test_defined_names(self):
        defined_names = self.model.defined_process_names()
        self.assertEqual(defined_names, self.expected_defined_process_names)

    # TODO: Somehow test the correct parsing of coopertions (system equation)

    def test_actions(self):
        actual_actions = self.model.get_process_actions()
        self.assertEqual(actual_actions, self.expected_actions_dictionary)

    def test_initial_state(self):
        initial_state = self.model.get_initial_state()
        self.assertEqual(initial_state.local_states, self.expected_initial_state)

    def test_state_space_size(self):
        state_space = pypepa.build_state_space(self.model)
        self.assertEqual(len(state_space), self.expected_state_space_size)

class TestGenMatrix(unittest.TestCase):
    def setUp(self):
        self.model_source = simple_components + "\nP || Q"
    def test_build_matrix(self):
        expected_gen_matrix = numpy.zeros((4,4), dtype=numpy.float64)

        expected_gen_matrix[0,1] = 1.0
        expected_gen_matrix[0,2] = 1.0
        expected_gen_matrix[0,0] = -2.0

        expected_gen_matrix[1,0] = 1.0
        expected_gen_matrix[1,3] = 1.0
        expected_gen_matrix[1,1] = -2.0

        expected_gen_matrix[2,0] = 1.0
        expected_gen_matrix[2,3] = 1.0
        expected_gen_matrix[2,2] = -2.0

        expected_gen_matrix[3,1] = 1.0
        expected_gen_matrix[3,2] = 1.0
        expected_gen_matrix[3,3] = -2.0

        self.model = pypepa.parse_model(self.model_source)
        state_space = pypepa.build_state_space(self.model)
        gen_matrix  = pypepa.get_generator_matrix(state_space)
        self.assertEqual(expected_gen_matrix, gen_matrix)

class TestSimpleSingleCoop(TestModelBase):
    def setUp(self):
        # This model has most of the same results as the base test case
        # So I'll just call super here rather than copy and paste, but in
        # general it shouldn't be necessary to call super here.
        super(TestSimpleSingleCoop, self).setUp()
        self.model_source = simple_components + "\nP <a> Q"
        self.model = pypepa.parse_model(self.model_source)

class TestSimpleDoubleCoop(TestModelBase):
    def setUp(self):
        # Similar to the above case we're only using super here because we can
        # and so many of th expected results are the same.
        super(TestSimpleDoubleCoop, self).setUp()
        self.model_source = simple_components + "\nP <a, b> Q"
        self.model = pypepa.parse_model(self.model_source)
        self.expected_state_space_size = 2

class TestSimpleAlias(TestModelBase):
    def setUp(self):
        # Similar to the above case we're only using super here because we can
        # and so many of th expected results are the same.
        super(TestSimpleAlias, self).setUp()
        self.model_source = "A = P;\n" + simple_components + "\nP || Q"
        self.model = pypepa.parse_model(self.model_source)

        self.expected_defined_process_names.add("A")

        self.expected_actions_dictionary["A"] = self.expected_actions_dictionary["P"]

    # Note, if you expect everything to fail, you can decorate the class with
    # unittest.expectedFailure, however I prefer this as if you decorate the
    # entire class, then it is essentially the same as skipping the tests, that
    # is no report is given saying how many expected failures there were.
    @unittest.expectedFailure
    def test_actions(self):
        super(TestSimpleAlias, self).test_actions()

    @unittest.expectedFailure
    def test_state_space_size(self):
        super(TestSimpleAlias, self).test_state_space_size()

class TestSimpleChoice(TestModelBase):
    def setUp(self):
        self.model_source = simple_choice_component + "\nP"
        self.model = pypepa.parse_model(self.model_source)

        self.expected_used_process_names = set(["P", "P1", "P2"])
        self.expected_defined_process_names = self.expected_used_process_names

        self.expected_actions_dictionary = dict()
        self.expected_actions_dictionary["P"] = [ Action("a", 1.0, "P1"),
                                                  Action("b", 1.0, "P2") ]
        self.expected_actions_dictionary["P1" ] = [ Action("c", 1.0, "P") ]
        self.expected_actions_dictionary["P2" ] = [ Action("d", 1.0, "P") ]

        self.expected_initial_state = [ "P" ]
        self.expected_state_space_size = 3

class TestChoiceAlias(TestModelBase):
    def setUp(self):
        self.model_source = """P = P1 + P2;
                               P1 = (a, 1.0).P3;
                               P2 = (b, 1.0).P3;
                               P3 = (c, 1.0).P;
                               P
                            """
        self.model = pypepa.parse_model(self.model_source)

        self.expected_used_process_names = set(["P", "P1", "P2", "P3"])
        self.expected_defined_process_names = self.expected_used_process_names

        self.expected_actions_dictionary = dict()
        self.expected_actions_dictionary["P"] = [ Action("a", 1.0, "P3"),
                                                  Action("b", 1.0, "P3") ]
        self.expected_actions_dictionary["P1" ] = [ Action("a", 1.0, "P3") ]
        self.expected_actions_dictionary["P2" ] = [ Action("b", 1.0, "P3") ]
        self.expected_actions_dictionary["P3" ] = [ Action("c", 1.0, "P") ]

        self.expected_initial_state = [ "P" ]
        self.expected_state_space_size = 4

    @unittest.expectedFailure
    def test_actions(self):
        super(TestChoiceAlias, self).test_actions()

    @unittest.expectedFailure
    def test_state_space_size(self):
        super(TestChoiceAlias, self).test_state_space_size()

class TestPypepa(unittest.TestCase):
    """A simple test only because I'm not sure how to generically test the
       parsing of the system equation. Once I figure that out I can move this
       into TestModelBase
    """
    def test_cooperation_parser(self):
        model_source = simple_components + "\n P <a> P"
        model = pypepa.parse_model(model_source)
        self.assertEqual(model.system_equation.cooperation_set, ["a"])
        model_source = simple_components + "\nP || Q"
        model = pypepa.parse_model(model_source)
        self.assertEqual(model.system_equation.cooperation_set, [])
        model_source = simple_components + "\nP <a,b>Q"
        model = pypepa.parse_model(model_source)
        self.assertEqual(model.system_equation.cooperation_set, ["a", "b"])

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    unittest.main()
<|endoftext|>


<commit_before># encoding: utf-8
from __future__ import unicode_literals

from random import choice
import time
import pickle
import json

from twitter import Twitter, NoAuth, OAuth, read_token_file, TwitterHTTPError
from twitter.api import TwitterDictResponse, TwitterListResponse
from twitter.cmdline import CONSUMER_KEY, CONSUMER_SECRET

noauth = NoAuth()
oauth = OAuth(*read_token_file('tests/oauth_creds')
              + (CONSUMER_KEY, CONSUMER_SECRET))

twitter11 = Twitter(domain='api.twitter.com',
                    auth=oauth,
                    api_version='1.1')

twitter11_na = Twitter(domain='api.twitter.com',
                       auth=noauth,
                       api_version='1.1')

AZaz = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"

def get_random_str():
    return ''.join(choice(AZaz) for _ in range(10))

def test_API_set_tweet():
    random_tweet = "A random tweet " + get_random_str()
    twitter11.statuses.update(status=random_tweet)
    time.sleep(5)
    recent = twitter11.statuses.home_timeline()
    assert recent
    assert isinstance(recent.rate_limit_remaining, int)
    assert isinstance(recent.rate_limit_reset, int)
    texts = [tweet['text'] for tweet in recent]
    assert random_tweet in texts

def test_API_set_unicode_tweet():
    random_tweet = "A random tweet with unicode üøπ" + get_random_str()
    twitter11.statuses.update(status=random_tweet)
    time.sleep(5)
    recent = twitter11.statuses.home_timeline()
    assert recent
    texts = [tweet['text'] for tweet in recent]
    assert random_tweet in texts

def test_search():
    # In 1.1, search works on api.twitter.com not search.twitter.com
    # and requires authorisation
    results = twitter11.search.tweets(q='foo')
    assert results

def test_get_trends():
    # This is one method of inserting parameters, using named
    # underscore params.
    world_trends = twitter11.trends.available(_woeid=1)
    assert world_trends

def test_get_trends_2():
    # This is a nicer variation of the same call as above.
    world_trends = twitter11.trends._(1)
    assert world_trends

def test_get_trends_3():
    # Of course they broke it all again in 1.1...
    assert twitter11.trends.place(_id=1)

def test_TwitterHTTPError_raised_for_invalid_oauth():
    test_passed = False
    try:
        twitter11_na.statuses.mentions_timeline()
    except TwitterHTTPError:
        # this is the error we are looking for :)
        test_passed = True
    assert test_passed

def test_picklability():
    res = TwitterDictResponse({'a': 'b'})
    p = pickle.dumps(res)
    res2 = pickle.loads(p)
    assert res == res2
    assert res2['a'] == 'b'

    res = TwitterListResponse([1, 2, 3])
    p = pickle.dumps(res)
    res2 = pickle.loads(p)
    assert res == res2
    assert res2[2] == 3

def test_jsonifability():
    res = TwitterDictResponse({'a': 'b'})
    p = json.dumps(res)
    res2 = json.loads(p)
    assert res == res2
    assert res2['a'] == 'b'

    res = TwitterListResponse([1, 2, 3])
    p = json.dumps(res)
    res2 = json.loads(p)
    assert res == res2
    assert res2[2] == 3
<commit_msg>add tests for update_with_media api function<commit_after># encoding: utf-8
from __future__ import unicode_literals

import os
from random import choice
import time
import pickle
import json

from twitter import Twitter, NoAuth, OAuth, read_token_file, TwitterHTTPError
from twitter.api import TwitterDictResponse, TwitterListResponse
from twitter.cmdline import CONSUMER_KEY, CONSUMER_SECRET

noauth = NoAuth()
oauth = OAuth(*read_token_file('tests/oauth_creds')
              + (CONSUMER_KEY, CONSUMER_SECRET))

twitter11 = Twitter(domain='api.twitter.com',
                    auth=oauth,
                    api_version='1.1')

twitter11_na = Twitter(domain='api.twitter.com',
                       auth=noauth,
                       api_version='1.1')

AZaz = "abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"

def get_random_str():
    return ''.join(choice(AZaz) for _ in range(10))

def test_API_set_tweet():
    random_tweet = "A random tweet " + get_random_str()
    twitter11.statuses.update(status=random_tweet)
    time.sleep(5)
    recent = twitter11.statuses.home_timeline()
    assert recent
    assert isinstance(recent.rate_limit_remaining, int)
    assert isinstance(recent.rate_limit_reset, int)
    texts = [tweet['text'] for tweet in recent]
    assert random_tweet in texts

def test_API_set_unicode_tweet():
    random_tweet = "A random tweet with unicode üøπ" + get_random_str()
    twitter11.statuses.update(status=random_tweet)
    time.sleep(5)
    recent = twitter11.statuses.home_timeline()
    assert recent
    texts = [tweet['text'] for tweet in recent]
    assert random_tweet in texts

def clean_link(text):
    pos = text.find(" http://t.co")
    if pos != -1:
        return text[:pos]
    return text

__location__ = os.path.realpath(
    os.path.join(os.getcwd(), os.path.dirname(__file__)))

def test_API_set_unicode_twitpic(base64=False):
    random_tweet = "A random twitpic from %s with unicode üøπ" % \
                    ("base64" if base64 else "file") + get_random_str()
    if base64:
        img = b"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB94JFhMBAJv5kaUAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAA4UlEQVQoz7WSIZLGIAxG6c5OFZjianBcIOfgPkju1DsEBWfAUEcNGGpY8Xe7dDoVFRvHfO8NJGRorZE39UVe1nd/WNfVObcsi3OOEAIASikAmOf5D2q/FWPUWgshKKWfiFIqhNBaxxhPjPQ05/z+Bs557xw9hBC89ymlu5BS8t6HEC5NW2sR8alRRLTWXoRSSinlSejT12M9BAAAgCeoTw9BSimlfBIu6WdYtVZEVErdaaUUItZaL/9wOsaY83YAMMb0dGtt6Jdv3/ec87ZtOWdCCGNsmibG2DiOJzP8+7b+AAOmsiPxyHWCAAAAAElFTkSuQmCC"
    else:
        with open(os.path.join(__location__, "test.png"), "rb") as f:
            img = f.read()
    params = {"status": random_tweet, "media[]": img}
    if base64:
        params["_base64"] = True
    twitter11.statuses.update_with_media(**params)
    time.sleep(5)
    recent = twitter11.statuses.home_timeline()
    assert recent
    texts = [clean_link(tweet['text']) for tweet in recent]
    assert random_tweet in texts

def test_API_set_unicode_twitpic_base64():
    test_API_set_unicode_twitpic(base64=True)

def test_search():
    # In 1.1, search works on api.twitter.com not search.twitter.com
    # and requires authorisation
    results = twitter11.search.tweets(q='foo')
    assert results

def test_get_trends():
    # This is one method of inserting parameters, using named
    # underscore params.
    world_trends = twitter11.trends.available(_woeid=1)
    assert world_trends

def test_get_trends_2():
    # This is a nicer variation of the same call as above.
    world_trends = twitter11.trends._(1)
    assert world_trends

def test_get_trends_3():
    # Of course they broke it all again in 1.1...
    assert twitter11.trends.place(_id=1)

def test_TwitterHTTPError_raised_for_invalid_oauth():
    test_passed = False
    try:
        twitter11_na.statuses.mentions_timeline()
    except TwitterHTTPError:
        # this is the error we are looking for :)
        test_passed = True
    assert test_passed

def test_picklability():
    res = TwitterDictResponse({'a': 'b'})
    p = pickle.dumps(res)
    res2 = pickle.loads(p)
    assert res == res2
    assert res2['a'] == 'b'

    res = TwitterListResponse([1, 2, 3])
    p = pickle.dumps(res)
    res2 = pickle.loads(p)
    assert res == res2
    assert res2[2] == 3

def test_jsonifability():
    res = TwitterDictResponse({'a': 'b'})
    p = json.dumps(res)
    res2 = json.loads(p)
    assert res == res2
    assert res2['a'] == 'b'

    res = TwitterListResponse([1, 2, 3])
    p = json.dumps(res)
    res2 = json.loads(p)
    assert res == res2
    assert res2[2] == 3
<|endoftext|>


<commit_before>from __future__ import absolute_import

import sys
from nose import SkipTest
from flask import Flask
from flask.ext.assets import Environment, ManageAssets
from webassets.script import GenericArgparseImplementation
from tests.helpers import TempEnvironmentHelper

# Flask-script seemingly no longer supports 2.6
if sys.version_info[:2] == (2, 6):
    raise SkipTest()

try:
    from flask.ext.script import Manager
except:
    raise SkipTest()

# The CLI likes to log to stderr, which isn't nice to the test output.
import logging
stdout_log = logging.getLogger(__name__)
stdout_log.addHandler(logging.StreamHandler(sys.stdout))

class TestScript(TempEnvironmentHelper):

    def test_call(self):
        # Setup the webassets.script with a mock main() function,
        # so we can check whether our call via Flask-Script actually
        # goes through.
        test_inst = self
        class DummyArgparseImplementation(GenericArgparseImplementation):
            def run_with_argv(self, argv):
                test_inst.last_script_call = argv
                return 0

        mgmt = Manager(self.app)
        mgmt.add_command('assets',
                ManageAssets(self.env, impl=DummyArgparseImplementation))

        try:
            # -h is a great test as that is something Flask-Script might
            # want to claim for itself.
            sys.argv = ['./manage.py', 'assets', '-h']
            mgmt.run()
        except SystemExit:
            # Always raised, regardless of success or failure of command
            pass
        assert self.last_script_call == ['-h']

    def test_call_auto_env(self):
        """Regression test: Passing the environment to the ManageAssets command
        is optional, it can be auto-detected."""
        mgmt = Manager(self.app)
        mgmt.add_command('assets', ManageAssets())

        try:
            # Used to raise an error due to the env not being properly set.
            sys.argv = ['./manage.py', 'assets', 'build']
            mgmt.run()
        except SystemExit:
            # Always raised, regardless of success or failure of command
            pass

    def test_parse_templates(self):
        """Test the --parse-templates option.
        """
        # Create a file in the app's templates directory
        self.app.template_folder = self.path('templates')
        self.create_files({
            'templates/template.html': """
            {% assets "in", output="output" %}
                {{ ASSET_URL }}
            {% endassets %}
            """,
            'in': "foo"
        })

        # Run the build command with --parse-templates, which should pick
        # up the bundle we defined in above template.
        mgmt = Manager(self.app)
        mgmt.add_command('assets', ManageAssets(log=stdout_log))
        mgmt.handle('test', ['assets', '--parse-templates', 'build'])

        assert self.exists('output')

<commit_msg>Move check for flask-script before importing ManageAssets<commit_after>from __future__ import absolute_import

from nose import SkipTest

# check for flask-script before importing things that fail if it's not present
try:
    from flask.ext.script import Manager
except:
    raise SkipTest()

import sys
from flask import Flask
from flask.ext.assets import Environment, ManageAssets
from webassets.script import GenericArgparseImplementation
from tests.helpers import TempEnvironmentHelper

# Flask-script seemingly no longer supports 2.6
if sys.version_info[:2] == (2, 6):
    raise SkipTest()

# The CLI likes to log to stderr, which isn't nice to the test output.
import logging
stdout_log = logging.getLogger(__name__)
stdout_log.addHandler(logging.StreamHandler(sys.stdout))

class TestScript(TempEnvironmentHelper):

    def test_call(self):
        # Setup the webassets.script with a mock main() function,
        # so we can check whether our call via Flask-Script actually
        # goes through.
        test_inst = self
        class DummyArgparseImplementation(GenericArgparseImplementation):
            def run_with_argv(self, argv):
                test_inst.last_script_call = argv
                return 0

        mgmt = Manager(self.app)
        mgmt.add_command('assets',
                ManageAssets(self.env, impl=DummyArgparseImplementation))

        try:
            # -h is a great test as that is something Flask-Script might
            # want to claim for itself.
            sys.argv = ['./manage.py', 'assets', '-h']
            mgmt.run()
        except SystemExit:
            # Always raised, regardless of success or failure of command
            pass
        assert self.last_script_call == ['-h']

    def test_call_auto_env(self):
        """Regression test: Passing the environment to the ManageAssets command
        is optional, it can be auto-detected."""
        mgmt = Manager(self.app)
        mgmt.add_command('assets', ManageAssets())

        try:
            # Used to raise an error due to the env not being properly set.
            sys.argv = ['./manage.py', 'assets', 'build']
            mgmt.run()
        except SystemExit:
            # Always raised, regardless of success or failure of command
            pass

    def test_parse_templates(self):
        """Test the --parse-templates option.
        """
        # Create a file in the app's templates directory
        self.app.template_folder = self.path('templates')
        self.create_files({
            'templates/template.html': """
            {% assets "in", output="output" %}
                {{ ASSET_URL }}
            {% endassets %}
            """,
            'in': "foo"
        })

        # Run the build command with --parse-templates, which should pick
        # up the bundle we defined in above template.
        mgmt = Manager(self.app)
        mgmt.add_command('assets', ManageAssets(log=stdout_log))
        mgmt.handle('test', ['assets', '--parse-templates', 'build'])

        assert self.exists('output')

<|endoftext|>


<commit_before>import pdir

def test_search_without_argument():
    dadada = 1
    cadada = 1
    vadada = 1
    apple1 = 1
    xapple2 = 1
    result, result2 = pdir().s('apple'), pdir().search('apple')
    assert repr(result) == (
        '\x1b[0;33mother:\x1b[0;m\n'
        '    \x1b[0;36mapple1\x1b[0;m\x1b[1;30m,'
        ' \x1b[0;m\x1b[0;36mxapple2\x1b[0;m')
    assert repr(result2) == (
        '\x1b[0;33mother:\x1b[0;m\n'
        '    \x1b[0;36mapple1\x1b[0;m\x1b[1;30m,'
        ' \x1b[0;m\x1b[0;36mxapple2\x1b[0;m')

def test_search_with_argument():
    class T(object):
        pass

    result, result2 = pdir(T).s('attr'), pdir(T).search('attr')
    assert repr(result) == '\n'.join([
        '\x1b[0;33mattribute access:\x1b[0;m', (
            '    \x1b[0;36m__delattr__\x1b[0;m\x1b[1;30m, '
            '\x1b[0;m\x1b[0;36m__getattribute__\x1b[0;m\x1b[1;30m, '
            '\x1b[0;m\x1b[0;36m__setattr__\x1b[0;m')])
    assert repr(result2) == '\n'.join([
        '\x1b[0;33mattribute access:\x1b[0;m', (
            '    \x1b[0;36m__delattr__\x1b[0;m\x1b[1;30m, '
            '\x1b[0;m\x1b[0;36m__getattribute__\x1b[0;m\x1b[1;30m, '
            '\x1b[0;m\x1b[0;36m__setattr__\x1b[0;m')])
<commit_msg>updated tests<commit_after>import pdir

def test_search_without_argument():
    dadada = 1
    cadada = 1
    vadada = 1
    apple1 = 1
    xapple2 = 1
    result, result2 = pdir().s('apple'), pdir().search('apple')
    assert repr(result) == (
        '\x1b[0;33mother:\x1b[0;m\n'
        '    \x1b[0;36mapple1\x1b[0;m\x1b[1;30m,'
        ' \x1b[0;m\x1b[0;36mxapple2\x1b[0;m')
    assert repr(result2) == (
        '\x1b[0;33mother:\x1b[0;m\n'
        '    \x1b[0;36mapple1\x1b[0;m\x1b[1;30m,'
        ' \x1b[0;m\x1b[0;36mxapple2\x1b[0;m')

def test_search_with_argument():
    class T(object):
        pass

    result, result2 = pdir(T).s('attr'), pdir(T).search('attr')
    result3, result4 = pdir(T).s('Attr'), pdir(T).search('Attr')
    expected = '\n'.join([
        '\x1b[0;33mattribute access:\x1b[0;m', (
            '    \x1b[0;36m__delattr__\x1b[0;m\x1b[1;30m, '
            '\x1b[0;m\x1b[0;36m__getattribute__\x1b[0;m\x1b[1;30m, '
            '\x1b[0;m\x1b[0;36m__setattr__\x1b[0;m')])
    assert repr(result) == expected
    assert repr(result2) == expected
    assert repr(result3) == expected
    assert repr(result4) == expected

    # Case sensitive
    result5, result6 = pdir(T).s('Attr', True), pdir(T).search('Attr', True)
    assert repr(result5) == ''
    assert repr(result6) == ''
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
import re
import time

import pytest
from PIL import Image, ImageStat
from plexapi.exceptions import BadRequest, NotFound
from plexapi.server import PlexServer
from plexapi.utils import download
from requests import Session

from . import conftest as utils

def test_server_attr(plex, account):
    assert plex._baseurl == utils.SERVER_BASEURL
    assert len(plex.friendlyName) >= 1
    assert len(plex.machineIdentifier) == 40
    assert plex.myPlex is True
    # if you run the tests very shortly after server creation the state in rare cases may be `unknown`
    assert plex.myPlexMappingState in ("mapped", "unknown")
    assert plex.myPlexSigninState == "ok"
    assert utils.is_int(plex.myPlexSubscription, gte=0)
    assert re.match(utils.REGEX_EMAIL, plex.myPlexUsername)
    assert plex.platform in ("Linux", "Windows")
    assert len(plex.platformVersion) >= 5
    assert plex._token == account.authenticationToken
    assert utils.is_int(plex.transcoderActiveVideoSessions, gte=0)
    assert utils.is_datetime(plex.updatedAt)
    assert len(plex.version) >= 5

def test_server_alert_listener(plex, movies):
    try:
        messages = []
        listener = plex.startAlertListener(messages.append)
        movies.refresh()
        utils.wait_until(lambda: len(messages) >= 3, delay=1, timeout=30)
        assert len(messages) >= 3
    finally:
        listener.stop()

@pytest.mark.req_client
def test_server_session():
    # TODO: Implement test_server_session
    pass

def test_server_library(plex):
    # TODO: Implement test_server_library
    assert plex.library

def test_server_url(plex):
    assert "ohno" in plex.url("ohno")

def test_server_transcodeImage(tmpdir, plex, show):
    width, height = 500, 500
    imgurl = plex.transcodeImage(show.banner, height, width)
    gray = imgurl = plex.transcodeImage(show.banner, height, width, saturation=0)
    resized_img = download(
        imgurl, plex._token, savepath=str(tmpdir), filename="resize_image"
    )
    original_img = download(
        show._server.url(show.banner),
        plex._token,
        savepath=str(tmpdir),
        filename="original_img",
    )
    grayscale_img = download(
        gray, plex._token, savepath=str(tmpdir), filename="grayscale_img"
    )
    with Image.open(resized_img) as image:
        assert width, height == image.size
    with Image.open(original_img) as image:
        assert width, height != image.size
    assert _detect_color_image(grayscale_img, thumb_size=150) == "grayscale"

def _detect_color_image(file, thumb_size=150, MSE_cutoff=22, adjust_color_bias=True):
    # http://stackoverflow.com/questions/20068945/detect-if-image-is-color-grayscale-or-black-and-white-with-python-pil
    pilimg = Image.open(file)
    bands = pilimg.getbands()
    if bands == ("R", "G", "B") or bands == ("R", "G", "B", "A"):
        thumb = pilimg.resize((thumb_size, thumb_size))
        sse, bias = 0, [0, 0, 0]
        if adjust_color_bias:
            bias = ImageStat.Stat(thumb).mean[:3]
            bias = [b - sum(bias) / 3 for b in bias]
        for pixel in thumb.getdata():
            mu = sum(pixel) / 3
            sse += sum(
                (pixel[i] - mu - bias[i]) * (pixel[i] - mu - bias[i]) for i in [0, 1, 2]
            )
        mse = float(sse) / (thumb_size * thumb_size)
        return "grayscale" if mse <= MSE_cutoff else "color"
    elif len(bands) == 1:
        return "blackandwhite"

def test_server_fetchitem_notfound(plex):
    with pytest.raises(NotFound):
        plex.fetchItem(123456789)

def test_server_search(plex, movie):
    title = movie.title
    #  this search seem to fail on my computer but not at travis, wtf.
    assert plex.search(title)
    assert plex.search(title, mediatype="movie")

def test_server_playlist(plex, show):
    episodes = show.episodes()
    playlist = plex.createPlaylist("test_playlist", episodes[:3])
    try:
        assert playlist.title == "test_playlist"
        with pytest.raises(NotFound):
            plex.playlist("<playlist-not-found>")
    finally:
        playlist.delete()

def test_server_playlists(plex, show):
    playlists = plex.playlists()
    count = len(playlists)
    episodes = show.episodes()
    playlist = plex.createPlaylist("test_playlist", episodes[:3])
    try:
        playlists = plex.playlists()
        assert len(playlists) == count + 1
    finally:
        playlist.delete()

def test_server_history(plex, movie):
    movie.markWatched()
    history = plex.history()
    assert len(history)
    movie.markUnwatched()

def test_server_Server_query(plex):
    assert plex.query("/")
    with pytest.raises(NotFound):
        assert plex.query("/asdf/1234/asdf", headers={"random_headers": "1234"})

def test_server_Server_session(account):
    # Mock Sesstion
    class MySession(Session):
        def __init__(self):
            super(self.__class__, self).__init__()
            self.plexapi_session_test = True

    # Test Code
    plex = PlexServer(
        utils.SERVER_BASEURL, account.authenticationToken, session=MySession()
    )
    assert hasattr(plex._session, "plexapi_session_test")

@pytest.mark.authenticated
def test_server_token_in_headers(plex):
    headers = plex._headers()
    assert "X-Plex-Token" in headers
    assert len(headers["X-Plex-Token"]) >= 1

def test_server_createPlayQueue(plex, movie):
    playqueue = plex.createPlayQueue(movie, shuffle=1, repeat=1)
    assert "shuffle=1" in playqueue._initpath
    assert "repeat=1" in playqueue._initpath
    assert playqueue.playQueueShuffled is True

def test_server_client_not_found(plex):
    with pytest.raises(NotFound):
        plex.client("<This-client-should-not-be-found>")

def test_server_sessions(plex):
    assert len(plex.sessions()) >= 0

def test_server_isLatest(plex, mocker):
    from os import environ

    is_latest = plex.isLatest()
    if environ.get("PLEX_CONTAINER_TAG") and environ["PLEX_CONTAINER_TAG"] != "latest":
        assert not is_latest
    else:
        return pytest.skip(
            "Do not forget to run with PLEX_CONTAINER_TAG != latest to ensure that update is available"
        )

def test_server_installUpdate(plex, mocker):
    m = mocker.MagicMock(release="aa")
    with utils.patch('plexapi.server.PlexServer.check_for_update', return_value=m):
        with utils.callable_http_patch():
            plex.installUpdate()

def test_server_check_for_update(plex, mocker):
    class R:
        def __init__(self, **kwargs):
            self.download_key = "plex.tv/release/1337"
            self.version = "1337"
            self.added = "gpu transcode"
            self.fixed = "fixed rare bug"
            self.downloadURL = "http://path-to-update"
            self.state = "downloaded"

    with utils.patch('plexapi.server.PlexServer.check_for_update', return_value=R()):
        rel = plex.check_for_update(force=False, download=True)
        assert rel.download_key == "plex.tv/release/1337"
        assert rel.version == "1337"
        assert rel.added == "gpu transcode"
        assert rel.fixed == "fixed rare bug"
        assert rel.downloadURL == "http://path-to-update"
        assert rel.state == "downloaded"

@pytest.mark.client
def test_server_clients(plex):
    assert len(plex.clients())
    client = plex.clients()[0]
    assert client._baseurl == utils.CLIENT_BASEURL
    assert client._server._baseurl == utils.SERVER_BASEURL
    assert client.protocol == 'plex'
    assert int(client.protocolVersion) in range(4)
    assert isinstance(client.machineIdentifier, str)
    assert client.deviceClass in ['phone', 'tablet', 'stb', 'tv', 'pc']
    assert set(client.protocolCapabilities).issubset({'timeline', 'playback', 'navigation', 'mirror', 'playqueues'})

@pytest.mark.authenticated
def test_server_account(plex):
    account = plex.account()
    assert account.authToken
    # TODO: Figure out why this is missing from time to time.
    # assert account.mappingError == 'publisherror'
    assert account.mappingErrorMessage is None
    assert account.mappingState == "mapped"
    if account.mappingError != "unreachable":
        if account.privateAddress is not None:
            assert re.match(utils.REGEX_IPADDR, account.privateAddress)
        assert int(account.privatePort) >= 1000
        assert re.match(utils.REGEX_IPADDR, account.publicAddress)
        assert int(account.publicPort) >= 1000
    else:
        assert account.privateAddress == ""
        assert int(account.privatePort) == 0
        assert account.publicAddress == ""
        assert int(account.publicPort) == 0
    assert account.signInState == "ok"
    assert isinstance(account.subscriptionActive, bool)
    if account.subscriptionActive:
        assert len(account.subscriptionFeatures)
    # Below check keeps failing.. it should go away.
    # else: assert sorted(account.subscriptionFeatures) == ['adaptive_bitrate',
    #     'download_certificates', 'federated-auth', 'news']
    assert (
        account.subscriptionState == "Active"
        if account.subscriptionActive
        else "Unknown"
    )
    assert re.match(utils.REGEX_EMAIL, account.username)

def test_server_downloadLogs(tmpdir, plex):
    plex.downloadLogs(savepath=str(tmpdir), unpack=True)
    assert len(tmpdir.listdir()) > 1

def test_server_downloadDatabases(tmpdir, plex):
    plex.downloadDatabases(savepath=str(tmpdir), unpack=True)
    assert len(tmpdir.listdir()) > 1

def test_server_allowMediaDeletion(account):
    plex = PlexServer(utils.SERVER_BASEURL, account.authenticationToken)
    # Check server current allowMediaDeletion setting
    if plex.allowMediaDeletion:
        # If allowed then test disallowed
        plex._allowMediaDeletion(False)
        time.sleep(1)
        plex = PlexServer(utils.SERVER_BASEURL, account.authenticationToken)
        assert plex.allowMediaDeletion is None
        # Test redundant toggle
        with pytest.raises(BadRequest):
            plex._allowMediaDeletion(False)

        plex._allowMediaDeletion(True)
        time.sleep(1)
        plex = PlexServer(utils.SERVER_BASEURL, account.authenticationToken)
        assert plex.allowMediaDeletion is True
        # Test redundant toggle
        with pytest.raises(BadRequest):
            plex._allowMediaDeletion(True)
    else:
        # If disallowed then test allowed
        plex._allowMediaDeletion(True)
        time.sleep(1)
        plex = PlexServer(utils.SERVER_BASEURL, account.authenticationToken)
        assert plex.allowMediaDeletion is True
        # Test redundant toggle
        with pytest.raises(BadRequest):
            plex._allowMediaDeletion(True)

        plex._allowMediaDeletion(False)
        time.sleep(1)
        plex = PlexServer(utils.SERVER_BASEURL, account.authenticationToken)
        assert plex.allowMediaDeletion is None
        # Test redundant toggle
        with pytest.raises(BadRequest):
            plex._allowMediaDeletion(False)
<commit_msg>Update test_server.py<commit_after># -*- coding: utf-8 -*-
import re
import time

import pytest
from PIL import Image, ImageStat
from plexapi.exceptions import BadRequest, NotFound
from plexapi.server import PlexServer
from plexapi.utils import download
from requests import Session

from . import conftest as utils

def test_server_attr(plex, account):
    assert plex._baseurl == utils.SERVER_BASEURL
    assert len(plex.friendlyName) >= 1
    assert len(plex.machineIdentifier) == 40
    assert plex.myPlex is True
    # if you run the tests very shortly after server creation the state in rare cases may be `unknown`
    assert plex.myPlexMappingState in ("mapped", "unknown")
    assert plex.myPlexSigninState == "ok"
    assert utils.is_int(plex.myPlexSubscription, gte=0)
    assert re.match(utils.REGEX_EMAIL, plex.myPlexUsername)
    assert plex.platform in ("Linux", "Windows")
    assert len(plex.platformVersion) >= 5
    assert plex._token == account.authenticationToken
    assert utils.is_int(plex.transcoderActiveVideoSessions, gte=0)
    assert utils.is_datetime(plex.updatedAt)
    assert len(plex.version) >= 5

def test_server_alert_listener(plex, movies):
    try:
        messages = []
        listener = plex.startAlertListener(messages.append)
        movies.refresh()
        utils.wait_until(lambda: len(messages) >= 3, delay=1, timeout=30)
        assert len(messages) >= 3
    finally:
        listener.stop()

@pytest.mark.req_client
def test_server_session():
    # TODO: Implement test_server_session
    pass

def test_server_library(plex):
    # TODO: Implement test_server_library
    assert plex.library

def test_server_url(plex):
    assert "ohno" in plex.url("ohno")

def test_server_transcodeImage(tmpdir, plex, show):
    width, height = 500, 500
    imgurl = plex.transcodeImage(show.banner, height, width)
    gray = imgurl = plex.transcodeImage(show.banner, height, width, saturation=0)
    resized_img = download(
        imgurl, plex._token, savepath=str(tmpdir), filename="resize_image"
    )
    original_img = download(
        show._server.url(show.banner),
        plex._token,
        savepath=str(tmpdir),
        filename="original_img",
    )
    grayscale_img = download(
        gray, plex._token, savepath=str(tmpdir), filename="grayscale_img"
    )
    with Image.open(resized_img) as image:
        assert width, height == image.size
    with Image.open(original_img) as image:
        assert width, height != image.size
    assert _detect_color_image(grayscale_img, thumb_size=150) == "grayscale"

def _detect_color_image(file, thumb_size=150, MSE_cutoff=22, adjust_color_bias=True):
    # http://stackoverflow.com/questions/20068945/detect-if-image-is-color-grayscale-or-black-and-white-with-python-pil
    pilimg = Image.open(file)
    bands = pilimg.getbands()
    if bands == ("R", "G", "B") or bands == ("R", "G", "B", "A"):
        thumb = pilimg.resize((thumb_size, thumb_size))
        sse, bias = 0, [0, 0, 0]
        if adjust_color_bias:
            bias = ImageStat.Stat(thumb).mean[:3]
            bias = [b - sum(bias) / 3 for b in bias]
        for pixel in thumb.getdata():
            mu = sum(pixel) / 3
            sse += sum(
                (pixel[i] - mu - bias[i]) * (pixel[i] - mu - bias[i]) for i in [0, 1, 2]
            )
        mse = float(sse) / (thumb_size * thumb_size)
        return "grayscale" if mse <= MSE_cutoff else "color"
    elif len(bands) == 1:
        return "blackandwhite"

def test_server_fetchitem_notfound(plex):
    with pytest.raises(NotFound):
        plex.fetchItem(123456789)

def test_server_search(plex, movie):
    title = movie.title
    #  this search seem to fail on my computer but not at travis, wtf.
    assert plex.search(title)
    assert plex.search(title, mediatype="movie")

def test_server_playlist(plex, show):
    episodes = show.episodes()
    playlist = plex.createPlaylist("test_playlist", episodes[:3])
    try:
        assert playlist.title == "test_playlist"
        with pytest.raises(NotFound):
            plex.playlist("<playlist-not-found>")
    finally:
        playlist.delete()

def test_server_playlists(plex, show):
    playlists = plex.playlists()
    count = len(playlists)
    episodes = show.episodes()
    playlist = plex.createPlaylist("test_playlist", episodes[:3])
    try:
        playlists = plex.playlists()
        assert len(playlists) == count + 1
    finally:
        playlist.delete()

def test_server_history(plex, movie):
    movie.markWatched()
    history = plex.history()
    assert len(history)
    movie.markUnwatched()

def test_server_Server_query(plex):
    assert plex.query("/")
    with pytest.raises(NotFound):
        assert plex.query("/asdf/1234/asdf", headers={"random_headers": "1234"})

def test_server_Server_session(account):
    # Mock Sesstion
    class MySession(Session):
        def __init__(self):
            super(self.__class__, self).__init__()
            self.plexapi_session_test = True

    # Test Code
    plex = PlexServer(
        utils.SERVER_BASEURL, account.authenticationToken, session=MySession()
    )
    assert hasattr(plex._session, "plexapi_session_test")

@pytest.mark.authenticated
def test_server_token_in_headers(plex):
    headers = plex._headers()
    assert "X-Plex-Token" in headers
    assert len(headers["X-Plex-Token"]) >= 1

def test_server_createPlayQueue(plex, movie):
    playqueue = plex.createPlayQueue(movie, shuffle=1, repeat=1)
    assert "shuffle=1" in playqueue._initpath
    assert "repeat=1" in playqueue._initpath
    assert playqueue.playQueueShuffled is True

def test_server_client_not_found(plex):
    with pytest.raises(NotFound):
        plex.client("<This-client-should-not-be-found>")

def test_server_sessions(plex):
    assert len(plex.sessions()) >= 0

def test_server_isLatest(plex, mocker):
    from os import environ

    is_latest = plex.isLatest()
    if environ.get("PLEX_CONTAINER_TAG") and environ["PLEX_CONTAINER_TAG"] != "latest":
        assert not is_latest
    else:
        return pytest.skip(
            "Do not forget to run with PLEX_CONTAINER_TAG != latest to ensure that update is available"
        )

def test_server_installUpdate(plex, mocker):
    m = mocker.MagicMock(release="aa")
    with utils.patch('plexapi.server.PlexServer.check_for_update', return_value=m):
        with utils.callable_http_patch():
            plex.installUpdate()

def test_server_check_for_update(plex, mocker):
    class R:
        def __init__(self, **kwargs):
            self.download_key = "plex.tv/release/1337"
            self.version = "1337"
            self.added = "gpu transcode"
            self.fixed = "fixed rare bug"
            self.downloadURL = "http://path-to-update"
            self.state = "downloaded"

    with utils.patch('plexapi.server.PlexServer.check_for_update', return_value=R()):
        rel = plex.check_for_update(force=False, download=True)
        assert rel.download_key == "plex.tv/release/1337"
        assert rel.version == "1337"
        assert rel.added == "gpu transcode"
        assert rel.fixed == "fixed rare bug"
        assert rel.downloadURL == "http://path-to-update"
        assert rel.state == "downloaded"

@pytest.mark.client
def test_server_clients(plex):
    assert len(plex.clients())
    client = plex.clients()[0]
    assert client._baseurl == utils.CLIENT_BASEURL
    assert client._server._baseurl == utils.SERVER_BASEURL
    assert client.protocol == 'plex'
    assert int(client.protocolVersion) in range(4)
    assert isinstance(client.machineIdentifier, str)
    assert client.deviceClass in ['phone', 'tablet', 'stb', 'tv', 'pc']
    assert set(client.protocolCapabilities).issubset({'timeline', 'playback', 'navigation', 'mirror', 'playqueues'})

@pytest.mark.authenticated
def test_server_account(plex):
    account = plex.account()
    assert account.authToken
    # TODO: Figure out why this is missing from time to time.
    # assert account.mappingError == 'publisherror'
    assert account.mappingErrorMessage is None
    assert account.mappingState == "mapped"
    if account.mappingError != "unreachable":
        if account.privateAddress is not None:
            # This seems to fail way to often..
            #assert re.match(utils.REGEX_IPADDR, account.privateAddress)
            assert len(account.privateAddress)
        assert int(account.privatePort) >= 1000
        assert re.match(utils.REGEX_IPADDR, account.publicAddress)
        assert int(account.publicPort) >= 1000
    else:
        assert account.privateAddress == ""
        assert int(account.privatePort) == 0
        assert account.publicAddress == ""
        assert int(account.publicPort) == 0
    assert account.signInState == "ok"
    assert isinstance(account.subscriptionActive, bool)
    if account.subscriptionActive:
        assert len(account.subscriptionFeatures)
    # Below check keeps failing.. it should go away.
    # else: assert sorted(account.subscriptionFeatures) == ['adaptive_bitrate',
    #     'download_certificates', 'federated-auth', 'news']
    assert (
        account.subscriptionState == "Active"
        if account.subscriptionActive
        else "Unknown"
    )
    assert re.match(utils.REGEX_EMAIL, account.username)

def test_server_downloadLogs(tmpdir, plex):
    plex.downloadLogs(savepath=str(tmpdir), unpack=True)
    assert len(tmpdir.listdir()) > 1

def test_server_downloadDatabases(tmpdir, plex):
    plex.downloadDatabases(savepath=str(tmpdir), unpack=True)
    assert len(tmpdir.listdir()) > 1

def test_server_allowMediaDeletion(account):
    plex = PlexServer(utils.SERVER_BASEURL, account.authenticationToken)
    # Check server current allowMediaDeletion setting
    if plex.allowMediaDeletion:
        # If allowed then test disallowed
        plex._allowMediaDeletion(False)
        time.sleep(1)
        plex = PlexServer(utils.SERVER_BASEURL, account.authenticationToken)
        assert plex.allowMediaDeletion is None
        # Test redundant toggle
        with pytest.raises(BadRequest):
            plex._allowMediaDeletion(False)

        plex._allowMediaDeletion(True)
        time.sleep(1)
        plex = PlexServer(utils.SERVER_BASEURL, account.authenticationToken)
        assert plex.allowMediaDeletion is True
        # Test redundant toggle
        with pytest.raises(BadRequest):
            plex._allowMediaDeletion(True)
    else:
        # If disallowed then test allowed
        plex._allowMediaDeletion(True)
        time.sleep(1)
        plex = PlexServer(utils.SERVER_BASEURL, account.authenticationToken)
        assert plex.allowMediaDeletion is True
        # Test redundant toggle
        with pytest.raises(BadRequest):
            plex._allowMediaDeletion(True)

        plex._allowMediaDeletion(False)
        time.sleep(1)
        plex = PlexServer(utils.SERVER_BASEURL, account.authenticationToken)
        assert plex.allowMediaDeletion is None
        # Test redundant toggle
        with pytest.raises(BadRequest):
            plex._allowMediaDeletion(False)
<|endoftext|>


<commit_before>import filecmp
import json
import os
import shutil
import zipfile

import bsdiff4
import pytest

from server.DiffHead import DiffHead
from server.RepositoryManager import RepositoryManager, InvalidRepositoryPathError

def create_simplefile(path: str, name: str, content: str) -> str:
    abs_path = os.path.join(path, name)

    with open(abs_path, 'w+') as file:
        file.write(content)
        return abs_path

@pytest.fixture()
def empty_repo_with_2_version(tmpdir):
    os.chdir(tmpdir.strpath)

    repo_folder = tmpdir.mkdir("test_repo")
    v1_folder = repo_folder.mkdir("v1")
    v2_folder = repo_folder.mkdir("v2")

    versionfile = repo_folder.join(".versions")
    versionfile.write("v1")

    return tmpdir, repo_folder, v1_folder, v2_folder

def test_invalid_repo_folder(tmpdir):
    os.chdir(tmpdir.strpath)

    with pytest.raises(InvalidRepositoryPathError):
        RepositoryManager(os.path.join(tmpdir.strpath, 'non_existing_folder'))

def test_empty_repo(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_update()

    with zipfile.ZipFile(os.path.join(v1_folder.strpath, '.delta_to', 'v2.zip')) as baseZip:
        baseZip.extractall(os.path.join(v1_folder.strpath, '.delta_to', 'v2'))

    assert os.path.exists(os.path.join(v1_folder.strpath, '.delta_to', 'v2', '.bireus'))  # delta file written
    with open(os.path.join(v1_folder.strpath, '.delta_to', 'v2', '.bireus')) as json_file:
        json_result = json.load(json_file)
        assert json_result['repository'] == "test_repo"
        assert json_result['base_version'] == "v1"
        assert json_result['target_version'] == "v2"
        assert len(json_result['items']) == 0

    delta = DiffHead.load_json_file(os.path.join(v1_folder.strpath, '.delta_to', 'v2', '.bireus'))
    assert delta.repository == "test_repo"
    assert delta.base_version == "v1"
    assert delta.target_version == "v2"
    assert len(delta.items) == 0

def test_folder_removed(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version

    v1_folder_FR = v1_folder.mkdir("fr")  # folder FR removed

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_update()

    with zipfile.ZipFile(os.path.join(v1_folder.strpath, '.delta_to', 'v2.zip')) as baseZip:
        baseZip.extractall(os.path.join(v1_folder.strpath, '.delta_to', 'v2'))

    result = DiffHead.load_json_file(os.path.join(v1_folder.strpath, '.delta_to', 'v2', '.bireus'))
    assert len(result.items) == 1
    assert result.items[0].type == "directory"
    assert result.items[0].name == "fr"
    assert result.items[0].action == "remove"
    assert len(result.items[0].items) == 0

def test_folder_added(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version

    v2_folder_FA = v2_folder.mkdir("fa")  # folder FA added

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_update()

    with zipfile.ZipFile(os.path.join(v1_folder.strpath, '.delta_to', 'v2.zip')) as baseZip:
        baseZip.extractall(os.path.join(v1_folder.strpath, '.delta_to', 'v2'))

    result = DiffHead.load_json_file(os.path.join(v1_folder.strpath, '.delta_to', 'v2', '.bireus'))
    assert len(result.items) == 1
    assert result.items[0].type == "directory"
    assert result.items[0].name == "fa"
    assert result.items[0].action == "add"
    assert len(result.items[0].items) == 0

def test_folder_unchanged(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version

    v1_folder_FU = v1_folder.mkdir("fu")  # folder FU unchanged
    v2_folder_FU = v2_folder.mkdir("fu")  # folder FU unchanged

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_update()

    with zipfile.ZipFile(os.path.join(v1_folder.strpath, '.delta_to', 'v2.zip')) as baseZip:
        baseZip.extractall(os.path.join(v1_folder.strpath, '.delta_to', 'v2'))

    result = DiffHead.load_json_file(os.path.join(v1_folder.strpath, '.delta_to', 'v2', '.bireus'))
    assert len(result.items) == 1
    assert result.items[0].type == "directory"
    assert result.items[0].name == "fu"
    assert result.items[0].action == "delta"
    assert len(result.items[0].items) == 0

def test_subfolder_added(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version

    v2_folder_top = v2_folder.mkdir("top")  # folder FA added
    v2_folder_sub = v2_folder_top.mkdir("sub")

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_update()

    with zipfile.ZipFile(os.path.join(v1_folder.strpath, '.delta_to', 'v2.zip')) as baseZip:
        baseZip.extractall(os.path.join(v1_folder.strpath, '.delta_to', 'v2'))

    result = DiffHead.load_json_file(os.path.join(v1_folder.strpath, '.delta_to', 'v2', '.bireus'))
    assert len(result.items) == 1
    assert result.items[0].type == "directory"
    assert result.items[0].name == "top"
    assert result.items[0].action == "add"
    assert len(result.items[0].items) == 1
    assert result.items[0].items[0].type == "directory"
    assert result.items[0].items[0].name == "sub"
    assert result.items[0].items[0].action == "add"

def test_file_removed(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version

    create_simplefile(v1_folder.strpath, "test.txt", "test")

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_update()

    with zipfile.ZipFile(os.path.join(v1_folder.strpath, '.delta_to', 'v2.zip')) as baseZip:
        baseZip.extractall(os.path.join(v1_folder.strpath, '.delta_to', 'v2'))

    result = DiffHead.load_json_file(os.path.join(v1_folder.strpath, '.delta_to', 'v2', '.bireus'))
    assert len(result.items) == 1
    assert result.items[0].type == "file"
    assert result.items[0].name == "test.txt"
    assert result.items[0].action == "remove"
    assert len(result.items[0].items) == 0

def test_file_added(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version

    create_simplefile(v2_folder.strpath, "test.txt", "test")

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_update()

    with zipfile.ZipFile(os.path.join(v1_folder.strpath, '.delta_to', 'v2.zip')) as baseZip:
        baseZip.extractall(os.path.join(v1_folder.strpath, '.delta_to', 'v2'))

    result = DiffHead.load_json_file(os.path.join(v1_folder.strpath, '.delta_to', 'v2', '.bireus'))
    assert len(result.items) == 1
    assert result.items[0].type == "file"
    assert result.items[0].name == "test.txt"
    assert result.items[0].action == "add"
    assert len(result.items[0].items) == 0

def test_file_changed(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version

    create_simplefile(v1_folder.strpath, "test.txt", "Das ist die alte Version!")
    create_simplefile(v2_folder.strpath, "test.txt", "Das ist die neue Version!")

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_update()

    with zipfile.ZipFile(os.path.join(v1_folder.strpath, '.delta_to', 'v2.zip')) as baseZip:
        baseZip.extractall(os.path.join(v1_folder.strpath, '.delta_to', 'v2'))

    result = DiffHead.load_json_file(os.path.join(v1_folder.strpath, '.delta_to', 'v2', '.bireus'))
    assert len(result.items) == 1
    assert result.items[0].type == "file"
    assert result.items[0].name == "test.txt"
    assert result.items[0].action == "bsdiff"
    assert len(result.items[0].items) == 0

    assert os.path.exists(os.path.join(v1_folder.strpath, '.delta_to', 'v2', 'test.txt'))
    bsdiff4.file_patch(os.path.join(v1_folder.strpath, 'test.txt'),
                       os.path.join(v1_folder.strpath, '.delta_to', 'v2', 'test.txt.patched'),
                       os.path.join(v1_folder.strpath, '.delta_to', 'v2', 'test.txt'))
    assert filecmp.cmp(os.path.join(v2_folder.strpath, 'test.txt'),
                       os.path.join(v1_folder.strpath, '.delta_to', 'v2', 'test.txt.patched'))

def test_file_unchanged(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version

    create_simplefile(v1_folder.strpath, "test.txt", "Das ist die gleiche Version!")
    create_simplefile(v2_folder.strpath, "test.txt", "Das ist die gleiche Version!")

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_update()

    with zipfile.ZipFile(os.path.join(v1_folder.strpath, '.delta_to', 'v2.zip')) as baseZip:
        baseZip.extractall(os.path.join(v1_folder.strpath, '.delta_to', 'v2'))

    result = DiffHead.load_json_file(os.path.join(v1_folder.strpath, '.delta_to', 'v2', '.bireus'))
    assert len(result.items) == 1
    assert result.items[0].type == "file"
    assert result.items[0].name == "test.txt"
    assert result.items[0].action == "unchanged"
    assert len(result.items[0].items) == 0

def test_zipdelta(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version

    v1_zipdir = tmpdir.mkdir("test_zipdelta_v1")
    create_simplefile(v1_zipdir.strpath, "test.txt", "Das ist die alte Version!")
    shutil.make_archive(os.path.join(v1_folder.strpath, "test"), 'zip', v1_zipdir.strpath)

    v2_zipdir = tmpdir.mkdir("test_zipdelta_v2")
    create_simplefile(v2_zipdir.strpath, "test.txt", "Das ist die neue Version!")
    shutil.make_archive(os.path.join(v2_folder.strpath, "test"), 'zip', v2_zipdir.strpath)

    shutil.rmtree(v1_zipdir.strpath)
    shutil.rmtree(v2_zipdir.strpath)

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_update()

    with zipfile.ZipFile(os.path.join(v1_folder.strpath, '.delta_to', 'v2.zip')) as baseZip:
        baseZip.extractall(os.path.join(v1_folder.strpath, '.delta_to', 'v2'))

    result = DiffHead.load_json_file(os.path.join(v1_folder.strpath, '.delta_to', 'v2', '.bireus'))
    assert len(result.items) == 1
    assert result.items[0].type == "file"
    assert result.items[0].name == "test.zip"
    assert result.items[0].action == "zipdelta"
    assert len(result.items[0].items) == 1

def test_cleanup(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version
    delta_folder1 = v1_folder.mkdir(".delta_to").strpath

    assert os.path.exists(delta_folder1)

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_cleanup()

    assert not os.path.exists(delta_folder1)

def test_forward_only(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version

    v2_folder_FA = v2_folder.mkdir("fa")  # folder FA added

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_update(forward_only=True)

    assert os.path.exists(os.path.join(v1_folder.strpath, ".delta_to"))
    assert not os.path.exists(os.path.join(v2_folder.strpath, ".delta_to"))

def test_forward_only_negative(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version

    v2_folder_FA = v2_folder.mkdir("fa")  # folder FA added

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_update(forward_only=False)

    assert os.path.exists(os.path.join(v1_folder.strpath, ".delta_to"))
    assert os.path.exists(os.path.join(v2_folder.strpath, ".delta_to"))
<commit_msg>fix broken server test due to DiffHead's first item being the empty directory now<commit_after>import filecmp
import json
import os
import shutil
import zipfile

import bsdiff4
import pytest

from server.RepositoryManager import RepositoryManager, InvalidRepositoryPathError
from shared.DiffHead import DiffHead

def create_simplefile(path: str, name: str, content: str) -> str:
    abs_path = os.path.join(path, name)

    with open(abs_path, 'w+') as file:
        file.write(content)
        return abs_path

@pytest.fixture()
def empty_repo_with_2_version(tmpdir):
    os.chdir(tmpdir.strpath)

    repo_folder = tmpdir.mkdir("test_repo")
    v1_folder = repo_folder.mkdir("v1")
    v2_folder = repo_folder.mkdir("v2")

    versionfile = repo_folder.join(".versions")
    versionfile.write("v1")

    return tmpdir, repo_folder, v1_folder, v2_folder

def test_invalid_repo_folder(tmpdir):
    os.chdir(tmpdir.strpath)

    with pytest.raises(InvalidRepositoryPathError):
        RepositoryManager(os.path.join(tmpdir.strpath, 'non_existing_folder'))

def test_empty_repo(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_update()

    with zipfile.ZipFile(os.path.join(v1_folder.strpath, '.delta_to', 'v2.zip')) as baseZip:
        baseZip.extractall(os.path.join(v1_folder.strpath, '.delta_to', 'v2'))

    assert os.path.exists(os.path.join(v1_folder.strpath, '.delta_to', 'v2', '.bireus'))  # delta file written
    with open(os.path.join(v1_folder.strpath, '.delta_to', 'v2', '.bireus')) as json_file:
        json_result = json.load(json_file)
        assert json_result['repository'] == "test_repo"
        assert json_result['base_version'] == "v1"
        assert json_result['target_version'] == "v2"
        assert len(json_result['items']) == 1
        assert json_result['items'][0]['name'] == ''
        assert json_result['items'][0]['type'] == 'directory'
        assert json_result['items'][0]['action'] == 'delta'
        assert len(json_result['items'][0]['items']) == 0

    delta = DiffHead.load_json_file(os.path.join(v1_folder.strpath, '.delta_to', 'v2', '.bireus'))
    assert delta.repository == "test_repo"
    assert delta.base_version == "v1"
    assert delta.target_version == "v2"
    assert len(delta.items) == 1

def test_folder_removed(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version

    v1_folder_FR = v1_folder.mkdir("fr")  # folder FR removed

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_update()

    with zipfile.ZipFile(os.path.join(v1_folder.strpath, '.delta_to', 'v2.zip')) as baseZip:
        baseZip.extractall(os.path.join(v1_folder.strpath, '.delta_to', 'v2'))

    result = DiffHead.load_json_file(os.path.join(v1_folder.strpath, '.delta_to', 'v2', '.bireus')).items[0]
    assert len(result.items) == 1
    assert result.items[0].type == "directory"
    assert result.items[0].name == "fr"
    assert result.items[0].action == "remove"
    assert len(result.items[0].items) == 0

def test_folder_added(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version

    v2_folder_FA = v2_folder.mkdir("fa")  # folder FA added

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_update()

    with zipfile.ZipFile(os.path.join(v1_folder.strpath, '.delta_to', 'v2.zip')) as baseZip:
        baseZip.extractall(os.path.join(v1_folder.strpath, '.delta_to', 'v2'))

    result = DiffHead.load_json_file(os.path.join(v1_folder.strpath, '.delta_to', 'v2', '.bireus')).items[0]
    assert len(result.items) == 1
    assert result.items[0].type == "directory"
    assert result.items[0].name == "fa"
    assert result.items[0].action == "add"
    assert len(result.items[0].items) == 0

def test_folder_unchanged(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version

    v1_folder_FU = v1_folder.mkdir("fu")  # folder FU unchanged
    v2_folder_FU = v2_folder.mkdir("fu")  # folder FU unchanged

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_update()

    with zipfile.ZipFile(os.path.join(v1_folder.strpath, '.delta_to', 'v2.zip')) as baseZip:
        baseZip.extractall(os.path.join(v1_folder.strpath, '.delta_to', 'v2'))

    result = DiffHead.load_json_file(os.path.join(v1_folder.strpath, '.delta_to', 'v2', '.bireus')).items[0]
    assert len(result.items) == 1
    assert result.items[0].type == "directory"
    assert result.items[0].name == "fu"
    assert result.items[0].action == "delta"
    assert len(result.items[0].items) == 0

def test_subfolder_added(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version

    v2_folder_top = v2_folder.mkdir("top")  # folder FA added
    v2_folder_sub = v2_folder_top.mkdir("sub")

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_update()

    with zipfile.ZipFile(os.path.join(v1_folder.strpath, '.delta_to', 'v2.zip')) as baseZip:
        baseZip.extractall(os.path.join(v1_folder.strpath, '.delta_to', 'v2'))

    result = DiffHead.load_json_file(os.path.join(v1_folder.strpath, '.delta_to', 'v2', '.bireus')).items[0]
    assert len(result.items) == 1
    assert result.items[0].type == "directory"
    assert result.items[0].name == "top"
    assert result.items[0].action == "add"
    assert len(result.items[0].items) == 1
    assert result.items[0].items[0].type == "directory"
    assert result.items[0].items[0].name == "sub"
    assert result.items[0].items[0].action == "add"

def test_file_removed(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version

    create_simplefile(v1_folder.strpath, "test.txt", "test")

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_update()

    with zipfile.ZipFile(os.path.join(v1_folder.strpath, '.delta_to', 'v2.zip')) as baseZip:
        baseZip.extractall(os.path.join(v1_folder.strpath, '.delta_to', 'v2'))

    result = DiffHead.load_json_file(os.path.join(v1_folder.strpath, '.delta_to', 'v2', '.bireus')).items[0]
    assert len(result.items) == 1
    assert result.items[0].type == "file"
    assert result.items[0].name == "test.txt"
    assert result.items[0].action == "remove"
    assert len(result.items[0].items) == 0

def test_file_added(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version

    create_simplefile(v2_folder.strpath, "test.txt", "test")

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_update()

    with zipfile.ZipFile(os.path.join(v1_folder.strpath, '.delta_to', 'v2.zip')) as baseZip:
        baseZip.extractall(os.path.join(v1_folder.strpath, '.delta_to', 'v2'))

    result = DiffHead.load_json_file(os.path.join(v1_folder.strpath, '.delta_to', 'v2', '.bireus')).items[0]
    assert len(result.items) == 1
    assert result.items[0].type == "file"
    assert result.items[0].name == "test.txt"
    assert result.items[0].action == "add"
    assert len(result.items[0].items) == 0

def test_file_changed(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version

    create_simplefile(v1_folder.strpath, "test.txt", "Das ist die alte Version!")
    create_simplefile(v2_folder.strpath, "test.txt", "Das ist die neue Version!")

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_update()

    with zipfile.ZipFile(os.path.join(v1_folder.strpath, '.delta_to', 'v2.zip')) as baseZip:
        baseZip.extractall(os.path.join(v1_folder.strpath, '.delta_to', 'v2'))

    result = DiffHead.load_json_file(os.path.join(v1_folder.strpath, '.delta_to', 'v2', '.bireus')).items[0]
    assert len(result.items) == 1
    assert result.items[0].type == "file"
    assert result.items[0].name == "test.txt"
    assert result.items[0].action == "bsdiff"
    assert len(result.items[0].items) == 0

    assert os.path.exists(os.path.join(v1_folder.strpath, '.delta_to', 'v2', 'test.txt'))
    bsdiff4.file_patch(os.path.join(v1_folder.strpath, 'test.txt'),
                       os.path.join(v1_folder.strpath, '.delta_to', 'v2', 'test.txt.patched'),
                       os.path.join(v1_folder.strpath, '.delta_to', 'v2', 'test.txt'))
    assert filecmp.cmp(os.path.join(v2_folder.strpath, 'test.txt'),
                       os.path.join(v1_folder.strpath, '.delta_to', 'v2', 'test.txt.patched'))

def test_file_unchanged(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version

    create_simplefile(v1_folder.strpath, "test.txt", "Das ist die gleiche Version!")
    create_simplefile(v2_folder.strpath, "test.txt", "Das ist die gleiche Version!")

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_update()

    with zipfile.ZipFile(os.path.join(v1_folder.strpath, '.delta_to', 'v2.zip')) as baseZip:
        baseZip.extractall(os.path.join(v1_folder.strpath, '.delta_to', 'v2'))

    result = DiffHead.load_json_file(os.path.join(v1_folder.strpath, '.delta_to', 'v2', '.bireus')).items[0]
    assert len(result.items) == 1
    assert result.items[0].type == "file"
    assert result.items[0].name == "test.txt"
    assert result.items[0].action == "unchanged"
    assert len(result.items[0].items) == 0

def test_zipdelta(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version

    v1_zipdir = tmpdir.mkdir("test_zipdelta_v1")
    create_simplefile(v1_zipdir.strpath, "test.txt", "Das ist die alte Version!")
    shutil.make_archive(os.path.join(v1_folder.strpath, "test"), 'zip', v1_zipdir.strpath)

    v2_zipdir = tmpdir.mkdir("test_zipdelta_v2")
    create_simplefile(v2_zipdir.strpath, "test.txt", "Das ist die neue Version!")
    shutil.make_archive(os.path.join(v2_folder.strpath, "test"), 'zip', v2_zipdir.strpath)

    shutil.rmtree(v1_zipdir.strpath)
    shutil.rmtree(v2_zipdir.strpath)

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_update()

    with zipfile.ZipFile(os.path.join(v1_folder.strpath, '.delta_to', 'v2.zip')) as baseZip:
        baseZip.extractall(os.path.join(v1_folder.strpath, '.delta_to', 'v2'))

    result = DiffHead.load_json_file(os.path.join(v1_folder.strpath, '.delta_to', 'v2', '.bireus')).items[0]
    assert len(result.items) == 1
    assert result.items[0].type == "file"
    assert result.items[0].name == "test.zip"
    assert result.items[0].action == "zipdelta"
    assert len(result.items[0].items) == 1

def test_cleanup(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version
    delta_folder1 = v1_folder.mkdir(".delta_to").strpath

    assert os.path.exists(delta_folder1)

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_cleanup()

    assert not os.path.exists(delta_folder1)

def test_forward_only(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version

    v2_folder_FA = v2_folder.mkdir("fa")  # folder FA added

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_update(forward_only=True)

    assert os.path.exists(os.path.join(v1_folder.strpath, ".delta_to"))
    assert not os.path.exists(os.path.join(v2_folder.strpath, ".delta_to"))

def test_forward_only_negative(empty_repo_with_2_version):
    tmpdir, repo_folder, v1_folder, v2_folder = empty_repo_with_2_version

    v2_folder_FA = v2_folder.mkdir("fa")  # folder FA added

    repo_manager = RepositoryManager(tmpdir.strpath)
    repo_manager.full_update(forward_only=False)

    assert os.path.exists(os.path.join(v1_folder.strpath, ".delta_to"))
    assert os.path.exists(os.path.join(v2_folder.strpath, ".delta_to"))
<|endoftext|>


<commit_before>from sympy.physics.mechanics import *
#from pydy-viz import Shape, Cube,

def test_shape():
    point_list = [(1, 0, 0), (2, 3, 1), (-1, 5, -1), (-4, 2, 5)]
    shape = Shape('shape')

    #checking setter methods ..
    shape.set_point_list(point_list)
    shape.set_color('RED')  #abstract method (abc package)
    shape.set_center([0, 0, 0]) #abstract method

    #checking getter methods ...
    assert shape.get_name() == 'shape' #abstract method

    #How to compare lists?
    assert shape.get_point_list() ==  [(1, 0, 0), (2, 3, 1), \
                                      (-1, 5, -1), (-4, 2, 5)]

    assert shape.get_color() == 'RED' #abstract method
    #Again how to compare tuples
    assert shape.get_center() == [0, 0, 0]  #abstractmethod

def test_cube():
    cube = Cube('cube')
    cube.set_length(10)
    cube.set_color('BLUE')
    cube.set_center([0, 0, 0])

    assert cube.get_name() == 'Cube'
    assert cube.get_length() == 10
    assert cube.get_point_list() ==  [(5, 5, 5), (5, 5, -5), \
                                     (5, -5, 5), (-5, -5, -5), \
                                       (-5 ,5 , 5), (-5, 5, -5), \
                                          (-5, -5, 5), (-5, -5, -5)]
    assert cube.color() == 'BLUE'
    assert cube.get_center() == [0, 0, 0]

    assert isinstance(cube, Shape) == True

def test_cylinder():
    cylinder = Cylinder('cylinder')
    cylinder.set_height(10)
    cylinder.set_radius(5)
    cylinder.set_color('BLACK')
    cylinder.set_center([0, 0, 0])

    assert cylinder.get_name() == 'cylinder'
    assert cylinder.get_height() == 10
    assert cylinder.get_radius() == 5
    assert cylinder.color() == 'BLACK'
    assert cylinder.get_center() == (0, 0, 0)

    assert isinstance(cylinder,Shape) == True

def test_cone():
    cone = Cone('cone')
    cone.set_height(10)
    cone.set_radius(5)
    cone.set_color('GREEN')
    cone.set_center([0, 0, 0])	 #base center, or geometric center?

    assert cone.get_name() == 'cone'
    assert cone.get_height() == 10
    assert cone.get_radius() == 5
    assert cone.get_color() == 'GREEN'
    assert cone.get_center() == [0, 0, 0]

    assert isinstance(cone,Shape) == True

<commit_msg>Added tests for Shapes as per discussed to include attributes, instead of explicit getter,setter methods<commit_after>from sympy.physics.mechanics import *
from numpy.testing import assert_allclose
#from pydy-viz import Shape, Cube,

def test_shape():
    point_list = [[1, 0, 0], [2, 3, 1], [-1, 5, -1], [-4, 2, 5]]
    shape = Shape('shape')

    shape.point_list = point_list
    shape.color = 'RED'  #abstract method (abc package), a @property
    shape.center = [0, 0, 0] #abstract method

    assert shape.name == 'shape' #abstract method, a @property
    assert_allclose(shape.point_list, point_list)
    assert shape.color == 'RED' #abstract method
    assert_allclose(shape.center, [0, 0, 0])

def test_cube():
    cube = Cube('cube')
    cube.length = 10
    cube.color = 'BLUE'
    cube.center = [0, 0, 0]

    assert cube.name == 'Cube'
    assert cube.length == 10
    assert cube.color == 'BLUE'
    point_list = [[5, 5, 5], [5, 5, -5], \
                    [5, -5, 5], [-5, -5, -5], \
                        [-5, 5, 5], [-5, 5, -5], \
                           [-5, -5, 5], [-5, -5, -5]]

    assert_allclose(cube.point_list,point_list)
    assert_allclose(cube.center, [0, 0, 0])

    assert isinstance(cube, Shape) == True

def test_cylinder():
    cylinder = Cylinder('cylinder')
    cylinder.height = 10
    cylinder.radius = 5
    cylinder.color = 'BLACK'
    cylinder.center = [0, 0, 0]

    assert cylinder.name == 'cylinder'
    assert cylinder.height == 10
    assert cylinder.radius == 5
    assert cylinder.color == 'BLACK'
    assert_allclose(cylinder.center, [0, 0, 0])

    assert isinstance(cylinder, Shape) == True

def test_cone():
    cone = Cone('cone')
    cone.height = 10
    cone.radius = 5
    cone.color = 'GREEN'
    cone.center = [0, 0, 0]	 #base center, or geometric center?

    assert cone.name == 'cone'
    assert cone.height == 10
    assert cone.radius == 5
    assert cone.color == 'GREEN'
    assert_allclose(cone.center, [0, 0, 0])

    assert isinstance(cone, Shape) == True

def test_sphere():
    sphere = Sphere('sphere')
    sphere.radius = 10
    sphere.color = 'GREY'
    sphere.center = [0, 0, 0]

    assert sphere.name == 'sphere'
    assert sphere.radius == 10
    assert sphere.color == 'GREY'
    assert_allclose(sphere.center, [0, 0, 0])

    assert isinstance(sphere, Shape) == True

def test_circle():
    circle = Circle('circle')
    circle.radius = 10
    circle.color = 'CYAN'
    circle.center = [0, 0, 0]

    assert circle.name == 'circle'
    assert circle.radius == 10
    assert circle.color == 'CYAN'
    assert_allclose(circle.center, [0, 0, 0])

    assert isinstance(circle, Shape) == True

def test_mesh_shape():
    pass

def test_tetrahedron():
    pass

def test_octahedron():
    pass

def test_icosahedron():
    pass

def test_plane():
    pass

def test_torus():
    pass

def test_tube():
    pass

def test_torus_knot():
    pass

<|endoftext|>


<commit_before>import singer
import unittest
import datetime
import dateutil

class TestSinger(unittest.TestCase):
    def test_parse_message_record_good(self):
        message = singer.parse_message(
            '{"type": "RECORD", "record": {"name": "foo"}, "stream": "users"}')
        self.assertEqual(
            message,
            singer.RecordMessage(record={'name': 'foo'}, stream='users'))

    def test_parse_message_record_with_version_good(self):
        message = singer.parse_message(
            '{"type": "RECORD", "record": {"name": "foo"}, "stream": "users", "version": 2}')
        self.assertEqual(
            message,
            singer.RecordMessage(record={'name': 'foo'}, stream='users', version=2))

    def test_parse_message_record_naive_extraction_time(self):
        with self.assertRaisesRegex(ValueError, "must be either None or an aware datetime"):
            message = singer.parse_message(
                '{"type": "RECORD", "record": {"name": "foo"}, "stream": "users", "version": 2, "time_extracted": "1970-01-02T00:00:00"}')

    def test_parse_message_record_aware_extraction_time(self):
        message = singer.parse_message(
            '{"type": "RECORD", "record": {"name": "foo"}, "stream": "users", "version": 2, "time_extracted": "1970-01-02T00:00:00.000Z"}')
        expected = singer.RecordMessage(
            record={'name': 'foo'},
            stream='users',
            version=2,
            time_extracted=dateutil.parser.parse("1970-01-02T00:00:00.000Z"))
        print(message)
        print(expected)
        self.assertEqual(message, expected)

    def test_extraction_time_strftime(self):
        """ Test that we're not corrupting timestamps with cross platform parsing. (Test case for OSX, specifically) """
        message = singer.RecordMessage(
            record={'name': 'foo'},
            stream='users',
            version=2,
            time_extracted=dateutil.parser.parse("1970-01-02T00:00:00.000Z"))
        expected = "1970-01-02T00:00:00.000000Z"
        self.assertEqual(message.asdict()["time_extracted"], expected)

    def test_parse_message_record_missing_record(self):
        with self.assertRaises(Exception):
            singer.parse_message('{"type": "RECORD", "stream": "users"}')

    def test_parse_message_record_missing_stream(self):
        with self.assertRaises(Exception):
            singer.parse_message(
                '{"type": "RECORD", "record": {"name": "foo"}}')

    def test_parse_message_schema_good(self):
        message = singer.parse_message('{"type": "SCHEMA", "stream": "users", "schema": {"type": "object", "properties": {"name": {"type": "string"}}}, "key_properties": ["name"]}')  # nopep8
        self.assertEqual(
            message,
            singer.SchemaMessage(
                stream='users',
                key_properties=['name'],
                schema={'type': 'object',
                        'properties': {
                            'name': {'type': 'string'}}}))

    def test_parse_message_schema_missing_stream(self):
        with self.assertRaises(Exception):
            message = singer.parse_message('{"type": "SCHEMA", "schema": {"type": "object", "properties": {"name": {"type": "string"}}}, "key_properties": ["name"]}')  # nopep8

    def test_parse_message_schema_missing_schema(self):
        with self.assertRaises(Exception):
            message = singer.parse_message(
                '{"type": "SCHEMA", "stream": "users", "key_properties": ["name"]}')  # nopep8

    def test_parse_message_schema_missing_key_properties(self):
        with self.assertRaises(Exception):
            message = singer.parse_message('{"type": "SCHEMA", "stream": "users", "schema": {"type": "object", "properties": {"name": {"type": "string"}}}}')  # nopep8

    def test_parse_message_state_good(self):
        message = singer.parse_message(
            '{"type": "STATE", "value": {"seq": 1}}')
        self.assertEqual(message, singer.StateMessage(value={'seq': 1}))

    def test_parse_message_state_missing_value(self):
        with self.assertRaises(Exception):
            singer.parse_message('{"type": "STATE"}')

    def test_round_trip(self):

        record_message = singer.RecordMessage(
            record={'name': 'foo'},
            stream='users')

        schema_message = singer.SchemaMessage(
            stream='users',
            key_properties=['name'],
            schema={'type': 'object',
                    'properties': {
                        'name': {'type': 'string'}}})

        state_message = singer.StateMessage(value={'seq': 1})

        self.assertEqual(record_message,
                         singer.parse_message(singer.format_message(record_message)))
        self.assertEqual(schema_message,
                         singer.parse_message(singer.format_message(schema_message)))
        self.assertEqual(state_message,
                         singer.parse_message(singer.format_message(state_message)))

    ## These three tests just confirm that writing doesn't throw

    def test_write_record(self):
        singer.write_record("users", {"name": "mike"})

    def test_write_schema(self):
        schema={'type': 'object',
                'properties': {
                    'name': {'type': 'string'}}}
        singer.write_schema("users", schema, ["name"])

    def test_write_state(self):
        singer.write_state({"foo": 1})

if __name__ == '__main__':
    unittest.main()
<commit_msg>adding tests<commit_after>import singer
import unittest
import datetime
import dateutil
from decimal import Decimal

class TestSinger(unittest.TestCase):
    def test_parse_message_record_good(self):
        message = singer.parse_message(
            '{"type": "RECORD", "record": {"name": "foo"}, "stream": "users"}')
        self.assertEqual(
            message,
            singer.RecordMessage(record={'name': 'foo'}, stream='users'))

    def test_parse_message_record_with_version_good(self):
        message = singer.parse_message(
            '{"type": "RECORD", "record": {"name": "foo"}, "stream": "users", "version": 2}')
        self.assertEqual(
            message,
            singer.RecordMessage(record={'name': 'foo'}, stream='users', version=2))

    def test_parse_message_record_naive_extraction_time(self):
        with self.assertRaisesRegex(ValueError, "must be either None or an aware datetime"):
            message = singer.parse_message(
                '{"type": "RECORD", "record": {"name": "foo"}, "stream": "users", "version": 2, "time_extracted": "1970-01-02T00:00:00"}')

    def test_parse_message_record_aware_extraction_time(self):
        message = singer.parse_message(
            '{"type": "RECORD", "record": {"name": "foo"}, "stream": "users", "version": 2, "time_extracted": "1970-01-02T00:00:00.000Z"}')
        expected = singer.RecordMessage(
            record={'name': 'foo'},
            stream='users',
            version=2,
            time_extracted=dateutil.parser.parse("1970-01-02T00:00:00.000Z"))
        print(message)
        print(expected)
        self.assertEqual(message, expected)

    def test_extraction_time_strftime(self):
        """ Test that we're not corrupting timestamps with cross platform parsing. (Test case for OSX, specifically) """
        message = singer.RecordMessage(
            record={'name': 'foo'},
            stream='users',
            version=2,
            time_extracted=dateutil.parser.parse("1970-01-02T00:00:00.000Z"))
        expected = "1970-01-02T00:00:00.000000Z"
        self.assertEqual(message.asdict()["time_extracted"], expected)

    def test_parse_message_record_missing_record(self):
        with self.assertRaises(Exception):
            singer.parse_message('{"type": "RECORD", "stream": "users"}')

    def test_parse_message_record_missing_stream(self):
        with self.assertRaises(Exception):
            singer.parse_message(
                '{"type": "RECORD", "record": {"name": "foo"}}')

    def test_parse_message_schema_good(self):
        message = singer.parse_message('{"type": "SCHEMA", "stream": "users", "schema": {"type": "object", "properties": {"name": {"type": "string"}}}, "key_properties": ["name"]}')  # nopep8
        self.assertEqual(
            message,
            singer.SchemaMessage(
                stream='users',
                key_properties=['name'],
                schema={'type': 'object',
                        'properties': {
                            'name': {'type': 'string'}}}))

    def test_parse_message_schema_missing_stream(self):
        with self.assertRaises(Exception):
            message = singer.parse_message('{"type": "SCHEMA", "schema": {"type": "object", "properties": {"name": {"type": "string"}}}, "key_properties": ["name"]}')  # nopep8

    def test_parse_message_schema_missing_schema(self):
        with self.assertRaises(Exception):
            message = singer.parse_message(
                '{"type": "SCHEMA", "stream": "users", "key_properties": ["name"]}')  # nopep8

    def test_parse_message_schema_missing_key_properties(self):
        with self.assertRaises(Exception):
            message = singer.parse_message('{"type": "SCHEMA", "stream": "users", "schema": {"type": "object", "properties": {"name": {"type": "string"}}}}')  # nopep8

    def test_parse_message_state_good(self):
        message = singer.parse_message(
            '{"type": "STATE", "value": {"seq": 1}}')
        self.assertEqual(message, singer.StateMessage(value={'seq': 1}))

    def test_parse_message_state_missing_value(self):
        with self.assertRaises(Exception):
            singer.parse_message('{"type": "STATE"}')

    def test_round_trip(self):
        record_message = singer.RecordMessage(
            record={'name': 'foo'},
            stream='users')

        schema_message = singer.SchemaMessage(
            stream='users',
            key_properties=['name'],
            schema={'type': 'object',
                    'properties': {
                        'name': {'type': 'string'}}})

        state_message = singer.StateMessage(value={'seq': 1})

        self.assertEqual(record_message,
                         singer.parse_message(singer.format_message(record_message)))
        self.assertEqual(schema_message,
                         singer.parse_message(singer.format_message(schema_message)))
        self.assertEqual(state_message,
                         singer.parse_message(singer.format_message(state_message)))

    ## These three tests just confirm that writing doesn't throw

    def test_write_record(self):
        singer.write_record("users", {"name": "mike"})

    def test_write_schema(self):
        schema={'type': 'object',
                'properties': {
                    'name': {'type': 'string'}}}
        singer.write_schema("users", schema, ["name"])

    def test_write_state(self):
        singer.write_state({"foo": 1})

class TestParsingNumbers(unittest.TestCase):
    def create_record(self, value):
        raw = '{"type": "RECORD", "stream": "test", "record": {"value": ' + value + '}}'
        parsed = singer.parse_message(raw)
        return parsed.record['value']

    def test_parse_int_zero(self):
        value = self.create_record('0')
        self.assertEqual(type(value), int)
        self.assertEqual(value, 0)

    def test_parse_regular_decimal(self):
        value = self.create_record('3.14')
        self.assertEqual(Decimal('3.14'), value)

    def test_parse_large_decimal(self):
        value = self.create_record('9999999999999999.9999')
        self.assertEqual(Decimal('9999999999999999.9999'), value)

    def test_parse_small_decimal(self):
        value = self.create_record('-9999999999999999.9999')
        self.assertEqual(Decimal('-9999999999999999.9999'), value)

    def test_parse_absurdly_large_decimal(self):
        value_str = '9' * 1024 + '.' + '9' * 1024
        value = self.create_record(value_str)
        self.assertEqual(Decimal(value_str), value)

    def test_parse_absurdly_large_int(self):
        value_str = '9' * 1024
        value = self.create_record(value_str)
        self.assertEqual(int(value_str), value)
        self.assertEqual(int, type(value))

    def test_parse_bulk_decs(self):
        value_strs = [
            '-9999999999999999.9999999999999999999999',
            '0',
            '9999999999999999.9999999999999999999999',
            '-7187498962233394.3739812942138415666763',
            '9273972760690975.2044306442955715221042',
            '29515565286974.1188802122612813004366',
            '9176089101347578.2596296292040288441238',
            '-8416853039392703.306423225471199148379',
            '1285266411314091.3002668125515694162268',
            '6051872750342125.3812886238958681227336',
            '-1132031605459408.5571559429308939781468',
            '-6387836755056303.0038029604189860431045',
            '4526059300505414'
        ]
        for value_str in value_strs:
            value = self.create_record(value_str)
            self.assertEqual(Decimal(value_str), value)

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