# Path: salmon/metrics/serializers.py
# class MetricSerializer(serializers.ModelSerializer):
#     source = serializers.CharField(source='source.name', required=False)
#     value = serializers.FloatField(source='latest_value')
#     timestamp = serializers.DateTimeField(source='last_updated',
#                                           required=False)
# 
#     class Meta:
#         model = models.Metric
#         fields = ('source', 'name', 'value', 'timestamp')
# 
#     def validate_source(self, attrs, source):
#         if source in attrs:
#             try:
#                 reverse("history", args=[attrs[source]])
#             except NoReverseMatch:
#                 raise serializers.ValidationError("Source is invalid.")
#         return attrs
# 
#     def restore_object(self, attrs, instance=None):
#         kwargs = {'name': attrs['name']}
#         if 'source.name' in attrs:
#             source, created = models.Source.objects.get_or_create(
#                 name=attrs['source.name'])
#             if created:
#                 logger.debug('Created source: %s', source.name)
#             kwargs['source_id'] = source.pk
#         try:
#             instance = self.opts.model.objects.get(**kwargs)
#         except self.opts.model.DoesNotExist:
#             instance = self.opts.model(**kwargs)
#         instance.latest_value = attrs['latest_value']
#         instance.last_updated = attrs.get('timestamp', now())
#         return instance
# 
#     def save_object(self, obj, **kwargs):
#         if 'force_insert' in kwargs:
#             del(kwargs['force_insert'])
#         super(MetricSerializer, self).save_object(obj, **kwargs)
#         obj.add_latest_to_archive()
# 
# Path: salmon/metrics/models.py
# class Source(models.Model):
# class Metric(models.Model):
#     class Meta:
# class MetricGroup(Metric):
#     class Meta:
#     def __unicode__(self):
#     def get_absolute_url(self):
#     def __init__(self, *args, **kwargs):
#     def _reset_changes(self):
#     def whisper_filename(self):
#     def add_latest_to_archive(self):
#     def get_or_create_archive(self):
#     def load_archive(self, from_date, to_date=None):
#     def in_alert_state(self):
#     def get_value_display(self):
#     def time_between_updates(self):
#     def do_transform(self):
#     def do_counter_conversion(self):
#     def check_alarm(self):
#     def save(self, *args, **kwargs):
#     OPERATOR_CHOICES = (
#         ('lt', 'value < alert'),
#         ('le', 'value <= alert'),
#         ('eq', 'value == alert'),
#         ('ne', 'value != alert'),
#         ('ge', 'value >= alert'),
#         ('gt', 'value > alert'),
#     )
#     DISPLAY_CHOICES = (
#         ('float', 'Number'),
#         ('boolean', 'True/False'),
#         ('byte', 'Bytes'),
#         ('percentage', 'Percentage'),
#         ('second', 'Seconds'),
#     )


from django.test import TestCase
from salmon.metrics.serializers import MetricSerializer
from salmon.metrics import models


class TestSerializer(TestCase):

    def test_single(self):
        data = {'source': 'test.example.com',
                'name': 'load',
                'value': 0.1}
        serializer = MetricSerializer(data=data)
        self.assertTrue(serializer.is_valid())
        serializer.save()
        metric = models.Metric.objects.get(pk=serializer.object.pk)
        self.assertEqual(data['source'], metric.source.name)
        self.assertEqual(data['name'], metric.name)
        self.assertEqual(data['value'], metric.latest_value)
        self.assertFalse(metric.last_updated is None)


    def test_multi(self):
        data = [
            {'source': 'test.example.com', 'name': 'load', 'value': 0.1},
            {'source': 'multi.example.com', 'name': 'cpu', 'value': 55.5},
        ]
        serializer = MetricSerializer(data=data)
        self.assertTrue(serializer.is_valid())
        serializer.save()
        for item in data:

# Path: salmon/metrics/serializers.py
# class MetricSerializer(serializers.ModelSerializer):
#     source = serializers.CharField(source='source.name', required=False)
#     value = serializers.FloatField(source='latest_value')
#     timestamp = serializers.DateTimeField(source='last_updated',
#                                           required=False)
# 
#     class Meta:
#         model = models.Metric
#         fields = ('source', 'name', 'value', 'timestamp')
# 
#     def validate_source(self, attrs, source):
#         if source in attrs:
#             try:
#                 reverse("history", args=[attrs[source]])
#             except NoReverseMatch:
#                 raise serializers.ValidationError("Source is invalid.")
#         return attrs
# 
#     def restore_object(self, attrs, instance=None):
#         kwargs = {'name': attrs['name']}
#         if 'source.name' in attrs:
#             source, created = models.Source.objects.get_or_create(
#                 name=attrs['source.name'])
#             if created:
#                 logger.debug('Created source: %s', source.name)
#             kwargs['source_id'] = source.pk
#         try:
#             instance = self.opts.model.objects.get(**kwargs)
#         except self.opts.model.DoesNotExist:
#             instance = self.opts.model(**kwargs)
#         instance.latest_value = attrs['latest_value']
#         instance.last_updated = attrs.get('timestamp', now())
#         return instance
# 
#     def save_object(self, obj, **kwargs):
#         if 'force_insert' in kwargs:
#             del(kwargs['force_insert'])
#         super(MetricSerializer, self).save_object(obj, **kwargs)
#         obj.add_latest_to_archive()
# 
# Path: salmon/metrics/models.py
# class Source(models.Model):
# class Metric(models.Model):
#     class Meta:
# class MetricGroup(Metric):
#     class Meta:
#     def __unicode__(self):
#     def get_absolute_url(self):
#     def __init__(self, *args, **kwargs):
#     def _reset_changes(self):
#     def whisper_filename(self):
#     def add_latest_to_archive(self):
#     def get_or_create_archive(self):
#     def load_archive(self, from_date, to_date=None):
#     def in_alert_state(self):
#     def get_value_display(self):
#     def time_between_updates(self):
#     def do_transform(self):
#     def do_counter_conversion(self):
#     def check_alarm(self):
#     def save(self, *args, **kwargs):
#     OPERATOR_CHOICES = (
#         ('lt', 'value < alert'),
#         ('le', 'value <= alert'),
#         ('eq', 'value == alert'),
#         ('ne', 'value != alert'),
#         ('ge', 'value >= alert'),
#         ('gt', 'value > alert'),
#     )
#     DISPLAY_CHOICES = (
#         ('float', 'Number'),
#         ('boolean', 'True/False'),
#         ('byte', 'Bytes'),
#         ('percentage', 'Percentage'),
#         ('second', 'Seconds'),
#     )


# Path: salmon/metrics/tests/test_serializers.py
from django.test import TestCase
from salmon.metrics.serializers import MetricSerializer
from salmon.metrics import models



class TestSerializer(TestCase):

    def test_single(self):
        data = {'source': 'test.example.com',
                'name': 'load',
                'value': 0.1}
        serializer = MetricSerializer(data=data)
        self.assertTrue(serializer.is_valid())
        serializer.save()
        metric = models.Metric.objects.get(pk=serializer.object.pk)
        self.assertEqual(data['source'], metric.source.name)
        self.assertEqual(data['name'], metric.name)
        self.assertEqual(data['value'], metric.latest_value)
        self.assertFalse(metric.last_updated is None)


    def test_multi(self):
        data = [
            {'source': 'test.example.com', 'name': 'load', 'value': 0.1},
            {'source': 'multi.example.com', 'name': 'cpu', 'value': 55.5},
        ]
        serializer = MetricSerializer(data=data)
        self.assertTrue(serializer.is_valid())
        serializer.save()
        for item in data:

            source = models.Source.objects.get(name=item['source'])