summaryrefslogtreecommitdiff
path: root/linaropy/series.py
blob: e1d435d6e16b1b339a55b5f300723d43440fbbe5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
import unittest
import logging
import os
import uuid
import string
from collections import OrderedDict
import copy

from linaropy.vers import Spin, Rc, Vendor, Package, packageFromStr

from datetime import datetime
from dateutil.relativedelta import relativedelta


class Series(object):
    """
    A Series represents a package candidate, snapshot, or release and includes
    version, package, date, and spin information.
    """
    series = ['candidate', 'snapshot', 'release']
    serieslongupper = ['Release-Candidate', 'Snapshot', 'Release']

    # @ seriestype - 'type' of either 'candidate', 'snapshot', or 'release'
    # @ package - String or Package object representing the series package
    #             name with version string, e.g., 'GCC-5.3.1'
    # @ vendor - String or Vendor object representing the vendor that is
    #            tagged on this series.
    # @ date - String or 'datetime' object representing the YYYY.MM of this
    #          series.  It defaults to 'today'
    # @ spin - Optional Spin, str, or int
    # @ rc - Optional Rc, str, or int
    # This will make sure snapshot doesn't have an rc and release doesn't have
    # an rc for instance.
    def __init__(self, seriestype, vendor=None, package=None,
                 date=datetime.today(), spin=None, rc=None, strict=True):
        """
        Create a Series to store the details on a package release, snapshot,
        or release-candidate.

        Parameters
        ----------
        seriestype : str
            "candidate", "release", or "snapshot"

        vendor : str
            A String representing the vendor for the series.  The default is
            inherited from the Vendor class.

        package : str or Package
            Designate the package that this Series represents, for example,
            'gcc'.  The default is inherited from the Package class.

        date : str or datetime
            "YYYY.MM", "YY.MM", or a datetime object representing the Series.

        spin : Spin
            A spin number for the Series.

        rc : Rc
            An rc number for the Series.

        strict=True : bool
            Enforce rules regarding whether candidates can/cannot have Rcs.
        """
        if isinstance(spin, Spin):
            self.spin = spin
        else:
            # Spin will raise an exception if spin is the wrong type.
            # A None parameter will create a Spin with an internal value of
            # None.
            self.spin = Spin(spin)

        if isinstance(rc, Rc):
            self.rc = rc
        else:
            # Rc will raise an exception if rc is the wrong type.  A None parameter
            # will create an Rc with an internal value of None.
            self.rc = Rc(rc)

        if isinstance(date, datetime):
            # Force all of the days of the month to 15 to unify comparisons.
            date.replace(day=15)
            self.date = date
        else:
            # 'date' is a string.  If the input date can't be parsed by datetime
            # it will throw an exception.  We can't recover from it so just pass
            # it up.
            if len(date) < 10:
                tmpdate = datetime.strptime(date, "%Y.%m")
            else:
                tmpdate = datetime.strptime(date, "%Y.%m.%d")
            # Force all of the days of the month to 15 to unify comparisons.
            self.date = tmpdate.replace(day=15)

        # If the input vendor=None just instantiate the default vendor.
        if not vendor:
            self.vendor = Vendor()
        else:
            self.vendor = vendor

        if not package:
            raise TypeError('Series requires an input package.')
        elif isinstance(package, Package):
            self.package = package
        elif isinstance(package, str):
            self.package = packageFromStr(package)
        else:
            # There can't be a defaut package because it requires a version.
            raise TypeError(
                "Series 'package' unrecognized type " + str(type(package)))

        # We might want to uniquely identify a particular Series object.
        self.uniqueid = str(uuid.uuid4())

        # We store a seriestype as an integer into an enumeration array
        # so that the names can be changed as desired.
        try:
            self.seriestype = Series.series.index(seriestype.lower())
        except ValueError:
            self.seriestype = -1  # no match
            raise TypeError('Invalid series type %s.' % seriestype)

        # rc can only be non-None for release-candidates.
        if strict:
            if self.seriestype == Series.series.index("snapshot"):
                if self.rc.val != 0:
                    raise ValueError('A snapshot series cannot have an rc.')
            elif self.seriestype == Series.series.index("release"):
                if self.rc.val != 0:
                    raise ValueError('A release series cannot have an rc.')

        if self.seriestype == Series.series.index(
                "candidate") and self.rc.val is 0:
            raise TypeError('A candidate series must have an rc specified.')

        # We need an OrderedDict because we want to parse/capture -%X and .%X
        # before %X and a regular dict won't guarantee that iterkeys returns in
        # the inserted order.. This dict starts out empty and we'll populate it
        # in the same way we will udpate it later.  This is used for the
        # __format__ function for quick formatting.
        self.fmt = OrderedDict()
        self.fmt['%N'] = None
        self.fmt['-%L'] = None
        self.fmt['.%L'] = None
        self.fmt['%L'] = None
        self.fmt['%P'] = None
        self.fmt['%l'] = None
        self.fmt['%V'] = None
        self.fmt['%v'] = None
        self.fmt['%E'] = None
        self.fmt['%e'] = None
        self.fmt['%M'] = None
        self.fmt['%m'] = None
        self.fmt['%p'] = None
        self.fmt['%D'] = None
        self.fmt['%h'] = None
        self.fmt['%d'] = None
        # Match and strip the key '-' as Spin might be empty.
        self.fmt['-%S'] = None
        # Match and strip the key '.' as Spin might be empty.
        self.fmt['.%S'] = None
        self.fmt['%S'] = None
        # Match and strip the key '-' as Rc might be empty.
        self.fmt['-%R'] = None
        # Match and strip the key '.' as Rc might be empty.
        self.fmt['.%R'] = None
        self.fmt['%R'] = None

        # Fill in the values.
        for key in self.fmt.keys():
            self.update_fmtdict(key)

    def update_fmtdict(self, key):
        if key == '%N':
            self.fmt['%N'] = self.get_namespace()
        elif key == '-%L':
            self.fmt['-%L'] = self.serieslabel()
            return
        elif key == '.%L':
            # Only prepend '.' if there's actually a series label.
            label = self.serieslabel()
            self.fmt['.%L'] = str.replace(label, '-', '.')
            return
        elif key == '%L':
            self.fmt['%L'] = self.serieslabel().strip('-')
            return
        elif key == '%P':
            self.fmt['%P'] = self.package.package
        elif key == '%l':
            self.fmt['%l'] = self.package.package.lower()
        elif key == '%V':
            self.fmt['%V'] = str(self.vendor)
        elif key == '%v':
            self.fmt['%v'] = self.vendor.lower()
        elif key == '%E':
            self.fmt['%E'] = self.package.version.strfversion("%M%m")
        elif key == '%e':
            self.fmt['%e'] = self.package.version.strfversion("%M%m%p")
        elif key == '%M':
            self.fmt['%M'] = self.package.version.strfversion("%M")
        elif key == '%m':
            self.fmt['%m'] = self.package.version.strfversion("%m")
        elif key == '%p':
            self.fmt['%p'] = self.package.version.strfversion("%p")
        elif key == '%D':
            self.fmt['%D'] = self.date.strftime("%Y.%m")
        elif key == '%h':
            self.fmt['%h'] = self.get_server()
        elif key == '%d':
            self.fmt['%d'] = self.get_dir()
        elif key == '-%S':
            # This will include the '-' if present.
            self.fmt['-%S'] = str(self.spin)
        elif key == '.%S':
            spin = str(self.spin)
            self.fmt['.%S'] = str.replace(spin, '-', '.')
        elif key == '%S':
            self.fmt['%S'] = str(self.spin).strip('-')
        elif key == '-%R':
            # This will include the '-' is present.
            self.fmt['-%R'] = str(self.rc)
        elif key == '.%R':
            rc = str(self.rc)
            self.fmt['.%R'] = str.replace(rc, '-', '.')
        elif key == '%R':
            self.fmt['%R'] = str(self.rc).strip('-')
        else:
            raise KeyError('Unknown format key.')

    def __format__(self, format_spec):
        """
        Format an output string based on format spec.

        This function will take a format spec which includes mixture of text to
        be preserved as well as format designators which indicate series
        information to be substituted in place.  Take the following format_spec:

            "%V released this product"

        This would be formatted as "Linaro released this product"

        call using:

        formattedstr=format(series_instance, 'string_with_delimiters')

        delimiters
        ----------

        %N : git repository branch namespace.

        %L : series label

            This is only valid for snapshots.  Releases and candidates will
            result in an empty string.

            Note: This is special.  If -%L or .%L is in the format_spec and
            there is no series label (for release and candidates) then the
            leading '-' or '.' will be stripped as well.

        %P : package name

        %l : lowercase package name

        %V : vendor

        %v : lowercase vendor

        %E : Version Major.Minor
            Note: if Minor doen't exist the . delimiter won't be displayed.

        %E : Version Major.Minor.Point
            Note: if Minor or Point don't exist the . delimiters won't be
            displayed.

        %M : Version Major

        %m : Version Minor
            Note: if Minor doesn't exist the . delimiter won't be displayed.

        %p : Version Point
            Note: if Point doesn't exist the . delimiter won't be displayed.

        %D : Series date in YYYY.MM format.

        %h : snapshot or release server.

        %d : Series dir representation.

        %S : Spin number
            Note: This is special.  If -%S or .%S is in the format_spec and
            there is no Spin then the leading '-' or '.' will be stripped as
            well.

        %R : Rc number
            Note: This is special.  If -%R or .%R is in the format_spec and
            there is no Rc then the leading '-' or '.' will be stripped as
            well.
        """
        ret = ''
        # Iterate across the dictionary and for each key found replace the key
        # with the contents of the fmt dictionary.
        ret = format_spec
        for key in self.fmt.keys():
            if key in ret:
                # Update the relevant keys everytime through because the user
                # might have changed things.
                self.update_fmtdict(key)
                replac = self.fmt[key]
                ret = str.replace(ret, key, replac)
        return ret

    def serieslabel(self):
        # Only the 'snapshot-' is used in a label.
        if self.seriestype == Series.series.index("snapshot"):
            return '-' + Series.series[self.seriestype]
        else:
            return ''

    def shorttype(self):
        return Series.series[self.seriestype]

    def longlowertype(self):
        return Series.serieslongupper[self.seriestype].lower()

    def longuppertype(self):
        return Series.serieslongupper[self.seriestype]

    def __str__(self):
        return Series.series[self.seriestype] + "_" + self.uniqueid

    def label(self):
        label = str(self.vendor) + self.serieslabel() + \
            '-' + str(self.package)
        label = label + '-' + self.date.strftime("%Y.%m")
        label = label + str(self.spin) + str(self.rc)
        return label

    def incrementMonth(self):
        self.date = self.date + relativedelta(months=1)

    def get_dir(self):
        dirstr = self.package.version.strfversion("%M%m")
        dirstr = dirstr + '-' + self.date.strftime("%Y.%m")
        dirstr = dirstr + str(self.spin)
        dirstr = dirstr + str(self.rc)
        return dirstr

    def get_server(self):
        namespace = 'snapshots'
        if self.seriestype == Series.series.index("release"):
            namespace = 'releases'
        return namespace

    def get_namespace(self):
        namespace = 'releases'
        if self.seriestype == Series.series.index("snapshot"):
            namespace = 'snapshots'
        return namespace

    # TODO: Document what a conformant branch name looks like.
    # Return a conformant branch name from the Series information.
    def branchname(self):
        """
        Return a branchname in the form of:

        <namespace>/<vendor>-<package_version>-<date>-<spin>-<rc>

        return value
        ------------
        string represensting the branch name.
        """
        branchname = ''
        if self.seriestype == Series.series.index("snapshot"):
            branchname = branchname + 'snapshots/'
        else:
            branchname = branchname + 'releases/'

        branchname = branchname + self.vendor.lower()
        branchname = branchname + '-' + \
            self.package.version.strfversion("%M%m")
        branchname = branchname + '-' + self.date.strftime("%Y.%m")
        branchname = branchname + str(self.spin)
        branchname = branchname + str(self.rc)

        return branchname


def series_from_branchname(branch=None):
    """
    Create a Series from a branch name string.

    Parameters
    ----------
    branch : str

        The branchname of a package as it lives in a git repository.  A properly formed
        branch name has the following elements, where options in brackets are optional:

        <namespace>/<package-version>-<YYYY>.<MM>[-spin][-rcN]

        Snapshot
        --------
        snapshots/<foo>[!-rcN]

        Candidate
        ---------
        releases/<foo>-rcN

        Release
        -------
        releases/<foo>[!-rcN]
    """
    logging.info("Branch is %s." % branch)
    if not isinstance(branch, str):
        raise TypeError(
            'series_from_branchname requires a basestring as input')

    if not branch:
        raise TypeError(
            'series_from_branchname requires a non-empty string as input')

    # Get the part before the '/'.  That's the namespace
    try:
        namespace = branch.rsplit('/', 1)[0]
    except IndexError:
        raise ValueError(
            'string must have a namespace, e.g., <namespace>/<everything_else>')

    # Get everything after the '/'.
    try:
        seriesstr = branch.rsplit('/', 1)[1]
    except IndexError:
        raise ValueError(
            "string must delimit the namespace from the right branch with a"
            " '/' char, e.g., <namespace>/<vendor>-<package_version>")

    # TODO: Are these necessary or did the previous cases cover it?
    # if namespace == u'':
    #    raise ValueError("Couldn't parse a namespace from input string")
    # This will catch where there's a namespace/ but no right hand value after
    # the /.
    if seriesstr == '':
        raise ValueError(
            "Couldn't parse a series from input string.  Missing a branch name.")

    keys = ['vendor', 'version', 'date', 'spin', 'rc']
    # This might generate key errors, depending on whether anything can be
    # parsed from the right-hand values.
    values = seriesstr.split('-')
    dictionary = dict(list(zip(keys, values)))

    # if there is no spin but there is an 'rcX' in the spin key:value pair
    # it means that there's really no spin but should be in the rc key:value
    # pair.
    if "spin" in dictionary and "rc" in dictionary["spin"]:
        dictionary["rc"] = dictionary["spin"]
        dictionary.pop("spin", None)

    # We need to have None fields in the missing keys for when we call the
    # Series constructor.
    if "rc" not in dictionary:
        dictionary["rc"] = None
    else:
        # strip the "rc" and just leave the int.
        if dictionary["rc"].startswith("rc"):
            try:
                dictionary["rc"] = int(dictionary["rc"][2:])
            except ValueError:
                raise TypeError("The rc value must be an integer.")

    # We need to have None fields in the missing keys for when we call the
    # Series constructor.
    if "spin" not in dictionary:
        dictionary["spin"] = None
    else:
        if not dictionary["spin"].isnumeric():
            raise TypeError("The spin must be numeric.")

    seriesdate = datetime.today
    if dictionary["date"]:
        datekeys = ['year', 'month', 'day']
        datevalues = dictionary["date"].split('.')
        datefields = dict(list(zip(datekeys, datevalues)))
        if "day" not in datefields:
            datefields["day"] = "15"
        seriesdate = datetime(int(datefields["year"]), int(
            datefields["month"]), int(datefields["day"]))

    if "snapshots" in namespace and dictionary["rc"]:
        raise ValueError(
            'A snapshots namespace can not have an rc.  This is a non-conforming input.')
    elif "releases" not in namespace and dictionary["rc"]:
        raise ValueError(
            'An rc must have a "releases" namespace. This is a non-conforming input.')
    elif dictionary["rc"]:
        seriesname = "candidate"
    elif "snapshots" in namespace:
        seriesname = "snapshot"
    elif "releases" in namespace:
        seriesname = "release"
    elif "snapshot" in namespace:
        raise ValueError(
            '"snapshot" is not a complete namespace.  The conforming namespace is "snapshots".')
    else:
        # TODO test for unknown namespace.
        raise ValueError('Unknown namespace in input string.')

    package = Package(package="GCC", version=dictionary["version"])
    series = Series(
        seriesname,
        package=package,
        date=seriesdate,
        spin=dictionary["spin"],
        rc=dictionary["rc"],
        strict=True)

    return series


def series_from_tag(tag=None):
    """
    Create a Series from a git tag name

    Parameters
    ----------
    tag : str

        The git tag of a package as it lives in a git repository.  A properly
        formed tag will take the following form:

        Snapshot
        --------
        linaro-snapshot-Maj.min-YYYY.MM[-spin]

        Candidate
        ---------
        linaro-Maj.min-YYYY.MM[-spin]-rcN

        Release
        -------
        linaro-Maj.min-YYYY.MM[-spin]
    """

    # TODO Test this.
    if not tag:
        raise ValueError('series_from_tag requires a tag')

    # TODO Test this.
    if not isinstance(tag, str):
        raise TypeError('series_from_tag requires a basestring as input')

    # This is default, we'll replace with 'snapshots' if we detect that the
    # tag is indeed a snapshot.
    namespace = "releases"

    # since 'snapshots' tags aren't the same as release and rc tags we need
    # to force conformance, i.e., remove "-snapshot", but record the
    # namespace as snapshots while we're at it.
    if "snapshot" in tag:
        tag = str.replace(tag, "-snapshot", '')
        namespace = "snapshots"

    # Now we're going to cheat and fabricate a false branchname.
    branchname = namespace + '/' + tag

    # ... in which case we can reuse this function.
    return series_from_branchname(branchname)

from linaropy.vers import versionFromStr


class TestSeries(unittest.TestCase):
    """Test the Series class using the unittest framework."""

    def test_missing_seriestype(self):
        with self.assertRaises(TypeError):
            spin = Spin()
            rc = Rc()
            candidate = Series(package="GCC-5.3.1", spin=spin, rc=rc)

    def test_no_match(self):
        with self.assertRaises(TypeError):
            candidate = Series("foobar", package="GCC-5.3.1")

    def test_partial_seriestype_match(self):
        with self.assertRaises(TypeError):
            candidate = Series("candid", package="GCC-5.3.1")

    def test_excessive_seriestype_match(self):
        with self.assertRaises(TypeError):
            candidate = Series("candidate2", package="GCC-5.3.1")

    def test_match_release(self):
        release = Series("release", package="GCC-5.3.1")
        self.assertEqual(str(release).split("_")[0], "release")

    def test_match_candidate_wrongcase(self):
        candidate = Series("Candidate", package="GCC-5.3.1", rc="1")
        self.assertEqual(str(candidate).split("_")[0], "candidate")

    def test_match_snapshot_wrongcase(self):
        snapshot = Series("SNAPSHOT", package="GCC-5.3.1")
        self.assertEqual(str(snapshot).split("_")[0], "snapshot")

    def test_longlowertype_candidate(self):
        candidate = Series("candidate", package="GCC-5.3.1", rc="1")
        self.assertEqual(candidate.longlowertype(), "release-candidate")

    def test_longuppertype_candidate(self):
        candidate = Series("candidate", package="GCC-5.3.1", rc="4")
        self.assertEqual(candidate.longuppertype(), "Release-Candidate")

    def test_shorttype_candidate(self):
        candidate = Series("candidate", package="GCC-5.3.1", rc="1")
        self.assertEqual(candidate.shorttype(), "candidate")

    def test_serieslabel_candidate(self):
        candidate = Series("candidate", package="GCC-5.3.1", rc="1")
        self.assertEqual(candidate.serieslabel(), "")

    def test_serieslabel_release(self):
        candidate = Series("release", package="GCC-5.3.1")
        self.assertEqual(candidate.serieslabel(), "")

    def test_serieslabel_snapshot(self):
        candidate = Series("snapshot", package="GCC-5.3.1")
        self.assertEqual(candidate.serieslabel(), "-snapshot")

    def test_empty_rc(self):
        rc = Rc(7)
        candidate = Series("candidate", package="GCC-5.3.1", rc=rc)
        self.assertEqual(candidate.rc.vers, 7)
        self.assertEqual(str(candidate.rc), "FOO")

    def test_empty_rc(self):
        rc = Rc()
        release = Series("release", package="GCC-5.3.1", rc=rc)
        self.assertEqual(str(release.rc), "")

        release2 = Series("release", package="GCC-5.3.1")
        self.assertEqual(str(release2.rc), "")

    def test_specified_rc(self):
        rc = Rc(7)
        candidate = Series("candidate", package="GCC-5.3.1", rc=rc)
        self.assertEqual(candidate.rc.val, 7)
        self.assertEqual(str(candidate.rc), "-rc7")

    def test_candidate_with_no_rc(self):
        with self.assertRaises(TypeError):
            candidate = Series("candidate", package="GCC-5.3.1")

        with self.assertRaises(TypeError):
            rc = Rc()
            candidate2 = Series("candidate", package="GCC-5.3.1", rc=rc)

    def test_rc_as_string(self):
        candidate = Series("candidate", package="GCC-5.3.1", rc="7")
        self.assertEqual(candidate.rc.val, 7)
        self.assertEqual(str(candidate.rc), "-rc7")

    def test_rc_as_int(self):
        candidate = Series("candidate", package="GCC-5.3.1", rc=7)
        self.assertEqual(candidate.rc.val, 7)
        self.assertEqual(str(candidate.rc), "-rc7")

    def test_rc_as_typeerror(self):
        floatrc = 7.0
        with self.assertRaises(TypeError):
            snapshot = Series("snapshot", package="GCC-5.3.1", rc=floatrc)

    def test_rc_as_negative(self):
        with self.assertRaises(ValueError):
            snapshot = Series("snapshot", package="GCC-5.3.1", rc="-1")

    def test_missing_spin(self):
        snapshot = Series("snapshot", package="GCC-5.3.1")
        self.assertEqual(snapshot.spin.val, 0)
        self.assertEqual(str(snapshot.spin), "")

    def test_specified_spin(self):
        spin = Spin(7)
        snapshot = Series("snapshot", package="GCC-5.3.1", spin=spin)
        self.assertEqual(snapshot.spin.val, 7)
        self.assertEqual(str(snapshot.spin), "-7")

    def test_empty_spin(self):
        spin = Spin()
        snapshot = Series("snapshot", package="GCC-5.3.1", spin=spin)
        self.assertEqual(str(snapshot.spin), "")

    def test_spin_as_string(self):
        snapshot = Series("snapshot", spin="7", package="GCC-5.3.1")
        self.assertEqual(snapshot.spin.val, 7)
        self.assertEqual(str(snapshot.spin), "-7")

    def test_spin_as_int(self):
        snapshot = Series("snapshot", spin=7, package="GCC-5.3.1")
        self.assertEqual(snapshot.spin.val, 7)
        self.assertEqual(str(snapshot.spin), "-7")

    def test_spin_as_typeerror(self):
        floatspin = 7.0
        with self.assertRaises(TypeError):
            snapshot = Series("snapshot", spin=floatspin, package="GCC-5.3.1")

    def test_spin_as_negative(self):
        with self.assertRaises(ValueError):
            snapshot = Series("snapshot", spin="-1", package="GCC-5.3.1")

    def test_empty_spin_and_rc(self):
        release = Series("release", package="GCC-5.3.1")
        self.assertEqual(release.spin.val, 0)
        self.assertEqual(release.rc.val, 0)
        self.assertEqual(str(release.spin), "")
        self.assertEqual(str(release.rc), "")

    def test_package_as_Package(self):
        package = Package("GCC", "5.3.1")
        release = Series("release", package)
        self.assertEqual(str(release.package), "GCC-5.3.1")

    def test_package_as_Package(self):
        # Create a Version instead of a package
        package = versionFromStr("5.3.1")
        with self.assertRaises(TypeError):
            candidate = Series("candidate", package)

    def test_package_as_None(self):
        package = None
        with self.assertRaises(TypeError):
            candidate = Series("candidate", package)

    def test_getbranchname(self):
        candidate = Series("candidate", package="GCC-5.3.1",
                           date=datetime(2016, 0o5, 15), spin="1", rc="1")
        self.assertEqual(candidate.branchname(),
                         "releases/linaro-5.3-2016.05-1-rc1")
        release = Series("release", package="GCC-5.3.1",
                         date=datetime(2016, 0o5, 15), spin="1", rc=None)
        self.assertEqual(release.branchname(), "releases/linaro-5.3-2016.05-1")

    def test_date_string(self):
        candidate = Series("candidate", package="GCC-5.3.1",
                           date="2016.05.27", spin="1", rc="1")
        self.assertEqual(datetime(2016, 0o5, 15), candidate.date)

        candidate2 = Series("candidate", package="GCC-5.3.1",
                            date="2016.05", spin="1", rc="1")
        self.assertEqual(datetime(2016, 0o5, 15), candidate2.date)

        with self.assertRaises(TypeError):
            candidate3 = Series("candidate", package="GCC-5.3.1",
                                date=datetime("20161034234"), spin="1", rc="1")

    def test_series_strict_true(self):
        with self.assertRaises(ValueError):
            snapshot = Series(
                "snapshot",
                package="GCC-5.3.1",
                date=datetime(
                    2016,
                    0o5,
                    15),
                spin="1",
                rc="1",
                strict=True)

        with self.assertRaises(ValueError):
            snapshot = Series("snapshot", package="GCC-5.3.1",
                              date=datetime(2016, 0o5, 15), spin="1", rc="1")

        with self.assertRaises(ValueError):
            release = Series(
                "release",
                package="GCC-5.3.1",
                date=datetime(
                    2016,
                    0o5,
                    15),
                spin="1",
                rc="1",
                strict=True)

        with self.assertRaises(ValueError):
            release = Series("release", package="GCC-5.3.1",
                             date=datetime(2016, 0o5, 15), spin="1", rc="1")

    def test_series_strict_false(self):
        snapshot = Series(
            "snapshot",
            package="GCC-5.3.1",
            date=datetime(
                2016,
                0o5,
                15),
            spin="6",
            rc="1",
            strict=False)
        self.assertEqual(snapshot.branchname(),
                         "snapshots/linaro-5.3-2016.05-6-rc1")

        release = Series(
            "release",
            package="GCC-5.3.1",
            date=datetime(
                2016,
                0o5,
                15),
            spin="1",
            rc="1",
            strict=False)
        self.assertEqual(release.branchname(),
                         "releases/linaro-5.3-2016.05-1-rc1")

        release = Series("release", package="GCC-5.3.1",
                         date=datetime(2016, 0o5, 15), rc="1", strict=False)
        self.assertEqual(release.branchname(),
                         "releases/linaro-5.3-2016.05-rc1")

    # These tests will verify that a branchname can be read, a series created,
    # and then the same branch name recreated.
    def test_series_from_branchname(self):

        branch2 = 'snapshots/linaro-5.3-2016.05-6'
        series2 = series_from_branchname(branch=branch2)
        self.assertEqual(series2.branchname(),
                         'snapshots/linaro-5.3-2016.05-6')

        branch3 = 'snapshots/linaro-5.3-2016.05'
        series3 = series_from_branchname(branch=branch3)
        self.assertEqual(series3.branchname(), 'snapshots/linaro-5.3-2016.05')

        branch4 = 'releases/linaro-5.3-2016.05-6-rc1'
        series4 = series_from_branchname(branch=branch4)
        self.assertEqual(series4.branchname(),
                         'releases/linaro-5.3-2016.05-6-rc1')

        branch5 = 'releases/linaro-5.3-2016.05-rc1'
        series5 = series_from_branchname(branch=branch5)
        self.assertEqual(series5.branchname(),
                         'releases/linaro-5.3-2016.05-rc1')

        branch6 = 'releases/linaro-5.3-2016.05-6'
        series6 = series_from_branchname(branch=branch6)
        self.assertEqual(series6.branchname(),
                         'releases/linaro-5.3-2016.05-6')

        branch7 = 'releases/linaro-5.3-2016.05'
        series7 = series_from_branchname(branch=branch7)
        self.assertEqual(series7.branchname(), 'releases/linaro-5.3-2016.05')

        # -rc1 is invalid with a snapshots namespace.
        branch8 = 'snapshots/linaro-5.3-2016.05-6-rc1'
        with self.assertRaises(ValueError):
            series8 = series_from_branchname(branch=branch8)

        # Wrong branchname.. it should be 'snapshots'
        branch9 = 'snapshot/linaro-5.3-2016.05-6-rc1'
        with self.assertRaises(ValueError):
            series9 = series_from_branchname(branch=branch9)

        # Wrong branchname.. it should be 'snapshots'
        branch10 = 'snapshot/linaro-5.3-2016.05-6'
        with self.assertRaises(ValueError):
            series10 = series_from_branchname(branch=branch10)

        # namespace required.
        branch11 = 'linaro-5.3-2016.05-6'
        with self.assertRaises(ValueError):
            series11 = series_from_branchname(branch=branch11)

        # it should complain about missing the right-hand values.
        branch12 = 'snapshots/'
        with self.assertRaises(ValueError):
            series12 = series_from_branchname(branch=branch12)

        # It won't parse because of a missing namespace /
        branch13 = 'snapshots'
        with self.assertRaises(ValueError):
            series13 = series_from_branchname(branch=branch13)

        branch14 = 'snapshots/foo'
        with self.assertRaises(KeyError):
            series14 = series_from_branchname(branch=branch14)

        # unknown namespace.
        branch15 = 'foobarnamespace/linaro-5.3-2016.05-6'
        with self.assertRaises(ValueError):
            series15 = series_from_branchname(branch=branch15)

        # This will fail on a non-datetime input.
        branch16 = 'snapshots/linaro-5.3-asdf'
        with self.assertRaises(ValueError):
            series16 = series_from_branchname(branch=branch16)

        # This will fail with an invalid spin.
        branch17 = 'snapshots/linaro-5.3-2016.05-a'
        with self.assertRaises(TypeError):
            series17 = series_from_branchname(branch=branch17)

        # This will fail with an invalid rc.
        branch18 = 'snapshots/linaro-5.3-2016.05-rcasdfn'
        with self.assertRaises(TypeError):
            series18 = series_from_branchname(branch=branch18)

        # This will fail with an invalid rc.
        branch19 = 'snapshots/linaro-5.3-2016.05-9-rcasdfn'
        with self.assertRaises(TypeError):
            series19 = series_from_branchname(branch=branch19)

    # TODO: Test series.label (as there was a runtime bug)

    def test_snapshot_series_from_tag(self):
        tag = 'linaro-snapshot-5.3-2016.05-6'
        series = series_from_tag(tag=tag)
        self.assertEqual(series.branchname(),
                         'snapshots/linaro-5.3-2016.05-6')

    def test_invalid_snapshot_series_from_tag(self):
        # We can't have -rc1 on a snapshot.
        tag = 'linaro-snapshot-5.3-2016.05-6-rc1'
        with self.assertRaises(ValueError):
            series = series_from_tag(tag=tag)

    def test_candidate_series_from_tag(self):
        tag = 'linaro-5.3-2016.05-6-rc1'
        series = series_from_tag(tag=tag)
        self.assertEqual(series.branchname(),
                         'releases/linaro-5.3-2016.05-6-rc1')

    def test_release_series_from_tag(self):
        tag = 'linaro-5.3-2016.05-6'
        series = series_from_tag(tag=tag)
        self.assertEqual(series.branchname(), 'releases/linaro-5.3-2016.05-6')

    def test_series_from_tag_invalid_spin(self):
        tag = 'linaro-5.3-2016.05-abc'
        with self.assertRaises(TypeError):
            series = series_from_tag(tag=tag)

    def test_series_from_tag_invalid_rc(self):
        tag = 'linaro-5.3-2016.05-rcabf'
        with self.assertRaises(TypeError):
            series = series_from_tag(tag=tag)

    def test_series_from_tag_invalid_rc_with_valid_spin(self):
        tag = 'linaro-5.3-2016.05-9-rcabf'
        with self.assertRaises(TypeError):
            series = series_from_tag(tag=tag)


class TestSeriesFormat(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        snaptag = 'linaro-snapshot-5.3-2016.05-6'
        reltag = 'linaro-5.3-2016.05-6'
        rctag = 'linaro-5.3-2016.05-6-rc1'
        cls.snapseries = series_from_tag(tag=snaptag)
        cls.relseries = series_from_tag(tag=reltag)
        cls.rcseries = series_from_tag(tag=rctag)

    def test_format_N_snap(self):
        f = format(self.snapseries, '%N')
        self.assertEqual(f, 'snapshots')

    def test_format_N_rel(self):
        f = format(self.relseries, '%N')
        self.assertEqual(f, 'releases')

    def test_format_N_rc(self):
        f = format(self.rcseries, '%N')
        self.assertEqual(f, 'releases')

    def test_format_dashL_snap(self):
        f = format(self.snapseries, 'foo-%L-bar')
        self.assertEqual(f, 'foo-snapshot-bar')

    def test_format_dashL_rel(self):
        f = format(self.relseries, 'foo-%L-bar')
        self.assertEqual(f, 'foo-bar')

    def test_format_dashL_rc(self):
        f = format(self.rcseries, 'foo-%L-bar')
        self.assertEqual(f, 'foo-bar')

    def test_format_dotL_snap(self):
        f = format(self.snapseries, 'foo.%L.bar')
        self.assertEqual(f, 'foo.snapshot.bar')

    def test_format_dotL_rel(self):
        f = format(self.relseries, 'foo.%L.bar')
        self.assertEqual(f, 'foo.bar')

    def test_format_dotL_rc(self):
        f = format(self.rcseries, 'foo.%L.bar')
        self.assertEqual(f, 'foo.bar')

    def test_format_L_snap(self):
        f = format(self.snapseries, 'foo%Lbar')
        self.assertEqual(f, 'foosnapshotbar')

    def test_format_L_rel(self):
        f = format(self.relseries, 'foo%Lbar')
        self.assertEqual(f, 'foobar')

    def test_format_L_rc(self):
        f = format(self.rcseries, 'foo%Lbar')
        self.assertEqual(f, 'foobar')

    def test_format_dashP(self):
        f = format(self.snapseries, 'foo-%P-bar')
        self.assertEqual(f, 'foo-GCC-bar')

    def test_format_dotP(self):
        f = format(self.snapseries, 'foo.%P.bar')
        self.assertEqual(f, 'foo.GCC.bar')

    def test_format_P(self):
        f = format(self.snapseries, 'foo%Pbar')
        self.assertEqual(f, 'fooGCCbar')

    def test_format_dashl(self):
        f = format(self.snapseries, 'foo-%l-bar')
        self.assertEqual(f, 'foo-gcc-bar')

    def test_format_dotl(self):
        f = format(self.snapseries, 'foo.%l.bar')
        self.assertEqual(f, 'foo.gcc.bar')

    def test_format_l(self):
        f = format(self.snapseries, 'foo%lbar')
        self.assertEqual(f, 'foogccbar')

    def test_format_V(self):
        f = format(self.snapseries, 'foo.%V.bar')
        self.assertEqual(f, 'foo.Linaro.bar')

    def test_format_v(self):
        f = format(self.snapseries, 'foo.%v.bar')
        self.assertEqual(f, 'foo.linaro.bar')

    def test_format_E(self):
        f = format(self.snapseries, 'gcc-%E')
        self.assertEqual(f, 'gcc-5.3')

    # This shouldn't show a trailing - after the minor because of a point.
    def test_format_E_with_fabricated_minor(self):
        minorseries = copy.deepcopy(self.snapseries)
        minorseries.package.version.point = 9
        f = format(minorseries, 'gcc-%E')
        self.assertEqual(f, 'gcc-5.3')

    def test_format_e(self):
        f = format(self.snapseries, 'gcc-%e')
        self.assertEqual(f, 'gcc-5.3')

    def test_format_e_fabricate_minor(self):
        minorseries = copy.deepcopy(self.snapseries)
        minorseries.package.version.point = 9
        f = format(minorseries, 'gcc-%e')
        self.assertEqual(f, 'gcc-5.3.9')

    def test_format_M(self):
        f = format(self.snapseries, 'gcc-%M')
        self.assertEqual(f, 'gcc-5')

    def test_format_m(self):
        f = format(self.snapseries, 'gcc-X.%m')
        self.assertEqual(f, 'gcc-X.3')

    def test_format_p(self):
        f = format(self.snapseries, 'gcc-X.Y.%p')
        self.assertEqual(f, 'gcc-X.Y.')

    def test_format_p_fabricate_minor(self):
        minorseries = copy.deepcopy(self.snapseries)
        minorseries.package.version.point = 9
        f = format(minorseries, 'gcc-X.Y.%p')
        self.assertEqual(f, 'gcc-X.Y.9')

    def test_format_D(self):
        f = format(self.snapseries, 'foo-%D-bar')
        self.assertEqual(f, 'foo-2016.05-bar')

    def test_format_snap_h(self):
        f = format(self.snapseries, 'http://%h.')
        self.assertEqual(f, 'http://snapshots.')

    def test_format_release_h(self):
        f = format(self.relseries, 'http://%h.')
        self.assertEqual(f, 'http://releases.')

    def test_format_snap_h(self):
        f = format(self.snapseries, 'http://%h.')
        self.assertEqual(f, 'http://snapshots.')

    def test_format_snap_d(self):
        f = format(
            self.snapseries,
            'http://%h.linaro.org/components/toolchain/binaries/%d')
        self.assertEqual(
            f,
            'http://snapshots.linaro.org/components/'
            'toolchain/binaries/5.3-2016.05-6')

    def test_format_rel_d(self):
        f = format(
            self.relseries,
            'http://%h.linaro.org/components/toolchain/binaries/%d')
        self.assertEqual(
            f,
            'http://releases.linaro.org/components/'
            'toolchain/binaries/5.3-2016.05-6')

    def test_format_rc_d(self):
        f = format(
            self.rcseries,
            'http://%h.linaro.org/components/toolchain/binaries/%d')
        self.assertEqual(
            f,
            'http://snapshots.linaro.org/components/'
            'toolchain/binaries/5.3-2016.05-6-rc1')

    def test_format_snap_d(self):
        f = format(
            self.snapseries,
            'http://%h.linaro.org/components/toolchain/binaries/%d')
        self.assertEqual(
            f,
            'http://snapshots.linaro.org/components/'
            'toolchain/binaries/5.3-2016.05-6')

    def test_format_rel_d(self):
        f = format(
            self.relseries,
            'http://%h.linaro.org/components/toolchain/binaries/%d')
        self.assertEqual(
            f,
            'http://releases.linaro.org/components/'
            'toolchain/binaries/5.3-2016.05-6')

    def test_format_rc_d(self):
        f = format(
            self.rcseries,
            'http://%h.linaro.org/components/toolchain/binaries/%d')
        self.assertEqual(
            f,
            'http://snapshots.linaro.org/components/'
            'toolchain/binaries/5.3-2016.05-6-rc1')

    def test_format_snap_d(self):
        f = format(
            self.snapseries,
            'http://%h.linaro.org/components/toolchain/binaries/%d')
        self.assertEqual(
            f,
            'http://snapshots.linaro.org/components/'
            'toolchain/binaries/5.3-2016.05-6')

    def test_format_rel_d(self):
        f = format(
            self.relseries,
            'http://%h.linaro.org/components/toolchain/binaries/%d')
        self.assertEqual(
            f,
            'http://releases.linaro.org/components/'
            'toolchain/binaries/5.3-2016.05-6')

    def test_format_rc_d(self):
        f = format(
            self.rcseries,
            'http://%h.linaro.org/components/toolchain/binaries/%d')
        self.assertEqual(
            f,
            'http://snapshots.linaro.org/components/'
            'toolchain/binaries/5.3-2016.05-6-rc1')

    def test_format_dashS(self):
        f = format(self.snapseries, 'foo-%S-bar')
        self.assertEqual(f, 'foo-6-bar')

    def test_format_dashS_no_spin(self):
        nospinseries = copy.deepcopy(self.snapseries)
        nospinseries.spin = Spin()
        f = format(nospinseries, 'foo-%S-bar')
        self.assertEqual(f, 'foo-bar')

    def test_format_dotS(self):
        f = format(self.snapseries, 'foo.%S.bar')
        self.assertEqual(f, 'foo.6.bar')

    def test_format_dotS_no_spin(self):
        nospinseries = copy.deepcopy(self.snapseries)
        nospinseries.spin = Spin()
        f = format(nospinseries, 'foo.%S.bar')
        self.assertEqual(f, 'foo.bar')

    def test_format_S(self):
        f = format(self.snapseries, 'foo%Sbar')
        self.assertEqual(f, 'foo6bar')

    def test_format_S_no_spin(self):
        nospinseries = copy.deepcopy(self.snapseries)
        nospinseries.spin = Spin()
        f = format(nospinseries, 'foo%Sbar')
        self.assertEqual(f, 'foobar')

    def test_format_dashR(self):
        f = format(self.rcseries, '2016.05-6-%R')
        self.assertEqual(f, '2016.05-6-rc1')

    def test_format_dashR_fabricate_norc(self):
        norcseries = copy.deepcopy(self.rcseries)
        norcseries.rc = Rc()
        f = format(norcseries, '2016.05-6-%R')
        self.assertEqual(f, '2016.05-6')

    def test_format_dotR(self):
        f = format(self.rcseries, '2016.05-6.%R')
        self.assertEqual(f, '2016.05-6.rc1')

    def test_format_dotR_fabricate_norc(self):
        norcseries = copy.deepcopy(self.rcseries)
        norcseries.rc = Rc()
        f = format(norcseries, '2016.05-6.%R')
        self.assertEqual(f, '2016.05-6')

    def test_format_R(self):
        f = format(self.rcseries, '2016.05-6-%R')
        self.assertEqual(f, '2016.05-6-rc1')

    def test_format_R_fabricate_norc(self):
        norcseries = copy.deepcopy(self.rcseries)
        norcseries.rc = Rc()
        f = format(norcseries, '2016.05-6#%R')
        self.assertEqual(f, '2016.05-6#')

if __name__ == '__main__':
    # logging.basicConfig(level="INFO")
    unittest.main()