コード例 #1
0
class StationViewApiTest(TestCase):
    """
    Tests the Station View API
    """
    station = None

    def setUp(self):
        self.antenna = AntennaFactory()
        self.encoder = JSONEncoder()
        self.station = StationFactory.create(antennas=[self.antenna])

    def test_station_view_api(self):

        ants = self.station.antenna.all()
        ser_ants = [" ".join([ant.band, ant.get_antenna_type_display()]) for ant in ants]

        station_serialized = {
            u'altitude': self.station.alt,
            u'antenna': ser_ants,
            u'created': self.encoder.default(self.station.created),
            u'description': self.station.description,
            u'id': self.station.id,
            u'last_seen': self.encoder.default(self.station.last_seen),
            u'lat': self.station.lat,
            u'lng': self.station.lng,
            u'location': self.station.location,
            u'min_horizon': self.station.horizon,
            u'name': self.station.name,
            u'observations': 0,
            u'qthlocator': self.station.qthlocator,
            u'status': self.station.get_status_display()}

        response = self.client.get('/api/stations/')
        response_json = json.loads(response.content)
        self.assertEqual(response_json, [station_serialized])
コード例 #2
0
    def json(self, dict=False, original=False, **kwargs):
        """
        Returns a NetJSON NetworkGraph Node object.

        If ``original`` is passed, the data will be returned
        as it has been collected from the network (used when
        doing the comparison).
        """
        netjson = OrderedDict({'id': self.netjson_id})
        label = self.get_name()
        if label:
            netjson['label'] = label
        for attr in ['local_addresses', 'properties']:
            value = getattr(self, attr)
            if value or attr == 'properties':
                netjson[attr] = deepcopy(value)
        if not original:
            netjson['properties'].update(deepcopy(self.user_properties))
            netjson['properties']['created'] = JSONEncoder().default(
                self.created)
            netjson['properties']['modified'] = JSONEncoder().default(
                self.modified)
        if dict:
            return netjson
        return json.dumps(netjson, cls=JSONEncoder, **kwargs)
コード例 #3
0
 def test_json(self):
     t = self.topology_model.objects.first()
     n = t._create_node(
         label='test node',
         addresses=['192.168.0.1', '10.0.0.1'],
         properties={"gateway": True},
     )
     self.assertEqual(
         dict(n.json(dict=True)),
         {
             'id': '192.168.0.1',
             'label': 'test node',
             'local_addresses': ['10.0.0.1'],
             'properties': {
                 'gateway': True,
                 'created': JSONEncoder().default(n.created),
                 'modified': JSONEncoder().default(n.modified),
             },
         },
     )
     self.assertIsInstance(n.json(), str)
     with self.subTest('testing original=True'):
         netjson = n.json(dict=True, original=True)
         self.assertNotIn('created', netjson['properties'])
         self.assertNotIn('modified', netjson['properties'])
コード例 #4
0
    def perform_update(self, serializer):

        existing_customer = self.get_object()
        updated_customer = serializer.save()

        json_encoder = JSONEncoder()
        existing_customer_data = json_encoder.encode(
            self.serializer_class(existing_customer).data
        )
        updated_customer_data = json_encoder.encode(serializer.data)

        if existing_customer_data != updated_customer_data:
            adapter = get_adapter(self.request)
            context = {
                "customer": updated_customer,
            }
            managers_emails = updated_customer.customer_users.managers(
            ).values_list("user__email", flat=True)
            adapter.send_mail(
                "astrosat_users/email/update_customer",
                managers_emails,
                context,
                fail_silently=True,
            )

        return updated_customer
コード例 #5
0
 def json(self, dict=False, **kwargs):
     """
     returns a NetJSON NetworkGraph Node object
     """
     netjson = OrderedDict({'id': self.netjson_id})
     for attr in ['label', 'local_addresses', 'properties']:
         value = getattr(self, attr)
         if value or attr == 'properties':
             netjson[attr] = value
     netjson['properties']['created'] = JSONEncoder().default(self.created)
     netjson['properties']['modified'] = JSONEncoder().default(
         self.modified)
     if dict:
         return netjson
     return json.dumps(netjson, cls=JSONEncoder, **kwargs)
コード例 #6
0
    def render(
        self,
        data: Any,
        accepted_media_type: Optional[str] = None,
        renderer_context: Any = None,
    ) -> bytes:
        """
        Render `data` into JSON, returning a bytestring.
        """
        if data is None:
            return b""

        renderer_context = renderer_context or {}

        ret = orjson.dumps(
            data,
            option=orjson.OPT_NON_STR_KEYS,
            default=JSONEncoder().default,
        )

        # We always fully escape \u2028 and \u2029 to ensure we output JSON
        # that is a strict javascript subset.
        # See: http://timelessrepo.com/json-isnt-a-javascript-subset
        ret = ret.replace(b"\u2028", b"\\u2028").replace(b"\u2029", b"\\u2029")
        return ret
コード例 #7
0
    def _serialize_datetime(cls, dt):  # pylint: disable=invalid-name
        """ Serializes datetime values using Django REST Framework's encoder.

        Use this to simplify equality assertions.
        """
        if dt:
            return JSONEncoder().default(dt)
        return None
コード例 #8
0
    def perform_update(self, serializer):

        existing_customer_user = self.get_object()
        updated_customer_user = serializer.save()

        json_encoder = JSONEncoder()
        existing_customer_user_user_data = json_encoder.encode(
            self.serializer_class(existing_customer_user).data["user"]
        )
        updated_customer_user_user_data = json_encoder.encode(
            serializer.data["user"]
        )

        adapter = get_adapter(self.request)
        context = {
            "user": updated_customer_user.user,
            "customer": updated_customer_user.customer,
        }

        if existing_customer_user_user_data != updated_customer_user_user_data:
            template_prefix = "astrosat_users/email/update_user"
            adapter.send_mail(
                template_prefix, updated_customer_user.user.email, context, fail_silently=True,
            )

        if existing_customer_user.customer_user_type != updated_customer_user.customer_user_type:

            if updated_customer_user.customer_user_type == CustomerUserType.MANAGER:
                # customer_user was something else, now it's a MANAGER
                template_prefix = "astrosat_users/email/admin_assign"
            elif existing_customer_user.customer_user_type == CustomerUserType.MANAGER:
                # customer_user was a MANAGER, now it's something else
                template_prefix = "astrosat_users/email/admin_revoke"

            adapter.send_mail(
                template_prefix, updated_customer_user.user.email, context, fail_silently=True,
            )

        return updated_customer_user
コード例 #9
0
 def _serialize_course_mode(course_mode):
     """ Serialize a CourseMode to a dict. """
     # encode the datetime (if nonempty) using DRF's encoder, simplifying
     # equality assertions.
     expires = course_mode.expiration_datetime
     if expires is not None:
         expires = JSONEncoder().default(expires)
     return {
         u'name': course_mode.mode_slug,
         u'currency': course_mode.currency.lower(),
         u'price': course_mode.min_price,
         u'sku': course_mode.sku,
         u'expires': expires,
     }
コード例 #10
0
ファイル: renderers.py プロジェクト: bibbox/app-azizi-onadata
 def default(self, obj):
     # Handle Decimal NaN values
     if isinstance(obj, decimal.Decimal) and math.isnan(obj):
         return None
     return JSONEncoder.default(self, obj)
コード例 #11
0
 def setUp(self):
     self.antenna = AntennaFactory()
     self.encoder = JSONEncoder()
     self.station = StationFactory.create(antennas=[self.antenna])
コード例 #12
0
class JSONEncoderTests(TestCase):
    """
    Tests the JSONEncoder method
    """

    def setUp(self):
        self.encoder = JSONEncoder()

    def test_encode_decimal(self):
        """
        Tests encoding a decimal
        """
        d = Decimal(3.14)
        assert d == float(d)

    def test_encode_datetime(self):
        """
        Tests encoding a datetime object
        """
        current_time = datetime.now()
        assert self.encoder.default(current_time) == current_time.isoformat()

    def test_encode_time(self):
        """
        Tests encoding a timezone
        """
        current_time = datetime.now().time()
        assert self.encoder.default(current_time) == current_time.isoformat()[:12]

    def test_encode_time_tz(self):
        """
        Tests encoding a timezone aware timestamp
        """

        class UTC(tzinfo):
            """
            Class extending tzinfo to mimic UTC time
            """
            def utcoffset(self, dt):
                return timedelta(0)

            def tzname(self, dt):
                return "UTC"

            def dst(self, dt):
                return timedelta(0)

        current_time = datetime.now().time()
        current_time = current_time.replace(tzinfo=UTC())
        with self.assertRaises(ValueError):
            self.encoder.default(current_time)

    def test_encode_date(self):
        """
        Tests encoding a date object
        """
        current_date = date.today()
        assert self.encoder.default(current_date) == current_date.isoformat()

    def test_encode_timedelta(self):
        """
        Tests encoding a timedelta object
        """
        delta = timedelta(hours=1)
        assert self.encoder.default(delta) == str(delta.total_seconds())

    def test_encode_uuid(self):
        """
        Tests encoding a UUID object
        """
        unique_id = uuid4()
        assert self.encoder.default(unique_id) == str(unique_id)
コード例 #13
0
 def default(self, obj):
     if isinstance(obj, (Server, Tenant, QuotaSet)):
         return obj.to_dict()
     return JSONEncoder.default(self, obj)
コード例 #14
0
ファイル: renderers.py プロジェクト: onaio/onadata
 def default(self, obj):  # pylint: disable=method-hidden
     # Handle Decimal NaN values
     if isinstance(obj, decimal.Decimal) and math.isnan(obj):
         return None
     return JSONEncoder.default(self, obj)
コード例 #15
0
class JSONEncoderTests(TestCase):
    """
    Tests the JSONEncoder method
    """

    def setUp(self):
        self.encoder = JSONEncoder()

    def test_encode_decimal(self):
        """
        Tests encoding a decimal
        """
        d = Decimal(3.14)
        assert self.encoder.default(d) == float(d)

    def test_encode_datetime(self):
        """
        Tests encoding a datetime object
        """
        current_time = datetime.now()
        assert self.encoder.default(current_time) == current_time.isoformat()
        current_time_utc = current_time.replace(tzinfo=utc)
        assert self.encoder.default(current_time_utc) == current_time.isoformat() + 'Z'

    def test_encode_time(self):
        """
        Tests encoding a timezone
        """
        current_time = datetime.now().time()
        assert self.encoder.default(current_time) == current_time.isoformat()

    def test_encode_time_tz(self):
        """
        Tests encoding a timezone aware timestamp
        """
        current_time = datetime.now().time()
        current_time = current_time.replace(tzinfo=utc)
        with pytest.raises(ValueError):
            self.encoder.default(current_time)

    def test_encode_date(self):
        """
        Tests encoding a date object
        """
        current_date = date.today()
        assert self.encoder.default(current_date) == current_date.isoformat()

    def test_encode_timedelta(self):
        """
        Tests encoding a timedelta object
        """
        delta = timedelta(hours=1)
        assert self.encoder.default(delta) == str(delta.total_seconds())

    def test_encode_uuid(self):
        """
        Tests encoding a UUID object
        """
        unique_id = uuid4()
        assert self.encoder.default(unique_id) == str(unique_id)

    @pytest.mark.skipif(not coreapi, reason='coreapi is not installed')
    def test_encode_coreapi_raises_error(self):
        """
        Tests encoding a coreapi objects raises proper error
        """
        with pytest.raises(RuntimeError):
            self.encoder.default(coreapi.Document())

        with pytest.raises(RuntimeError):
            self.encoder.default(coreapi.Error())

    def test_encode_object_with_tolist(self):
        """
        Tests encoding a object with tolist method
        """
        foo = MockList()
        assert self.encoder.default(foo) == [1, 2, 3]
コード例 #16
0
class JSONEncoderTests(TestCase):
    """
    Tests the JSONEncoder method
    """
    def setUp(self):
        self.encoder = JSONEncoder()

    def test_encode_decimal(self):
        """
        Tests encoding a decimal
        """
        d = Decimal(3.14)
        assert self.encoder.default(d) == float(d)

    def test_encode_datetime(self):
        """
        Tests encoding a datetime object
        """
        current_time = datetime.now()
        assert self.encoder.default(current_time) == current_time.isoformat()
        current_time_utc = current_time.replace(tzinfo=utc)
        assert self.encoder.default(
            current_time_utc) == current_time.isoformat() + 'Z'

    def test_encode_time(self):
        """
        Tests encoding a timezone
        """
        current_time = datetime.now().time()
        assert self.encoder.default(current_time) == current_time.isoformat()

    def test_encode_time_tz(self):
        """
        Tests encoding a timezone aware timestamp
        """
        current_time = datetime.now().time()
        current_time = current_time.replace(tzinfo=utc)
        with pytest.raises(ValueError):
            self.encoder.default(current_time)

    def test_encode_date(self):
        """
        Tests encoding a date object
        """
        current_date = date.today()
        assert self.encoder.default(current_date) == current_date.isoformat()

    def test_encode_timedelta(self):
        """
        Tests encoding a timedelta object
        """
        delta = timedelta(hours=1)
        assert self.encoder.default(delta) == str(delta.total_seconds())

    def test_encode_uuid(self):
        """
        Tests encoding a UUID object
        """
        unique_id = uuid4()
        assert self.encoder.default(unique_id) == str(unique_id)

    @pytest.mark.skipif(not coreapi, reason='coreapi is not installed')
    def test_encode_coreapi_raises_error(self):
        """
        Tests encoding a coreapi objects raises proper error
        """
        with pytest.raises(RuntimeError):
            self.encoder.default(coreapi.Document())

        with pytest.raises(RuntimeError):
            self.encoder.default(coreapi.Error())

    def test_encode_object_with_tolist(self):
        """
        Tests encoding a object with tolist method
        """
        foo = MockList()
        assert self.encoder.default(foo) == [1, 2, 3]
コード例 #17
0
 def default(self, obj):  # pylint: disable=method-hidden
     # Handle Decimal NaN values
     if isinstance(obj, decimal.Decimal) and math.isnan(obj):
         return None
     return JSONEncoder.default(self, obj)
コード例 #18
0
 def setUp(self):
     self.encoder = JSONEncoder()