<commit_before>from decimal import Decimal
import unittest
from mock import Mock
from flask.ext.restful.fields import MarshallingException
from flask.ext.restful.utils import OrderedDict
from flask_restful import fields
from datetime import datetime, timedelta, tzinfo
from flask import Flask
#noinspection PyUnresolvedReferences
from nose.tools import assert_equals  # you need it for tests in form of continuations


class Foo(object):
    def __init__(self):
        self.hey = 3


class Bar(object):
    def __marshallable__(self):
        return {"hey": 3}


class TZ(tzinfo):
    def utcoffset(self, dt):
        return timedelta(hours=2)


def check_field(expected, field, value):
    assert_equals(expected, field.output('a', {'a': value}))


def test_float():
    values = [
        ("-3.13", -3.13),
        (str(-3.13), -3.13),
        (3, 3.0),
    ]
    for value, expected in values:
        yield check_field, expected, fields.Float(), value


def test_boolean():
    values = [
        (True, True),
        (False, False),
        ({}, False),
        ("false", True),  # These are different from php
        ("0", True),      # Will this be a problem?
    ]
    for value, expected in values:
        yield check_field, expected, fields.Boolean(), value


class FieldsTestCase(unittest.TestCase):

    def test_decimal_trash(self):
        self.assertRaises(MarshallingException, lambda: fields.Float().output('a', {'a': 'Foo'}))

    def test_basic_dictionary(self):
        obj = {"foo": 3}
        field = fields.String()
        self.assertEquals(field.output("foo", obj), "3")

    def test_no_attribute(self):
        obj = {"bar": 3}
        field = fields.String()
        self.assertEquals(field.output("foo", obj), None)

    def test_date_field_invalid(self):
        obj = {"bar": 3}
        field = fields.DateTime()
        self.assertRaises(MarshallingException, lambda: field.output("bar", obj))

    def test_attribute(self):
        obj = {"bar": 3}
        field = fields.String(attribute="bar")
        self.assertEquals(field.output("foo", obj), "3")

    def test_formatting_field_none(self):
        obj = {}
        field = fields.FormattedString("/foo/{0[account_sid]}/{0[sid]}/")
        self.assertRaises(MarshallingException, lambda: field.output("foo", obj))

    def test_formatting_field_tuple(self):
        obj = (3, 4)
        field = fields.FormattedString("/foo/{0[account_sid]}/{0[sid]}/")
        self.assertRaises(MarshallingException, lambda: field.output("foo", obj))

    def test_formatting_field_dict(self):
        obj = {
            "sid": 3,
            "account_sid": 4,
        }
        field = fields.FormattedString("/foo/{account_sid}/{sid}/")
        self.assertEquals(field.output("foo", obj), "/foo/4/3/")

    def test_formatting_field(self):
        obj = Mock()
        obj.sid = 3
        obj.account_sid = 4
        field = fields.FormattedString("/foo/{account_sid}/{sid}/")
        self.assertEquals(field.output("foo", obj), "/foo/4/3/")

    def test_basic_field(self):
        obj = Mock()
        obj.foo = 3
        field = fields.Raw()
        self.assertEquals(field.output("foo", obj), 3)

    def test_raw_field(self):
        obj = Mock()
        obj.foo = 3
        field = fields.Raw()
        self.assertEquals(field.output("foo", obj), 3)

    def test_nested_raw_field(self):
        foo = Mock()
        bar = Mock()
        bar.value = 3
        foo.bar = bar
        field = fields.Raw()
        self.assertEquals(field.output("bar.value", foo), 3)

    def test_formatted_string_invalid_obj(self):
        field = fields.FormattedString("{hey}")
        self.assertRaises(MarshallingException, lambda: field.output("hey", None))

    def test_formatted_string(self):
        field = fields.FormattedString("{hey}")
        self.assertEquals("3", field.output("hey", Foo()))

    def test_string_with_attribute(self):
        field = fields.String(attribute="hey")
        self.assertEquals("3", field.output("foo", Foo()))

    def test_string_with_lambda(self):
        field = fields.String(attribute=lambda x: x.hey)
        self.assertEquals("3", field.output("foo", Foo()))

    def test_url_invalid_object(self):
        app = Flask(__name__)
        app.add_url_rule("/<hey>", "foobar", view_func=lambda x: x)
        field = fields.Url("foobar")

        with app.test_request_context("/"):
            self.assertRaises(MarshallingException, lambda: field.output("hey", None))

    def test_url(self):
        app = Flask(__name__)
        app.add_url_rule("/<hey>", "foobar", view_func=lambda x: x)
        field = fields.Url("foobar")

        with app.test_request_context("/"):
            self.assertEquals("/3", field.output("hey", Foo()))

    def test_url_absolute(self):
        app = Flask(__name__)
        app.add_url_rule("/<hey>", "foobar", view_func=lambda x: x)
        field = fields.Url("foobar", absolute=True)

        with app.test_request_context("/"):
            self.assertEquals("http://localhost/3", field.output("hey", Foo()))

    def test_url_absolute_scheme(self):
        """Url.scheme should override current_request.scheme"""
        app = Flask(__name__)
        app.add_url_rule("/<hey>", "foobar", view_func=lambda x: x)
        field = fields.Url("foobar", absolute=True, scheme='https')

        with app.test_request_context("/", base_url="http://localhost"):
            self.assertEquals("https://localhost/3", field.output("hey", Foo()))

    def test_int(self):
        field = fields.Integer()
        self.assertEquals(3, field.output("hey", {'hey': 3}))
<commit_msg>Get endpoint from request context, to use with blueprints.<commit_after>from decimal import Decimal
import unittest
from mock import Mock
from flask.ext.restful.fields import MarshallingException
from flask.ext.restful.utils import OrderedDict
from flask_restful import fields
from datetime import datetime, timedelta, tzinfo
from flask import Flask, Blueprint
#noinspection PyUnresolvedReferences
from nose.tools import assert_equals  # you need it for tests in form of continuations


class Foo(object):
    def __init__(self):
        self.hey = 3


class Bar(object):
    def __marshallable__(self):
        return {"hey": 3}


class TZ(tzinfo):
    def utcoffset(self, dt):
        return timedelta(hours=2)


def check_field(expected, field, value):
    assert_equals(expected, field.output('a', {'a': value}))


def test_float():
    values = [
        ("-3.13", -3.13),
        (str(-3.13), -3.13),
        (3, 3.0),
    ]
    for value, expected in values:
        yield check_field, expected, fields.Float(), value


def test_boolean():
    values = [
        (True, True),
        (False, False),
        ({}, False),
        ("false", True),  # These are different from php
        ("0", True),      # Will this be a problem?
    ]
    for value, expected in values:
        yield check_field, expected, fields.Boolean(), value


class FieldsTestCase(unittest.TestCase):

    def test_decimal_trash(self):
        self.assertRaises(MarshallingException, lambda: fields.Float().output('a', {'a': 'Foo'}))

    def test_basic_dictionary(self):
        obj = {"foo": 3}
        field = fields.String()
        self.assertEquals(field.output("foo", obj), "3")

    def test_no_attribute(self):
        obj = {"bar": 3}
        field = fields.String()
        self.assertEquals(field.output("foo", obj), None)

    def test_date_field_invalid(self):
        obj = {"bar": 3}
        field = fields.DateTime()
        self.assertRaises(MarshallingException, lambda: field.output("bar", obj))

    def test_attribute(self):
        obj = {"bar": 3}
        field = fields.String(attribute="bar")
        self.assertEquals(field.output("foo", obj), "3")

    def test_formatting_field_none(self):
        obj = {}
        field = fields.FormattedString("/foo/{0[account_sid]}/{0[sid]}/")
        self.assertRaises(MarshallingException, lambda: field.output("foo", obj))

    def test_formatting_field_tuple(self):
        obj = (3, 4)
        field = fields.FormattedString("/foo/{0[account_sid]}/{0[sid]}/")
        self.assertRaises(MarshallingException, lambda: field.output("foo", obj))

    def test_formatting_field_dict(self):
        obj = {
            "sid": 3,
            "account_sid": 4,
        }
        field = fields.FormattedString("/foo/{account_sid}/{sid}/")
        self.assertEquals(field.output("foo", obj), "/foo/4/3/")

    def test_formatting_field(self):
        obj = Mock()
        obj.sid = 3
        obj.account_sid = 4
        field = fields.FormattedString("/foo/{account_sid}/{sid}/")
        self.assertEquals(field.output("foo", obj), "/foo/4/3/")

    def test_basic_field(self):
        obj = Mock()
        obj.foo = 3
        field = fields.Raw()
        self.assertEquals(field.output("foo", obj), 3)

    def test_raw_field(self):
        obj = Mock()
        obj.foo = 3
        field = fields.Raw()
        self.assertEquals(field.output("foo", obj), 3)

    def test_nested_raw_field(self):
        foo = Mock()
        bar = Mock()
        bar.value = 3
        foo.bar = bar
        field = fields.Raw()
        self.assertEquals(field.output("bar.value", foo), 3)

    def test_formatted_string_invalid_obj(self):
        field = fields.FormattedString("{hey}")
        self.assertRaises(MarshallingException, lambda: field.output("hey", None))

    def test_formatted_string(self):
        field = fields.FormattedString("{hey}")
        self.assertEquals("3", field.output("hey", Foo()))

    def test_string_with_attribute(self):
        field = fields.String(attribute="hey")
        self.assertEquals("3", field.output("foo", Foo()))

    def test_string_with_lambda(self):
        field = fields.String(attribute=lambda x: x.hey)
        self.assertEquals("3", field.output("foo", Foo()))

    def test_url_invalid_object(self):
        app = Flask(__name__)
        app.add_url_rule("/<hey>", "foobar", view_func=lambda x: x)
        field = fields.Url("foobar")

        with app.test_request_context("/"):
            self.assertRaises(MarshallingException, lambda: field.output("hey", None))

    def test_url(self):
        app = Flask(__name__)
        app.add_url_rule("/<hey>", "foobar", view_func=lambda x: x)
        field = fields.Url("foobar")

        with app.test_request_context("/"):
            self.assertEquals("/3", field.output("hey", Foo()))

    def test_url_absolute(self):
        app = Flask(__name__)
        app.add_url_rule("/<hey>", "foobar", view_func=lambda x: x)
        field = fields.Url("foobar", absolute=True)

        with app.test_request_context("/"):
            self.assertEquals("http://localhost/3", field.output("hey", Foo()))

    def test_url_absolute_scheme(self):
        """Url.scheme should override current_request.scheme"""
        app = Flask(__name__)
        app.add_url_rule("/<hey>", "foobar", view_func=lambda x: x)
        field = fields.Url("foobar", absolute=True, scheme='https')

        with app.test_request_context("/", base_url="http://localhost"):
            self.assertEquals("https://localhost/3", field.output("hey", Foo()))

    def test_url_without_endpoint_invalid_object(self):
        app = Flask(__name__)
        app.add_url_rule("/<hey>", "foobar", view_func=lambda x: x)
        field = fields.Url()

        with app.test_request_context("/hey"):
            self.assertRaises(MarshallingException, lambda: field.output("hey", None))

    def test_url_without_endpoint(self):
        app = Flask(__name__)
        app.add_url_rule("/<hey>", "foobar", view_func=lambda x: x)
        field = fields.Url()

        with app.test_request_context("/hey"):
            self.assertEquals("/3", field.output("hey", Foo()))

    def test_url_without_endpoint_absolute(self):
        app = Flask(__name__)
        app.add_url_rule("/<hey>", "foobar", view_func=lambda x: x)
        field = fields.Url(absolute=True)

        with app.test_request_context("/hey"):
            self.assertEquals("http://localhost/3", field.output("hey", Foo()))

    def test_url_without_endpoint_absolute_scheme(self):
        app = Flask(__name__)
        app.add_url_rule("/<hey>", "foobar", view_func=lambda x: x)
        field = fields.Url(absolute=True, scheme='https')

        with app.test_request_context("/hey", base_url="http://localhost"):
            self.assertEquals("https://localhost/3", field.output("hey", Foo()))

    def test_url_with_blueprint_invalid_object(self):
        app = Flask(__name__)
        bp = Blueprint("foo", __name__, url_prefix="/foo")
        bp.add_url_rule("/<hey>", "foobar", view_func=lambda x: x)
        app.register_blueprint(bp)
        field = fields.Url()

        with app.test_request_context("/foo/hey"):
            self.assertRaises(MarshallingException, lambda: field.output("hey", None))

    def test_url_with_blueprint(self):
        app = Flask(__name__)
        bp = Blueprint("foo", __name__, url_prefix="/foo")
        bp.add_url_rule("/<hey>", "foobar", view_func=lambda x: x)
        app.register_blueprint(bp)
        field = fields.Url()

        with app.test_request_context("/foo/hey"):
            self.assertEquals("/foo/3", field.output("hey", Foo()))

    def test_url_with_blueprint_absolute(self):
        app = Flask(__name__)
        bp = Blueprint("foo", __name__, url_prefix="/foo")
        bp.add_url_rule("/<hey>", "foobar", view_func=lambda x: x)
        app.register_blueprint(bp)
        field = fields.Url(absolute=True)

        with app.test_request_context("/foo/hey"):
            self.assertEquals("http://localhost/foo/3", field.output("hey", Foo()))

    def test_url_with_blueprint_absolute_scheme(self):
        app = Flask(__name__)
        bp = Blueprint("foo", __name__, url_prefix="/foo")
        bp.add_url_rule("/<hey>", "foobar", view_func=lambda x: x)
        app.register_blueprint(bp)
        field = fields.Url(absolute=True, scheme='https')

        with app.test_request_context("/foo/hey", base_url="http://localhost"):
            self.assertEquals("https://localhost/foo/3", field.output("hey", Foo()))

    def test_int(self):
        field = fields.Integer()
        self.assertEquals(3, field.output("hey", {'hey': 3}))

{'fraction_non_alphanumeric': 0.1492014569907537, 'fraction_numerical': 0.007845334827682824, 'mean_word_length': 2.8880718954248366, 'pattern_counts': {'":': 14, '<': 19, '<?xml version=': 0, '>': 19, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5133527', 'n_tokens_mistral': 4550, 'n_tokens_neox': 4305, 'n_words': 903}