def testList_TestFormat(self, module_name): properties.VALUES.core.user_output_enabled.Set( True) # So we see the output self.StartObjectPatch(times, 'LOCAL', times.GetTimeZone('PST')) self.Run('{} jobs list'.format(module_name)) self.AssertOutputEquals("""\ JOB_ID STATUS CREATED opName1 STATE_UNSPECIFIED 2015-12-31T16:00:00 opName2 SUCCEEDED 2016-01-01T16:00:00 """, normalize_space=True)
def TransformDate(r, format='%Y-%m-%dT%H:%M:%S', unit=1, undefined='', tz=None, tz_default=None): """Formats the resource as a strftime() format. Args: r: A timestamp number or an object with 3 or more of these fields: year, month, day, hour, minute, second, millisecond, microsecond, nanosecond. format: The strftime(3) format. unit: If the resource is a Timestamp then divide by _unit_ to yield seconds. undefined: Returns this value if the resource is not a valid time. tz: Return the time relative to the tz timezone if specified, the explicit timezone in the resource if it has one, otherwise the local timezone. For example, ...date(tz=EST5EDT, tz_default=UTC). tz_default: The default timezone if the resource does not have a timezone suffix. Returns: The strftime() date format for r or undefined if r does not contain a valid time. """ # Check if r has an isoformat() method. try: r = r.isoformat() except (AttributeError, TypeError, ValueError): pass tz_in = times.GetTimeZone(tz_default) if tz_default else None # Check if r is a timestamp. try: timestamp = float(r) / float(unit) dt = times.GetDateTimeFromTimeStamp(timestamp, tz_in) return times.FormatDateTime(dt, format) except (TypeError, ValueError): pass # Check if r is a serialized datetime object. original_repr = resource_property.Get(r, ['datetime'], None) if original_repr and isinstance(original_repr, basestring): r = original_repr tz_out = times.GetTimeZone(tz) if tz else None # Check if r is a date/time string. try: dt = times.ParseDateTime(r, tz_in) return times.FormatDateTime(dt, format, tz_out) except (AttributeError, ImportError, TypeError, ValueError): pass def _FormatFromParts(): """Returns the formatted time from broken down time parts in r. Raises: TypeError: For invalid time part errors. ValueError: For time conversion errors or not enough valid time parts. Returns: The formatted time from broken down time parts in r. """ valid = 0 parts = [] now = datetime.datetime.now(tz_in) for part in ('year', 'month', 'day', 'hour', 'minute', 'second'): value = resource_property.Get(r, [part], None) if value is None: # Missing parts default to now. value = getattr(now, part, 0) else: valid += 1 parts.append(int(value)) # The last value is microseconds. Add in any subsecond parts but don't count # them in the validity check. parts.append(0) for i, part in enumerate(['nanosecond', 'microsecond', 'millisecond']): value = resource_property.Get(r, [part], None) if value is not None: parts[-1] += int(int(value) * 1000**(i - 1)) # year&month&day or hour&minute&second would be OK, "3" covers those and any # combination of 3 non-subsecond date/time parts. if valid < 3: raise ValueError parts.append(tz_in) dt = datetime.datetime(*parts) return times.FormatDateTime(dt, format, tz_out) try: return _FormatFromParts() except (TypeError, ValueError): pass # Does anyone really know what time it is? return undefined
def SetUp(self): prediction_input_class = self.short_msgs.PredictionInput self.data_formats = prediction_input_class.DataFormatValueValuesEnum self.states = self.short_msgs.Job.StateValueValuesEnum # For consistent output of times self.StartObjectPatch(times, 'LOCAL', times.GetTimeZone('PST'))
def Run(self, args): """This is what gets called when the user runs this command. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. Yields: Some value that we want to have printed later. """ client = core_apis.GetClientInstance('cloudbuild', 'v1') messages = core_apis.GetMessagesModule('cloudbuild', 'v1') if args.ongoing: tz = times.GetTimeZone('UTC') now = times.Now(tz) now_seconds = times.GetTimeStampFromDateTime(now) # We are wrapping list_pager.YieldFromList in another yield loop so that # we can use custom exit-early and filtering functionality. This code will # be simplified once the cloudbuild service supports server-side filtering. # # The exit-early is to ensure that, when listing ongoing builds, the command # doesn't page through the entire history of terminated builds to find out # that there weren't any. The build list will always be delivered in sorted # order with createTime descending. # # The custom filtering checks build.status to see if a build is ongoing or # not, and skips those that are terminated. # # We copy and decrement the limit, because otherwise YieldFromList would # not understand when to stop, due to skipping terminated builds. # # We cannot give YieldFromList a predicate, because it would not know that # it needs to stop paging after a certain time threshold - with no ongoing # builds it would page through the entire build history. limit = args.limit for build in list_pager.YieldFromList( client.projects_builds, messages.CloudbuildProjectsBuildsListRequest( pageSize=args.page_size, projectId=properties.VALUES.core.project.Get()), field='builds', batch_size_attribute='pageSize'): if args.ongoing: tz_create_time = build.createTime create_time = times.ParseDateTime(tz_create_time, tz) create_seconds = times.GetTimeStampFromDateTime(create_time) delta_seconds = now_seconds - create_seconds if delta_seconds > _ONGOING_THRESHOLD_SECONDS: break if build.status not in [ messages.Build.StatusValueValuesEnum.QUEUED, messages.Build.StatusValueValuesEnum.WORKING]: continue yield build limit -= 1 if limit == 0: break