1
+ import boto3
2
+ from datetime import datetime
3
+ import xml .etree .ElementTree as ET
4
+ import os
5
+
6
+
7
+ xml_path = "../integration_tests.xml"
8
+
9
+ def readXML_and_publish_metrics_to_cw ():
10
+ if os .path .isfile (xml_path ):
11
+ tree = ET .parse (xml_path )
12
+ testsuite = tree .find ("testsuite" )
13
+ failures = testsuite .attrib ["failures" ]
14
+ tests = testsuite .attrib ["tests" ]
15
+ successes = int (tests ) - int (failures )
16
+ success_rate = (successes / int (tests ))* 100
17
+ else :
18
+ print ("f{xml_path} does not exists." )
19
+ print (os .getcwd ())
20
+ failures = 0
21
+ successes = 0
22
+ tests = 0
23
+ success_rate = 0
24
+
25
+ timestamp = datetime .now ().strftime ("%Y-%m-%dT%H:%M:%S" )
26
+
27
+ print (f"Failures: { failures } " )
28
+ print (f"Total tests: { tests } " )
29
+ print (f"Success: { successes } " )
30
+
31
+ # push to cloudwatch
32
+ cw_client = boto3 .client ("cloudwatch" )
33
+ project_name = os .getenv ("PROJECT_NAME" )
34
+
35
+ # Define the metric data
36
+ metric_data = [
37
+ {
38
+ "MetricName" : "failures" ,
39
+ "Timestamp" : timestamp ,
40
+ "Dimensions" : [
41
+ {"Name" : "CodeBuild Project Name" , "Value" : project_name },
42
+ ],
43
+ "Value" : int (failures ),
44
+ "Unit" : "Count" ,
45
+ },
46
+ {
47
+ "MetricName" : "total_tests" ,
48
+ "Timestamp" : timestamp ,
49
+ "Dimensions" : [
50
+ {"Name" : "CodeBuild Project Name" , "Value" : project_name },
51
+ ],
52
+ "Value" : int (tests ),
53
+ "Unit" : "Count" ,
54
+ },
55
+ {
56
+ "MetricName" : "successes" ,
57
+ "Timestamp" : timestamp ,
58
+ "Dimensions" : [
59
+ {"Name" : "CodeBuild Project Name" , "Value" : project_name },
60
+ ],
61
+ "Value" : int (successes ),
62
+ "Unit" : "Count" ,
63
+ },
64
+ {
65
+ "MetricName" : "success_rate" ,
66
+ "Timestamp" : timestamp ,
67
+ "Dimensions" : [
68
+ {"Name" : "CodeBuild Project Name" , "Value" : project_name },
69
+ ],
70
+ "Value" : int (success_rate ),
71
+ "Unit" : "Percent" ,
72
+ },
73
+ ]
74
+
75
+ # Use the put_metric_data method to push the metric data to CloudWatch
76
+ try :
77
+ response = cw_client .put_metric_data (
78
+ Namespace = "Canary_Metrics" , MetricData = metric_data
79
+ )
80
+ if response ["ResponseMetadata" ]["HTTPStatusCode" ] == 200 :
81
+ print ("Successfully pushed data to CloudWatch" )
82
+ # return 200 status code if successful
83
+ return 200
84
+ else :
85
+ # raise exception if the status code is not 200
86
+ raise Exception (
87
+ "Unexpected response status code: {}" .format (
88
+ response ["ResponseMetadata" ]["HTTPStatusCode" ]
89
+ )
90
+ )
91
+ except Exception as e :
92
+ print ("Error pushing data to CloudWatch: {}" .format (e ))
93
+ # raise exception if there was an error pushing data to CloudWatch
94
+ raise
95
+
96
+
97
+ def main ():
98
+ readXML_and_publish_metrics_to_cw ()
99
+
100
+
101
+ if __name__ == "__main__" :
102
+ main ()
0 commit comments