hexsha
stringlengths
40
40
size
int64
4
996k
ext
stringclasses
8 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
245
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
245
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
245
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
4
996k
avg_line_length
float64
1.33
58.2k
max_line_length
int64
2
323k
alphanum_fraction
float64
0
0.97
content_no_comment
stringlengths
0
946k
is_comment_constant_removed
bool
2 classes
is_sharp_comment_removed
bool
1 class
f7f9e5056e4a3b02770ce07610f9be27dfc8239f
1,966
py
Python
src/fhir_types/FHIR_TestScript_Action2.py
anthem-ai/fhir-types
42348655fb3a9b3f131b911d6bc0782da8c14ce4
[ "Apache-2.0" ]
2
2022-02-03T00:51:30.000Z
2022-02-03T18:42:43.000Z
src/fhir_types/FHIR_TestScript_Action2.py
anthem-ai/fhir-types
42348655fb3a9b3f131b911d6bc0782da8c14ce4
[ "Apache-2.0" ]
null
null
null
src/fhir_types/FHIR_TestScript_Action2.py
anthem-ai/fhir-types
42348655fb3a9b3f131b911d6bc0782da8c14ce4
[ "Apache-2.0" ]
null
null
null
from typing import Any, List, Literal, TypedDict from .FHIR_string import FHIR_string from .FHIR_TestScript_Operation import FHIR_TestScript_Operation # A structured set of tests against a FHIR server or client implementation to determine compliance against the FHIR specification. FHIR_TestScript_Action2 = TypedDict( "FHIR_TestScript_Action2", { # Unique id for the element within a resource (for internal references). This may be any string value that does not contain spaces. "id": FHIR_string, # May be used to represent additional information that is not part of the basic definition of the element. To make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer can define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. "extension": List[Any], # May be used to represent additional information that is not part of the basic definition of the element and that modifies the understanding of the element in which it is contained and/or the understanding of the containing element's descendants. Usually modifier elements provide negation or qualification. To make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer can define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. Applications processing a resource are required to check for modifier extensions.Modifier extensions SHALL NOT change the meaning of any elements on Resource or DomainResource (including cannot change the meaning of modifierExtension itself). "modifierExtension": List[Any], # An operation would involve a REST request to a server. "operation": FHIR_TestScript_Operation, }, total=False, )
93.619048
836
0.782299
from typing import Any, List, Literal, TypedDict from .FHIR_string import FHIR_string from .FHIR_TestScript_Operation import FHIR_TestScript_Operation FHIR_TestScript_Action2 = TypedDict( "FHIR_TestScript_Action2", { "id": FHIR_string, "extension": List[Any], "modifierExtension": List[Any], # An operation would involve a REST request to a server. "operation": FHIR_TestScript_Operation, }, total=False, )
true
true
f7f9e6136cf2b9d9a4761731340966e9b8e18751
1,784
py
Python
leetcode/648.py
GihwanKim/Baekjoon
52eb2bf80bb1243697858445e5b5e2d50d78be4e
[ "MIT" ]
null
null
null
leetcode/648.py
GihwanKim/Baekjoon
52eb2bf80bb1243697858445e5b5e2d50d78be4e
[ "MIT" ]
null
null
null
leetcode/648.py
GihwanKim/Baekjoon
52eb2bf80bb1243697858445e5b5e2d50d78be4e
[ "MIT" ]
null
null
null
""" File: 648.py Title: Replace Words Difficulty: Medium URL: https://leetcode.com/problems/replace-words/ """ import unittest from typing import List class Solution: def replaceWords(self, dict: List[str], sentence: str) -> str: tree = {} for root in dict: current = None for c in root: if current is None: if c not in tree: tree[c] = {} current = tree[c] else: if c not in current: current[c] = {} current = current[c] current[0] = True def replace(word: str): successor = "" current = None for c in word: if current is None: if c in tree: current = tree[c] successor += c else: return word else: if 0 in current: return successor elif c in current: current = current[c] successor += c else: return word return successor return " ".join(list(map(replace, sentence.split()))) class SolutionTestCase(unittest.TestCase): def test_example1(self): # Input dict = ["cat", "bat", "rat"] sentence = "the cattle was rattled by the battery" # Output output = "the cat was rat by the bat" solution = Solution() self.assertEqual(solution.replaceWords(dict, sentence), output) if __name__ == "__main__": unittest.main()
25.855072
71
0.446188
import unittest from typing import List class Solution: def replaceWords(self, dict: List[str], sentence: str) -> str: tree = {} for root in dict: current = None for c in root: if current is None: if c not in tree: tree[c] = {} current = tree[c] else: if c not in current: current[c] = {} current = current[c] current[0] = True def replace(word: str): successor = "" current = None for c in word: if current is None: if c in tree: current = tree[c] successor += c else: return word else: if 0 in current: return successor elif c in current: current = current[c] successor += c else: return word return successor return " ".join(list(map(replace, sentence.split()))) class SolutionTestCase(unittest.TestCase): def test_example1(self): dict = ["cat", "bat", "rat"] sentence = "the cattle was rattled by the battery" output = "the cat was rat by the bat" solution = Solution() self.assertEqual(solution.replaceWords(dict, sentence), output) if __name__ == "__main__": unittest.main()
true
true
f7f9e68079332f17d27731b8322c8a7b4214cc44
102
py
Python
sitetecnosul/django_assertions.py
joao0710/tecnosul
9a1bc3d5089d1c8cbc5a3827209e5a85d96c3cc3
[ "MIT" ]
null
null
null
sitetecnosul/django_assertions.py
joao0710/tecnosul
9a1bc3d5089d1c8cbc5a3827209e5a85d96c3cc3
[ "MIT" ]
9
2021-03-26T14:49:34.000Z
2021-06-03T00:33:14.000Z
sitetecnosul/django_assertions.py
joao0710/tecnosul
9a1bc3d5089d1c8cbc5a3827209e5a85d96c3cc3
[ "MIT" ]
2
2021-03-22T21:04:31.000Z
2021-05-12T13:23:05.000Z
from django.test import TestCase _test_case = TestCase() assert_contains = _test_case.assertContains
20.4
43
0.833333
from django.test import TestCase _test_case = TestCase() assert_contains = _test_case.assertContains
true
true
f7f9e6a7dc24fe5b46cb03e58ddcc3dc056636f7
3,693
py
Python
src/edge_update_function/main.py
aws-samples/personalization-apis
3e13353052304c25a8e59ed20fa8496cd7568b1a
[ "MIT-0" ]
5
2022-02-09T19:21:03.000Z
2022-03-29T16:44:20.000Z
src/edge_update_function/main.py
aws-samples/personalization-apis
3e13353052304c25a8e59ed20fa8496cd7568b1a
[ "MIT-0" ]
1
2022-02-18T18:36:07.000Z
2022-02-18T18:36:07.000Z
src/edge_update_function/main.py
aws-samples/personalization-apis
3e13353052304c25a8e59ed20fa8496cd7568b1a
[ "MIT-0" ]
1
2022-02-09T08:20:17.000Z
2022-02-09T08:20:17.000Z
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 import os import io import json import boto3 import logging import zipfile from urllib.request import urlopen from crhelper import CfnResource logger = logging.getLogger() logger.setLevel(logging.INFO) helper = CfnResource() lambda_client = boto3.client('lambda') def update_function(event): user_pool_id = event['ResourceProperties']['UserPoolId'] cognito_region = event['ResourceProperties']['CognitoRegion'] source_url = event['ResourceProperties'].get('SourceUrl') edge_function_arn = event['ResourceProperties']['EdgeFunctionArn'] function_filename = event['ResourceProperties'].get('FunctionFilename', 'index.js') logger.info("Downloading well-known jwks.json from Cognito") jwks_url = f'https://cognito-idp.{cognito_region}.amazonaws.com/{user_pool_id}/.well-known/jwks.json' with urlopen(jwks_url) as http_response: jwks = str(http_response.read()) jwks = jwks.replace('b\'{', '{') jwks = jwks.replace('}\'', '}') logger.debug(json.dumps(jwks, indent = 2, default = str)) if not source_url: logger.info('SourceUrl not specified so determining code location from Lambda for "Templated" alias') # The "Templated" alias is created when the edge auth function is deployed and represents the original # version of the function that is templated with replacement variables. response = lambda_client.get_function( FunctionName = f'{edge_function_arn}:Templated' ) source_url = response['Code']['Location'] logger.info("Building updated function zip archive") js = None with urlopen(source_url) as zip_resp: with zipfile.ZipFile(io.BytesIO(zip_resp.read())) as zin: with zipfile.ZipFile('/tmp/edge-code.zip', 'w') as zout: zout.comment = zin.comment for item in zin.infolist(): if item.filename == function_filename: js = io.TextIOWrapper(io.BytesIO(zin.read(item.filename))).read() else: zout.writestr(item, zin.read(item.filename)) if not js: raise Exception(f'Function code archive does not contain the file "{function_filename}"') js = js.replace('##JWKS##', jwks) js = js.replace('##USERPOOLID##', user_pool_id) js = js.replace('##COGNITOREGION##', cognito_region) logger.info('Writing updated js file %s to archive', function_filename) with zipfile.ZipFile('/tmp/edge-code.zip', mode='a', compression=zipfile.ZIP_DEFLATED) as zf: zf.writestr(function_filename, js) # Load file into memory with open('/tmp/edge-code.zip', 'rb') as file_data: bytes_content = file_data.read() logger.info('Updating lambda function with updated code archive') response = lambda_client.update_function_code( FunctionName = edge_function_arn, ZipFile = bytes_content ) logger.debug(response) @helper.create @helper.update def create_or_update_resource(event, _): update_function(event) def lambda_handler(event, context): logger.info(os.environ) logger.info(json.dumps(event, indent = 2, default = str)) # If the event has a RequestType, we're being called by CFN as custom resource if event.get('RequestType'): logger.info('Function called from CloudFormation as custom resource') helper(event, context) else: logger.info('Function called outside of CloudFormation') # Call function directly (i.e. testing in Lambda console or called directly) update_function(event)
37.683673
110
0.683726
import os import io import json import boto3 import logging import zipfile from urllib.request import urlopen from crhelper import CfnResource logger = logging.getLogger() logger.setLevel(logging.INFO) helper = CfnResource() lambda_client = boto3.client('lambda') def update_function(event): user_pool_id = event['ResourceProperties']['UserPoolId'] cognito_region = event['ResourceProperties']['CognitoRegion'] source_url = event['ResourceProperties'].get('SourceUrl') edge_function_arn = event['ResourceProperties']['EdgeFunctionArn'] function_filename = event['ResourceProperties'].get('FunctionFilename', 'index.js') logger.info("Downloading well-known jwks.json from Cognito") jwks_url = f'https://cognito-idp.{cognito_region}.amazonaws.com/{user_pool_id}/.well-known/jwks.json' with urlopen(jwks_url) as http_response: jwks = str(http_response.read()) jwks = jwks.replace('b\'{', '{') jwks = jwks.replace('}\'', '}') logger.debug(json.dumps(jwks, indent = 2, default = str)) if not source_url: logger.info('SourceUrl not specified so determining code location from Lambda for "Templated" alias') response = lambda_client.get_function( FunctionName = f'{edge_function_arn}:Templated' ) source_url = response['Code']['Location'] logger.info("Building updated function zip archive") js = None with urlopen(source_url) as zip_resp: with zipfile.ZipFile(io.BytesIO(zip_resp.read())) as zin: with zipfile.ZipFile('/tmp/edge-code.zip', 'w') as zout: zout.comment = zin.comment for item in zin.infolist(): if item.filename == function_filename: js = io.TextIOWrapper(io.BytesIO(zin.read(item.filename))).read() else: zout.writestr(item, zin.read(item.filename)) if not js: raise Exception(f'Function code archive does not contain the file "{function_filename}"') js = js.replace('##JWKS##', jwks) js = js.replace('##USERPOOLID##', user_pool_id) js = js.replace('##COGNITOREGION##', cognito_region) logger.info('Writing updated js file %s to archive', function_filename) with zipfile.ZipFile('/tmp/edge-code.zip', mode='a', compression=zipfile.ZIP_DEFLATED) as zf: zf.writestr(function_filename, js) with open('/tmp/edge-code.zip', 'rb') as file_data: bytes_content = file_data.read() logger.info('Updating lambda function with updated code archive') response = lambda_client.update_function_code( FunctionName = edge_function_arn, ZipFile = bytes_content ) logger.debug(response) @helper.create @helper.update def create_or_update_resource(event, _): update_function(event) def lambda_handler(event, context): logger.info(os.environ) logger.info(json.dumps(event, indent = 2, default = str)) if event.get('RequestType'): logger.info('Function called from CloudFormation as custom resource') helper(event, context) else: logger.info('Function called outside of CloudFormation') # Call function directly (i.e. testing in Lambda console or called directly) update_function(event)
true
true
f7f9e6ecda9b35f096e44ae0a3f1a4c9159d9aa7
2,330
py
Python
pyplan/pyplan/companies/views.py
jorgedouglas71/pyplan-ide
5ad0e4a2592b5f2716ff680018f717c65de140f5
[ "MIT" ]
null
null
null
pyplan/pyplan/companies/views.py
jorgedouglas71/pyplan-ide
5ad0e4a2592b5f2716ff680018f717c65de140f5
[ "MIT" ]
null
null
null
pyplan/pyplan/companies/views.py
jorgedouglas71/pyplan-ide
5ad0e4a2592b5f2716ff680018f717c65de140f5
[ "MIT" ]
null
null
null
from rest_framework import status, viewsets from rest_framework.decorators import action from rest_framework.permissions import IsAdminUser from rest_framework.response import Response from pyplan.pyplan.company_preference.service import CompanyPreferenceService from pyplan.pyplan.preference.serializers import PreferenceSerializer from .models import Company from .permissions import CompanyPermissions from .serializers import CompanySerializer, CreateCompanySerializer, CompanyWithGroupsAndDeptsSerializer, UpdateCompanySerializer from .service import CompaniesService from .pagination import CompanyPagination class CompanyViewSet(viewsets.ModelViewSet): """ Updates and retrieves companies """ queryset = Company.objects.all() permission_classes = (CompanyPermissions,) pagination_class = CompanyPagination def get_serializer_class(self): if self.action in ['create']: return CreateCompanySerializer elif self.action in ['update', 'partial_update']: return UpdateCompanySerializer return CompanySerializer @action(methods=['get'], detail=False) def list_with_groups_and_depts(self, request): try: service = CompaniesService(request) response = service.list_with_groups_and_depts() if len(response) > 0: return Response(CompanyWithGroupsAndDeptsSerializer(response, many=True).data) return Response(status=status.HTTP_204_NO_CONTENT) except Exception as ex: return Response(str(ex), status.HTTP_406_NOT_ACCEPTABLE) @action(methods=['get'], detail=False) def preferences(self, request): preferences = CompanyPreferenceService(request).getCompanyPreferences() if preferences: return Response(PreferenceSerializer(preferences, many=True).data) return Response(status=status.HTTP_204_NO_CONTENT) @action(methods=['get'], detail=False) def preference_by_code(self, request): code = str(request.query_params.get("code", None)) if code: preference = CompanyPreferenceService(request).getCompanyPreference(code) if preference: return Response(PreferenceSerializer(preference).data) return Response(status=status.HTTP_204_NO_CONTENT)
40.877193
129
0.734764
from rest_framework import status, viewsets from rest_framework.decorators import action from rest_framework.permissions import IsAdminUser from rest_framework.response import Response from pyplan.pyplan.company_preference.service import CompanyPreferenceService from pyplan.pyplan.preference.serializers import PreferenceSerializer from .models import Company from .permissions import CompanyPermissions from .serializers import CompanySerializer, CreateCompanySerializer, CompanyWithGroupsAndDeptsSerializer, UpdateCompanySerializer from .service import CompaniesService from .pagination import CompanyPagination class CompanyViewSet(viewsets.ModelViewSet): queryset = Company.objects.all() permission_classes = (CompanyPermissions,) pagination_class = CompanyPagination def get_serializer_class(self): if self.action in ['create']: return CreateCompanySerializer elif self.action in ['update', 'partial_update']: return UpdateCompanySerializer return CompanySerializer @action(methods=['get'], detail=False) def list_with_groups_and_depts(self, request): try: service = CompaniesService(request) response = service.list_with_groups_and_depts() if len(response) > 0: return Response(CompanyWithGroupsAndDeptsSerializer(response, many=True).data) return Response(status=status.HTTP_204_NO_CONTENT) except Exception as ex: return Response(str(ex), status.HTTP_406_NOT_ACCEPTABLE) @action(methods=['get'], detail=False) def preferences(self, request): preferences = CompanyPreferenceService(request).getCompanyPreferences() if preferences: return Response(PreferenceSerializer(preferences, many=True).data) return Response(status=status.HTTP_204_NO_CONTENT) @action(methods=['get'], detail=False) def preference_by_code(self, request): code = str(request.query_params.get("code", None)) if code: preference = CompanyPreferenceService(request).getCompanyPreference(code) if preference: return Response(PreferenceSerializer(preference).data) return Response(status=status.HTTP_204_NO_CONTENT)
true
true
f7f9e75d9eb62df28508d8273551463e49b1c637
6,202
py
Python
idact/detail/config/client/client_cluster_config.py
intdata-bsc/idact
54cb65a711c145351e205970c27c83e6393cccf5
[ "MIT" ]
5
2018-12-06T15:40:34.000Z
2019-06-19T11:22:58.000Z
idact/detail/config/client/client_cluster_config.py
garstka/idact
b9c8405c94db362c4a51d6bfdf418b14f06f0da1
[ "MIT" ]
9
2018-12-06T16:35:26.000Z
2019-04-28T19:01:40.000Z
idact/detail/config/client/client_cluster_config.py
intdata-bsc/idact
54cb65a711c145351e205970c27c83e6393cccf5
[ "MIT" ]
2
2019-04-28T19:18:58.000Z
2019-06-17T06:56:28.000Z
"""This module contains the implementation of the cluster config interface.""" from typing import Optional, Dict from idact.core.auth import AuthMethod from idact.core.config import ClusterConfig, RetryConfig from idact.core.retry import Retry from idact.detail.config.client.setup_actions_config import \ SetupActionsConfigImpl from idact.detail.config.defaults.provide_defaults_for_retries import \ provide_defaults_for_retries from idact.detail.config.validation.validate_hostname import validate_hostname from idact.detail.config.validation.validate_bool import validate_bool from idact.detail.config.validation.validate_key_path import validate_key_path from idact.detail.config.validation.validate_notebook_defaults import \ validate_notebook_defaults from idact.detail.config.validation.validate_port import validate_port from idact.detail.config.validation.validate_retry_config_dict import \ validate_retry_config_dict from idact.detail.config.validation.validate_scratch import validate_scratch from idact.detail.config.validation.validate_setup_actions_config import \ validate_setup_actions_config from idact.detail.config.validation.validate_username import validate_username class ClusterConfigImpl(ClusterConfig): """Client-side cluster config. For parameter description, see :class:`.ClusterConfig`. For defaults, see :func:`.add_cluster`. For notebook defaults, see :mod:`.jupyter_app.main` """ def __init__(self, host: str, port: int, user: str, auth: AuthMethod, key: Optional[str] = None, install_key: bool = True, disable_sshd: bool = False, setup_actions: Optional[SetupActionsConfigImpl] = None, scratch: Optional[str] = None, notebook_defaults: Optional[dict] = None, retries: Optional[Dict[Retry, RetryConfig]] = None, use_jupyter_lab: bool = True): if install_key is None: install_key = True if disable_sshd is None: disable_sshd = False if setup_actions is None: setup_actions = SetupActionsConfigImpl() if scratch is None: scratch = '$HOME' if notebook_defaults is None: notebook_defaults = {} if retries is None: retries = {} if use_jupyter_lab is None: use_jupyter_lab = True retries = provide_defaults_for_retries(retries) self._host = None self.host = host self._port = None self.port = port self._user = None self.user = user self._auth = None self.auth = auth self._key = None self.key = key self._install_key = None self.install_key = install_key self._disable_sshd = None self.disable_sshd = disable_sshd self._setup_actions = validate_setup_actions_config(setup_actions) self._scratch = None self.scratch = scratch self._notebook_defaults = None self.notebook_defaults = notebook_defaults self._retries = validate_retry_config_dict(retries, 'retries') self._use_jupyter_lab = None self.use_jupyter_lab = use_jupyter_lab @property def host(self) -> str: return self._host @host.setter def host(self, value: str): self._host = validate_hostname(value) @property def port(self) -> int: return self._port @port.setter def port(self, value: int): self._port = validate_port(value) @property def user(self) -> str: return self._user @user.setter def user(self, value: str): self._user = validate_username(value) @property def auth(self) -> AuthMethod: return self._auth @auth.setter def auth(self, value: AuthMethod): self._auth = value @property def key(self) -> Optional[str]: return self._key @key.setter def key(self, value: Optional[str]): self._key = validate_key_path(value) @property def install_key(self) -> bool: return self._install_key @install_key.setter def install_key(self, value: bool): self._install_key = validate_bool(value, 'install_key') @property def disable_sshd(self) -> bool: return self._disable_sshd @disable_sshd.setter def disable_sshd(self, value: bool): self._disable_sshd = validate_bool(value, 'disable_sshd') @property def setup_actions(self) -> SetupActionsConfigImpl: return self._setup_actions @property def scratch(self) -> str: return self._scratch @scratch.setter def scratch(self, value: str): self._scratch = validate_scratch(value) def __eq__(self, other): return self.__dict__ == other.__dict__ def __str__(self): return ("({host}," " {port}," " {user}," " auth={auth}," " key={key}," " install_key={install_key}," " disable_sshd={disable_sshd})") \ .format(host=self._host, port=self._port, user=self._user, auth=self._auth, key=repr(self._key), install_key=self._install_key, disable_sshd=self._disable_sshd) def __repr__(self): return str(self) @property def notebook_defaults(self) -> dict: """Defaults for the notebook app.""" return self._notebook_defaults @notebook_defaults.setter def notebook_defaults(self, value: dict): self._notebook_defaults = validate_notebook_defaults(value) @property def retries(self) -> Dict[Retry, RetryConfig]: return self._retries @property def use_jupyter_lab(self) -> bool: return self._use_jupyter_lab @use_jupyter_lab.setter def use_jupyter_lab(self, value: bool): self._use_jupyter_lab = validate_bool(value, 'use_jupyter_lab')
29.393365
78
0.638504
from typing import Optional, Dict from idact.core.auth import AuthMethod from idact.core.config import ClusterConfig, RetryConfig from idact.core.retry import Retry from idact.detail.config.client.setup_actions_config import \ SetupActionsConfigImpl from idact.detail.config.defaults.provide_defaults_for_retries import \ provide_defaults_for_retries from idact.detail.config.validation.validate_hostname import validate_hostname from idact.detail.config.validation.validate_bool import validate_bool from idact.detail.config.validation.validate_key_path import validate_key_path from idact.detail.config.validation.validate_notebook_defaults import \ validate_notebook_defaults from idact.detail.config.validation.validate_port import validate_port from idact.detail.config.validation.validate_retry_config_dict import \ validate_retry_config_dict from idact.detail.config.validation.validate_scratch import validate_scratch from idact.detail.config.validation.validate_setup_actions_config import \ validate_setup_actions_config from idact.detail.config.validation.validate_username import validate_username class ClusterConfigImpl(ClusterConfig): def __init__(self, host: str, port: int, user: str, auth: AuthMethod, key: Optional[str] = None, install_key: bool = True, disable_sshd: bool = False, setup_actions: Optional[SetupActionsConfigImpl] = None, scratch: Optional[str] = None, notebook_defaults: Optional[dict] = None, retries: Optional[Dict[Retry, RetryConfig]] = None, use_jupyter_lab: bool = True): if install_key is None: install_key = True if disable_sshd is None: disable_sshd = False if setup_actions is None: setup_actions = SetupActionsConfigImpl() if scratch is None: scratch = '$HOME' if notebook_defaults is None: notebook_defaults = {} if retries is None: retries = {} if use_jupyter_lab is None: use_jupyter_lab = True retries = provide_defaults_for_retries(retries) self._host = None self.host = host self._port = None self.port = port self._user = None self.user = user self._auth = None self.auth = auth self._key = None self.key = key self._install_key = None self.install_key = install_key self._disable_sshd = None self.disable_sshd = disable_sshd self._setup_actions = validate_setup_actions_config(setup_actions) self._scratch = None self.scratch = scratch self._notebook_defaults = None self.notebook_defaults = notebook_defaults self._retries = validate_retry_config_dict(retries, 'retries') self._use_jupyter_lab = None self.use_jupyter_lab = use_jupyter_lab @property def host(self) -> str: return self._host @host.setter def host(self, value: str): self._host = validate_hostname(value) @property def port(self) -> int: return self._port @port.setter def port(self, value: int): self._port = validate_port(value) @property def user(self) -> str: return self._user @user.setter def user(self, value: str): self._user = validate_username(value) @property def auth(self) -> AuthMethod: return self._auth @auth.setter def auth(self, value: AuthMethod): self._auth = value @property def key(self) -> Optional[str]: return self._key @key.setter def key(self, value: Optional[str]): self._key = validate_key_path(value) @property def install_key(self) -> bool: return self._install_key @install_key.setter def install_key(self, value: bool): self._install_key = validate_bool(value, 'install_key') @property def disable_sshd(self) -> bool: return self._disable_sshd @disable_sshd.setter def disable_sshd(self, value: bool): self._disable_sshd = validate_bool(value, 'disable_sshd') @property def setup_actions(self) -> SetupActionsConfigImpl: return self._setup_actions @property def scratch(self) -> str: return self._scratch @scratch.setter def scratch(self, value: str): self._scratch = validate_scratch(value) def __eq__(self, other): return self.__dict__ == other.__dict__ def __str__(self): return ("({host}," " {port}," " {user}," " auth={auth}," " key={key}," " install_key={install_key}," " disable_sshd={disable_sshd})") \ .format(host=self._host, port=self._port, user=self._user, auth=self._auth, key=repr(self._key), install_key=self._install_key, disable_sshd=self._disable_sshd) def __repr__(self): return str(self) @property def notebook_defaults(self) -> dict: return self._notebook_defaults @notebook_defaults.setter def notebook_defaults(self, value: dict): self._notebook_defaults = validate_notebook_defaults(value) @property def retries(self) -> Dict[Retry, RetryConfig]: return self._retries @property def use_jupyter_lab(self) -> bool: return self._use_jupyter_lab @use_jupyter_lab.setter def use_jupyter_lab(self, value: bool): self._use_jupyter_lab = validate_bool(value, 'use_jupyter_lab')
true
true
f7f9e7c09fe1e93d154729124f9f23b6f0cf513c
416
py
Python
seasonal_events/migrations/0005_season_active.py
Riphiphip/website
dc5bf64f24d5cf78661686af0281705f4d1d2576
[ "MIT" ]
25
2016-04-13T20:25:37.000Z
2021-11-26T14:41:00.000Z
seasonal_events/migrations/0005_season_active.py
Riphiphip/website
dc5bf64f24d5cf78661686af0281705f4d1d2576
[ "MIT" ]
358
2016-02-20T21:13:27.000Z
2022-03-31T20:06:03.000Z
seasonal_events/migrations/0005_season_active.py
Riphiphip/website
dc5bf64f24d5cf78661686af0281705f4d1d2576
[ "MIT" ]
7
2016-04-18T14:03:15.000Z
2022-02-04T14:19:47.000Z
# Generated by Django 2.0.9 on 2019-03-04 18:39 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('seasonal_events', '0004_season_header_name'), ] operations = [ migrations.AddField( model_name='season', name='active', field=models.BooleanField(default=True, verbose_name='aktiv'), ), ]
21.894737
74
0.615385
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('seasonal_events', '0004_season_header_name'), ] operations = [ migrations.AddField( model_name='season', name='active', field=models.BooleanField(default=True, verbose_name='aktiv'), ), ]
true
true
f7f9e85b0b7708d155724b7d6ab3f4f044887e89
1,807
py
Python
src/cms/publications/migrations/0016_auto_20210531_1041.py
UniversitaDellaCalabria/uniCMS
b0af4e1a767867f0a9b3c135a5c84587e713cb71
[ "Apache-2.0" ]
6
2021-01-26T17:22:53.000Z
2022-02-15T10:09:03.000Z
src/cms/publications/migrations/0016_auto_20210531_1041.py
UniversitaDellaCalabria/uniCMS
b0af4e1a767867f0a9b3c135a5c84587e713cb71
[ "Apache-2.0" ]
5
2020-12-24T14:29:23.000Z
2021-08-10T10:32:18.000Z
src/cms/publications/migrations/0016_auto_20210531_1041.py
UniversitaDellaCalabria/uniCMS
b0af4e1a767867f0a9b3c135a5c84587e713cb71
[ "Apache-2.0" ]
2
2020-12-24T14:13:39.000Z
2020-12-30T16:48:52.000Z
# Generated by Django 3.2.3 on 2021-05-31 10:41 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('cmsmedias', '0008_alter_media_file'), ('cmspublications', '0015_auto_20210531_1013'), ] operations = [ migrations.CreateModel( name='PublicationMediaCollection', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True)), ('modified', models.DateTimeField(auto_now=True)), ('order', models.IntegerField(blank=True, default=10, null=True)), ('is_active', models.BooleanField(default=False)), ('collection', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='cmsmedias.mediacollection')), ('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='publicationmediacollection_created_by', to=settings.AUTH_USER_MODEL)), ('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='publicationmediacollection_modified_by', to=settings.AUTH_USER_MODEL)), ('publication', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='cmspublications.publication')), ], options={ 'verbose_name_plural': 'Publication Media Collection', }, ), migrations.DeleteModel( name='PublicationGallery', ), ]
47.552632
204
0.660764
from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('cmsmedias', '0008_alter_media_file'), ('cmspublications', '0015_auto_20210531_1013'), ] operations = [ migrations.CreateModel( name='PublicationMediaCollection', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', models.DateTimeField(auto_now_add=True)), ('modified', models.DateTimeField(auto_now=True)), ('order', models.IntegerField(blank=True, default=10, null=True)), ('is_active', models.BooleanField(default=False)), ('collection', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='cmsmedias.mediacollection')), ('created_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='publicationmediacollection_created_by', to=settings.AUTH_USER_MODEL)), ('modified_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='publicationmediacollection_modified_by', to=settings.AUTH_USER_MODEL)), ('publication', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='cmspublications.publication')), ], options={ 'verbose_name_plural': 'Publication Media Collection', }, ), migrations.DeleteModel( name='PublicationGallery', ), ]
true
true
f7f9e93d0e31153aac0a99843a7847eb1145fe35
3,724
py
Python
pypureclient/flasharray/FA_2_6/models/array_encryption.py
Flav-STOR-WL/py-pure-client
03b889c997d90380ac5d6380ca5d5432792d3e89
[ "BSD-2-Clause" ]
14
2018-12-07T18:30:27.000Z
2022-02-22T09:12:33.000Z
pypureclient/flasharray/FA_2_6/models/array_encryption.py
Flav-STOR-WL/py-pure-client
03b889c997d90380ac5d6380ca5d5432792d3e89
[ "BSD-2-Clause" ]
28
2019-09-17T21:03:52.000Z
2022-03-29T22:07:35.000Z
pypureclient/flasharray/FA_2_6/models/array_encryption.py
Flav-STOR-WL/py-pure-client
03b889c997d90380ac5d6380ca5d5432792d3e89
[ "BSD-2-Clause" ]
15
2020-06-11T15:50:08.000Z
2022-03-21T09:27:25.000Z
# coding: utf-8 """ FlashArray REST API No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: 2.6 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re import six import typing from ....properties import Property if typing.TYPE_CHECKING: from pypureclient.flasharray.FA_2_6 import models class ArrayEncryption(object): """ 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_at_rest': 'ArrayencryptionDataAtRest', 'module_version': 'str' } attribute_map = { 'data_at_rest': 'data_at_rest', 'module_version': 'module_version' } required_args = { } def __init__( self, data_at_rest=None, # type: models.ArrayencryptionDataAtRest module_version=None, # type: str ): """ Keyword args: data_at_rest (ArrayencryptionDataAtRest) module_version (str): The version of the Purity encryption module installed on the array. Security certifications are carried out on a per-version basis. On non-encrypt builds, an encryption module may be installed without being enabled. Values include `FA-1.0`, `FA-1.1`, `FA-1.2`, `FA-1.3`, and so on. """ if data_at_rest is not None: self.data_at_rest = data_at_rest if module_version is not None: self.module_version = module_version def __setattr__(self, key, value): if key not in self.attribute_map: raise KeyError("Invalid key `{}` for `ArrayEncryption`".format(key)) self.__dict__[key] = value def __getattribute__(self, item): value = object.__getattribute__(self, item) if isinstance(value, Property): raise AttributeError else: return value def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): if hasattr(self, attr): 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(ArrayEncryption, 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, ArrayEncryption): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
31.559322
315
0.574651
import pprint import re import six import typing from ....properties import Property if typing.TYPE_CHECKING: from pypureclient.flasharray.FA_2_6 import models class ArrayEncryption(object): swagger_types = { 'data_at_rest': 'ArrayencryptionDataAtRest', 'module_version': 'str' } attribute_map = { 'data_at_rest': 'data_at_rest', 'module_version': 'module_version' } required_args = { } def __init__( self, data_at_rest=None, module_version=None, ): if data_at_rest is not None: self.data_at_rest = data_at_rest if module_version is not None: self.module_version = module_version def __setattr__(self, key, value): if key not in self.attribute_map: raise KeyError("Invalid key `{}` for `ArrayEncryption`".format(key)) self.__dict__[key] = value def __getattribute__(self, item): value = object.__getattribute__(self, item) if isinstance(value, Property): raise AttributeError else: return value def to_dict(self): result = {} for attr, _ in six.iteritems(self.swagger_types): if hasattr(self, attr): 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(ArrayEncryption, dict): for key, value in self.items(): result[key] = value return result def to_str(self): return pprint.pformat(self.to_dict()) def __repr__(self): return self.to_str() def __eq__(self, other): if not isinstance(other, ArrayEncryption): return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
true
true
f7f9ea24bc45128cf5450faf35109ac41cb5b241
307
py
Python
HackerRank/Python_Learn/01_Introduction/07_Write_A_Function.py
Zubieta/CPP
fb4a3cbf2e4edcc590df15663cd28fb9ecab679c
[ "MIT" ]
8
2017-03-02T07:56:45.000Z
2021-08-07T20:20:19.000Z
HackerRank/Python_Learn/01_Introduction/07_Write_A_Function.py
zubie7a/Algorithms
fb4a3cbf2e4edcc590df15663cd28fb9ecab679c
[ "MIT" ]
null
null
null
HackerRank/Python_Learn/01_Introduction/07_Write_A_Function.py
zubie7a/Algorithms
fb4a3cbf2e4edcc590df15663cd28fb9ecab679c
[ "MIT" ]
1
2021-08-07T20:20:20.000Z
2021-08-07T20:20:20.000Z
# https://www.hackerrank.com/challenges/write-a-function def is_leap(yr): leap = False # Leap year: # * Divisible by 4 # * Not divisible by 100, unless divisible by 400 too. if (yr % 4 == 0 and yr % 100 != 0) or (yr % 100 == 0 and yr % 400 == 0): leap = True return leap
30.7
76
0.57329
def is_leap(yr): leap = False if (yr % 4 == 0 and yr % 100 != 0) or (yr % 100 == 0 and yr % 400 == 0): leap = True return leap
true
true
f7f9ea6733ebc0e12ef6331341c1010df404a952
2,891
py
Python
core_lib/dfa.py
zeerorg/Compiler-Design-Lab
4a0e73fbcf5c4ea92504d27bf4727766ef6c2347
[ "MIT" ]
null
null
null
core_lib/dfa.py
zeerorg/Compiler-Design-Lab
4a0e73fbcf5c4ea92504d27bf4727766ef6c2347
[ "MIT" ]
null
null
null
core_lib/dfa.py
zeerorg/Compiler-Design-Lab
4a0e73fbcf5c4ea92504d27bf4727766ef6c2347
[ "MIT" ]
null
null
null
class DFA_Node: def __init__(self, a: int, b: int): self.a = a self.b = b def __iter__(self): yield ('a', self.a) yield ('b', self.b) def as_dict(): return { 'a': self.a, 'b': self.b } def __str__(self): return "a: {}, b: {}".format(self.a, self.b) def __repr__(self): return self.__str__() def __getitem__(self, k): return self.__getattribute__(k) class DFA: """ Class which implements dfa and a dict from self.graph = { 0: DFA_Node, 2: DFA_Node } """ def __init__(self, init_state: int, final_states: list, graph: dict): self.init_state = init_state self.final_states = final_states self.graph = graph def __getitem__(self, key) -> DFA_Node: return self.graph[key] def __setitem__(self, name, val): self.graph[name] = val def __str__(self): final_str = ["STATE\t\tINPUT\t\tNext State"] to_check = [self.init_state] checked = [] while len(to_check) > 0: state = to_check.pop(0) if state in checked: continue checked.append(state) for inp, next_state in self.__getitem__(state): to_check.append(next_state) string = [] if state in self.final_states: string.append("+") else: string.append(" ") if state == self.init_state: if string[-1] == " ": string.pop() string.append("-") string.append("{}\t\t {}\t\t {}".format(state, inp, next_state)) final_str.append(''.join(string)) return '\n'.join(final_str) def get(self, key): return self.graph.get(key, set()) def get_raw_dfa_str(self, mapping: list): final_str = ["STATE\t\tINPUT\t\tNext State"] to_check = [self.init_state] checked = [] while len(to_check) > 0: state = to_check.pop(0) if state in checked: continue checked.append(state) for inp, next_state in self.__getitem__(state): to_check.append(next_state) string = [] if state in self.final_states: string.append("+") else: string.append(" ") if state == self.init_state: if string[-1] == " ": string.pop() string.append("-") string.append("{}\t\t {}\t\t {}".format(list(mapping[state]), inp, list(mapping[next_state]))) final_str.append(''.join(string)) return '\n'.join(final_str)
28.343137
110
0.484262
class DFA_Node: def __init__(self, a: int, b: int): self.a = a self.b = b def __iter__(self): yield ('a', self.a) yield ('b', self.b) def as_dict(): return { 'a': self.a, 'b': self.b } def __str__(self): return "a: {}, b: {}".format(self.a, self.b) def __repr__(self): return self.__str__() def __getitem__(self, k): return self.__getattribute__(k) class DFA: def __init__(self, init_state: int, final_states: list, graph: dict): self.init_state = init_state self.final_states = final_states self.graph = graph def __getitem__(self, key) -> DFA_Node: return self.graph[key] def __setitem__(self, name, val): self.graph[name] = val def __str__(self): final_str = ["STATE\t\tINPUT\t\tNext State"] to_check = [self.init_state] checked = [] while len(to_check) > 0: state = to_check.pop(0) if state in checked: continue checked.append(state) for inp, next_state in self.__getitem__(state): to_check.append(next_state) string = [] if state in self.final_states: string.append("+") else: string.append(" ") if state == self.init_state: if string[-1] == " ": string.pop() string.append("-") string.append("{}\t\t {}\t\t {}".format(state, inp, next_state)) final_str.append(''.join(string)) return '\n'.join(final_str) def get(self, key): return self.graph.get(key, set()) def get_raw_dfa_str(self, mapping: list): final_str = ["STATE\t\tINPUT\t\tNext State"] to_check = [self.init_state] checked = [] while len(to_check) > 0: state = to_check.pop(0) if state in checked: continue checked.append(state) for inp, next_state in self.__getitem__(state): to_check.append(next_state) string = [] if state in self.final_states: string.append("+") else: string.append(" ") if state == self.init_state: if string[-1] == " ": string.pop() string.append("-") string.append("{}\t\t {}\t\t {}".format(list(mapping[state]), inp, list(mapping[next_state]))) final_str.append(''.join(string)) return '\n'.join(final_str)
true
true
f7f9eafff60694d0c1d23a9b15904deb860b2fe2
3,189
py
Python
test/programytest/mappings/test_person.py
motazsaad/fit-bot-fb-clt
580477aa1ec91855b621d9ae276f2705962f6a87
[ "MIT" ]
5
2018-08-21T00:13:45.000Z
2018-09-01T20:00:55.000Z
test/programytest/mappings/test_person.py
motazsaad/fit-bot-fb-clt
580477aa1ec91855b621d9ae276f2705962f6a87
[ "MIT" ]
1
2018-09-12T18:30:17.000Z
2018-09-12T18:30:17.000Z
test/programytest/mappings/test_person.py
motazsaad/fit-bot-fb-clt
580477aa1ec91855b621d9ae276f2705962f6a87
[ "MIT" ]
5
2018-08-21T00:08:36.000Z
2018-09-23T06:11:04.000Z
import unittest import os from programy.mappings.person import PersonCollection from programy.storage.factory import StorageFactory from programy.storage.stores.file.config import FileStorageConfiguration from programy.storage.stores.file.engine import FileStorageEngine from programy.storage.stores.file.config import FileStoreConfiguration class PersonTests(unittest.TestCase): def test_initialise_collection(self): collection = PersonCollection() self.assertIsNotNone(collection) def test_collection_operations(self): person_text = """ " with you "," with me2 " " with me "," with you2 " " are you "," am I2 " " with me "," with you2 " """ collection = PersonCollection() self.assertIsNotNone(collection) collection.load_from_text(person_text) self.assertEqual(collection.personalise_string(" with me "), "with you2") self.assertEqual(collection.personalise_string("Hello are you with me"), "Hello am i2 with you2") pattern = collection.person(" with you ") self.assertIsNotNone(pattern) self.assertEqual(" WITH ME2 ", pattern[1]) def test_load(self): storage_factory = StorageFactory() file_store_config = FileStorageConfiguration() file_store_config._person_storage = FileStoreConfiguration(file=os.path.dirname(__file__) + os.sep + "test_files" + os.sep + "person.txt", format="text", extension="txt", encoding="utf-8", delete_on_start=False) storage_engine = FileStorageEngine(file_store_config) storage_factory._storage_engines[StorageFactory.PERSON] = storage_engine storage_factory._store_to_engine_map[StorageFactory.PERSON] = storage_engine collection = PersonCollection() self.assertIsNotNone(collection) collection.load(storage_factory) self.assertEqual(collection.personalise_string(" with me "), "with you2") self.assertEqual(collection.personalise_string("Hello are you with me"), "Hello am i2 with you2") def test_reload(self): storage_factory = StorageFactory() file_store_config = FileStorageConfiguration() file_store_config._person_storage = FileStoreConfiguration(file=os.path.dirname(__file__) + os.sep + "test_files" + os.sep + "person.txt", format="text", extension="txt", encoding="utf-8", delete_on_start=False) storage_engine = FileStorageEngine(file_store_config) storage_factory._storage_engines[StorageFactory.PERSON] = storage_engine storage_factory._store_to_engine_map[StorageFactory.PERSON] = storage_engine collection = PersonCollection() self.assertIsNotNone(collection) collection.load(storage_factory) self.assertEqual(collection.personalise_string(" with me "), "with you2") self.assertEqual(collection.personalise_string("Hello are you with me"), "Hello am i2 with you2") collection.reload(storage_factory) self.assertEqual(collection.personalise_string(" with me "), "with you2") self.assertEqual(collection.personalise_string("Hello are you with me"), "Hello am i2 with you2")
40.884615
219
0.718407
import unittest import os from programy.mappings.person import PersonCollection from programy.storage.factory import StorageFactory from programy.storage.stores.file.config import FileStorageConfiguration from programy.storage.stores.file.engine import FileStorageEngine from programy.storage.stores.file.config import FileStoreConfiguration class PersonTests(unittest.TestCase): def test_initialise_collection(self): collection = PersonCollection() self.assertIsNotNone(collection) def test_collection_operations(self): person_text = """ " with you "," with me2 " " with me "," with you2 " " are you "," am I2 " " with me "," with you2 " """ collection = PersonCollection() self.assertIsNotNone(collection) collection.load_from_text(person_text) self.assertEqual(collection.personalise_string(" with me "), "with you2") self.assertEqual(collection.personalise_string("Hello are you with me"), "Hello am i2 with you2") pattern = collection.person(" with you ") self.assertIsNotNone(pattern) self.assertEqual(" WITH ME2 ", pattern[1]) def test_load(self): storage_factory = StorageFactory() file_store_config = FileStorageConfiguration() file_store_config._person_storage = FileStoreConfiguration(file=os.path.dirname(__file__) + os.sep + "test_files" + os.sep + "person.txt", format="text", extension="txt", encoding="utf-8", delete_on_start=False) storage_engine = FileStorageEngine(file_store_config) storage_factory._storage_engines[StorageFactory.PERSON] = storage_engine storage_factory._store_to_engine_map[StorageFactory.PERSON] = storage_engine collection = PersonCollection() self.assertIsNotNone(collection) collection.load(storage_factory) self.assertEqual(collection.personalise_string(" with me "), "with you2") self.assertEqual(collection.personalise_string("Hello are you with me"), "Hello am i2 with you2") def test_reload(self): storage_factory = StorageFactory() file_store_config = FileStorageConfiguration() file_store_config._person_storage = FileStoreConfiguration(file=os.path.dirname(__file__) + os.sep + "test_files" + os.sep + "person.txt", format="text", extension="txt", encoding="utf-8", delete_on_start=False) storage_engine = FileStorageEngine(file_store_config) storage_factory._storage_engines[StorageFactory.PERSON] = storage_engine storage_factory._store_to_engine_map[StorageFactory.PERSON] = storage_engine collection = PersonCollection() self.assertIsNotNone(collection) collection.load(storage_factory) self.assertEqual(collection.personalise_string(" with me "), "with you2") self.assertEqual(collection.personalise_string("Hello are you with me"), "Hello am i2 with you2") collection.reload(storage_factory) self.assertEqual(collection.personalise_string(" with me "), "with you2") self.assertEqual(collection.personalise_string("Hello are you with me"), "Hello am i2 with you2")
true
true
f7f9eb0533f34decf9be06537dc3e19c8fd36579
3,906
py
Python
A3/A3Part4.py
mortarsynth/Audio-Signal-Processing-for-Music-Applications
4674d9e15885401d69d4a468e3ad756ea2600523
[ "MIT" ]
null
null
null
A3/A3Part4.py
mortarsynth/Audio-Signal-Processing-for-Music-Applications
4674d9e15885401d69d4a468e3ad756ea2600523
[ "MIT" ]
null
null
null
A3/A3Part4.py
mortarsynth/Audio-Signal-Processing-for-Music-Applications
4674d9e15885401d69d4a468e3ad756ea2600523
[ "MIT" ]
null
null
null
import sys sys.path.append('../../software/models/') from dftModel import dftAnal, dftSynth from scipy.signal import get_window import numpy as np """ A3-Part-4: Suppressing frequency components using DFT model Given a frame of the signal, write a function that uses the dftModel functions to suppress all the frequency components <= 70Hz in the signal and returns the output of the dftModel with and without filtering. You will use the DFT model to implement a very basic form of filtering to suppress frequency components. When working close to mains power lines, there is a 50/60 Hz hum that can get introduced into the audio signal. You will try to remove that using a basic DFT model based filter. You will work on just one frame of a synthetic audio signal to see the effect of filtering. You can use the functions dftAnal and dftSynth provided by the dftModel file of sms-tools. Use dftAnal to obtain the magnitude spectrum (in dB) and phase spectrum of the audio signal. Set the values of the magnitude spectrum that correspond to frequencies <= 70 Hz to -120dB (there may not be a bin corresponding exactly to 70 Hz, choose the nearest bin of equal or higher frequency, e.g., using np.ceil()). If you have doubts converting from frequency (Hz) to bins, you can review the beginning of theory lecture 2T1. Use dftSynth to synthesize the filtered output signal and return the output. The function should also return the output of dftSynth without any filtering (without altering the magnitude spectrum in any way). You will use a hamming window to smooth the signal. Hence, do not forget to scale the output signals by the sum of the window values (as done in sms-tools/software/models_interface/dftModel_function.py). To understand the effect of filtering, you can plot both the filtered output and non-filtered output of the dftModel. Please note that this question is just for illustrative purposes and filtering is not usually done this way - such sharp cutoffs introduce artifacts in the output. The input is a M length input signal x that contains undesired frequencies below 70 Hz, sampling frequency fs and the FFT size N. The output is a tuple with two elements (y, yfilt), where y is the output of dftModel with the unaltered original signal and yfilt is the filtered output of the dftModel. Caveat: In python (as well as numpy) variable assignment is by reference. if you assign B = A, and modify B, the value of A also gets modified. If you do not want this to happen, consider using B = A.copy(). This creates a copy of A and assigns it to B, and hence, you can modify B without affecting A. Test case 1: For an input signal with 40 Hz, 100 Hz, 200 Hz, 1000 Hz components, yfilt will only contain 100 Hz, 200 Hz and 1000 Hz components. Test case 2: For an input signal with 23 Hz, 36 Hz, 230 Hz, 900 Hz, 2300 Hz components, yfilt will only contain 230 Hz, 900 Hz and 2300 Hz components. """ def suppressFreqDFTmodel(x, fs, N): """ Inputs: x (numpy array) = input signal of length M (odd) fs (float) = sampling frequency (Hz) N (positive integer) = FFT size Outputs: The function should return a tuple (y, yfilt) y (numpy array) = Output of the dftSynth() without filtering (M samples long) yfilt (numpy array) = Output of the dftSynth() with filtering (M samples long) The first few lines of the code have been written for you, do not modify it. """ M = len(x) w = get_window('hamming', M) outputScaleFactor = sum(w) ## Your code here mX, pX = dftAnal(x,w,N) mX_filt = mX.copy() thresh_sample = int(np.ceil(70 / fs * N)) mX_filt[:thresh_sample+1] = -120.0 signal_reconst = dftSynth(mX, pX, w.size) * outputScaleFactor signal_reconst_filt = dftSynth(mX_filt, pX, w.size) * outputScaleFactor return (signal_reconst, signal_reconst_filt)
54.25
113
0.743984
import sys sys.path.append('../../software/models/') from dftModel import dftAnal, dftSynth from scipy.signal import get_window import numpy as np def suppressFreqDFTmodel(x, fs, N): M = len(x) w = get_window('hamming', M) outputScaleFactor = sum(w) tAnal(x,w,N) mX_filt = mX.copy() thresh_sample = int(np.ceil(70 / fs * N)) mX_filt[:thresh_sample+1] = -120.0 signal_reconst = dftSynth(mX, pX, w.size) * outputScaleFactor signal_reconst_filt = dftSynth(mX_filt, pX, w.size) * outputScaleFactor return (signal_reconst, signal_reconst_filt)
true
true
f7f9eb962555bf3b3394113c9a6f83fa75f8c5f9
103,255
py
Python
Lib/test/test_xml_etree.py
sireliah/polish-python
605df4944c2d3bc25f8bf6964b274c0a0d297cc3
[ "PSF-2.0" ]
1
2018-06-21T18:21:24.000Z
2018-06-21T18:21:24.000Z
Lib/test/test_xml_etree.py
sireliah/polish-python
605df4944c2d3bc25f8bf6964b274c0a0d297cc3
[ "PSF-2.0" ]
null
null
null
Lib/test/test_xml_etree.py
sireliah/polish-python
605df4944c2d3bc25f8bf6964b274c0a0d297cc3
[ "PSF-2.0" ]
null
null
null
# IMPORTANT: the same tests are run z "test_xml_etree_c" w order # to ensure consistency between the C implementation oraz the Python # implementation. # # For this purpose, the module-level "ET" symbol jest temporarily # monkey-patched when running the "test_xml_etree_c" test suite. zaimportuj html zaimportuj io zaimportuj operator zaimportuj pickle zaimportuj sys zaimportuj types zaimportuj unittest zaimportuj warnings zaimportuj weakref z itertools zaimportuj product z test zaimportuj support z test.support zaimportuj TESTFN, findfile, import_fresh_module, gc_collect # pyET jest the pure-Python implementation. # # ET jest pyET w test_xml_etree oraz jest the C accelerated version w # test_xml_etree_c. pyET = Nic ET = Nic SIMPLE_XMLFILE = findfile("simple.xml", subdir="xmltestdata") spróbuj: SIMPLE_XMLFILE.encode("utf-8") wyjąwszy UnicodeEncodeError: podnieś unittest.SkipTest("filename jest nie encodable to utf8") SIMPLE_NS_XMLFILE = findfile("simple-ns.xml", subdir="xmltestdata") SAMPLE_XML = """\ <body> <tag class='a'>text</tag> <tag class='b' /> <section> <tag class='b' id='inner'>subtext</tag> </section> </body> """ SAMPLE_SECTION = """\ <section> <tag class='b' id='inner'>subtext</tag> <nexttag /> <nextsection> <tag /> </nextsection> </section> """ SAMPLE_XML_NS = """ <body xmlns="http://effbot.org/ns"> <tag>text</tag> <tag /> <section> <tag>subtext</tag> </section> </body> """ SAMPLE_XML_NS_ELEMS = """ <root> <h:table xmlns:h="hello"> <h:tr> <h:td>Apples</h:td> <h:td>Bananas</h:td> </h:tr> </h:table> <f:table xmlns:f="foo"> <f:name>African Coffee Table</f:name> <f:width>80</f:width> <f:length>120</f:length> </f:table> </root> """ ENTITY_XML = """\ <!DOCTYPE points [ <!ENTITY % user-entities SYSTEM 'user-entities.xml'> %user-entities; ]> <document>&entity;</document> """ klasa ModuleTest(unittest.TestCase): # TODO: this should be removed once we get rid of the global module vars def test_sanity(self): # Import sanity. z xml.etree zaimportuj ElementTree z xml.etree zaimportuj ElementInclude z xml.etree zaimportuj ElementPath def serialize(elem, to_string=Prawda, encoding='unicode', **options): jeżeli encoding != 'unicode': file = io.BytesIO() inaczej: file = io.StringIO() tree = ET.ElementTree(elem) tree.write(file, encoding=encoding, **options) jeżeli to_string: zwróć file.getvalue() inaczej: file.seek(0) zwróć file def summarize_list(seq): zwróć [elem.tag dla elem w seq] klasa ElementTestCase: @classmethod def setUpClass(cls): cls.modules = {pyET, ET} def pickleRoundTrip(self, obj, name, dumper, loader, proto): save_m = sys.modules[name] spróbuj: sys.modules[name] = dumper temp = pickle.dumps(obj, proto) sys.modules[name] = loader result = pickle.loads(temp) wyjąwszy pickle.PicklingError jako pe: # pyET must be second, because pyET may be (equal to) ET. human = dict([(ET, "cET"), (pyET, "pyET")]) podnieś support.TestFailed("Failed to round-trip %r z %r to %r" % (obj, human.get(dumper, dumper), human.get(loader, loader))) z pe w_końcu: sys.modules[name] = save_m zwróć result def assertEqualElements(self, alice, bob): self.assertIsInstance(alice, (ET.Element, pyET.Element)) self.assertIsInstance(bob, (ET.Element, pyET.Element)) self.assertEqual(len(list(alice)), len(list(bob))) dla x, y w zip(alice, bob): self.assertEqualElements(x, y) properties = operator.attrgetter('tag', 'tail', 'text', 'attrib') self.assertEqual(properties(alice), properties(bob)) # -------------------------------------------------------------------- # element tree tests klasa ElementTreeTest(unittest.TestCase): def serialize_check(self, elem, expected): self.assertEqual(serialize(elem), expected) def test_interface(self): # Test element tree interface. def check_string(string): len(string) dla char w string: self.assertEqual(len(char), 1, msg="expected one-character string, got %r" % char) new_string = string + "" new_string = string + " " string[:0] def check_mapping(mapping): len(mapping) keys = mapping.keys() items = mapping.items() dla key w keys: item = mapping[key] mapping["key"] = "value" self.assertEqual(mapping["key"], "value", msg="expected value string, got %r" % mapping["key"]) def check_element(element): self.assertPrawda(ET.iselement(element), msg="not an element") self.assertPrawda(hasattr(element, "tag"), msg="no tag member") self.assertPrawda(hasattr(element, "attrib"), msg="no attrib member") self.assertPrawda(hasattr(element, "text"), msg="no text member") self.assertPrawda(hasattr(element, "tail"), msg="no tail member") check_string(element.tag) check_mapping(element.attrib) jeżeli element.text jest nie Nic: check_string(element.text) jeżeli element.tail jest nie Nic: check_string(element.tail) dla elem w element: check_element(elem) element = ET.Element("tag") check_element(element) tree = ET.ElementTree(element) check_element(tree.getroot()) element = ET.Element("t\xe4g", key="value") tree = ET.ElementTree(element) self.assertRegex(repr(element), r"^<Element 't\xe4g' at 0x.*>$") element = ET.Element("tag", key="value") # Make sure all standard element methods exist. def check_method(method): self.assertPrawda(hasattr(method, '__call__'), msg="%s nie callable" % method) check_method(element.append) check_method(element.extend) check_method(element.insert) check_method(element.remove) check_method(element.getchildren) check_method(element.find) check_method(element.iterfind) check_method(element.findall) check_method(element.findtext) check_method(element.clear) check_method(element.get) check_method(element.set) check_method(element.keys) check_method(element.items) check_method(element.iter) check_method(element.itertext) check_method(element.getiterator) # These methods zwróć an iterable. See bug 6472. def check_iter(it): check_method(it.__next__) check_iter(element.iterfind("tag")) check_iter(element.iterfind("*")) check_iter(tree.iterfind("tag")) check_iter(tree.iterfind("*")) # These aliases are provided: self.assertEqual(ET.XML, ET.fromstring) self.assertEqual(ET.PI, ET.ProcessingInstruction) def test_simpleops(self): # Basic method sanity checks. elem = ET.XML("<body><tag/></body>") self.serialize_check(elem, '<body><tag /></body>') e = ET.Element("tag2") elem.append(e) self.serialize_check(elem, '<body><tag /><tag2 /></body>') elem.remove(e) self.serialize_check(elem, '<body><tag /></body>') elem.insert(0, e) self.serialize_check(elem, '<body><tag2 /><tag /></body>') elem.remove(e) elem.extend([e]) self.serialize_check(elem, '<body><tag /><tag2 /></body>') elem.remove(e) element = ET.Element("tag", key="value") self.serialize_check(element, '<tag key="value" />') # 1 subelement = ET.Element("subtag") element.append(subelement) self.serialize_check(element, '<tag key="value"><subtag /></tag>') # 2 element.insert(0, subelement) self.serialize_check(element, '<tag key="value"><subtag /><subtag /></tag>') # 3 element.remove(subelement) self.serialize_check(element, '<tag key="value"><subtag /></tag>') # 4 element.remove(subelement) self.serialize_check(element, '<tag key="value" />') # 5 przy self.assertRaises(ValueError) jako cm: element.remove(subelement) self.assertEqual(str(cm.exception), 'list.remove(x): x nie w list') self.serialize_check(element, '<tag key="value" />') # 6 element[0:0] = [subelement, subelement, subelement] self.serialize_check(element[1], '<subtag />') self.assertEqual(element[1:9], [element[1], element[2]]) self.assertEqual(element[:9:2], [element[0], element[2]]) usuń element[1:2] self.serialize_check(element, '<tag key="value"><subtag /><subtag /></tag>') def test_cdata(self): # Test CDATA handling (etc). self.serialize_check(ET.XML("<tag>hello</tag>"), '<tag>hello</tag>') self.serialize_check(ET.XML("<tag>&#104;&#101;&#108;&#108;&#111;</tag>"), '<tag>hello</tag>') self.serialize_check(ET.XML("<tag><![CDATA[hello]]></tag>"), '<tag>hello</tag>') def test_file_init(self): stringfile = io.BytesIO(SAMPLE_XML.encode("utf-8")) tree = ET.ElementTree(file=stringfile) self.assertEqual(tree.find("tag").tag, 'tag') self.assertEqual(tree.find("section/tag").tag, 'tag') tree = ET.ElementTree(file=SIMPLE_XMLFILE) self.assertEqual(tree.find("element").tag, 'element') self.assertEqual(tree.find("element/../empty-element").tag, 'empty-element') def test_path_cache(self): # Check that the path cache behaves sanely. z xml.etree zaimportuj ElementPath elem = ET.XML(SAMPLE_XML) dla i w range(10): ET.ElementTree(elem).find('./'+str(i)) cache_len_10 = len(ElementPath._cache) dla i w range(10): ET.ElementTree(elem).find('./'+str(i)) self.assertEqual(len(ElementPath._cache), cache_len_10) dla i w range(20): ET.ElementTree(elem).find('./'+str(i)) self.assertGreater(len(ElementPath._cache), cache_len_10) dla i w range(600): ET.ElementTree(elem).find('./'+str(i)) self.assertLess(len(ElementPath._cache), 500) def test_copy(self): # Test copy handling (etc). zaimportuj copy e1 = ET.XML("<tag>hello<foo/></tag>") e2 = copy.copy(e1) e3 = copy.deepcopy(e1) e1.find("foo").tag = "bar" self.serialize_check(e1, '<tag>hello<bar /></tag>') self.serialize_check(e2, '<tag>hello<bar /></tag>') self.serialize_check(e3, '<tag>hello<foo /></tag>') def test_attrib(self): # Test attribute handling. elem = ET.Element("tag") elem.get("key") # 1.1 self.assertEqual(elem.get("key", "default"), 'default') # 1.2 elem.set("key", "value") self.assertEqual(elem.get("key"), 'value') # 1.3 elem = ET.Element("tag", key="value") self.assertEqual(elem.get("key"), 'value') # 2.1 self.assertEqual(elem.attrib, {'key': 'value'}) # 2.2 attrib = {"key": "value"} elem = ET.Element("tag", attrib) attrib.clear() # check dla aliasing issues self.assertEqual(elem.get("key"), 'value') # 3.1 self.assertEqual(elem.attrib, {'key': 'value'}) # 3.2 attrib = {"key": "value"} elem = ET.Element("tag", **attrib) attrib.clear() # check dla aliasing issues self.assertEqual(elem.get("key"), 'value') # 4.1 self.assertEqual(elem.attrib, {'key': 'value'}) # 4.2 elem = ET.Element("tag", {"key": "other"}, key="value") self.assertEqual(elem.get("key"), 'value') # 5.1 self.assertEqual(elem.attrib, {'key': 'value'}) # 5.2 elem = ET.Element('test') elem.text = "aa" elem.set('testa', 'testval') elem.set('testb', 'test2') self.assertEqual(ET.tostring(elem), b'<test testa="testval" testb="test2">aa</test>') self.assertEqual(sorted(elem.keys()), ['testa', 'testb']) self.assertEqual(sorted(elem.items()), [('testa', 'testval'), ('testb', 'test2')]) self.assertEqual(elem.attrib['testb'], 'test2') elem.attrib['testb'] = 'test1' elem.attrib['testc'] = 'test2' self.assertEqual(ET.tostring(elem), b'<test testa="testval" testb="test1" testc="test2">aa</test>') def test_makeelement(self): # Test makeelement handling. elem = ET.Element("tag") attrib = {"key": "value"} subelem = elem.makeelement("subtag", attrib) self.assertIsNot(subelem.attrib, attrib, msg="attrib aliasing") elem.append(subelem) self.serialize_check(elem, '<tag><subtag key="value" /></tag>') elem.clear() self.serialize_check(elem, '<tag />') elem.append(subelem) self.serialize_check(elem, '<tag><subtag key="value" /></tag>') elem.extend([subelem, subelem]) self.serialize_check(elem, '<tag><subtag key="value" /><subtag key="value" /><subtag key="value" /></tag>') elem[:] = [subelem] self.serialize_check(elem, '<tag><subtag key="value" /></tag>') elem[:] = tuple([subelem]) self.serialize_check(elem, '<tag><subtag key="value" /></tag>') def test_parsefile(self): # Test parsing z file. tree = ET.parse(SIMPLE_XMLFILE) stream = io.StringIO() tree.write(stream, encoding='unicode') self.assertEqual(stream.getvalue(), '<root>\n' ' <element key="value">text</element>\n' ' <element>text</element>tail\n' ' <empty-element />\n' '</root>') tree = ET.parse(SIMPLE_NS_XMLFILE) stream = io.StringIO() tree.write(stream, encoding='unicode') self.assertEqual(stream.getvalue(), '<ns0:root xmlns:ns0="namespace">\n' ' <ns0:element key="value">text</ns0:element>\n' ' <ns0:element>text</ns0:element>tail\n' ' <ns0:empty-element />\n' '</ns0:root>') przy open(SIMPLE_XMLFILE) jako f: data = f.read() parser = ET.XMLParser() self.assertRegex(parser.version, r'^Expat ') parser.feed(data) self.serialize_check(parser.close(), '<root>\n' ' <element key="value">text</element>\n' ' <element>text</element>tail\n' ' <empty-element />\n' '</root>') target = ET.TreeBuilder() parser = ET.XMLParser(target=target) parser.feed(data) self.serialize_check(parser.close(), '<root>\n' ' <element key="value">text</element>\n' ' <element>text</element>tail\n' ' <empty-element />\n' '</root>') def test_parseliteral(self): element = ET.XML("<html><body>text</body></html>") self.assertEqual(ET.tostring(element, encoding='unicode'), '<html><body>text</body></html>') element = ET.fromstring("<html><body>text</body></html>") self.assertEqual(ET.tostring(element, encoding='unicode'), '<html><body>text</body></html>') sequence = ["<html><body>", "text</bo", "dy></html>"] element = ET.fromstringlist(sequence) self.assertEqual(ET.tostring(element), b'<html><body>text</body></html>') self.assertEqual(b"".join(ET.tostringlist(element)), b'<html><body>text</body></html>') self.assertEqual(ET.tostring(element, "ascii"), b"<?xml version='1.0' encoding='ascii'?>\n" b"<html><body>text</body></html>") _, ids = ET.XMLID("<html><body>text</body></html>") self.assertEqual(len(ids), 0) _, ids = ET.XMLID("<html><body id='body'>text</body></html>") self.assertEqual(len(ids), 1) self.assertEqual(ids["body"].tag, 'body') def test_iterparse(self): # Test iterparse interface. iterparse = ET.iterparse context = iterparse(SIMPLE_XMLFILE) action, elem = next(context) self.assertEqual((action, elem.tag), ('end', 'element')) self.assertEqual([(action, elem.tag) dla action, elem w context], [ ('end', 'element'), ('end', 'empty-element'), ('end', 'root'), ]) self.assertEqual(context.root.tag, 'root') context = iterparse(SIMPLE_NS_XMLFILE) self.assertEqual([(action, elem.tag) dla action, elem w context], [ ('end', '{namespace}element'), ('end', '{namespace}element'), ('end', '{namespace}empty-element'), ('end', '{namespace}root'), ]) events = () context = iterparse(SIMPLE_XMLFILE, events) self.assertEqual([(action, elem.tag) dla action, elem w context], []) events = () context = iterparse(SIMPLE_XMLFILE, events=events) self.assertEqual([(action, elem.tag) dla action, elem w context], []) events = ("start", "end") context = iterparse(SIMPLE_XMLFILE, events) self.assertEqual([(action, elem.tag) dla action, elem w context], [ ('start', 'root'), ('start', 'element'), ('end', 'element'), ('start', 'element'), ('end', 'element'), ('start', 'empty-element'), ('end', 'empty-element'), ('end', 'root'), ]) events = ("start", "end", "start-ns", "end-ns") context = iterparse(SIMPLE_NS_XMLFILE, events) self.assertEqual([(action, elem.tag) jeżeli action w ("start", "end") inaczej (action, elem) dla action, elem w context], [ ('start-ns', ('', 'namespace')), ('start', '{namespace}root'), ('start', '{namespace}element'), ('end', '{namespace}element'), ('start', '{namespace}element'), ('end', '{namespace}element'), ('start', '{namespace}empty-element'), ('end', '{namespace}empty-element'), ('end', '{namespace}root'), ('end-ns', Nic), ]) events = ('start-ns', 'end-ns') context = iterparse(io.StringIO(r"<root xmlns=''/>"), events) res = [action dla action, elem w context] self.assertEqual(res, ['start-ns', 'end-ns']) events = ("start", "end", "bogus") przy self.assertRaises(ValueError) jako cm: przy open(SIMPLE_XMLFILE, "rb") jako f: iterparse(f, events) self.assertEqual(str(cm.exception), "unknown event 'bogus'") source = io.BytesIO( b"<?xml version='1.0' encoding='iso-8859-1'?>\n" b"<body xmlns='http://&#233;ffbot.org/ns'\n" b" xmlns:cl\xe9='http://effbot.org/ns'>text</body>\n") events = ("start-ns",) context = iterparse(source, events) self.assertEqual([(action, elem) dla action, elem w context], [ ('start-ns', ('', 'http://\xe9ffbot.org/ns')), ('start-ns', ('cl\xe9', 'http://effbot.org/ns')), ]) source = io.StringIO("<document />junk") it = iterparse(source) action, elem = next(it) self.assertEqual((action, elem.tag), ('end', 'document')) przy self.assertRaises(ET.ParseError) jako cm: next(it) self.assertEqual(str(cm.exception), 'junk after document element: line 1, column 12') def test_writefile(self): elem = ET.Element("tag") elem.text = "text" self.serialize_check(elem, '<tag>text</tag>') ET.SubElement(elem, "subtag").text = "subtext" self.serialize_check(elem, '<tag>text<subtag>subtext</subtag></tag>') # Test tag suppression elem.tag = Nic self.serialize_check(elem, 'text<subtag>subtext</subtag>') elem.insert(0, ET.Comment("comment")) self.serialize_check(elem, 'text<!--comment--><subtag>subtext</subtag>') # assumes 1.3 elem[0] = ET.PI("key", "value") self.serialize_check(elem, 'text<?key value?><subtag>subtext</subtag>') def test_custom_builder(self): # Test parser w. custom builder. przy open(SIMPLE_XMLFILE) jako f: data = f.read() klasa Builder(list): def start(self, tag, attrib): self.append(("start", tag)) def end(self, tag): self.append(("end", tag)) def data(self, text): dalej builder = Builder() parser = ET.XMLParser(target=builder) parser.feed(data) self.assertEqual(builder, [ ('start', 'root'), ('start', 'element'), ('end', 'element'), ('start', 'element'), ('end', 'element'), ('start', 'empty-element'), ('end', 'empty-element'), ('end', 'root'), ]) przy open(SIMPLE_NS_XMLFILE) jako f: data = f.read() klasa Builder(list): def start(self, tag, attrib): self.append(("start", tag)) def end(self, tag): self.append(("end", tag)) def data(self, text): dalej def pi(self, target, data): self.append(("pi", target, data)) def comment(self, data): self.append(("comment", data)) builder = Builder() parser = ET.XMLParser(target=builder) parser.feed(data) self.assertEqual(builder, [ ('pi', 'pi', 'data'), ('comment', ' comment '), ('start', '{namespace}root'), ('start', '{namespace}element'), ('end', '{namespace}element'), ('start', '{namespace}element'), ('end', '{namespace}element'), ('start', '{namespace}empty-element'), ('end', '{namespace}empty-element'), ('end', '{namespace}root'), ]) def test_getchildren(self): # Test Element.getchildren() przy open(SIMPLE_XMLFILE, "rb") jako f: tree = ET.parse(f) self.assertEqual([summarize_list(elem.getchildren()) dla elem w tree.getroot().iter()], [ ['element', 'element', 'empty-element'], [], [], [], ]) self.assertEqual([summarize_list(elem.getchildren()) dla elem w tree.getiterator()], [ ['element', 'element', 'empty-element'], [], [], [], ]) elem = ET.XML(SAMPLE_XML) self.assertEqual(len(elem.getchildren()), 3) self.assertEqual(len(elem[2].getchildren()), 1) self.assertEqual(elem[:], elem.getchildren()) child1 = elem[0] child2 = elem[2] usuń elem[1:2] self.assertEqual(len(elem.getchildren()), 2) self.assertEqual(child1, elem[0]) self.assertEqual(child2, elem[1]) elem[0:2] = [child2, child1] self.assertEqual(child2, elem[0]) self.assertEqual(child1, elem[1]) self.assertNotEqual(child1, elem[0]) elem.clear() self.assertEqual(elem.getchildren(), []) def test_writestring(self): elem = ET.XML("<html><body>text</body></html>") self.assertEqual(ET.tostring(elem), b'<html><body>text</body></html>') elem = ET.fromstring("<html><body>text</body></html>") self.assertEqual(ET.tostring(elem), b'<html><body>text</body></html>') def test_encoding(self): def check(encoding, body=''): xml = ("<?xml version='1.0' encoding='%s'?><xml>%s</xml>" % (encoding, body)) self.assertEqual(ET.XML(xml.encode(encoding)).text, body) self.assertEqual(ET.XML(xml).text, body) check("ascii", 'a') check("us-ascii", 'a') check("iso-8859-1", '\xbd') check("iso-8859-15", '\u20ac') check("cp437", '\u221a') check("mac-roman", '\u02da') def xml(encoding): zwróć "<?xml version='1.0' encoding='%s'?><xml />" % encoding def bxml(encoding): zwróć xml(encoding).encode(encoding) supported_encodings = [ 'ascii', 'utf-8', 'utf-8-sig', 'utf-16', 'utf-16be', 'utf-16le', 'iso8859-1', 'iso8859-2', 'iso8859-3', 'iso8859-4', 'iso8859-5', 'iso8859-6', 'iso8859-7', 'iso8859-8', 'iso8859-9', 'iso8859-10', 'iso8859-13', 'iso8859-14', 'iso8859-15', 'iso8859-16', 'cp437', 'cp720', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857', 'cp858', 'cp860', 'cp861', 'cp862', 'cp863', 'cp865', 'cp866', 'cp869', 'cp874', 'cp1006', 'cp1125', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', 'cp1256', 'cp1257', 'cp1258', 'mac-cyrillic', 'mac-greek', 'mac-iceland', 'mac-latin2', 'mac-roman', 'mac-turkish', 'iso2022-jp', 'iso2022-jp-1', 'iso2022-jp-2', 'iso2022-jp-2004', 'iso2022-jp-3', 'iso2022-jp-ext', 'koi8-r', 'koi8-t', 'koi8-u', 'kz1048', 'hz', 'ptcp154', ] dla encoding w supported_encodings: self.assertEqual(ET.tostring(ET.XML(bxml(encoding))), b'<xml />') unsupported_ascii_compatible_encodings = [ 'big5', 'big5hkscs', 'cp932', 'cp949', 'cp950', 'euc-jp', 'euc-jis-2004', 'euc-jisx0213', 'euc-kr', 'gb2312', 'gbk', 'gb18030', 'iso2022-kr', 'johab', 'shift-jis', 'shift-jis-2004', 'shift-jisx0213', 'utf-7', ] dla encoding w unsupported_ascii_compatible_encodings: self.assertRaises(ValueError, ET.XML, bxml(encoding)) unsupported_ascii_incompatible_encodings = [ 'cp037', 'cp424', 'cp500', 'cp864', 'cp875', 'cp1026', 'cp1140', 'utf_32', 'utf_32_be', 'utf_32_le', ] dla encoding w unsupported_ascii_incompatible_encodings: self.assertRaises(ET.ParseError, ET.XML, bxml(encoding)) self.assertRaises(ValueError, ET.XML, xml('undefined').encode('ascii')) self.assertRaises(LookupError, ET.XML, xml('xxx').encode('ascii')) def test_methods(self): # Test serialization methods. e = ET.XML("<html><link/><script>1 &lt; 2</script></html>") e.tail = "\n" self.assertEqual(serialize(e), '<html><link /><script>1 &lt; 2</script></html>\n') self.assertEqual(serialize(e, method=Nic), '<html><link /><script>1 &lt; 2</script></html>\n') self.assertEqual(serialize(e, method="xml"), '<html><link /><script>1 &lt; 2</script></html>\n') self.assertEqual(serialize(e, method="html"), '<html><link><script>1 < 2</script></html>\n') self.assertEqual(serialize(e, method="text"), '1 < 2\n') def test_issue18347(self): e = ET.XML('<html><CamelCase>text</CamelCase></html>') self.assertEqual(serialize(e), '<html><CamelCase>text</CamelCase></html>') self.assertEqual(serialize(e, method="html"), '<html><CamelCase>text</CamelCase></html>') def test_entity(self): # Test entity handling. # 1) good entities e = ET.XML("<document title='&#x8230;'>test</document>") self.assertEqual(serialize(e, encoding="us-ascii"), b'<document title="&#33328;">test</document>') self.serialize_check(e, '<document title="\u8230">test</document>') # 2) bad entities przy self.assertRaises(ET.ParseError) jako cm: ET.XML("<document>&entity;</document>") self.assertEqual(str(cm.exception), 'undefined entity: line 1, column 10') przy self.assertRaises(ET.ParseError) jako cm: ET.XML(ENTITY_XML) self.assertEqual(str(cm.exception), 'undefined entity &entity;: line 5, column 10') # 3) custom entity parser = ET.XMLParser() parser.entity["entity"] = "text" parser.feed(ENTITY_XML) root = parser.close() self.serialize_check(root, '<document>text</document>') def test_namespace(self): # Test namespace issues. # 1) xml namespace elem = ET.XML("<tag xml:lang='en' />") self.serialize_check(elem, '<tag xml:lang="en" />') # 1.1 # 2) other "well-known" namespaces elem = ET.XML("<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' />") self.serialize_check(elem, '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" />') # 2.1 elem = ET.XML("<html:html xmlns:html='http://www.w3.org/1999/xhtml' />") self.serialize_check(elem, '<html:html xmlns:html="http://www.w3.org/1999/xhtml" />') # 2.2 elem = ET.XML("<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope' />") self.serialize_check(elem, '<ns0:Envelope xmlns:ns0="http://schemas.xmlsoap.org/soap/envelope" />') # 2.3 # 3) unknown namespaces elem = ET.XML(SAMPLE_XML_NS) self.serialize_check(elem, '<ns0:body xmlns:ns0="http://effbot.org/ns">\n' ' <ns0:tag>text</ns0:tag>\n' ' <ns0:tag />\n' ' <ns0:section>\n' ' <ns0:tag>subtext</ns0:tag>\n' ' </ns0:section>\n' '</ns0:body>') def test_qname(self): # Test QName handling. # 1) decorated tags elem = ET.Element("{uri}tag") self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" />') # 1.1 elem = ET.Element(ET.QName("{uri}tag")) self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" />') # 1.2 elem = ET.Element(ET.QName("uri", "tag")) self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" />') # 1.3 elem = ET.Element(ET.QName("uri", "tag")) subelem = ET.SubElement(elem, ET.QName("uri", "tag1")) subelem = ET.SubElement(elem, ET.QName("uri", "tag2")) self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri"><ns0:tag1 /><ns0:tag2 /></ns0:tag>') # 1.4 # 2) decorated attributes elem.clear() elem.attrib["{uri}key"] = "value" self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" ns0:key="value" />') # 2.1 elem.clear() elem.attrib[ET.QName("{uri}key")] = "value" self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" ns0:key="value" />') # 2.2 # 3) decorated values are nie converted by default, but the # QName wrapper can be used dla values elem.clear() elem.attrib["{uri}key"] = "{uri}value" self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" ns0:key="{uri}value" />') # 3.1 elem.clear() elem.attrib["{uri}key"] = ET.QName("{uri}value") self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" ns0:key="ns0:value" />') # 3.2 elem.clear() subelem = ET.Element("tag") subelem.attrib["{uri1}key"] = ET.QName("{uri2}value") elem.append(subelem) elem.append(subelem) self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" xmlns:ns1="uri1" xmlns:ns2="uri2">' '<tag ns1:key="ns2:value" />' '<tag ns1:key="ns2:value" />' '</ns0:tag>') # 3.3 # 4) Direct QName tests self.assertEqual(str(ET.QName('ns', 'tag')), '{ns}tag') self.assertEqual(str(ET.QName('{ns}tag')), '{ns}tag') q1 = ET.QName('ns', 'tag') q2 = ET.QName('ns', 'tag') self.assertEqual(q1, q2) q2 = ET.QName('ns', 'other-tag') self.assertNotEqual(q1, q2) self.assertNotEqual(q1, 'ns:tag') self.assertEqual(q1, '{ns}tag') def test_doctype_public(self): # Test PUBLIC doctype. elem = ET.XML('<!DOCTYPE html PUBLIC' ' "-//W3C//DTD XHTML 1.0 Transitional//EN"' ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' '<html>text</html>') def test_xpath_tokenizer(self): # Test the XPath tokenizer. z xml.etree zaimportuj ElementPath def check(p, expected): self.assertEqual([op albo tag dla op, tag w ElementPath.xpath_tokenizer(p)], expected) # tests z the xml specification check("*", ['*']) check("text()", ['text', '()']) check("@name", ['@', 'name']) check("@*", ['@', '*']) check("para[1]", ['para', '[', '1', ']']) check("para[last()]", ['para', '[', 'last', '()', ']']) check("*/para", ['*', '/', 'para']) check("/doc/chapter[5]/section[2]", ['/', 'doc', '/', 'chapter', '[', '5', ']', '/', 'section', '[', '2', ']']) check("chapter//para", ['chapter', '//', 'para']) check("//para", ['//', 'para']) check("//olist/item", ['//', 'olist', '/', 'item']) check(".", ['.']) check(".//para", ['.', '//', 'para']) check("..", ['..']) check("../@lang", ['..', '/', '@', 'lang']) check("chapter[title]", ['chapter', '[', 'title', ']']) check("employee[@secretary oraz @assistant]", ['employee', '[', '@', 'secretary', '', 'and', '', '@', 'assistant', ']']) # additional tests check("{http://spam}egg", ['{http://spam}egg']) check("./spam.egg", ['.', '/', 'spam.egg']) check(".//{http://spam}egg", ['.', '//', '{http://spam}egg']) def test_processinginstruction(self): # Test ProcessingInstruction directly self.assertEqual(ET.tostring(ET.ProcessingInstruction('test', 'instruction')), b'<?test instruction?>') self.assertEqual(ET.tostring(ET.PI('test', 'instruction')), b'<?test instruction?>') # Issue #2746 self.assertEqual(ET.tostring(ET.PI('test', '<testing&>')), b'<?test <testing&>?>') self.assertEqual(ET.tostring(ET.PI('test', '<testing&>\xe3'), 'latin-1'), b"<?xml version='1.0' encoding='latin-1'?>\n" b"<?test <testing&>\xe3?>") def test_html_empty_elems_serialization(self): # issue 15970 # z http://www.w3.org/TR/html401/index/elements.html dla element w ['AREA', 'BASE', 'BASEFONT', 'BR', 'COL', 'FRAME', 'HR', 'IMG', 'INPUT', 'ISINDEX', 'LINK', 'META', 'PARAM']: dla elem w [element, element.lower()]: expected = '<%s>' % elem serialized = serialize(ET.XML('<%s />' % elem), method='html') self.assertEqual(serialized, expected) serialized = serialize(ET.XML('<%s></%s>' % (elem,elem)), method='html') self.assertEqual(serialized, expected) klasa XMLPullParserTest(unittest.TestCase): def _feed(self, parser, data, chunk_size=Nic): jeżeli chunk_size jest Nic: parser.feed(data) inaczej: dla i w range(0, len(data), chunk_size): parser.feed(data[i:i+chunk_size]) def assert_event_tags(self, parser, expected): events = parser.read_events() self.assertEqual([(action, elem.tag) dla action, elem w events], expected) def test_simple_xml(self): dla chunk_size w (Nic, 1, 5): przy self.subTest(chunk_size=chunk_size): parser = ET.XMLPullParser() self.assert_event_tags(parser, []) self._feed(parser, "<!-- comment -->\n", chunk_size) self.assert_event_tags(parser, []) self._feed(parser, "<root>\n <element key='value'>text</element", chunk_size) self.assert_event_tags(parser, []) self._feed(parser, ">\n", chunk_size) self.assert_event_tags(parser, [('end', 'element')]) self._feed(parser, "<element>text</element>tail\n", chunk_size) self._feed(parser, "<empty-element/>\n", chunk_size) self.assert_event_tags(parser, [ ('end', 'element'), ('end', 'empty-element'), ]) self._feed(parser, "</root>\n", chunk_size) self.assert_event_tags(parser, [('end', 'root')]) self.assertIsNic(parser.close()) def test_feed_while_iterating(self): parser = ET.XMLPullParser() it = parser.read_events() self._feed(parser, "<root>\n <element key='value'>text</element>\n") action, elem = next(it) self.assertEqual((action, elem.tag), ('end', 'element')) self._feed(parser, "</root>\n") action, elem = next(it) self.assertEqual((action, elem.tag), ('end', 'root')) przy self.assertRaises(StopIteration): next(it) def test_simple_xml_with_ns(self): parser = ET.XMLPullParser() self.assert_event_tags(parser, []) self._feed(parser, "<!-- comment -->\n") self.assert_event_tags(parser, []) self._feed(parser, "<root xmlns='namespace'>\n") self.assert_event_tags(parser, []) self._feed(parser, "<element key='value'>text</element") self.assert_event_tags(parser, []) self._feed(parser, ">\n") self.assert_event_tags(parser, [('end', '{namespace}element')]) self._feed(parser, "<element>text</element>tail\n") self._feed(parser, "<empty-element/>\n") self.assert_event_tags(parser, [ ('end', '{namespace}element'), ('end', '{namespace}empty-element'), ]) self._feed(parser, "</root>\n") self.assert_event_tags(parser, [('end', '{namespace}root')]) self.assertIsNic(parser.close()) def test_ns_events(self): parser = ET.XMLPullParser(events=('start-ns', 'end-ns')) self._feed(parser, "<!-- comment -->\n") self._feed(parser, "<root xmlns='namespace'>\n") self.assertEqual( list(parser.read_events()), [('start-ns', ('', 'namespace'))]) self._feed(parser, "<element key='value'>text</element") self._feed(parser, ">\n") self._feed(parser, "<element>text</element>tail\n") self._feed(parser, "<empty-element/>\n") self._feed(parser, "</root>\n") self.assertEqual(list(parser.read_events()), [('end-ns', Nic)]) self.assertIsNic(parser.close()) def test_events(self): parser = ET.XMLPullParser(events=()) self._feed(parser, "<root/>\n") self.assert_event_tags(parser, []) parser = ET.XMLPullParser(events=('start', 'end')) self._feed(parser, "<!-- comment -->\n") self.assert_event_tags(parser, []) self._feed(parser, "<root>\n") self.assert_event_tags(parser, [('start', 'root')]) self._feed(parser, "<element key='value'>text</element") self.assert_event_tags(parser, [('start', 'element')]) self._feed(parser, ">\n") self.assert_event_tags(parser, [('end', 'element')]) self._feed(parser, "<element xmlns='foo'>text<empty-element/></element>tail\n") self.assert_event_tags(parser, [ ('start', '{foo}element'), ('start', '{foo}empty-element'), ('end', '{foo}empty-element'), ('end', '{foo}element'), ]) self._feed(parser, "</root>") self.assertIsNic(parser.close()) self.assert_event_tags(parser, [('end', 'root')]) parser = ET.XMLPullParser(events=('start',)) self._feed(parser, "<!-- comment -->\n") self.assert_event_tags(parser, []) self._feed(parser, "<root>\n") self.assert_event_tags(parser, [('start', 'root')]) self._feed(parser, "<element key='value'>text</element") self.assert_event_tags(parser, [('start', 'element')]) self._feed(parser, ">\n") self.assert_event_tags(parser, []) self._feed(parser, "<element xmlns='foo'>text<empty-element/></element>tail\n") self.assert_event_tags(parser, [ ('start', '{foo}element'), ('start', '{foo}empty-element'), ]) self._feed(parser, "</root>") self.assertIsNic(parser.close()) def test_events_sequence(self): # Test that events can be some sequence that's nie just a tuple albo list eventset = {'end', 'start'} parser = ET.XMLPullParser(events=eventset) self._feed(parser, "<foo>bar</foo>") self.assert_event_tags(parser, [('start', 'foo'), ('end', 'foo')]) klasa DummyIter: def __init__(self): self.events = iter(['start', 'end', 'start-ns']) def __iter__(self): zwróć self def __next__(self): zwróć next(self.events) parser = ET.XMLPullParser(events=DummyIter()) self._feed(parser, "<foo>bar</foo>") self.assert_event_tags(parser, [('start', 'foo'), ('end', 'foo')]) def test_unknown_event(self): przy self.assertRaises(ValueError): ET.XMLPullParser(events=('start', 'end', 'bogus')) # # xinclude tests (samples z appendix C of the xinclude specification) XINCLUDE = {} XINCLUDE["C1.xml"] = """\ <?xml version='1.0'?> <document xmlns:xi="http://www.w3.org/2001/XInclude"> <p>120 Mz jest adequate dla an average home user.</p> <xi:include href="disclaimer.xml"/> </document> """ XINCLUDE["disclaimer.xml"] = """\ <?xml version='1.0'?> <disclaimer> <p>The opinions represented herein represent those of the individual oraz should nie be interpreted jako official policy endorsed by this organization.</p> </disclaimer> """ XINCLUDE["C2.xml"] = """\ <?xml version='1.0'?> <document xmlns:xi="http://www.w3.org/2001/XInclude"> <p>This document has been accessed <xi:include href="count.txt" parse="text"/> times.</p> </document> """ XINCLUDE["count.txt"] = "324387" XINCLUDE["C2b.xml"] = """\ <?xml version='1.0'?> <document xmlns:xi="http://www.w3.org/2001/XInclude"> <p>This document has been <em>accessed</em> <xi:include href="count.txt" parse="text"/> times.</p> </document> """ XINCLUDE["C3.xml"] = """\ <?xml version='1.0'?> <document xmlns:xi="http://www.w3.org/2001/XInclude"> <p>The following jest the source of the "data.xml" resource:</p> <example><xi:include href="data.xml" parse="text"/></example> </document> """ XINCLUDE["data.xml"] = """\ <?xml version='1.0'?> <data> <item><![CDATA[Brooks & Shields]]></item> </data> """ XINCLUDE["C5.xml"] = """\ <?xml version='1.0'?> <div xmlns:xi="http://www.w3.org/2001/XInclude"> <xi:include href="example.txt" parse="text"> <xi:fallback> <xi:include href="fallback-example.txt" parse="text"> <xi:fallback><a href="mailto:bob@example.org">Report error</a></xi:fallback> </xi:include> </xi:fallback> </xi:include> </div> """ XINCLUDE["default.xml"] = """\ <?xml version='1.0'?> <document xmlns:xi="http://www.w3.org/2001/XInclude"> <p>Example.</p> <xi:include href="{}"/> </document> """.format(html.escape(SIMPLE_XMLFILE, Prawda)) # # badly formatted xi:include tags XINCLUDE_BAD = {} XINCLUDE_BAD["B1.xml"] = """\ <?xml version='1.0'?> <document xmlns:xi="http://www.w3.org/2001/XInclude"> <p>120 Mz jest adequate dla an average home user.</p> <xi:include href="disclaimer.xml" parse="BAD_TYPE"/> </document> """ XINCLUDE_BAD["B2.xml"] = """\ <?xml version='1.0'?> <div xmlns:xi="http://www.w3.org/2001/XInclude"> <xi:fallback></xi:fallback> </div> """ klasa XIncludeTest(unittest.TestCase): def xinclude_loader(self, href, parse="xml", encoding=Nic): spróbuj: data = XINCLUDE[href] wyjąwszy KeyError: podnieś OSError("resource nie found") jeżeli parse == "xml": data = ET.XML(data) zwróć data def none_loader(self, href, parser, encoding=Nic): zwróć Nic def _my_loader(self, href, parse): # Used to avoid a test-dependency problem where the default loader # of ElementInclude uses the pyET parser dla cET tests. jeżeli parse == 'xml': przy open(href, 'rb') jako f: zwróć ET.parse(f).getroot() inaczej: zwróć Nic def test_xinclude_default(self): z xml.etree zaimportuj ElementInclude doc = self.xinclude_loader('default.xml') ElementInclude.include(doc, self._my_loader) self.assertEqual(serialize(doc), '<document>\n' ' <p>Example.</p>\n' ' <root>\n' ' <element key="value">text</element>\n' ' <element>text</element>tail\n' ' <empty-element />\n' '</root>\n' '</document>') def test_xinclude(self): z xml.etree zaimportuj ElementInclude # Basic inclusion example (XInclude C.1) document = self.xinclude_loader("C1.xml") ElementInclude.include(document, self.xinclude_loader) self.assertEqual(serialize(document), '<document>\n' ' <p>120 Mz jest adequate dla an average home user.</p>\n' ' <disclaimer>\n' ' <p>The opinions represented herein represent those of the individual\n' ' oraz should nie be interpreted jako official policy endorsed by this\n' ' organization.</p>\n' '</disclaimer>\n' '</document>') # C1 # Textual inclusion example (XInclude C.2) document = self.xinclude_loader("C2.xml") ElementInclude.include(document, self.xinclude_loader) self.assertEqual(serialize(document), '<document>\n' ' <p>This document has been accessed\n' ' 324387 times.</p>\n' '</document>') # C2 # Textual inclusion after sibling element (based on modified XInclude C.2) document = self.xinclude_loader("C2b.xml") ElementInclude.include(document, self.xinclude_loader) self.assertEqual(serialize(document), '<document>\n' ' <p>This document has been <em>accessed</em>\n' ' 324387 times.</p>\n' '</document>') # C2b # Textual inclusion of XML example (XInclude C.3) document = self.xinclude_loader("C3.xml") ElementInclude.include(document, self.xinclude_loader) self.assertEqual(serialize(document), '<document>\n' ' <p>The following jest the source of the "data.xml" resource:</p>\n' " <example>&lt;?xml version='1.0'?&gt;\n" '&lt;data&gt;\n' ' &lt;item&gt;&lt;![CDATA[Brooks &amp; Shields]]&gt;&lt;/item&gt;\n' '&lt;/data&gt;\n' '</example>\n' '</document>') # C3 # Fallback example (XInclude C.5) # Note! Fallback support jest nie yet implemented document = self.xinclude_loader("C5.xml") przy self.assertRaises(OSError) jako cm: ElementInclude.include(document, self.xinclude_loader) self.assertEqual(str(cm.exception), 'resource nie found') self.assertEqual(serialize(document), '<div xmlns:ns0="http://www.w3.org/2001/XInclude">\n' ' <ns0:include href="example.txt" parse="text">\n' ' <ns0:fallback>\n' ' <ns0:include href="fallback-example.txt" parse="text">\n' ' <ns0:fallback><a href="mailto:bob@example.org">Report error</a></ns0:fallback>\n' ' </ns0:include>\n' ' </ns0:fallback>\n' ' </ns0:include>\n' '</div>') # C5 def test_xinclude_failures(self): z xml.etree zaimportuj ElementInclude # Test failure to locate included XML file. document = ET.XML(XINCLUDE["C1.xml"]) przy self.assertRaises(ElementInclude.FatalIncludeError) jako cm: ElementInclude.include(document, loader=self.none_loader) self.assertEqual(str(cm.exception), "cannot load 'disclaimer.xml' jako 'xml'") # Test failure to locate included text file. document = ET.XML(XINCLUDE["C2.xml"]) przy self.assertRaises(ElementInclude.FatalIncludeError) jako cm: ElementInclude.include(document, loader=self.none_loader) self.assertEqual(str(cm.exception), "cannot load 'count.txt' jako 'text'") # Test bad parse type. document = ET.XML(XINCLUDE_BAD["B1.xml"]) przy self.assertRaises(ElementInclude.FatalIncludeError) jako cm: ElementInclude.include(document, loader=self.none_loader) self.assertEqual(str(cm.exception), "unknown parse type w xi:include tag ('BAD_TYPE')") # Test xi:fallback outside xi:include. document = ET.XML(XINCLUDE_BAD["B2.xml"]) przy self.assertRaises(ElementInclude.FatalIncludeError) jako cm: ElementInclude.include(document, loader=self.none_loader) self.assertEqual(str(cm.exception), "xi:fallback tag must be child of xi:include " "('{http://www.w3.org/2001/XInclude}fallback')") # -------------------------------------------------------------------- # reported bugs klasa BugsTest(unittest.TestCase): def test_bug_xmltoolkit21(self): # marshaller gives obscure errors dla non-string values def check(elem): przy self.assertRaises(TypeError) jako cm: serialize(elem) self.assertEqual(str(cm.exception), 'cannot serialize 123 (type int)') elem = ET.Element(123) check(elem) # tag elem = ET.Element("elem") elem.text = 123 check(elem) # text elem = ET.Element("elem") elem.tail = 123 check(elem) # tail elem = ET.Element("elem") elem.set(123, "123") check(elem) # attribute key elem = ET.Element("elem") elem.set("123", 123) check(elem) # attribute value def test_bug_xmltoolkit25(self): # typo w ElementTree.findtext elem = ET.XML(SAMPLE_XML) tree = ET.ElementTree(elem) self.assertEqual(tree.findtext("tag"), 'text') self.assertEqual(tree.findtext("section/tag"), 'subtext') def test_bug_xmltoolkit28(self): # .//tag causes exceptions tree = ET.XML("<doc><table><tbody/></table></doc>") self.assertEqual(summarize_list(tree.findall(".//thead")), []) self.assertEqual(summarize_list(tree.findall(".//tbody")), ['tbody']) def test_bug_xmltoolkitX1(self): # dump() doesn't flush the output buffer tree = ET.XML("<doc><table><tbody/></table></doc>") przy support.captured_stdout() jako stdout: ET.dump(tree) self.assertEqual(stdout.getvalue(), '<doc><table><tbody /></table></doc>\n') def test_bug_xmltoolkit39(self): # non-ascii element oraz attribute names doesn't work tree = ET.XML(b"<?xml version='1.0' encoding='iso-8859-1'?><t\xe4g />") self.assertEqual(ET.tostring(tree, "utf-8"), b'<t\xc3\xa4g />') tree = ET.XML(b"<?xml version='1.0' encoding='iso-8859-1'?>" b"<tag \xe4ttr='v&#228;lue' />") self.assertEqual(tree.attrib, {'\xe4ttr': 'v\xe4lue'}) self.assertEqual(ET.tostring(tree, "utf-8"), b'<tag \xc3\xa4ttr="v\xc3\xa4lue" />') tree = ET.XML(b"<?xml version='1.0' encoding='iso-8859-1'?>" b'<t\xe4g>text</t\xe4g>') self.assertEqual(ET.tostring(tree, "utf-8"), b'<t\xc3\xa4g>text</t\xc3\xa4g>') tree = ET.Element("t\u00e4g") self.assertEqual(ET.tostring(tree, "utf-8"), b'<t\xc3\xa4g />') tree = ET.Element("tag") tree.set("\u00e4ttr", "v\u00e4lue") self.assertEqual(ET.tostring(tree, "utf-8"), b'<tag \xc3\xa4ttr="v\xc3\xa4lue" />') def test_bug_xmltoolkit54(self): # problems handling internally defined entities e = ET.XML("<!DOCTYPE doc [<!ENTITY ldots '&#x8230;'>]>" '<doc>&ldots;</doc>') self.assertEqual(serialize(e, encoding="us-ascii"), b'<doc>&#33328;</doc>') self.assertEqual(serialize(e), '<doc>\u8230</doc>') def test_bug_xmltoolkit55(self): # make sure we're reporting the first error, nie the last przy self.assertRaises(ET.ParseError) jako cm: ET.XML(b"<!DOCTYPE doc SYSTEM 'doc.dtd'>" b'<doc>&ldots;&ndots;&rdots;</doc>') self.assertEqual(str(cm.exception), 'undefined entity &ldots;: line 1, column 36') def test_bug_xmltoolkit60(self): # Handle crash w stream source. klasa ExceptionFile: def read(self, x): podnieś OSError self.assertRaises(OSError, ET.parse, ExceptionFile()) def test_bug_xmltoolkit62(self): # Don't crash when using custom entities. ENTITIES = {'rsquo': '\u2019', 'lsquo': '\u2018'} parser = ET.XMLParser() parser.entity.update(ENTITIES) parser.feed("""<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE patent-application-publication SYSTEM "pap-v15-2001-01-31.dtd" []> <patent-application-publication> <subdoc-abstract> <paragraph id="A-0001" lvl="0">A new cultivar of Begonia plant named &lsquo;BCT9801BEG&rsquo;.</paragraph> </subdoc-abstract> </patent-application-publication>""") t = parser.close() self.assertEqual(t.find('.//paragraph').text, 'A new cultivar of Begonia plant named \u2018BCT9801BEG\u2019.') def test_bug_xmltoolkit63(self): # Check reference leak. def xmltoolkit63(): tree = ET.TreeBuilder() tree.start("tag", {}) tree.data("text") tree.end("tag") xmltoolkit63() count = sys.getrefcount(Nic) dla i w range(1000): xmltoolkit63() self.assertEqual(sys.getrefcount(Nic), count) def test_bug_200708_newline(self): # Preserve newlines w attributes. e = ET.Element('SomeTag', text="def _f():\n zwróć 3\n") self.assertEqual(ET.tostring(e), b'<SomeTag text="def _f():&#10; zwróć 3&#10;" />') self.assertEqual(ET.XML(ET.tostring(e)).get("text"), 'def _f():\n zwróć 3\n') self.assertEqual(ET.tostring(ET.XML(ET.tostring(e))), b'<SomeTag text="def _f():&#10; zwróć 3&#10;" />') def test_bug_200708_close(self): # Test default builder. parser = ET.XMLParser() # default parser.feed("<element>some text</element>") self.assertEqual(parser.close().tag, 'element') # Test custom builder. klasa EchoTarget: def close(self): zwróć ET.Element("element") # simulate root parser = ET.XMLParser(EchoTarget()) parser.feed("<element>some text</element>") self.assertEqual(parser.close().tag, 'element') def test_bug_200709_default_namespace(self): e = ET.Element("{default}elem") s = ET.SubElement(e, "{default}elem") self.assertEqual(serialize(e, default_namespace="default"), # 1 '<elem xmlns="default"><elem /></elem>') e = ET.Element("{default}elem") s = ET.SubElement(e, "{default}elem") s = ET.SubElement(e, "{not-default}elem") self.assertEqual(serialize(e, default_namespace="default"), # 2 '<elem xmlns="default" xmlns:ns1="not-default">' '<elem />' '<ns1:elem />' '</elem>') e = ET.Element("{default}elem") s = ET.SubElement(e, "{default}elem") s = ET.SubElement(e, "elem") # unprefixed name przy self.assertRaises(ValueError) jako cm: serialize(e, default_namespace="default") # 3 self.assertEqual(str(cm.exception), 'cannot use non-qualified names przy default_namespace option') def test_bug_200709_register_namespace(self): e = ET.Element("{http://namespace.invalid/does/not/exist/}title") self.assertEqual(ET.tostring(e), b'<ns0:title xmlns:ns0="http://namespace.invalid/does/not/exist/" />') ET.register_namespace("foo", "http://namespace.invalid/does/not/exist/") e = ET.Element("{http://namespace.invalid/does/not/exist/}title") self.assertEqual(ET.tostring(e), b'<foo:title xmlns:foo="http://namespace.invalid/does/not/exist/" />') # And the Dublin Core namespace jest w the default list: e = ET.Element("{http://purl.org/dc/elements/1.1/}title") self.assertEqual(ET.tostring(e), b'<dc:title xmlns:dc="http://purl.org/dc/elements/1.1/" />') def test_bug_200709_element_comment(self): # Not sure jeżeli this can be fixed, really (since the serializer needs # ET.Comment, nie cET.comment). a = ET.Element('a') a.append(ET.Comment('foo')) self.assertEqual(a[0].tag, ET.Comment) a = ET.Element('a') a.append(ET.PI('foo')) self.assertEqual(a[0].tag, ET.PI) def test_bug_200709_element_insert(self): a = ET.Element('a') b = ET.SubElement(a, 'b') c = ET.SubElement(a, 'c') d = ET.Element('d') a.insert(0, d) self.assertEqual(summarize_list(a), ['d', 'b', 'c']) a.insert(-1, d) self.assertEqual(summarize_list(a), ['d', 'b', 'd', 'c']) def test_bug_200709_iter_comment(self): a = ET.Element('a') b = ET.SubElement(a, 'b') comment_b = ET.Comment("TEST-b") b.append(comment_b) self.assertEqual(summarize_list(a.iter(ET.Comment)), [ET.Comment]) # -------------------------------------------------------------------- # reported on bugs.python.org def test_bug_1534630(self): bob = ET.TreeBuilder() e = bob.data("data") e = bob.start("tag", {}) e = bob.end("tag") e = bob.close() self.assertEqual(serialize(e), '<tag />') def test_issue6233(self): e = ET.XML(b"<?xml version='1.0' encoding='utf-8'?>" b'<body>t\xc3\xa3g</body>') self.assertEqual(ET.tostring(e, 'ascii'), b"<?xml version='1.0' encoding='ascii'?>\n" b'<body>t&#227;g</body>') e = ET.XML(b"<?xml version='1.0' encoding='iso-8859-1'?>" b'<body>t\xe3g</body>') self.assertEqual(ET.tostring(e, 'ascii'), b"<?xml version='1.0' encoding='ascii'?>\n" b'<body>t&#227;g</body>') def test_issue3151(self): e = ET.XML('<prefix:localname xmlns:prefix="${stuff}"/>') self.assertEqual(e.tag, '{${stuff}}localname') t = ET.ElementTree(e) self.assertEqual(ET.tostring(e), b'<ns0:localname xmlns:ns0="${stuff}" />') def test_issue6565(self): elem = ET.XML("<body><tag/></body>") self.assertEqual(summarize_list(elem), ['tag']) newelem = ET.XML(SAMPLE_XML) elem[:] = newelem[:] self.assertEqual(summarize_list(elem), ['tag', 'tag', 'section']) def test_issue10777(self): # Registering a namespace twice caused a "dictionary changed size during # iteration" bug. ET.register_namespace('test10777', 'http://myuri/') ET.register_namespace('test10777', 'http://myuri/') # -------------------------------------------------------------------- klasa BasicElementTest(ElementTestCase, unittest.TestCase): def test_augmentation_type_errors(self): e = ET.Element('joe') self.assertRaises(TypeError, e.append, 'b') self.assertRaises(TypeError, e.extend, [ET.Element('bar'), 'foo']) self.assertRaises(TypeError, e.insert, 0, 'foo') def test_cyclic_gc(self): klasa Dummy: dalej # Test the shortest cycle: d->element->d d = Dummy() d.dummyref = ET.Element('joe', attr=d) wref = weakref.ref(d) usuń d gc_collect() self.assertIsNic(wref()) # A longer cycle: d->e->e2->d e = ET.Element('joe') d = Dummy() d.dummyref = e wref = weakref.ref(d) e2 = ET.SubElement(e, 'foo', attr=d) usuń d, e, e2 gc_collect() self.assertIsNic(wref()) # A cycle between Element objects jako children of one another # e1->e2->e3->e1 e1 = ET.Element('e1') e2 = ET.Element('e2') e3 = ET.Element('e3') e1.append(e2) e2.append(e2) e3.append(e1) wref = weakref.ref(e1) usuń e1, e2, e3 gc_collect() self.assertIsNic(wref()) def test_weakref(self): flag = Nieprawda def wref_cb(w): nonlocal flag flag = Prawda e = ET.Element('e') wref = weakref.ref(e, wref_cb) self.assertEqual(wref().tag, 'e') usuń e self.assertEqual(flag, Prawda) self.assertEqual(wref(), Nic) def test_get_keyword_args(self): e1 = ET.Element('foo' , x=1, y=2, z=3) self.assertEqual(e1.get('x', default=7), 1) self.assertEqual(e1.get('w', default=7), 7) def test_pickle(self): # issue #16076: the C implementation wasn't pickleable. dla proto w range(2, pickle.HIGHEST_PROTOCOL + 1): dla dumper, loader w product(self.modules, repeat=2): e = dumper.Element('foo', bar=42) e.text = "text goes here" e.tail = "opposite of head" dumper.SubElement(e, 'child').append(dumper.Element('grandchild')) e.append(dumper.Element('child')) e.findall('.//grandchild')[0].set('attr', 'other value') e2 = self.pickleRoundTrip(e, 'xml.etree.ElementTree', dumper, loader, proto) self.assertEqual(e2.tag, 'foo') self.assertEqual(e2.attrib['bar'], 42) self.assertEqual(len(e2), 2) self.assertEqualElements(e, e2) def test_pickle_issue18997(self): dla proto w range(2, pickle.HIGHEST_PROTOCOL + 1): dla dumper, loader w product(self.modules, repeat=2): XMLTEXT = """<?xml version="1.0"?> <group><dogs>4</dogs> </group>""" e1 = dumper.fromstring(XMLTEXT) jeżeli hasattr(e1, '__getstate__'): self.assertEqual(e1.__getstate__()['tag'], 'group') e2 = self.pickleRoundTrip(e1, 'xml.etree.ElementTree', dumper, loader, proto) self.assertEqual(e2.tag, 'group') self.assertEqual(e2[0].tag, 'dogs') klasa BadElementTest(ElementTestCase, unittest.TestCase): def test_extend_mutable_list(self): klasa X: @property def __class__(self): L[:] = [ET.Element('baz')] zwróć ET.Element L = [X()] e = ET.Element('foo') spróbuj: e.extend(L) wyjąwszy TypeError: dalej klasa Y(X, ET.Element): dalej L = [Y('x')] e = ET.Element('foo') e.extend(L) def test_extend_mutable_list2(self): klasa X: @property def __class__(self): usuń L[:] zwróć ET.Element L = [X(), ET.Element('baz')] e = ET.Element('foo') spróbuj: e.extend(L) wyjąwszy TypeError: dalej klasa Y(X, ET.Element): dalej L = [Y('bar'), ET.Element('baz')] e = ET.Element('foo') e.extend(L) def test_remove_with_mutating(self): klasa X(ET.Element): def __eq__(self, o): usuń e[:] zwróć Nieprawda e = ET.Element('foo') e.extend([X('bar')]) self.assertRaises(ValueError, e.remove, ET.Element('baz')) e = ET.Element('foo') e.extend([ET.Element('bar')]) self.assertRaises(ValueError, e.remove, X('baz')) klasa MutatingElementPath(str): def __new__(cls, elem, *args): self = str.__new__(cls, *args) self.elem = elem zwróć self def __eq__(self, o): usuń self.elem[:] zwróć Prawda MutatingElementPath.__hash__ = str.__hash__ klasa BadElementPath(str): def __eq__(self, o): podnieś 1/0 BadElementPath.__hash__ = str.__hash__ klasa BadElementPathTest(ElementTestCase, unittest.TestCase): def setUp(self): super().setUp() z xml.etree zaimportuj ElementPath self.path_cache = ElementPath._cache ElementPath._cache = {} def tearDown(self): z xml.etree zaimportuj ElementPath ElementPath._cache = self.path_cache super().tearDown() def test_find_with_mutating(self): e = ET.Element('foo') e.extend([ET.Element('bar')]) e.find(MutatingElementPath(e, 'x')) def test_find_with_error(self): e = ET.Element('foo') e.extend([ET.Element('bar')]) spróbuj: e.find(BadElementPath('x')) wyjąwszy ZeroDivisionError: dalej def test_findtext_with_mutating(self): e = ET.Element('foo') e.extend([ET.Element('bar')]) e.findtext(MutatingElementPath(e, 'x')) def test_findtext_with_error(self): e = ET.Element('foo') e.extend([ET.Element('bar')]) spróbuj: e.findtext(BadElementPath('x')) wyjąwszy ZeroDivisionError: dalej def test_findall_with_mutating(self): e = ET.Element('foo') e.extend([ET.Element('bar')]) e.findall(MutatingElementPath(e, 'x')) def test_findall_with_error(self): e = ET.Element('foo') e.extend([ET.Element('bar')]) spróbuj: e.findall(BadElementPath('x')) wyjąwszy ZeroDivisionError: dalej klasa ElementTreeTypeTest(unittest.TestCase): def test_istype(self): self.assertIsInstance(ET.ParseError, type) self.assertIsInstance(ET.QName, type) self.assertIsInstance(ET.ElementTree, type) self.assertIsInstance(ET.Element, type) self.assertIsInstance(ET.TreeBuilder, type) self.assertIsInstance(ET.XMLParser, type) def test_Element_subclass_trivial(self): klasa MyElement(ET.Element): dalej mye = MyElement('foo') self.assertIsInstance(mye, ET.Element) self.assertIsInstance(mye, MyElement) self.assertEqual(mye.tag, 'foo') # test that attribute assignment works (issue 14849) mye.text = "joe" self.assertEqual(mye.text, "joe") def test_Element_subclass_constructor(self): klasa MyElement(ET.Element): def __init__(self, tag, attrib={}, **extra): super(MyElement, self).__init__(tag + '__', attrib, **extra) mye = MyElement('foo', {'a': 1, 'b': 2}, c=3, d=4) self.assertEqual(mye.tag, 'foo__') self.assertEqual(sorted(mye.items()), [('a', 1), ('b', 2), ('c', 3), ('d', 4)]) def test_Element_subclass_new_method(self): klasa MyElement(ET.Element): def newmethod(self): zwróć self.tag mye = MyElement('joe') self.assertEqual(mye.newmethod(), 'joe') klasa ElementFindTest(unittest.TestCase): def test_find_simple(self): e = ET.XML(SAMPLE_XML) self.assertEqual(e.find('tag').tag, 'tag') self.assertEqual(e.find('section/tag').tag, 'tag') self.assertEqual(e.find('./tag').tag, 'tag') e[2] = ET.XML(SAMPLE_SECTION) self.assertEqual(e.find('section/nexttag').tag, 'nexttag') self.assertEqual(e.findtext('./tag'), 'text') self.assertEqual(e.findtext('section/tag'), 'subtext') # section/nexttag jest found but has no text self.assertEqual(e.findtext('section/nexttag'), '') self.assertEqual(e.findtext('section/nexttag', 'default'), '') # tog doesn't exist oraz 'default' kicks w self.assertIsNic(e.findtext('tog')) self.assertEqual(e.findtext('tog', 'default'), 'default') # Issue #16922 self.assertEqual(ET.XML('<tag><empty /></tag>').findtext('empty'), '') def test_find_xpath(self): LINEAR_XML = ''' <body> <tag class='a'/> <tag class='b'/> <tag class='c'/> <tag class='d'/> </body>''' e = ET.XML(LINEAR_XML) # Test dla numeric indexing oraz last() self.assertEqual(e.find('./tag[1]').attrib['class'], 'a') self.assertEqual(e.find('./tag[2]').attrib['class'], 'b') self.assertEqual(e.find('./tag[last()]').attrib['class'], 'd') self.assertEqual(e.find('./tag[last()-1]').attrib['class'], 'c') self.assertEqual(e.find('./tag[last()-2]').attrib['class'], 'b') self.assertRaisesRegex(SyntaxError, 'XPath', e.find, './tag[0]') self.assertRaisesRegex(SyntaxError, 'XPath', e.find, './tag[-1]') self.assertRaisesRegex(SyntaxError, 'XPath', e.find, './tag[last()-0]') self.assertRaisesRegex(SyntaxError, 'XPath', e.find, './tag[last()+1]') def test_findall(self): e = ET.XML(SAMPLE_XML) e[2] = ET.XML(SAMPLE_SECTION) self.assertEqual(summarize_list(e.findall('.')), ['body']) self.assertEqual(summarize_list(e.findall('tag')), ['tag', 'tag']) self.assertEqual(summarize_list(e.findall('tog')), []) self.assertEqual(summarize_list(e.findall('tog/foo')), []) self.assertEqual(summarize_list(e.findall('*')), ['tag', 'tag', 'section']) self.assertEqual(summarize_list(e.findall('.//tag')), ['tag'] * 4) self.assertEqual(summarize_list(e.findall('section/tag')), ['tag']) self.assertEqual(summarize_list(e.findall('section//tag')), ['tag'] * 2) self.assertEqual(summarize_list(e.findall('section/*')), ['tag', 'nexttag', 'nextsection']) self.assertEqual(summarize_list(e.findall('section//*')), ['tag', 'nexttag', 'nextsection', 'tag']) self.assertEqual(summarize_list(e.findall('section/.//*')), ['tag', 'nexttag', 'nextsection', 'tag']) self.assertEqual(summarize_list(e.findall('*/*')), ['tag', 'nexttag', 'nextsection']) self.assertEqual(summarize_list(e.findall('*//*')), ['tag', 'nexttag', 'nextsection', 'tag']) self.assertEqual(summarize_list(e.findall('*/tag')), ['tag']) self.assertEqual(summarize_list(e.findall('*/./tag')), ['tag']) self.assertEqual(summarize_list(e.findall('./tag')), ['tag'] * 2) self.assertEqual(summarize_list(e.findall('././tag')), ['tag'] * 2) self.assertEqual(summarize_list(e.findall('.//tag[@class]')), ['tag'] * 3) self.assertEqual(summarize_list(e.findall('.//tag[@class="a"]')), ['tag']) self.assertEqual(summarize_list(e.findall('.//tag[@class="b"]')), ['tag'] * 2) self.assertEqual(summarize_list(e.findall('.//tag[@id]')), ['tag']) self.assertEqual(summarize_list(e.findall('.//section[tag]')), ['section']) self.assertEqual(summarize_list(e.findall('.//section[element]')), []) self.assertEqual(summarize_list(e.findall('../tag')), []) self.assertEqual(summarize_list(e.findall('section/../tag')), ['tag'] * 2) self.assertEqual(e.findall('section//'), e.findall('section//*')) def test_test_find_with_ns(self): e = ET.XML(SAMPLE_XML_NS) self.assertEqual(summarize_list(e.findall('tag')), []) self.assertEqual( summarize_list(e.findall("{http://effbot.org/ns}tag")), ['{http://effbot.org/ns}tag'] * 2) self.assertEqual( summarize_list(e.findall(".//{http://effbot.org/ns}tag")), ['{http://effbot.org/ns}tag'] * 3) def test_findall_different_nsmaps(self): root = ET.XML(''' <a xmlns:x="X" xmlns:y="Y"> <x:b><c/></x:b> <b/> <c><x:b/><b/></c><y:b/> </a>''') nsmap = {'xx': 'X'} self.assertEqual(len(root.findall(".//xx:b", namespaces=nsmap)), 2) self.assertEqual(len(root.findall(".//b", namespaces=nsmap)), 2) nsmap = {'xx': 'Y'} self.assertEqual(len(root.findall(".//xx:b", namespaces=nsmap)), 1) self.assertEqual(len(root.findall(".//b", namespaces=nsmap)), 2) def test_bad_find(self): e = ET.XML(SAMPLE_XML) przy self.assertRaisesRegex(SyntaxError, 'cannot use absolute path'): e.findall('/tag') def test_find_through_ElementTree(self): e = ET.XML(SAMPLE_XML) self.assertEqual(ET.ElementTree(e).find('tag').tag, 'tag') self.assertEqual(ET.ElementTree(e).findtext('tag'), 'text') self.assertEqual(summarize_list(ET.ElementTree(e).findall('tag')), ['tag'] * 2) # this produces a warning self.assertEqual(summarize_list(ET.ElementTree(e).findall('//tag')), ['tag'] * 3) klasa ElementIterTest(unittest.TestCase): def _ilist(self, elem, tag=Nic): zwróć summarize_list(elem.iter(tag)) def test_basic(self): doc = ET.XML("<html><body>this jest a <i>paragraph</i>.</body>..</html>") self.assertEqual(self._ilist(doc), ['html', 'body', 'i']) self.assertEqual(self._ilist(doc.find('body')), ['body', 'i']) self.assertEqual(next(doc.iter()).tag, 'html') self.assertEqual(''.join(doc.itertext()), 'this jest a paragraph...') self.assertEqual(''.join(doc.find('body').itertext()), 'this jest a paragraph.') self.assertEqual(next(doc.itertext()), 'this jest a ') # iterparse should zwróć an iterator sourcefile = serialize(doc, to_string=Nieprawda) self.assertEqual(next(ET.iterparse(sourcefile))[0], 'end') # With an explitit parser too (issue #9708) sourcefile = serialize(doc, to_string=Nieprawda) parser = ET.XMLParser(target=ET.TreeBuilder()) self.assertEqual(next(ET.iterparse(sourcefile, parser=parser))[0], 'end') tree = ET.ElementTree(Nic) self.assertRaises(AttributeError, tree.iter) # Issue #16913 doc = ET.XML("<root>a&amp;<sub>b&amp;</sub>c&amp;</root>") self.assertEqual(''.join(doc.itertext()), 'a&b&c&') def test_corners(self): # single root, no subelements a = ET.Element('a') self.assertEqual(self._ilist(a), ['a']) # one child b = ET.SubElement(a, 'b') self.assertEqual(self._ilist(a), ['a', 'b']) # one child oraz one grandchild c = ET.SubElement(b, 'c') self.assertEqual(self._ilist(a), ['a', 'b', 'c']) # two children, only first przy grandchild d = ET.SubElement(a, 'd') self.assertEqual(self._ilist(a), ['a', 'b', 'c', 'd']) # replace first child by second a[0] = a[1] usuń a[1] self.assertEqual(self._ilist(a), ['a', 'd']) def test_iter_by_tag(self): doc = ET.XML(''' <document> <house> <room>bedroom1</room> <room>bedroom2</room> </house> <shed>nothing here </shed> <house> <room>bedroom8</room> </house> </document>''') self.assertEqual(self._ilist(doc, 'room'), ['room'] * 3) self.assertEqual(self._ilist(doc, 'house'), ['house'] * 2) # test that iter also accepts 'tag' jako a keyword arg self.assertEqual( summarize_list(doc.iter(tag='room')), ['room'] * 3) # make sure both tag=Nic oraz tag='*' zwróć all tags all_tags = ['document', 'house', 'room', 'room', 'shed', 'house', 'room'] self.assertEqual(self._ilist(doc), all_tags) self.assertEqual(self._ilist(doc, '*'), all_tags) klasa TreeBuilderTest(unittest.TestCase): sample1 = ('<!DOCTYPE html PUBLIC' ' "-//W3C//DTD XHTML 1.0 Transitional//EN"' ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' '<html>text<div>subtext</div>tail</html>') sample2 = '''<toplevel>sometext</toplevel>''' def _check_sample1_element(self, e): self.assertEqual(e.tag, 'html') self.assertEqual(e.text, 'text') self.assertEqual(e.tail, Nic) self.assertEqual(e.attrib, {}) children = list(e) self.assertEqual(len(children), 1) child = children[0] self.assertEqual(child.tag, 'div') self.assertEqual(child.text, 'subtext') self.assertEqual(child.tail, 'tail') self.assertEqual(child.attrib, {}) def test_dummy_builder(self): klasa BaseDummyBuilder: def close(self): zwróć 42 klasa DummyBuilder(BaseDummyBuilder): data = start = end = lambda *a: Nic parser = ET.XMLParser(target=DummyBuilder()) parser.feed(self.sample1) self.assertEqual(parser.close(), 42) parser = ET.XMLParser(target=BaseDummyBuilder()) parser.feed(self.sample1) self.assertEqual(parser.close(), 42) parser = ET.XMLParser(target=object()) parser.feed(self.sample1) self.assertIsNic(parser.close()) def test_treebuilder_elementfactory_none(self): parser = ET.XMLParser(target=ET.TreeBuilder(element_factory=Nic)) parser.feed(self.sample1) e = parser.close() self._check_sample1_element(e) def test_subclass(self): klasa MyTreeBuilder(ET.TreeBuilder): def foobar(self, x): zwróć x * 2 tb = MyTreeBuilder() self.assertEqual(tb.foobar(10), 20) parser = ET.XMLParser(target=tb) parser.feed(self.sample1) e = parser.close() self._check_sample1_element(e) def test_element_factory(self): lst = [] def myfactory(tag, attrib): nonlocal lst lst.append(tag) zwróć ET.Element(tag, attrib) tb = ET.TreeBuilder(element_factory=myfactory) parser = ET.XMLParser(target=tb) parser.feed(self.sample2) parser.close() self.assertEqual(lst, ['toplevel']) def _check_element_factory_class(self, cls): tb = ET.TreeBuilder(element_factory=cls) parser = ET.XMLParser(target=tb) parser.feed(self.sample1) e = parser.close() self.assertIsInstance(e, cls) self._check_sample1_element(e) def test_element_factory_subclass(self): klasa MyElement(ET.Element): dalej self._check_element_factory_class(MyElement) def test_element_factory_pure_python_subclass(self): # Mimick SimpleTAL's behaviour (issue #16089): both versions of # TreeBuilder should be able to cope przy a subclass of the # pure Python Element class. base = ET._Element_Py # Not z a C extension self.assertEqual(base.__module__, 'xml.etree.ElementTree') # Force some multiple inheritance przy a C klasa to make things # more interesting. klasa MyElement(base, ValueError): dalej self._check_element_factory_class(MyElement) def test_doctype(self): klasa DoctypeParser: _doctype = Nic def doctype(self, name, pubid, system): self._doctype = (name, pubid, system) def close(self): zwróć self._doctype parser = ET.XMLParser(target=DoctypeParser()) parser.feed(self.sample1) self.assertEqual(parser.close(), ('html', '-//W3C//DTD XHTML 1.0 Transitional//EN', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd')) klasa XMLParserTest(unittest.TestCase): sample1 = b'<file><line>22</line></file>' sample2 = (b'<!DOCTYPE html PUBLIC' b' "-//W3C//DTD XHTML 1.0 Transitional//EN"' b' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' b'<html>text</html>') sample3 = ('<?xml version="1.0" encoding="iso-8859-1"?>\n' '<money value="$\xa3\u20ac\U0001017b">$\xa3\u20ac\U0001017b</money>') def _check_sample_element(self, e): self.assertEqual(e.tag, 'file') self.assertEqual(e[0].tag, 'line') self.assertEqual(e[0].text, '22') def test_constructor_args(self): # Positional args. The first (html) jest nie supported, but should be # nevertheless correctly accepted. parser = ET.XMLParser(Nic, ET.TreeBuilder(), 'utf-8') parser.feed(self.sample1) self._check_sample_element(parser.close()) # Now jako keyword args. parser2 = ET.XMLParser(encoding='utf-8', html=[{}], target=ET.TreeBuilder()) parser2.feed(self.sample1) self._check_sample_element(parser2.close()) def test_subclass(self): klasa MyParser(ET.XMLParser): dalej parser = MyParser() parser.feed(self.sample1) self._check_sample_element(parser.close()) def test_doctype_warning(self): parser = ET.XMLParser() przy self.assertWarns(DeprecationWarning): parser.doctype('html', '-//W3C//DTD XHTML 1.0 Transitional//EN', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd') parser.feed('<html/>') parser.close() przy warnings.catch_warnings(): warnings.simplefilter('error', DeprecationWarning) parser = ET.XMLParser() parser.feed(self.sample2) parser.close() def test_subclass_doctype(self): _doctype = Nic klasa MyParserWithDoctype(ET.XMLParser): def doctype(self, name, pubid, system): nonlocal _doctype _doctype = (name, pubid, system) parser = MyParserWithDoctype() przy self.assertWarns(DeprecationWarning): parser.feed(self.sample2) parser.close() self.assertEqual(_doctype, ('html', '-//W3C//DTD XHTML 1.0 Transitional//EN', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd')) _doctype = _doctype2 = Nic przy warnings.catch_warnings(): warnings.simplefilter('error', DeprecationWarning) klasa DoctypeParser: def doctype(self, name, pubid, system): nonlocal _doctype2 _doctype2 = (name, pubid, system) parser = MyParserWithDoctype(target=DoctypeParser()) parser.feed(self.sample2) parser.close() self.assertIsNic(_doctype) self.assertEqual(_doctype2, ('html', '-//W3C//DTD XHTML 1.0 Transitional//EN', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd')) def test_inherited_doctype(self): '''Ensure that ordinary usage jest nie deprecated (Issue 19176)''' przy warnings.catch_warnings(): warnings.simplefilter('error', DeprecationWarning) klasa MyParserWithoutDoctype(ET.XMLParser): dalej parser = MyParserWithoutDoctype() parser.feed(self.sample2) parser.close() def test_parse_string(self): parser = ET.XMLParser(target=ET.TreeBuilder()) parser.feed(self.sample3) e = parser.close() self.assertEqual(e.tag, 'money') self.assertEqual(e.attrib['value'], '$\xa3\u20ac\U0001017b') self.assertEqual(e.text, '$\xa3\u20ac\U0001017b') klasa NamespaceParseTest(unittest.TestCase): def test_find_with_namespace(self): nsmap = {'h': 'hello', 'f': 'foo'} doc = ET.fromstring(SAMPLE_XML_NS_ELEMS) self.assertEqual(len(doc.findall('{hello}table', nsmap)), 1) self.assertEqual(len(doc.findall('.//{hello}td', nsmap)), 2) self.assertEqual(len(doc.findall('.//{foo}name', nsmap)), 1) klasa ElementSlicingTest(unittest.TestCase): def _elem_tags(self, elemlist): zwróć [e.tag dla e w elemlist] def _subelem_tags(self, elem): zwróć self._elem_tags(list(elem)) def _make_elem_with_children(self, numchildren): """Create an Element przy a tag 'a', przy the given amount of children named 'a0', 'a1' ... oraz so on. """ e = ET.Element('a') dla i w range(numchildren): ET.SubElement(e, 'a%s' % i) zwróć e def test_getslice_single_index(self): e = self._make_elem_with_children(10) self.assertEqual(e[1].tag, 'a1') self.assertEqual(e[-2].tag, 'a8') self.assertRaises(IndexError, lambda: e[12]) def test_getslice_range(self): e = self._make_elem_with_children(6) self.assertEqual(self._elem_tags(e[3:]), ['a3', 'a4', 'a5']) self.assertEqual(self._elem_tags(e[3:6]), ['a3', 'a4', 'a5']) self.assertEqual(self._elem_tags(e[3:16]), ['a3', 'a4', 'a5']) self.assertEqual(self._elem_tags(e[3:5]), ['a3', 'a4']) self.assertEqual(self._elem_tags(e[3:-1]), ['a3', 'a4']) self.assertEqual(self._elem_tags(e[:2]), ['a0', 'a1']) def test_getslice_steps(self): e = self._make_elem_with_children(10) self.assertEqual(self._elem_tags(e[8:10:1]), ['a8', 'a9']) self.assertEqual(self._elem_tags(e[::3]), ['a0', 'a3', 'a6', 'a9']) self.assertEqual(self._elem_tags(e[::8]), ['a0', 'a8']) self.assertEqual(self._elem_tags(e[1::8]), ['a1', 'a9']) def test_getslice_negative_steps(self): e = self._make_elem_with_children(4) self.assertEqual(self._elem_tags(e[::-1]), ['a3', 'a2', 'a1', 'a0']) self.assertEqual(self._elem_tags(e[::-2]), ['a3', 'a1']) def test_delslice(self): e = self._make_elem_with_children(4) usuń e[0:2] self.assertEqual(self._subelem_tags(e), ['a2', 'a3']) e = self._make_elem_with_children(4) usuń e[0:] self.assertEqual(self._subelem_tags(e), []) e = self._make_elem_with_children(4) usuń e[::-1] self.assertEqual(self._subelem_tags(e), []) e = self._make_elem_with_children(4) usuń e[::-2] self.assertEqual(self._subelem_tags(e), ['a0', 'a2']) e = self._make_elem_with_children(4) usuń e[1::2] self.assertEqual(self._subelem_tags(e), ['a0', 'a2']) e = self._make_elem_with_children(2) usuń e[::2] self.assertEqual(self._subelem_tags(e), ['a1']) klasa IOTest(unittest.TestCase): def tearDown(self): support.unlink(TESTFN) def test_encoding(self): # Test encoding issues. elem = ET.Element("tag") elem.text = "abc" self.assertEqual(serialize(elem), '<tag>abc</tag>') self.assertEqual(serialize(elem, encoding="utf-8"), b'<tag>abc</tag>') self.assertEqual(serialize(elem, encoding="us-ascii"), b'<tag>abc</tag>') dla enc w ("iso-8859-1", "utf-16", "utf-32"): self.assertEqual(serialize(elem, encoding=enc), ("<?xml version='1.0' encoding='%s'?>\n" "<tag>abc</tag>" % enc).encode(enc)) elem = ET.Element("tag") elem.text = "<&\"\'>" self.assertEqual(serialize(elem), '<tag>&lt;&amp;"\'&gt;</tag>') self.assertEqual(serialize(elem, encoding="utf-8"), b'<tag>&lt;&amp;"\'&gt;</tag>') self.assertEqual(serialize(elem, encoding="us-ascii"), b'<tag>&lt;&amp;"\'&gt;</tag>') dla enc w ("iso-8859-1", "utf-16", "utf-32"): self.assertEqual(serialize(elem, encoding=enc), ("<?xml version='1.0' encoding='%s'?>\n" "<tag>&lt;&amp;\"'&gt;</tag>" % enc).encode(enc)) elem = ET.Element("tag") elem.attrib["key"] = "<&\"\'>" self.assertEqual(serialize(elem), '<tag key="&lt;&amp;&quot;\'&gt;" />') self.assertEqual(serialize(elem, encoding="utf-8"), b'<tag key="&lt;&amp;&quot;\'&gt;" />') self.assertEqual(serialize(elem, encoding="us-ascii"), b'<tag key="&lt;&amp;&quot;\'&gt;" />') dla enc w ("iso-8859-1", "utf-16", "utf-32"): self.assertEqual(serialize(elem, encoding=enc), ("<?xml version='1.0' encoding='%s'?>\n" "<tag key=\"&lt;&amp;&quot;'&gt;\" />" % enc).encode(enc)) elem = ET.Element("tag") elem.text = '\xe5\xf6\xf6<>' self.assertEqual(serialize(elem), '<tag>\xe5\xf6\xf6&lt;&gt;</tag>') self.assertEqual(serialize(elem, encoding="utf-8"), b'<tag>\xc3\xa5\xc3\xb6\xc3\xb6&lt;&gt;</tag>') self.assertEqual(serialize(elem, encoding="us-ascii"), b'<tag>&#229;&#246;&#246;&lt;&gt;</tag>') dla enc w ("iso-8859-1", "utf-16", "utf-32"): self.assertEqual(serialize(elem, encoding=enc), ("<?xml version='1.0' encoding='%s'?>\n" "<tag>åöö&lt;&gt;</tag>" % enc).encode(enc)) elem = ET.Element("tag") elem.attrib["key"] = '\xe5\xf6\xf6<>' self.assertEqual(serialize(elem), '<tag key="\xe5\xf6\xf6&lt;&gt;" />') self.assertEqual(serialize(elem, encoding="utf-8"), b'<tag key="\xc3\xa5\xc3\xb6\xc3\xb6&lt;&gt;" />') self.assertEqual(serialize(elem, encoding="us-ascii"), b'<tag key="&#229;&#246;&#246;&lt;&gt;" />') dla enc w ("iso-8859-1", "utf-16", "utf-16le", "utf-16be", "utf-32"): self.assertEqual(serialize(elem, encoding=enc), ("<?xml version='1.0' encoding='%s'?>\n" "<tag key=\"åöö&lt;&gt;\" />" % enc).encode(enc)) def test_write_to_filename(self): tree = ET.ElementTree(ET.XML('''<site />''')) tree.write(TESTFN) przy open(TESTFN, 'rb') jako f: self.assertEqual(f.read(), b'''<site />''') def test_write_to_text_file(self): tree = ET.ElementTree(ET.XML('''<site />''')) przy open(TESTFN, 'w', encoding='utf-8') jako f: tree.write(f, encoding='unicode') self.assertNieprawda(f.closed) przy open(TESTFN, 'rb') jako f: self.assertEqual(f.read(), b'''<site />''') def test_write_to_binary_file(self): tree = ET.ElementTree(ET.XML('''<site />''')) przy open(TESTFN, 'wb') jako f: tree.write(f) self.assertNieprawda(f.closed) przy open(TESTFN, 'rb') jako f: self.assertEqual(f.read(), b'''<site />''') def test_write_to_binary_file_with_bom(self): tree = ET.ElementTree(ET.XML('''<site />''')) # test BOM writing to buffered file przy open(TESTFN, 'wb') jako f: tree.write(f, encoding='utf-16') self.assertNieprawda(f.closed) przy open(TESTFN, 'rb') jako f: self.assertEqual(f.read(), '''<?xml version='1.0' encoding='utf-16'?>\n''' '''<site />'''.encode("utf-16")) # test BOM writing to non-buffered file przy open(TESTFN, 'wb', buffering=0) jako f: tree.write(f, encoding='utf-16') self.assertNieprawda(f.closed) przy open(TESTFN, 'rb') jako f: self.assertEqual(f.read(), '''<?xml version='1.0' encoding='utf-16'?>\n''' '''<site />'''.encode("utf-16")) def test_read_from_stringio(self): tree = ET.ElementTree() stream = io.StringIO('''<?xml version="1.0"?><site></site>''') tree.parse(stream) self.assertEqual(tree.getroot().tag, 'site') def test_write_to_stringio(self): tree = ET.ElementTree(ET.XML('''<site />''')) stream = io.StringIO() tree.write(stream, encoding='unicode') self.assertEqual(stream.getvalue(), '''<site />''') def test_read_from_bytesio(self): tree = ET.ElementTree() raw = io.BytesIO(b'''<?xml version="1.0"?><site></site>''') tree.parse(raw) self.assertEqual(tree.getroot().tag, 'site') def test_write_to_bytesio(self): tree = ET.ElementTree(ET.XML('''<site />''')) raw = io.BytesIO() tree.write(raw) self.assertEqual(raw.getvalue(), b'''<site />''') klasa dummy: dalej def test_read_from_user_text_reader(self): stream = io.StringIO('''<?xml version="1.0"?><site></site>''') reader = self.dummy() reader.read = stream.read tree = ET.ElementTree() tree.parse(reader) self.assertEqual(tree.getroot().tag, 'site') def test_write_to_user_text_writer(self): tree = ET.ElementTree(ET.XML('''<site />''')) stream = io.StringIO() writer = self.dummy() writer.write = stream.write tree.write(writer, encoding='unicode') self.assertEqual(stream.getvalue(), '''<site />''') def test_read_from_user_binary_reader(self): raw = io.BytesIO(b'''<?xml version="1.0"?><site></site>''') reader = self.dummy() reader.read = raw.read tree = ET.ElementTree() tree.parse(reader) self.assertEqual(tree.getroot().tag, 'site') tree = ET.ElementTree() def test_write_to_user_binary_writer(self): tree = ET.ElementTree(ET.XML('''<site />''')) raw = io.BytesIO() writer = self.dummy() writer.write = raw.write tree.write(writer) self.assertEqual(raw.getvalue(), b'''<site />''') def test_write_to_user_binary_writer_with_bom(self): tree = ET.ElementTree(ET.XML('''<site />''')) raw = io.BytesIO() writer = self.dummy() writer.write = raw.write writer.seekable = lambda: Prawda writer.tell = raw.tell tree.write(writer, encoding="utf-16") self.assertEqual(raw.getvalue(), '''<?xml version='1.0' encoding='utf-16'?>\n''' '''<site />'''.encode("utf-16")) def test_tostringlist_invariant(self): root = ET.fromstring('<tag>foo</tag>') self.assertEqual( ET.tostring(root, 'unicode'), ''.join(ET.tostringlist(root, 'unicode'))) self.assertEqual( ET.tostring(root, 'utf-16'), b''.join(ET.tostringlist(root, 'utf-16'))) def test_short_empty_elements(self): root = ET.fromstring('<tag>a<x />b<y></y>c</tag>') self.assertEqual( ET.tostring(root, 'unicode'), '<tag>a<x />b<y />c</tag>') self.assertEqual( ET.tostring(root, 'unicode', short_empty_elements=Prawda), '<tag>a<x />b<y />c</tag>') self.assertEqual( ET.tostring(root, 'unicode', short_empty_elements=Nieprawda), '<tag>a<x></x>b<y></y>c</tag>') klasa ParseErrorTest(unittest.TestCase): def test_subclass(self): self.assertIsInstance(ET.ParseError(), SyntaxError) def _get_error(self, s): spróbuj: ET.fromstring(s) wyjąwszy ET.ParseError jako e: zwróć e def test_error_position(self): self.assertEqual(self._get_error('foo').position, (1, 0)) self.assertEqual(self._get_error('<tag>&foo;</tag>').position, (1, 5)) self.assertEqual(self._get_error('foobar<').position, (1, 6)) def test_error_code(self): zaimportuj xml.parsers.expat.errors jako ERRORS self.assertEqual(self._get_error('foo').code, ERRORS.codes[ERRORS.XML_ERROR_SYNTAX]) klasa KeywordArgsTest(unittest.TestCase): # Test various issues przy keyword arguments dalejed to ET.Element # constructor oraz methods def test_issue14818(self): x = ET.XML("<a>foo</a>") self.assertEqual(x.find('a', Nic), x.find(path='a', namespaces=Nic)) self.assertEqual(x.findtext('a', Nic, Nic), x.findtext(path='a', default=Nic, namespaces=Nic)) self.assertEqual(x.findall('a', Nic), x.findall(path='a', namespaces=Nic)) self.assertEqual(list(x.iterfind('a', Nic)), list(x.iterfind(path='a', namespaces=Nic))) self.assertEqual(ET.Element('a').attrib, {}) elements = [ ET.Element('a', dict(href="#", id="foo")), ET.Element('a', attrib=dict(href="#", id="foo")), ET.Element('a', dict(href="#"), id="foo"), ET.Element('a', href="#", id="foo"), ET.Element('a', dict(href="#", id="foo"), href="#", id="foo"), ] dla e w elements: self.assertEqual(e.tag, 'a') self.assertEqual(e.attrib, dict(href="#", id="foo")) e2 = ET.SubElement(elements[0], 'foobar', attrib={'key1': 'value1'}) self.assertEqual(e2.attrib['key1'], 'value1') przy self.assertRaisesRegex(TypeError, 'must be dict, nie str'): ET.Element('a', "I'm nie a dict") przy self.assertRaisesRegex(TypeError, 'must be dict, nie str'): ET.Element('a', attrib="I'm nie a dict") # -------------------------------------------------------------------- klasa NoAcceleratorTest(unittest.TestCase): def setUp(self): jeżeli nie pyET: podnieś unittest.SkipTest('only dla the Python version') # Test that the C accelerator was nie imported dla pyET def test_correct_import_pyET(self): # The type of methods defined w Python code jest types.FunctionType, # dopóki the type of methods defined inside _elementtree jest # <class 'wrapper_descriptor'> self.assertIsInstance(pyET.Element.__init__, types.FunctionType) self.assertIsInstance(pyET.XMLParser.__init__, types.FunctionType) # -------------------------------------------------------------------- klasa CleanContext(object): """Provide default namespace mapping oraz path cache.""" checkwarnings = Nic def __init__(self, quiet=Nieprawda): jeżeli sys.flags.optimize >= 2: # under -OO, doctests cannot be run oraz therefore nie all warnings # will be emitted quiet = Prawda deprecations = ( # Search behaviour jest broken jeżeli search path starts przy "/". ("This search jest broken w 1.3 oraz earlier, oraz will be fixed " "in a future version. If you rely on the current behaviour, " "change it to '.+'", FutureWarning), # Element.getchildren() oraz Element.getiterator() are deprecated. ("This method will be removed w future versions. " "Use .+ instead.", DeprecationWarning), ("This method will be removed w future versions. " "Use .+ instead.", PendingDeprecationWarning)) self.checkwarnings = support.check_warnings(*deprecations, quiet=quiet) def __enter__(self): z xml.etree zaimportuj ElementPath self._nsmap = ET.register_namespace._namespace_map # Copy the default namespace mapping self._nsmap_copy = self._nsmap.copy() # Copy the path cache (should be empty) self._path_cache = ElementPath._cache ElementPath._cache = self._path_cache.copy() self.checkwarnings.__enter__() def __exit__(self, *args): z xml.etree zaimportuj ElementPath # Restore mapping oraz path cache self._nsmap.clear() self._nsmap.update(self._nsmap_copy) ElementPath._cache = self._path_cache self.checkwarnings.__exit__(*args) def test_main(module=Nic): # When invoked without a module, runs the Python ET tests by loading pyET. # Otherwise, uses the given module jako the ET. global pyET pyET = import_fresh_module('xml.etree.ElementTree', blocked=['_elementtree']) jeżeli module jest Nic: module = pyET global ET ET = module test_classes = [ ModuleTest, ElementSlicingTest, BasicElementTest, BadElementTest, BadElementPathTest, ElementTreeTest, IOTest, ParseErrorTest, XIncludeTest, ElementTreeTypeTest, ElementFindTest, ElementIterTest, TreeBuilderTest, XMLParserTest, XMLPullParserTest, BugsTest, ] # These tests will only run dla the pure-Python version that doesn't import # _elementtree. We can't use skipUnless here, because pyET jest filled w only # after the module jest loaded. jeżeli pyET jest nie ET: test_classes.extend([ NoAcceleratorTest, ]) spróbuj: # XXX the C module should give the same warnings jako the Python module przy CleanContext(quiet=(pyET jest nie ET)): support.run_unittest(*test_classes) w_końcu: # don't interfere przy subsequent tests ET = pyET = Nic jeżeli __name__ == '__main__': test_main()
37.492738
106
0.55915
zaimportuj html zaimportuj io zaimportuj operator zaimportuj pickle zaimportuj sys zaimportuj types zaimportuj unittest zaimportuj warnings zaimportuj weakref z itertools zaimportuj product z test zaimportuj support z test.support zaimportuj TESTFN, findfile, import_fresh_module, gc_collect pyET = Nic ET = Nic SIMPLE_XMLFILE = findfile("simple.xml", subdir="xmltestdata") spróbuj: SIMPLE_XMLFILE.encode("utf-8") wyjąwszy UnicodeEncodeError: podnieś unittest.SkipTest("filename jest nie encodable to utf8") SIMPLE_NS_XMLFILE = findfile("simple-ns.xml", subdir="xmltestdata") SAMPLE_XML = """\ <body> <tag class='a'>text</tag> <tag class='b' /> <section> <tag class='b' id='inner'>subtext</tag> </section> </body> """ SAMPLE_SECTION = """\ <section> <tag class='b' id='inner'>subtext</tag> <nexttag /> <nextsection> <tag /> </nextsection> </section> """ SAMPLE_XML_NS = """ <body xmlns="http://effbot.org/ns"> <tag>text</tag> <tag /> <section> <tag>subtext</tag> </section> </body> """ SAMPLE_XML_NS_ELEMS = """ <root> <h:table xmlns:h="hello"> <h:tr> <h:td>Apples</h:td> <h:td>Bananas</h:td> </h:tr> </h:table> <f:table xmlns:f="foo"> <f:name>African Coffee Table</f:name> <f:width>80</f:width> <f:length>120</f:length> </f:table> </root> """ ENTITY_XML = """\ <!DOCTYPE points [ <!ENTITY % user-entities SYSTEM 'user-entities.xml'> %user-entities; ]> <document>&entity;</document> """ klasa ModuleTest(unittest.TestCase): def test_sanity(self): z xml.etree zaimportuj ElementTree z xml.etree zaimportuj ElementInclude z xml.etree zaimportuj ElementPath def serialize(elem, to_string=Prawda, encoding='unicode', **options): jeżeli encoding != 'unicode': file = io.BytesIO() inaczej: file = io.StringIO() tree = ET.ElementTree(elem) tree.write(file, encoding=encoding, **options) jeżeli to_string: zwróć file.getvalue() inaczej: file.seek(0) zwróć file def summarize_list(seq): zwróć [elem.tag dla elem w seq] klasa ElementTestCase: @classmethod def setUpClass(cls): cls.modules = {pyET, ET} def pickleRoundTrip(self, obj, name, dumper, loader, proto): save_m = sys.modules[name] spróbuj: sys.modules[name] = dumper temp = pickle.dumps(obj, proto) sys.modules[name] = loader result = pickle.loads(temp) wyjąwszy pickle.PicklingError jako pe: human = dict([(ET, "cET"), (pyET, "pyET")]) podnieś support.TestFailed("Failed to round-trip %r z %r to %r" % (obj, human.get(dumper, dumper), human.get(loader, loader))) z pe w_końcu: sys.modules[name] = save_m zwróć result def assertEqualElements(self, alice, bob): self.assertIsInstance(alice, (ET.Element, pyET.Element)) self.assertIsInstance(bob, (ET.Element, pyET.Element)) self.assertEqual(len(list(alice)), len(list(bob))) dla x, y w zip(alice, bob): self.assertEqualElements(x, y) properties = operator.attrgetter('tag', 'tail', 'text', 'attrib') self.assertEqual(properties(alice), properties(bob)) klasa ElementTreeTest(unittest.TestCase): def serialize_check(self, elem, expected): self.assertEqual(serialize(elem), expected) def test_interface(self): def check_string(string): len(string) dla char w string: self.assertEqual(len(char), 1, msg="expected one-character string, got %r" % char) new_string = string + "" new_string = string + " " string[:0] def check_mapping(mapping): len(mapping) keys = mapping.keys() items = mapping.items() dla key w keys: item = mapping[key] mapping["key"] = "value" self.assertEqual(mapping["key"], "value", msg="expected value string, got %r" % mapping["key"]) def check_element(element): self.assertPrawda(ET.iselement(element), msg="not an element") self.assertPrawda(hasattr(element, "tag"), msg="no tag member") self.assertPrawda(hasattr(element, "attrib"), msg="no attrib member") self.assertPrawda(hasattr(element, "text"), msg="no text member") self.assertPrawda(hasattr(element, "tail"), msg="no tail member") check_string(element.tag) check_mapping(element.attrib) jeżeli element.text jest nie Nic: check_string(element.text) jeżeli element.tail jest nie Nic: check_string(element.tail) dla elem w element: check_element(elem) element = ET.Element("tag") check_element(element) tree = ET.ElementTree(element) check_element(tree.getroot()) element = ET.Element("t\xe4g", key="value") tree = ET.ElementTree(element) self.assertRegex(repr(element), r"^<Element 't\xe4g' at 0x.*>$") element = ET.Element("tag", key="value") def check_method(method): self.assertPrawda(hasattr(method, '__call__'), msg="%s nie callable" % method) check_method(element.append) check_method(element.extend) check_method(element.insert) check_method(element.remove) check_method(element.getchildren) check_method(element.find) check_method(element.iterfind) check_method(element.findall) check_method(element.findtext) check_method(element.clear) check_method(element.get) check_method(element.set) check_method(element.keys) check_method(element.items) check_method(element.iter) check_method(element.itertext) check_method(element.getiterator) def check_iter(it): check_method(it.__next__) check_iter(element.iterfind("tag")) check_iter(element.iterfind("*")) check_iter(tree.iterfind("tag")) check_iter(tree.iterfind("*")) self.assertEqual(ET.XML, ET.fromstring) self.assertEqual(ET.PI, ET.ProcessingInstruction) def test_simpleops(self): elem = ET.XML("<body><tag/></body>") self.serialize_check(elem, '<body><tag /></body>') e = ET.Element("tag2") elem.append(e) self.serialize_check(elem, '<body><tag /><tag2 /></body>') elem.remove(e) self.serialize_check(elem, '<body><tag /></body>') elem.insert(0, e) self.serialize_check(elem, '<body><tag2 /><tag /></body>') elem.remove(e) elem.extend([e]) self.serialize_check(elem, '<body><tag /><tag2 /></body>') elem.remove(e) element = ET.Element("tag", key="value") self.serialize_check(element, '<tag key="value" />') subelement = ET.Element("subtag") element.append(subelement) self.serialize_check(element, '<tag key="value"><subtag /></tag>') element.insert(0, subelement) self.serialize_check(element, '<tag key="value"><subtag /><subtag /></tag>') element.remove(subelement) self.serialize_check(element, '<tag key="value"><subtag /></tag>') element.remove(subelement) self.serialize_check(element, '<tag key="value" />') przy self.assertRaises(ValueError) jako cm: element.remove(subelement) self.assertEqual(str(cm.exception), 'list.remove(x): x nie w list') self.serialize_check(element, '<tag key="value" />') element[0:0] = [subelement, subelement, subelement] self.serialize_check(element[1], '<subtag />') self.assertEqual(element[1:9], [element[1], element[2]]) self.assertEqual(element[:9:2], [element[0], element[2]]) usuń element[1:2] self.serialize_check(element, '<tag key="value"><subtag /><subtag /></tag>') def test_cdata(self): self.serialize_check(ET.XML("<tag>hello</tag>"), '<tag>hello</tag>') self.serialize_check(ET.XML("<tag>&#104;&#101;&#108;&#108;&#111;</tag>"), '<tag>hello</tag>') self.serialize_check(ET.XML("<tag><![CDATA[hello]]></tag>"), '<tag>hello</tag>') def test_file_init(self): stringfile = io.BytesIO(SAMPLE_XML.encode("utf-8")) tree = ET.ElementTree(file=stringfile) self.assertEqual(tree.find("tag").tag, 'tag') self.assertEqual(tree.find("section/tag").tag, 'tag') tree = ET.ElementTree(file=SIMPLE_XMLFILE) self.assertEqual(tree.find("element").tag, 'element') self.assertEqual(tree.find("element/../empty-element").tag, 'empty-element') def test_path_cache(self): z xml.etree zaimportuj ElementPath elem = ET.XML(SAMPLE_XML) dla i w range(10): ET.ElementTree(elem).find('./'+str(i)) cache_len_10 = len(ElementPath._cache) dla i w range(10): ET.ElementTree(elem).find('./'+str(i)) self.assertEqual(len(ElementPath._cache), cache_len_10) dla i w range(20): ET.ElementTree(elem).find('./'+str(i)) self.assertGreater(len(ElementPath._cache), cache_len_10) dla i w range(600): ET.ElementTree(elem).find('./'+str(i)) self.assertLess(len(ElementPath._cache), 500) def test_copy(self): zaimportuj copy e1 = ET.XML("<tag>hello<foo/></tag>") e2 = copy.copy(e1) e3 = copy.deepcopy(e1) e1.find("foo").tag = "bar" self.serialize_check(e1, '<tag>hello<bar /></tag>') self.serialize_check(e2, '<tag>hello<bar /></tag>') self.serialize_check(e3, '<tag>hello<foo /></tag>') def test_attrib(self): elem = ET.Element("tag") elem.get("key") self.assertEqual(elem.get("key", "default"), 'default') elem.set("key", "value") self.assertEqual(elem.get("key"), 'value') elem = ET.Element("tag", key="value") self.assertEqual(elem.get("key"), 'value') self.assertEqual(elem.attrib, {'key': 'value'}) attrib = {"key": "value"} elem = ET.Element("tag", attrib) attrib.clear() self.assertEqual(elem.get("key"), 'value') self.assertEqual(elem.attrib, {'key': 'value'}) attrib = {"key": "value"} elem = ET.Element("tag", **attrib) attrib.clear() self.assertEqual(elem.get("key"), 'value') self.assertEqual(elem.attrib, {'key': 'value'}) elem = ET.Element("tag", {"key": "other"}, key="value") self.assertEqual(elem.get("key"), 'value') self.assertEqual(elem.attrib, {'key': 'value'}) elem = ET.Element('test') elem.text = "aa" elem.set('testa', 'testval') elem.set('testb', 'test2') self.assertEqual(ET.tostring(elem), b'<test testa="testval" testb="test2">aa</test>') self.assertEqual(sorted(elem.keys()), ['testa', 'testb']) self.assertEqual(sorted(elem.items()), [('testa', 'testval'), ('testb', 'test2')]) self.assertEqual(elem.attrib['testb'], 'test2') elem.attrib['testb'] = 'test1' elem.attrib['testc'] = 'test2' self.assertEqual(ET.tostring(elem), b'<test testa="testval" testb="test1" testc="test2">aa</test>') def test_makeelement(self): elem = ET.Element("tag") attrib = {"key": "value"} subelem = elem.makeelement("subtag", attrib) self.assertIsNot(subelem.attrib, attrib, msg="attrib aliasing") elem.append(subelem) self.serialize_check(elem, '<tag><subtag key="value" /></tag>') elem.clear() self.serialize_check(elem, '<tag />') elem.append(subelem) self.serialize_check(elem, '<tag><subtag key="value" /></tag>') elem.extend([subelem, subelem]) self.serialize_check(elem, '<tag><subtag key="value" /><subtag key="value" /><subtag key="value" /></tag>') elem[:] = [subelem] self.serialize_check(elem, '<tag><subtag key="value" /></tag>') elem[:] = tuple([subelem]) self.serialize_check(elem, '<tag><subtag key="value" /></tag>') def test_parsefile(self): tree = ET.parse(SIMPLE_XMLFILE) stream = io.StringIO() tree.write(stream, encoding='unicode') self.assertEqual(stream.getvalue(), '<root>\n' ' <element key="value">text</element>\n' ' <element>text</element>tail\n' ' <empty-element />\n' '</root>') tree = ET.parse(SIMPLE_NS_XMLFILE) stream = io.StringIO() tree.write(stream, encoding='unicode') self.assertEqual(stream.getvalue(), '<ns0:root xmlns:ns0="namespace">\n' ' <ns0:element key="value">text</ns0:element>\n' ' <ns0:element>text</ns0:element>tail\n' ' <ns0:empty-element />\n' '</ns0:root>') przy open(SIMPLE_XMLFILE) jako f: data = f.read() parser = ET.XMLParser() self.assertRegex(parser.version, r'^Expat ') parser.feed(data) self.serialize_check(parser.close(), '<root>\n' ' <element key="value">text</element>\n' ' <element>text</element>tail\n' ' <empty-element />\n' '</root>') target = ET.TreeBuilder() parser = ET.XMLParser(target=target) parser.feed(data) self.serialize_check(parser.close(), '<root>\n' ' <element key="value">text</element>\n' ' <element>text</element>tail\n' ' <empty-element />\n' '</root>') def test_parseliteral(self): element = ET.XML("<html><body>text</body></html>") self.assertEqual(ET.tostring(element, encoding='unicode'), '<html><body>text</body></html>') element = ET.fromstring("<html><body>text</body></html>") self.assertEqual(ET.tostring(element, encoding='unicode'), '<html><body>text</body></html>') sequence = ["<html><body>", "text</bo", "dy></html>"] element = ET.fromstringlist(sequence) self.assertEqual(ET.tostring(element), b'<html><body>text</body></html>') self.assertEqual(b"".join(ET.tostringlist(element)), b'<html><body>text</body></html>') self.assertEqual(ET.tostring(element, "ascii"), b"<?xml version='1.0' encoding='ascii'?>\n" b"<html><body>text</body></html>") _, ids = ET.XMLID("<html><body>text</body></html>") self.assertEqual(len(ids), 0) _, ids = ET.XMLID("<html><body id='body'>text</body></html>") self.assertEqual(len(ids), 1) self.assertEqual(ids["body"].tag, 'body') def test_iterparse(self): iterparse = ET.iterparse context = iterparse(SIMPLE_XMLFILE) action, elem = next(context) self.assertEqual((action, elem.tag), ('end', 'element')) self.assertEqual([(action, elem.tag) dla action, elem w context], [ ('end', 'element'), ('end', 'empty-element'), ('end', 'root'), ]) self.assertEqual(context.root.tag, 'root') context = iterparse(SIMPLE_NS_XMLFILE) self.assertEqual([(action, elem.tag) dla action, elem w context], [ ('end', '{namespace}element'), ('end', '{namespace}element'), ('end', '{namespace}empty-element'), ('end', '{namespace}root'), ]) events = () context = iterparse(SIMPLE_XMLFILE, events) self.assertEqual([(action, elem.tag) dla action, elem w context], []) events = () context = iterparse(SIMPLE_XMLFILE, events=events) self.assertEqual([(action, elem.tag) dla action, elem w context], []) events = ("start", "end") context = iterparse(SIMPLE_XMLFILE, events) self.assertEqual([(action, elem.tag) dla action, elem w context], [ ('start', 'root'), ('start', 'element'), ('end', 'element'), ('start', 'element'), ('end', 'element'), ('start', 'empty-element'), ('end', 'empty-element'), ('end', 'root'), ]) events = ("start", "end", "start-ns", "end-ns") context = iterparse(SIMPLE_NS_XMLFILE, events) self.assertEqual([(action, elem.tag) jeżeli action w ("start", "end") inaczej (action, elem) dla action, elem w context], [ ('start-ns', ('', 'namespace')), ('start', '{namespace}root'), ('start', '{namespace}element'), ('end', '{namespace}element'), ('start', '{namespace}element'), ('end', '{namespace}element'), ('start', '{namespace}empty-element'), ('end', '{namespace}empty-element'), ('end', '{namespace}root'), ('end-ns', Nic), ]) events = ('start-ns', 'end-ns') context = iterparse(io.StringIO(r"<root xmlns=''/>"), events) res = [action dla action, elem w context] self.assertEqual(res, ['start-ns', 'end-ns']) events = ("start", "end", "bogus") przy self.assertRaises(ValueError) jako cm: przy open(SIMPLE_XMLFILE, "rb") jako f: iterparse(f, events) self.assertEqual(str(cm.exception), "unknown event 'bogus'") source = io.BytesIO( b"<?xml version='1.0' encoding='iso-8859-1'?>\n" b"<body xmlns='http://&#233;ffbot.org/ns'\n" b" xmlns:cl\xe9='http://effbot.org/ns'>text</body>\n") events = ("start-ns",) context = iterparse(source, events) self.assertEqual([(action, elem) dla action, elem w context], [ ('start-ns', ('', 'http://\xe9ffbot.org/ns')), ('start-ns', ('cl\xe9', 'http://effbot.org/ns')), ]) source = io.StringIO("<document />junk") it = iterparse(source) action, elem = next(it) self.assertEqual((action, elem.tag), ('end', 'document')) przy self.assertRaises(ET.ParseError) jako cm: next(it) self.assertEqual(str(cm.exception), 'junk after document element: line 1, column 12') def test_writefile(self): elem = ET.Element("tag") elem.text = "text" self.serialize_check(elem, '<tag>text</tag>') ET.SubElement(elem, "subtag").text = "subtext" self.serialize_check(elem, '<tag>text<subtag>subtext</subtag></tag>') elem.tag = Nic self.serialize_check(elem, 'text<subtag>subtext</subtag>') elem.insert(0, ET.Comment("comment")) self.serialize_check(elem, 'text<!--comment--><subtag>subtext</subtag>') elem[0] = ET.PI("key", "value") self.serialize_check(elem, 'text<?key value?><subtag>subtext</subtag>') def test_custom_builder(self): przy open(SIMPLE_XMLFILE) jako f: data = f.read() klasa Builder(list): def start(self, tag, attrib): self.append(("start", tag)) def end(self, tag): self.append(("end", tag)) def data(self, text): dalej builder = Builder() parser = ET.XMLParser(target=builder) parser.feed(data) self.assertEqual(builder, [ ('start', 'root'), ('start', 'element'), ('end', 'element'), ('start', 'element'), ('end', 'element'), ('start', 'empty-element'), ('end', 'empty-element'), ('end', 'root'), ]) przy open(SIMPLE_NS_XMLFILE) jako f: data = f.read() klasa Builder(list): def start(self, tag, attrib): self.append(("start", tag)) def end(self, tag): self.append(("end", tag)) def data(self, text): dalej def pi(self, target, data): self.append(("pi", target, data)) def comment(self, data): self.append(("comment", data)) builder = Builder() parser = ET.XMLParser(target=builder) parser.feed(data) self.assertEqual(builder, [ ('pi', 'pi', 'data'), ('comment', ' comment '), ('start', '{namespace}root'), ('start', '{namespace}element'), ('end', '{namespace}element'), ('start', '{namespace}element'), ('end', '{namespace}element'), ('start', '{namespace}empty-element'), ('end', '{namespace}empty-element'), ('end', '{namespace}root'), ]) def test_getchildren(self): przy open(SIMPLE_XMLFILE, "rb") jako f: tree = ET.parse(f) self.assertEqual([summarize_list(elem.getchildren()) dla elem w tree.getroot().iter()], [ ['element', 'element', 'empty-element'], [], [], [], ]) self.assertEqual([summarize_list(elem.getchildren()) dla elem w tree.getiterator()], [ ['element', 'element', 'empty-element'], [], [], [], ]) elem = ET.XML(SAMPLE_XML) self.assertEqual(len(elem.getchildren()), 3) self.assertEqual(len(elem[2].getchildren()), 1) self.assertEqual(elem[:], elem.getchildren()) child1 = elem[0] child2 = elem[2] usuń elem[1:2] self.assertEqual(len(elem.getchildren()), 2) self.assertEqual(child1, elem[0]) self.assertEqual(child2, elem[1]) elem[0:2] = [child2, child1] self.assertEqual(child2, elem[0]) self.assertEqual(child1, elem[1]) self.assertNotEqual(child1, elem[0]) elem.clear() self.assertEqual(elem.getchildren(), []) def test_writestring(self): elem = ET.XML("<html><body>text</body></html>") self.assertEqual(ET.tostring(elem), b'<html><body>text</body></html>') elem = ET.fromstring("<html><body>text</body></html>") self.assertEqual(ET.tostring(elem), b'<html><body>text</body></html>') def test_encoding(self): def check(encoding, body=''): xml = ("<?xml version='1.0' encoding='%s'?><xml>%s</xml>" % (encoding, body)) self.assertEqual(ET.XML(xml.encode(encoding)).text, body) self.assertEqual(ET.XML(xml).text, body) check("ascii", 'a') check("us-ascii", 'a') check("iso-8859-1", '\xbd') check("iso-8859-15", '\u20ac') check("cp437", '\u221a') check("mac-roman", '\u02da') def xml(encoding): zwróć "<?xml version='1.0' encoding='%s'?><xml />" % encoding def bxml(encoding): zwróć xml(encoding).encode(encoding) supported_encodings = [ 'ascii', 'utf-8', 'utf-8-sig', 'utf-16', 'utf-16be', 'utf-16le', 'iso8859-1', 'iso8859-2', 'iso8859-3', 'iso8859-4', 'iso8859-5', 'iso8859-6', 'iso8859-7', 'iso8859-8', 'iso8859-9', 'iso8859-10', 'iso8859-13', 'iso8859-14', 'iso8859-15', 'iso8859-16', 'cp437', 'cp720', 'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp856', 'cp857', 'cp858', 'cp860', 'cp861', 'cp862', 'cp863', 'cp865', 'cp866', 'cp869', 'cp874', 'cp1006', 'cp1125', 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255', 'cp1256', 'cp1257', 'cp1258', 'mac-cyrillic', 'mac-greek', 'mac-iceland', 'mac-latin2', 'mac-roman', 'mac-turkish', 'iso2022-jp', 'iso2022-jp-1', 'iso2022-jp-2', 'iso2022-jp-2004', 'iso2022-jp-3', 'iso2022-jp-ext', 'koi8-r', 'koi8-t', 'koi8-u', 'kz1048', 'hz', 'ptcp154', ] dla encoding w supported_encodings: self.assertEqual(ET.tostring(ET.XML(bxml(encoding))), b'<xml />') unsupported_ascii_compatible_encodings = [ 'big5', 'big5hkscs', 'cp932', 'cp949', 'cp950', 'euc-jp', 'euc-jis-2004', 'euc-jisx0213', 'euc-kr', 'gb2312', 'gbk', 'gb18030', 'iso2022-kr', 'johab', 'shift-jis', 'shift-jis-2004', 'shift-jisx0213', 'utf-7', ] dla encoding w unsupported_ascii_compatible_encodings: self.assertRaises(ValueError, ET.XML, bxml(encoding)) unsupported_ascii_incompatible_encodings = [ 'cp037', 'cp424', 'cp500', 'cp864', 'cp875', 'cp1026', 'cp1140', 'utf_32', 'utf_32_be', 'utf_32_le', ] dla encoding w unsupported_ascii_incompatible_encodings: self.assertRaises(ET.ParseError, ET.XML, bxml(encoding)) self.assertRaises(ValueError, ET.XML, xml('undefined').encode('ascii')) self.assertRaises(LookupError, ET.XML, xml('xxx').encode('ascii')) def test_methods(self): e = ET.XML("<html><link/><script>1 &lt; 2</script></html>") e.tail = "\n" self.assertEqual(serialize(e), '<html><link /><script>1 &lt; 2</script></html>\n') self.assertEqual(serialize(e, method=Nic), '<html><link /><script>1 &lt; 2</script></html>\n') self.assertEqual(serialize(e, method="xml"), '<html><link /><script>1 &lt; 2</script></html>\n') self.assertEqual(serialize(e, method="html"), '<html><link><script>1 < 2</script></html>\n') self.assertEqual(serialize(e, method="text"), '1 < 2\n') def test_issue18347(self): e = ET.XML('<html><CamelCase>text</CamelCase></html>') self.assertEqual(serialize(e), '<html><CamelCase>text</CamelCase></html>') self.assertEqual(serialize(e, method="html"), '<html><CamelCase>text</CamelCase></html>') def test_entity(self): e = ET.XML("<document title='&#x8230;'>test</document>") self.assertEqual(serialize(e, encoding="us-ascii"), b'<document title="&#33328;">test</document>') self.serialize_check(e, '<document title="\u8230">test</document>') przy self.assertRaises(ET.ParseError) jako cm: ET.XML("<document>&entity;</document>") self.assertEqual(str(cm.exception), 'undefined entity: line 1, column 10') przy self.assertRaises(ET.ParseError) jako cm: ET.XML(ENTITY_XML) self.assertEqual(str(cm.exception), 'undefined entity &entity;: line 5, column 10') parser = ET.XMLParser() parser.entity["entity"] = "text" parser.feed(ENTITY_XML) root = parser.close() self.serialize_check(root, '<document>text</document>') def test_namespace(self): elem = ET.XML("<tag xml:lang='en' />") self.serialize_check(elem, '<tag xml:lang="en" />') elem = ET.XML("<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' />") self.serialize_check(elem, '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" />') elem = ET.XML("<html:html xmlns:html='http://www.w3.org/1999/xhtml' />") self.serialize_check(elem, '<html:html xmlns:html="http://www.w3.org/1999/xhtml" />') elem = ET.XML("<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope' />") self.serialize_check(elem, '<ns0:Envelope xmlns:ns0="http://schemas.xmlsoap.org/soap/envelope" />') elem = ET.XML(SAMPLE_XML_NS) self.serialize_check(elem, '<ns0:body xmlns:ns0="http://effbot.org/ns">\n' ' <ns0:tag>text</ns0:tag>\n' ' <ns0:tag />\n' ' <ns0:section>\n' ' <ns0:tag>subtext</ns0:tag>\n' ' </ns0:section>\n' '</ns0:body>') def test_qname(self): elem = ET.Element("{uri}tag") self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" />') elem = ET.Element(ET.QName("{uri}tag")) self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" />') elem = ET.Element(ET.QName("uri", "tag")) self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" />') elem = ET.Element(ET.QName("uri", "tag")) subelem = ET.SubElement(elem, ET.QName("uri", "tag1")) subelem = ET.SubElement(elem, ET.QName("uri", "tag2")) self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri"><ns0:tag1 /><ns0:tag2 /></ns0:tag>') elem.clear() elem.attrib["{uri}key"] = "value" self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" ns0:key="value" />') elem.clear() elem.attrib[ET.QName("{uri}key")] = "value" self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" ns0:key="value" />') elem.clear() elem.attrib["{uri}key"] = "{uri}value" self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" ns0:key="{uri}value" />') elem.clear() elem.attrib["{uri}key"] = ET.QName("{uri}value") self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" ns0:key="ns0:value" />') elem.clear() subelem = ET.Element("tag") subelem.attrib["{uri1}key"] = ET.QName("{uri2}value") elem.append(subelem) elem.append(subelem) self.serialize_check(elem, '<ns0:tag xmlns:ns0="uri" xmlns:ns1="uri1" xmlns:ns2="uri2">' '<tag ns1:key="ns2:value" />' '<tag ns1:key="ns2:value" />' '</ns0:tag>') self.assertEqual(str(ET.QName('ns', 'tag')), '{ns}tag') self.assertEqual(str(ET.QName('{ns}tag')), '{ns}tag') q1 = ET.QName('ns', 'tag') q2 = ET.QName('ns', 'tag') self.assertEqual(q1, q2) q2 = ET.QName('ns', 'other-tag') self.assertNotEqual(q1, q2) self.assertNotEqual(q1, 'ns:tag') self.assertEqual(q1, '{ns}tag') def test_doctype_public(self): elem = ET.XML('<!DOCTYPE html PUBLIC' ' "-//W3C//DTD XHTML 1.0 Transitional//EN"' ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' '<html>text</html>') def test_xpath_tokenizer(self): z xml.etree zaimportuj ElementPath def check(p, expected): self.assertEqual([op albo tag dla op, tag w ElementPath.xpath_tokenizer(p)], expected) check("*", ['*']) check("text()", ['text', '()']) check("@name", ['@', 'name']) check("@*", ['@', '*']) check("para[1]", ['para', '[', '1', ']']) check("para[last()]", ['para', '[', 'last', '()', ']']) check("*/para", ['*', '/', 'para']) check("/doc/chapter[5]/section[2]", ['/', 'doc', '/', 'chapter', '[', '5', ']', '/', 'section', '[', '2', ']']) check("chapter//para", ['chapter', '//', 'para']) check("//para", ['//', 'para']) check("//olist/item", ['//', 'olist', '/', 'item']) check(".", ['.']) check(".//para", ['.', '//', 'para']) check("..", ['..']) check("../@lang", ['..', '/', '@', 'lang']) check("chapter[title]", ['chapter', '[', 'title', ']']) check("employee[@secretary oraz @assistant]", ['employee', '[', '@', 'secretary', '', 'and', '', '@', 'assistant', ']']) check("{http://spam}egg", ['{http://spam}egg']) check("./spam.egg", ['.', '/', 'spam.egg']) check(".//{http://spam}egg", ['.', '//', '{http://spam}egg']) def test_processinginstruction(self): self.assertEqual(ET.tostring(ET.ProcessingInstruction('test', 'instruction')), b'<?test instruction?>') self.assertEqual(ET.tostring(ET.PI('test', 'instruction')), b'<?test instruction?>') self.assertEqual(ET.tostring(ET.PI('test', '<testing&>')), b'<?test <testing&>?>') self.assertEqual(ET.tostring(ET.PI('test', '<testing&>\xe3'), 'latin-1'), b"<?xml version='1.0' encoding='latin-1'?>\n" b"<?test <testing&>\xe3?>") def test_html_empty_elems_serialization(self): dla element w ['AREA', 'BASE', 'BASEFONT', 'BR', 'COL', 'FRAME', 'HR', 'IMG', 'INPUT', 'ISINDEX', 'LINK', 'META', 'PARAM']: dla elem w [element, element.lower()]: expected = '<%s>' % elem serialized = serialize(ET.XML('<%s />' % elem), method='html') self.assertEqual(serialized, expected) serialized = serialize(ET.XML('<%s></%s>' % (elem,elem)), method='html') self.assertEqual(serialized, expected) klasa XMLPullParserTest(unittest.TestCase): def _feed(self, parser, data, chunk_size=Nic): jeżeli chunk_size jest Nic: parser.feed(data) inaczej: dla i w range(0, len(data), chunk_size): parser.feed(data[i:i+chunk_size]) def assert_event_tags(self, parser, expected): events = parser.read_events() self.assertEqual([(action, elem.tag) dla action, elem w events], expected) def test_simple_xml(self): dla chunk_size w (Nic, 1, 5): przy self.subTest(chunk_size=chunk_size): parser = ET.XMLPullParser() self.assert_event_tags(parser, []) self._feed(parser, "<!-- comment -->\n", chunk_size) self.assert_event_tags(parser, []) self._feed(parser, "<root>\n <element key='value'>text</element", chunk_size) self.assert_event_tags(parser, []) self._feed(parser, ">\n", chunk_size) self.assert_event_tags(parser, [('end', 'element')]) self._feed(parser, "<element>text</element>tail\n", chunk_size) self._feed(parser, "<empty-element/>\n", chunk_size) self.assert_event_tags(parser, [ ('end', 'element'), ('end', 'empty-element'), ]) self._feed(parser, "</root>\n", chunk_size) self.assert_event_tags(parser, [('end', 'root')]) self.assertIsNic(parser.close()) def test_feed_while_iterating(self): parser = ET.XMLPullParser() it = parser.read_events() self._feed(parser, "<root>\n <element key='value'>text</element>\n") action, elem = next(it) self.assertEqual((action, elem.tag), ('end', 'element')) self._feed(parser, "</root>\n") action, elem = next(it) self.assertEqual((action, elem.tag), ('end', 'root')) przy self.assertRaises(StopIteration): next(it) def test_simple_xml_with_ns(self): parser = ET.XMLPullParser() self.assert_event_tags(parser, []) self._feed(parser, "<!-- comment -->\n") self.assert_event_tags(parser, []) self._feed(parser, "<root xmlns='namespace'>\n") self.assert_event_tags(parser, []) self._feed(parser, "<element key='value'>text</element") self.assert_event_tags(parser, []) self._feed(parser, ">\n") self.assert_event_tags(parser, [('end', '{namespace}element')]) self._feed(parser, "<element>text</element>tail\n") self._feed(parser, "<empty-element/>\n") self.assert_event_tags(parser, [ ('end', '{namespace}element'), ('end', '{namespace}empty-element'), ]) self._feed(parser, "</root>\n") self.assert_event_tags(parser, [('end', '{namespace}root')]) self.assertIsNic(parser.close()) def test_ns_events(self): parser = ET.XMLPullParser(events=('start-ns', 'end-ns')) self._feed(parser, "<!-- comment -->\n") self._feed(parser, "<root xmlns='namespace'>\n") self.assertEqual( list(parser.read_events()), [('start-ns', ('', 'namespace'))]) self._feed(parser, "<element key='value'>text</element") self._feed(parser, ">\n") self._feed(parser, "<element>text</element>tail\n") self._feed(parser, "<empty-element/>\n") self._feed(parser, "</root>\n") self.assertEqual(list(parser.read_events()), [('end-ns', Nic)]) self.assertIsNic(parser.close()) def test_events(self): parser = ET.XMLPullParser(events=()) self._feed(parser, "<root/>\n") self.assert_event_tags(parser, []) parser = ET.XMLPullParser(events=('start', 'end')) self._feed(parser, "<!-- comment -->\n") self.assert_event_tags(parser, []) self._feed(parser, "<root>\n") self.assert_event_tags(parser, [('start', 'root')]) self._feed(parser, "<element key='value'>text</element") self.assert_event_tags(parser, [('start', 'element')]) self._feed(parser, ">\n") self.assert_event_tags(parser, [('end', 'element')]) self._feed(parser, "<element xmlns='foo'>text<empty-element/></element>tail\n") self.assert_event_tags(parser, [ ('start', '{foo}element'), ('start', '{foo}empty-element'), ('end', '{foo}empty-element'), ('end', '{foo}element'), ]) self._feed(parser, "</root>") self.assertIsNic(parser.close()) self.assert_event_tags(parser, [('end', 'root')]) parser = ET.XMLPullParser(events=('start',)) self._feed(parser, "<!-- comment -->\n") self.assert_event_tags(parser, []) self._feed(parser, "<root>\n") self.assert_event_tags(parser, [('start', 'root')]) self._feed(parser, "<element key='value'>text</element") self.assert_event_tags(parser, [('start', 'element')]) self._feed(parser, ">\n") self.assert_event_tags(parser, []) self._feed(parser, "<element xmlns='foo'>text<empty-element/></element>tail\n") self.assert_event_tags(parser, [ ('start', '{foo}element'), ('start', '{foo}empty-element'), ]) self._feed(parser, "</root>") self.assertIsNic(parser.close()) def test_events_sequence(self): eventset = {'end', 'start'} parser = ET.XMLPullParser(events=eventset) self._feed(parser, "<foo>bar</foo>") self.assert_event_tags(parser, [('start', 'foo'), ('end', 'foo')]) klasa DummyIter: def __init__(self): self.events = iter(['start', 'end', 'start-ns']) def __iter__(self): zwróć self def __next__(self): zwróć next(self.events) parser = ET.XMLPullParser(events=DummyIter()) self._feed(parser, "<foo>bar</foo>") self.assert_event_tags(parser, [('start', 'foo'), ('end', 'foo')]) def test_unknown_event(self): przy self.assertRaises(ValueError): ET.XMLPullParser(events=('start', 'end', 'bogus')) # # xinclude tests (samples z appendix C of the xinclude specification) XINCLUDE = {} XINCLUDE["C1.xml"] = """\ <?xml version='1.0'?> <document xmlns:xi="http://www.w3.org/2001/XInclude"> <p>120 Mz jest adequate dla an average home user.</p> <xi:include href="disclaimer.xml"/> </document> """ XINCLUDE["disclaimer.xml"] = """\ <?xml version='1.0'?> <disclaimer> <p>The opinions represented herein represent those of the individual oraz should nie be interpreted jako official policy endorsed by this organization.</p> </disclaimer> """ XINCLUDE["C2.xml"] = """\ <?xml version='1.0'?> <document xmlns:xi="http://www.w3.org/2001/XInclude"> <p>This document has been accessed <xi:include href="count.txt" parse="text"/> times.</p> </document> """ XINCLUDE["count.txt"] = "324387" XINCLUDE["C2b.xml"] = """\ <?xml version='1.0'?> <document xmlns:xi="http://www.w3.org/2001/XInclude"> <p>This document has been <em>accessed</em> <xi:include href="count.txt" parse="text"/> times.</p> </document> """ XINCLUDE["C3.xml"] = """\ <?xml version='1.0'?> <document xmlns:xi="http://www.w3.org/2001/XInclude"> <p>The following jest the source of the "data.xml" resource:</p> <example><xi:include href="data.xml" parse="text"/></example> </document> """ XINCLUDE["data.xml"] = """\ <?xml version='1.0'?> <data> <item><![CDATA[Brooks & Shields]]></item> </data> """ XINCLUDE["C5.xml"] = """\ <?xml version='1.0'?> <div xmlns:xi="http://www.w3.org/2001/XInclude"> <xi:include href="example.txt" parse="text"> <xi:fallback> <xi:include href="fallback-example.txt" parse="text"> <xi:fallback><a href="mailto:bob@example.org">Report error</a></xi:fallback> </xi:include> </xi:fallback> </xi:include> </div> """ XINCLUDE["default.xml"] = """\ <?xml version='1.0'?> <document xmlns:xi="http://www.w3.org/2001/XInclude"> <p>Example.</p> <xi:include href="{}"/> </document> """.format(html.escape(SIMPLE_XMLFILE, Prawda)) # # badly formatted xi:include tags XINCLUDE_BAD = {} XINCLUDE_BAD["B1.xml"] = """\ <?xml version='1.0'?> <document xmlns:xi="http://www.w3.org/2001/XInclude"> <p>120 Mz jest adequate dla an average home user.</p> <xi:include href="disclaimer.xml" parse="BAD_TYPE"/> </document> """ XINCLUDE_BAD["B2.xml"] = """\ <?xml version='1.0'?> <div xmlns:xi="http://www.w3.org/2001/XInclude"> <xi:fallback></xi:fallback> </div> """ klasa XIncludeTest(unittest.TestCase): def xinclude_loader(self, href, parse="xml", encoding=Nic): spróbuj: data = XINCLUDE[href] wyjąwszy KeyError: podnieś OSError("resource nie found") jeżeli parse == "xml": data = ET.XML(data) zwróć data def none_loader(self, href, parser, encoding=Nic): zwróć Nic def _my_loader(self, href, parse): # Used to avoid a test-dependency problem where the default loader # of ElementInclude uses the pyET parser dla cET tests. jeżeli parse == 'xml': przy open(href, 'rb') jako f: zwróć ET.parse(f).getroot() inaczej: zwróć Nic def test_xinclude_default(self): z xml.etree zaimportuj ElementInclude doc = self.xinclude_loader('default.xml') ElementInclude.include(doc, self._my_loader) self.assertEqual(serialize(doc), '<document>\n' ' <p>Example.</p>\n' ' <root>\n' ' <element key="value">text</element>\n' ' <element>text</element>tail\n' ' <empty-element />\n' '</root>\n' '</document>') def test_xinclude(self): z xml.etree zaimportuj ElementInclude # Basic inclusion example (XInclude C.1) document = self.xinclude_loader("C1.xml") ElementInclude.include(document, self.xinclude_loader) self.assertEqual(serialize(document), '<document>\n' ' <p>120 Mz jest adequate dla an average home user.</p>\n' ' <disclaimer>\n' ' <p>The opinions represented herein represent those of the individual\n' ' oraz should nie be interpreted jako official policy endorsed by this\n' ' organization.</p>\n' '</disclaimer>\n' '</document>') # C1 # Textual inclusion example (XInclude C.2) document = self.xinclude_loader("C2.xml") ElementInclude.include(document, self.xinclude_loader) self.assertEqual(serialize(document), '<document>\n' ' <p>This document has been accessed\n' ' 324387 times.</p>\n' '</document>') # C2 # Textual inclusion after sibling element (based on modified XInclude C.2) document = self.xinclude_loader("C2b.xml") ElementInclude.include(document, self.xinclude_loader) self.assertEqual(serialize(document), '<document>\n' ' <p>This document has been <em>accessed</em>\n' ' 324387 times.</p>\n' '</document>') # C2b # Textual inclusion of XML example (XInclude C.3) document = self.xinclude_loader("C3.xml") ElementInclude.include(document, self.xinclude_loader) self.assertEqual(serialize(document), '<document>\n' ' <p>The following jest the source of the "data.xml" resource:</p>\n' " <example>&lt;?xml version='1.0'?&gt;\n" '&lt;data&gt;\n' ' &lt;item&gt;&lt;![CDATA[Brooks &amp; Shields]]&gt;&lt;/item&gt;\n' '&lt;/data&gt;\n' '</example>\n' '</document>') # C3 # Fallback example (XInclude C.5) # Note! Fallback support jest nie yet implemented document = self.xinclude_loader("C5.xml") przy self.assertRaises(OSError) jako cm: ElementInclude.include(document, self.xinclude_loader) self.assertEqual(str(cm.exception), 'resource nie found') self.assertEqual(serialize(document), '<div xmlns:ns0="http://www.w3.org/2001/XInclude">\n' ' <ns0:include href="example.txt" parse="text">\n' ' <ns0:fallback>\n' ' <ns0:include href="fallback-example.txt" parse="text">\n' ' <ns0:fallback><a href="mailto:bob@example.org">Report error</a></ns0:fallback>\n' ' </ns0:include>\n' ' </ns0:fallback>\n' ' </ns0:include>\n' '</div>') # C5 def test_xinclude_failures(self): z xml.etree zaimportuj ElementInclude # Test failure to locate included XML file. document = ET.XML(XINCLUDE["C1.xml"]) przy self.assertRaises(ElementInclude.FatalIncludeError) jako cm: ElementInclude.include(document, loader=self.none_loader) self.assertEqual(str(cm.exception), "cannot load 'disclaimer.xml' jako 'xml'") # Test failure to locate included text file. document = ET.XML(XINCLUDE["C2.xml"]) przy self.assertRaises(ElementInclude.FatalIncludeError) jako cm: ElementInclude.include(document, loader=self.none_loader) self.assertEqual(str(cm.exception), "cannot load 'count.txt' jako 'text'") # Test bad parse type. document = ET.XML(XINCLUDE_BAD["B1.xml"]) przy self.assertRaises(ElementInclude.FatalIncludeError) jako cm: ElementInclude.include(document, loader=self.none_loader) self.assertEqual(str(cm.exception), "unknown parse type w xi:include tag ('BAD_TYPE')") # Test xi:fallback outside xi:include. document = ET.XML(XINCLUDE_BAD["B2.xml"]) przy self.assertRaises(ElementInclude.FatalIncludeError) jako cm: ElementInclude.include(document, loader=self.none_loader) self.assertEqual(str(cm.exception), "xi:fallback tag must be child of xi:include " "('{http://www.w3.org/2001/XInclude}fallback')") # -------------------------------------------------------------------- # reported bugs klasa BugsTest(unittest.TestCase): def test_bug_xmltoolkit21(self): # marshaller gives obscure errors dla non-string values def check(elem): przy self.assertRaises(TypeError) jako cm: serialize(elem) self.assertEqual(str(cm.exception), 'cannot serialize 123 (type int)') elem = ET.Element(123) check(elem) # tag elem = ET.Element("elem") elem.text = 123 check(elem) # text elem = ET.Element("elem") elem.tail = 123 check(elem) # tail elem = ET.Element("elem") elem.set(123, "123") check(elem) # attribute key elem = ET.Element("elem") elem.set("123", 123) check(elem) # attribute value def test_bug_xmltoolkit25(self): # typo w ElementTree.findtext elem = ET.XML(SAMPLE_XML) tree = ET.ElementTree(elem) self.assertEqual(tree.findtext("tag"), 'text') self.assertEqual(tree.findtext("section/tag"), 'subtext') def test_bug_xmltoolkit28(self): # .//tag causes exceptions tree = ET.XML("<doc><table><tbody/></table></doc>") self.assertEqual(summarize_list(tree.findall(".//thead")), []) self.assertEqual(summarize_list(tree.findall(".//tbody")), ['tbody']) def test_bug_xmltoolkitX1(self): # dump() doesn't flush the output buffer tree = ET.XML("<doc><table><tbody/></table></doc>") przy support.captured_stdout() jako stdout: ET.dump(tree) self.assertEqual(stdout.getvalue(), '<doc><table><tbody /></table></doc>\n') def test_bug_xmltoolkit39(self): tree = ET.XML(b"<?xml version='1.0' encoding='iso-8859-1'?><t\xe4g />") self.assertEqual(ET.tostring(tree, "utf-8"), b'<t\xc3\xa4g />') tree = ET.XML(b"<?xml version='1.0' encoding='iso-8859-1'?>" b"<tag \xe4ttr='v&#228;lue' />") self.assertEqual(tree.attrib, {'\xe4ttr': 'v\xe4lue'}) self.assertEqual(ET.tostring(tree, "utf-8"), b'<tag \xc3\xa4ttr="v\xc3\xa4lue" />') tree = ET.XML(b"<?xml version='1.0' encoding='iso-8859-1'?>" b'<t\xe4g>text</t\xe4g>') self.assertEqual(ET.tostring(tree, "utf-8"), b'<t\xc3\xa4g>text</t\xc3\xa4g>') tree = ET.Element("t\u00e4g") self.assertEqual(ET.tostring(tree, "utf-8"), b'<t\xc3\xa4g />') tree = ET.Element("tag") tree.set("\u00e4ttr", "v\u00e4lue") self.assertEqual(ET.tostring(tree, "utf-8"), b'<tag \xc3\xa4ttr="v\xc3\xa4lue" />') def test_bug_xmltoolkit54(self): # problems handling internally defined entities e = ET.XML("<!DOCTYPE doc [<!ENTITY ldots '&#x8230;'>]>" '<doc>&ldots;</doc>') self.assertEqual(serialize(e, encoding="us-ascii"), b'<doc>& self.assertEqual(serialize(e), '<doc>\u8230</doc>') def test_bug_xmltoolkit55(self): # make sure we're reporting the first error, nie the last przy self.assertRaises(ET.ParseError) jako cm: ET.XML(b"<!DOCTYPE doc SYSTEM 'doc.dtd'>" b'<doc>&ldots;&ndots;&rdots;</doc>') self.assertEqual(str(cm.exception), 'undefined entity &ldots;: line 1, column 36') def test_bug_xmltoolkit60(self): klasa ExceptionFile: def read(self, x): podnieś OSError self.assertRaises(OSError, ET.parse, ExceptionFile()) def test_bug_xmltoolkit62(self): ENTITIES = {'rsquo': '\u2019', 'lsquo': '\u2018'} parser = ET.XMLParser() parser.entity.update(ENTITIES) parser.feed("""<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE patent-application-publication SYSTEM "pap-v15-2001-01-31.dtd" []> <patent-application-publication> <subdoc-abstract> <paragraph id="A-0001" lvl="0">A new cultivar of Begonia plant named &lsquo;BCT9801BEG&rsquo;.</paragraph> </subdoc-abstract> </patent-application-publication>""") t = parser.close() self.assertEqual(t.find('.//paragraph').text, 'A new cultivar of Begonia plant named \u2018BCT9801BEG\u2019.') def test_bug_xmltoolkit63(self): # Check reference leak. def xmltoolkit63(): tree = ET.TreeBuilder() tree.start("tag", {}) tree.data("text") tree.end("tag") xmltoolkit63() count = sys.getrefcount(Nic) dla i w range(1000): xmltoolkit63() self.assertEqual(sys.getrefcount(Nic), count) def test_bug_200708_newline(self): # Preserve newlines w attributes. e = ET.Element('SomeTag', text="def _f():\n zwróć 3\n") self.assertEqual(ET.tostring(e), b'<SomeTag text="def _f():&#10; zwróć 3&#10;" />') self.assertEqual(ET.XML(ET.tostring(e)).get("text"), 'def _f():\n zwróć 3\n') self.assertEqual(ET.tostring(ET.XML(ET.tostring(e))), b'<SomeTag text="def _f():&#10; zwróć 3&#10;" />') def test_bug_200708_close(self): # Test default builder. parser = ET.XMLParser() # default parser.feed("<element>some text</element>") self.assertEqual(parser.close().tag, 'element') # Test custom builder. klasa EchoTarget: def close(self): zwróć ET.Element("element") # simulate root parser = ET.XMLParser(EchoTarget()) parser.feed("<element>some text</element>") self.assertEqual(parser.close().tag, 'element') def test_bug_200709_default_namespace(self): e = ET.Element("{default}elem") s = ET.SubElement(e, "{default}elem") self.assertEqual(serialize(e, default_namespace="default"), # 1 '<elem xmlns="default"><elem /></elem>') e = ET.Element("{default}elem") s = ET.SubElement(e, "{default}elem") s = ET.SubElement(e, "{not-default}elem") self.assertEqual(serialize(e, default_namespace="default"), # 2 '<elem xmlns="default" xmlns:ns1="not-default">' '<elem />' '<ns1:elem />' '</elem>') e = ET.Element("{default}elem") s = ET.SubElement(e, "{default}elem") s = ET.SubElement(e, "elem") # unprefixed name przy self.assertRaises(ValueError) jako cm: serialize(e, default_namespace="default") # 3 self.assertEqual(str(cm.exception), 'cannot use non-qualified names przy default_namespace option') def test_bug_200709_register_namespace(self): e = ET.Element("{http://namespace.invalid/does/not/exist/}title") self.assertEqual(ET.tostring(e), b'<ns0:title xmlns:ns0="http://namespace.invalid/does/not/exist/" />') ET.register_namespace("foo", "http://namespace.invalid/does/not/exist/") e = ET.Element("{http://namespace.invalid/does/not/exist/}title") self.assertEqual(ET.tostring(e), b'<foo:title xmlns:foo="http://namespace.invalid/does/not/exist/" />') # And the Dublin Core namespace jest w the default list: e = ET.Element("{http://purl.org/dc/elements/1.1/}title") self.assertEqual(ET.tostring(e), b'<dc:title xmlns:dc="http://purl.org/dc/elements/1.1/" />') def test_bug_200709_element_comment(self): # Not sure jeżeli this can be fixed, really (since the serializer needs # ET.Comment, nie cET.comment). a = ET.Element('a') a.append(ET.Comment('foo')) self.assertEqual(a[0].tag, ET.Comment) a = ET.Element('a') a.append(ET.PI('foo')) self.assertEqual(a[0].tag, ET.PI) def test_bug_200709_element_insert(self): a = ET.Element('a') b = ET.SubElement(a, 'b') c = ET.SubElement(a, 'c') d = ET.Element('d') a.insert(0, d) self.assertEqual(summarize_list(a), ['d', 'b', 'c']) a.insert(-1, d) self.assertEqual(summarize_list(a), ['d', 'b', 'd', 'c']) def test_bug_200709_iter_comment(self): a = ET.Element('a') b = ET.SubElement(a, 'b') comment_b = ET.Comment("TEST-b") b.append(comment_b) self.assertEqual(summarize_list(a.iter(ET.Comment)), [ET.Comment]) # -------------------------------------------------------------------- # reported on bugs.python.org def test_bug_1534630(self): bob = ET.TreeBuilder() e = bob.data("data") e = bob.start("tag", {}) e = bob.end("tag") e = bob.close() self.assertEqual(serialize(e), '<tag />') def test_issue6233(self): e = ET.XML(b"<?xml version='1.0' encoding='utf-8'?>" b'<body>t\xc3\xa3g</body>') self.assertEqual(ET.tostring(e, 'ascii'), b"<?xml version='1.0' encoding='ascii'?>\n" b'<body>t& e = ET.XML(b"<?xml version='1.0' encoding='iso-8859-1'?>" b'<body>t\xe3g</body>') self.assertEqual(ET.tostring(e, 'ascii'), b"<?xml version='1.0' encoding='ascii'?>\n" b'<body>t& def test_issue3151(self): e = ET.XML('<prefix:localname xmlns:prefix="${stuff}"/>') self.assertEqual(e.tag, '{${stuff}}localname') t = ET.ElementTree(e) self.assertEqual(ET.tostring(e), b'<ns0:localname xmlns:ns0="${stuff}" />') def test_issue6565(self): elem = ET.XML("<body><tag/></body>") self.assertEqual(summarize_list(elem), ['tag']) newelem = ET.XML(SAMPLE_XML) elem[:] = newelem[:] self.assertEqual(summarize_list(elem), ['tag', 'tag', 'section']) def test_issue10777(self): # Registering a namespace twice caused a "dictionary changed size during # iteration" bug. ET.register_namespace('test10777', 'http://myuri/') ET.register_namespace('test10777', 'http://myuri/') # -------------------------------------------------------------------- klasa BasicElementTest(ElementTestCase, unittest.TestCase): def test_augmentation_type_errors(self): e = ET.Element('joe') self.assertRaises(TypeError, e.append, 'b') self.assertRaises(TypeError, e.extend, [ET.Element('bar'), 'foo']) self.assertRaises(TypeError, e.insert, 0, 'foo') def test_cyclic_gc(self): klasa Dummy: dalej # Test the shortest cycle: d->element->d d = Dummy() d.dummyref = ET.Element('joe', attr=d) wref = weakref.ref(d) usuń d gc_collect() self.assertIsNic(wref()) # A longer cycle: d->e->e2->d e = ET.Element('joe') d = Dummy() d.dummyref = e wref = weakref.ref(d) e2 = ET.SubElement(e, 'foo', attr=d) usuń d, e, e2 gc_collect() self.assertIsNic(wref()) # A cycle between Element objects jako children of one another # e1->e2->e3->e1 e1 = ET.Element('e1') e2 = ET.Element('e2') e3 = ET.Element('e3') e1.append(e2) e2.append(e2) e3.append(e1) wref = weakref.ref(e1) usuń e1, e2, e3 gc_collect() self.assertIsNic(wref()) def test_weakref(self): flag = Nieprawda def wref_cb(w): nonlocal flag flag = Prawda e = ET.Element('e') wref = weakref.ref(e, wref_cb) self.assertEqual(wref().tag, 'e') usuń e self.assertEqual(flag, Prawda) self.assertEqual(wref(), Nic) def test_get_keyword_args(self): e1 = ET.Element('foo' , x=1, y=2, z=3) self.assertEqual(e1.get('x', default=7), 1) self.assertEqual(e1.get('w', default=7), 7) def test_pickle(self): # issue #16076: the C implementation wasn't pickleable. dla proto w range(2, pickle.HIGHEST_PROTOCOL + 1): dla dumper, loader w product(self.modules, repeat=2): e = dumper.Element('foo', bar=42) e.text = "text goes here" e.tail = "opposite of head" dumper.SubElement(e, 'child').append(dumper.Element('grandchild')) e.append(dumper.Element('child')) e.findall('.//grandchild')[0].set('attr', 'other value') e2 = self.pickleRoundTrip(e, 'xml.etree.ElementTree', dumper, loader, proto) self.assertEqual(e2.tag, 'foo') self.assertEqual(e2.attrib['bar'], 42) self.assertEqual(len(e2), 2) self.assertEqualElements(e, e2) def test_pickle_issue18997(self): dla proto w range(2, pickle.HIGHEST_PROTOCOL + 1): dla dumper, loader w product(self.modules, repeat=2): XMLTEXT = """<?xml version="1.0"?> <group><dogs>4</dogs> </group>""" e1 = dumper.fromstring(XMLTEXT) jeżeli hasattr(e1, '__getstate__'): self.assertEqual(e1.__getstate__()['tag'], 'group') e2 = self.pickleRoundTrip(e1, 'xml.etree.ElementTree', dumper, loader, proto) self.assertEqual(e2.tag, 'group') self.assertEqual(e2[0].tag, 'dogs') klasa BadElementTest(ElementTestCase, unittest.TestCase): def test_extend_mutable_list(self): klasa X: @property def __class__(self): L[:] = [ET.Element('baz')] zwróć ET.Element L = [X()] e = ET.Element('foo') spróbuj: e.extend(L) wyjąwszy TypeError: dalej klasa Y(X, ET.Element): dalej L = [Y('x')] e = ET.Element('foo') e.extend(L) def test_extend_mutable_list2(self): klasa X: @property def __class__(self): usuń L[:] zwróć ET.Element L = [X(), ET.Element('baz')] e = ET.Element('foo') spróbuj: e.extend(L) wyjąwszy TypeError: dalej klasa Y(X, ET.Element): dalej L = [Y('bar'), ET.Element('baz')] e = ET.Element('foo') e.extend(L) def test_remove_with_mutating(self): klasa X(ET.Element): def __eq__(self, o): usuń e[:] zwróć Nieprawda e = ET.Element('foo') e.extend([X('bar')]) self.assertRaises(ValueError, e.remove, ET.Element('baz')) e = ET.Element('foo') e.extend([ET.Element('bar')]) self.assertRaises(ValueError, e.remove, X('baz')) klasa MutatingElementPath(str): def __new__(cls, elem, *args): self = str.__new__(cls, *args) self.elem = elem zwróć self def __eq__(self, o): usuń self.elem[:] zwróć Prawda MutatingElementPath.__hash__ = str.__hash__ klasa BadElementPath(str): def __eq__(self, o): podnieś 1/0 BadElementPath.__hash__ = str.__hash__ klasa BadElementPathTest(ElementTestCase, unittest.TestCase): def setUp(self): super().setUp() z xml.etree zaimportuj ElementPath self.path_cache = ElementPath._cache ElementPath._cache = {} def tearDown(self): z xml.etree zaimportuj ElementPath ElementPath._cache = self.path_cache super().tearDown() def test_find_with_mutating(self): e = ET.Element('foo') e.extend([ET.Element('bar')]) e.find(MutatingElementPath(e, 'x')) def test_find_with_error(self): e = ET.Element('foo') e.extend([ET.Element('bar')]) spróbuj: e.find(BadElementPath('x')) wyjąwszy ZeroDivisionError: dalej def test_findtext_with_mutating(self): e = ET.Element('foo') e.extend([ET.Element('bar')]) e.findtext(MutatingElementPath(e, 'x')) def test_findtext_with_error(self): e = ET.Element('foo') e.extend([ET.Element('bar')]) spróbuj: e.findtext(BadElementPath('x')) wyjąwszy ZeroDivisionError: dalej def test_findall_with_mutating(self): e = ET.Element('foo') e.extend([ET.Element('bar')]) e.findall(MutatingElementPath(e, 'x')) def test_findall_with_error(self): e = ET.Element('foo') e.extend([ET.Element('bar')]) spróbuj: e.findall(BadElementPath('x')) wyjąwszy ZeroDivisionError: dalej klasa ElementTreeTypeTest(unittest.TestCase): def test_istype(self): self.assertIsInstance(ET.ParseError, type) self.assertIsInstance(ET.QName, type) self.assertIsInstance(ET.ElementTree, type) self.assertIsInstance(ET.Element, type) self.assertIsInstance(ET.TreeBuilder, type) self.assertIsInstance(ET.XMLParser, type) def test_Element_subclass_trivial(self): klasa MyElement(ET.Element): dalej mye = MyElement('foo') self.assertIsInstance(mye, ET.Element) self.assertIsInstance(mye, MyElement) self.assertEqual(mye.tag, 'foo') mye.text = "joe" self.assertEqual(mye.text, "joe") def test_Element_subclass_constructor(self): klasa MyElement(ET.Element): def __init__(self, tag, attrib={}, **extra): super(MyElement, self).__init__(tag + '__', attrib, **extra) mye = MyElement('foo', {'a': 1, 'b': 2}, c=3, d=4) self.assertEqual(mye.tag, 'foo__') self.assertEqual(sorted(mye.items()), [('a', 1), ('b', 2), ('c', 3), ('d', 4)]) def test_Element_subclass_new_method(self): klasa MyElement(ET.Element): def newmethod(self): zwróć self.tag mye = MyElement('joe') self.assertEqual(mye.newmethod(), 'joe') klasa ElementFindTest(unittest.TestCase): def test_find_simple(self): e = ET.XML(SAMPLE_XML) self.assertEqual(e.find('tag').tag, 'tag') self.assertEqual(e.find('section/tag').tag, 'tag') self.assertEqual(e.find('./tag').tag, 'tag') e[2] = ET.XML(SAMPLE_SECTION) self.assertEqual(e.find('section/nexttag').tag, 'nexttag') self.assertEqual(e.findtext('./tag'), 'text') self.assertEqual(e.findtext('section/tag'), 'subtext') self.assertEqual(e.findtext('section/nexttag'), '') self.assertEqual(e.findtext('section/nexttag', 'default'), '') self.assertIsNic(e.findtext('tog')) self.assertEqual(e.findtext('tog', 'default'), 'default') # Issue #16922 self.assertEqual(ET.XML('<tag><empty /></tag>').findtext('empty'), '') def test_find_xpath(self): LINEAR_XML = ''' <body> <tag class='a'/> <tag class='b'/> <tag class='c'/> <tag class='d'/> </body>''' e = ET.XML(LINEAR_XML) # Test dla numeric indexing oraz last() self.assertEqual(e.find('./tag[1]').attrib['class'], 'a') self.assertEqual(e.find('./tag[2]').attrib['class'], 'b') self.assertEqual(e.find('./tag[last()]').attrib['class'], 'd') self.assertEqual(e.find('./tag[last()-1]').attrib['class'], 'c') self.assertEqual(e.find('./tag[last()-2]').attrib['class'], 'b') self.assertRaisesRegex(SyntaxError, 'XPath', e.find, './tag[0]') self.assertRaisesRegex(SyntaxError, 'XPath', e.find, './tag[-1]') self.assertRaisesRegex(SyntaxError, 'XPath', e.find, './tag[last()-0]') self.assertRaisesRegex(SyntaxError, 'XPath', e.find, './tag[last()+1]') def test_findall(self): e = ET.XML(SAMPLE_XML) e[2] = ET.XML(SAMPLE_SECTION) self.assertEqual(summarize_list(e.findall('.')), ['body']) self.assertEqual(summarize_list(e.findall('tag')), ['tag', 'tag']) self.assertEqual(summarize_list(e.findall('tog')), []) self.assertEqual(summarize_list(e.findall('tog/foo')), []) self.assertEqual(summarize_list(e.findall('*')), ['tag', 'tag', 'section']) self.assertEqual(summarize_list(e.findall('.//tag')), ['tag'] * 4) self.assertEqual(summarize_list(e.findall('section/tag')), ['tag']) self.assertEqual(summarize_list(e.findall('section//tag')), ['tag'] * 2) self.assertEqual(summarize_list(e.findall('section/*')), ['tag', 'nexttag', 'nextsection']) self.assertEqual(summarize_list(e.findall('section//*')), ['tag', 'nexttag', 'nextsection', 'tag']) self.assertEqual(summarize_list(e.findall('section/.//*')), ['tag', 'nexttag', 'nextsection', 'tag']) self.assertEqual(summarize_list(e.findall('*/*')), ['tag', 'nexttag', 'nextsection']) self.assertEqual(summarize_list(e.findall('*//*')), ['tag', 'nexttag', 'nextsection', 'tag']) self.assertEqual(summarize_list(e.findall('*/tag')), ['tag']) self.assertEqual(summarize_list(e.findall('*/./tag')), ['tag']) self.assertEqual(summarize_list(e.findall('./tag')), ['tag'] * 2) self.assertEqual(summarize_list(e.findall('././tag')), ['tag'] * 2) self.assertEqual(summarize_list(e.findall('.//tag[@class]')), ['tag'] * 3) self.assertEqual(summarize_list(e.findall('.//tag[@class="a"]')), ['tag']) self.assertEqual(summarize_list(e.findall('.//tag[@class="b"]')), ['tag'] * 2) self.assertEqual(summarize_list(e.findall('.//tag[@id]')), ['tag']) self.assertEqual(summarize_list(e.findall('.//section[tag]')), ['section']) self.assertEqual(summarize_list(e.findall('.//section[element]')), []) self.assertEqual(summarize_list(e.findall('../tag')), []) self.assertEqual(summarize_list(e.findall('section/../tag')), ['tag'] * 2) self.assertEqual(e.findall('section//'), e.findall('section//*')) def test_test_find_with_ns(self): e = ET.XML(SAMPLE_XML_NS) self.assertEqual(summarize_list(e.findall('tag')), []) self.assertEqual( summarize_list(e.findall("{http://effbot.org/ns}tag")), ['{http://effbot.org/ns}tag'] * 2) self.assertEqual( summarize_list(e.findall(".//{http://effbot.org/ns}tag")), ['{http://effbot.org/ns}tag'] * 3) def test_findall_different_nsmaps(self): root = ET.XML(''' <a xmlns:x="X" xmlns:y="Y"> <x:b><c/></x:b> <b/> <c><x:b/><b/></c><y:b/> </a>''') nsmap = {'xx': 'X'} self.assertEqual(len(root.findall(".//xx:b", namespaces=nsmap)), 2) self.assertEqual(len(root.findall(".//b", namespaces=nsmap)), 2) nsmap = {'xx': 'Y'} self.assertEqual(len(root.findall(".//xx:b", namespaces=nsmap)), 1) self.assertEqual(len(root.findall(".//b", namespaces=nsmap)), 2) def test_bad_find(self): e = ET.XML(SAMPLE_XML) przy self.assertRaisesRegex(SyntaxError, 'cannot use absolute path'): e.findall('/tag') def test_find_through_ElementTree(self): e = ET.XML(SAMPLE_XML) self.assertEqual(ET.ElementTree(e).find('tag').tag, 'tag') self.assertEqual(ET.ElementTree(e).findtext('tag'), 'text') self.assertEqual(summarize_list(ET.ElementTree(e).findall('tag')), ['tag'] * 2) # this produces a warning self.assertEqual(summarize_list(ET.ElementTree(e).findall('//tag')), ['tag'] * 3) klasa ElementIterTest(unittest.TestCase): def _ilist(self, elem, tag=Nic): zwróć summarize_list(elem.iter(tag)) def test_basic(self): doc = ET.XML("<html><body>this jest a <i>paragraph</i>.</body>..</html>") self.assertEqual(self._ilist(doc), ['html', 'body', 'i']) self.assertEqual(self._ilist(doc.find('body')), ['body', 'i']) self.assertEqual(next(doc.iter()).tag, 'html') self.assertEqual(''.join(doc.itertext()), 'this jest a paragraph...') self.assertEqual(''.join(doc.find('body').itertext()), 'this jest a paragraph.') self.assertEqual(next(doc.itertext()), 'this jest a ') # iterparse should zwróć an iterator sourcefile = serialize(doc, to_string=Nieprawda) self.assertEqual(next(ET.iterparse(sourcefile))[0], 'end') # With an explitit parser too (issue #9708) sourcefile = serialize(doc, to_string=Nieprawda) parser = ET.XMLParser(target=ET.TreeBuilder()) self.assertEqual(next(ET.iterparse(sourcefile, parser=parser))[0], 'end') tree = ET.ElementTree(Nic) self.assertRaises(AttributeError, tree.iter) # Issue #16913 doc = ET.XML("<root>a&amp;<sub>b&amp;</sub>c&amp;</root>") self.assertEqual(''.join(doc.itertext()), 'a&b&c&') def test_corners(self): # single root, no subelements a = ET.Element('a') self.assertEqual(self._ilist(a), ['a']) # one child b = ET.SubElement(a, 'b') self.assertEqual(self._ilist(a), ['a', 'b']) # one child oraz one grandchild c = ET.SubElement(b, 'c') self.assertEqual(self._ilist(a), ['a', 'b', 'c']) # two children, only first przy grandchild d = ET.SubElement(a, 'd') self.assertEqual(self._ilist(a), ['a', 'b', 'c', 'd']) # replace first child by second a[0] = a[1] usuń a[1] self.assertEqual(self._ilist(a), ['a', 'd']) def test_iter_by_tag(self): doc = ET.XML(''' <document> <house> <room>bedroom1</room> <room>bedroom2</room> </house> <shed>nothing here </shed> <house> <room>bedroom8</room> </house> </document>''') self.assertEqual(self._ilist(doc, 'room'), ['room'] * 3) self.assertEqual(self._ilist(doc, 'house'), ['house'] * 2) # test that iter also accepts 'tag' jako a keyword arg self.assertEqual( summarize_list(doc.iter(tag='room')), ['room'] * 3) # make sure both tag=Nic oraz tag='*' zwróć all tags all_tags = ['document', 'house', 'room', 'room', 'shed', 'house', 'room'] self.assertEqual(self._ilist(doc), all_tags) self.assertEqual(self._ilist(doc, '*'), all_tags) klasa TreeBuilderTest(unittest.TestCase): sample1 = ('<!DOCTYPE html PUBLIC' ' "-//W3C//DTD XHTML 1.0 Transitional//EN"' ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' '<html>text<div>subtext</div>tail</html>') sample2 = '''<toplevel>sometext</toplevel>''' def _check_sample1_element(self, e): self.assertEqual(e.tag, 'html') self.assertEqual(e.text, 'text') self.assertEqual(e.tail, Nic) self.assertEqual(e.attrib, {}) children = list(e) self.assertEqual(len(children), 1) child = children[0] self.assertEqual(child.tag, 'div') self.assertEqual(child.text, 'subtext') self.assertEqual(child.tail, 'tail') self.assertEqual(child.attrib, {}) def test_dummy_builder(self): klasa BaseDummyBuilder: def close(self): zwróć 42 klasa DummyBuilder(BaseDummyBuilder): data = start = end = lambda *a: Nic parser = ET.XMLParser(target=DummyBuilder()) parser.feed(self.sample1) self.assertEqual(parser.close(), 42) parser = ET.XMLParser(target=BaseDummyBuilder()) parser.feed(self.sample1) self.assertEqual(parser.close(), 42) parser = ET.XMLParser(target=object()) parser.feed(self.sample1) self.assertIsNic(parser.close()) def test_treebuilder_elementfactory_none(self): parser = ET.XMLParser(target=ET.TreeBuilder(element_factory=Nic)) parser.feed(self.sample1) e = parser.close() self._check_sample1_element(e) def test_subclass(self): klasa MyTreeBuilder(ET.TreeBuilder): def foobar(self, x): zwróć x * 2 tb = MyTreeBuilder() self.assertEqual(tb.foobar(10), 20) parser = ET.XMLParser(target=tb) parser.feed(self.sample1) e = parser.close() self._check_sample1_element(e) def test_element_factory(self): lst = [] def myfactory(tag, attrib): nonlocal lst lst.append(tag) zwróć ET.Element(tag, attrib) tb = ET.TreeBuilder(element_factory=myfactory) parser = ET.XMLParser(target=tb) parser.feed(self.sample2) parser.close() self.assertEqual(lst, ['toplevel']) def _check_element_factory_class(self, cls): tb = ET.TreeBuilder(element_factory=cls) parser = ET.XMLParser(target=tb) parser.feed(self.sample1) e = parser.close() self.assertIsInstance(e, cls) self._check_sample1_element(e) def test_element_factory_subclass(self): klasa MyElement(ET.Element): dalej self._check_element_factory_class(MyElement) def test_element_factory_pure_python_subclass(self): # Mimick SimpleTAL's behaviour (issue base = ET._Element_Py self.assertEqual(base.__module__, 'xml.etree.ElementTree') klasa MyElement(base, ValueError): dalej self._check_element_factory_class(MyElement) def test_doctype(self): klasa DoctypeParser: _doctype = Nic def doctype(self, name, pubid, system): self._doctype = (name, pubid, system) def close(self): zwróć self._doctype parser = ET.XMLParser(target=DoctypeParser()) parser.feed(self.sample1) self.assertEqual(parser.close(), ('html', '-//W3C//DTD XHTML 1.0 Transitional//EN', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd')) klasa XMLParserTest(unittest.TestCase): sample1 = b'<file><line>22</line></file>' sample2 = (b'<!DOCTYPE html PUBLIC' b' "-//W3C//DTD XHTML 1.0 Transitional//EN"' b' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' b'<html>text</html>') sample3 = ('<?xml version="1.0" encoding="iso-8859-1"?>\n' '<money value="$\xa3\u20ac\U0001017b">$\xa3\u20ac\U0001017b</money>') def _check_sample_element(self, e): self.assertEqual(e.tag, 'file') self.assertEqual(e[0].tag, 'line') self.assertEqual(e[0].text, '22') def test_constructor_args(self): parser = ET.XMLParser(Nic, ET.TreeBuilder(), 'utf-8') parser.feed(self.sample1) self._check_sample_element(parser.close()) parser2 = ET.XMLParser(encoding='utf-8', html=[{}], target=ET.TreeBuilder()) parser2.feed(self.sample1) self._check_sample_element(parser2.close()) def test_subclass(self): klasa MyParser(ET.XMLParser): dalej parser = MyParser() parser.feed(self.sample1) self._check_sample_element(parser.close()) def test_doctype_warning(self): parser = ET.XMLParser() przy self.assertWarns(DeprecationWarning): parser.doctype('html', '-//W3C//DTD XHTML 1.0 Transitional//EN', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd') parser.feed('<html/>') parser.close() przy warnings.catch_warnings(): warnings.simplefilter('error', DeprecationWarning) parser = ET.XMLParser() parser.feed(self.sample2) parser.close() def test_subclass_doctype(self): _doctype = Nic klasa MyParserWithDoctype(ET.XMLParser): def doctype(self, name, pubid, system): nonlocal _doctype _doctype = (name, pubid, system) parser = MyParserWithDoctype() przy self.assertWarns(DeprecationWarning): parser.feed(self.sample2) parser.close() self.assertEqual(_doctype, ('html', '-//W3C//DTD XHTML 1.0 Transitional//EN', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd')) _doctype = _doctype2 = Nic przy warnings.catch_warnings(): warnings.simplefilter('error', DeprecationWarning) klasa DoctypeParser: def doctype(self, name, pubid, system): nonlocal _doctype2 _doctype2 = (name, pubid, system) parser = MyParserWithDoctype(target=DoctypeParser()) parser.feed(self.sample2) parser.close() self.assertIsNic(_doctype) self.assertEqual(_doctype2, ('html', '-//W3C//DTD XHTML 1.0 Transitional//EN', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd')) def test_inherited_doctype(self): '''Ensure that ordinary usage jest nie deprecated (Issue 19176)''' przy warnings.catch_warnings(): warnings.simplefilter('error', DeprecationWarning) klasa MyParserWithoutDoctype(ET.XMLParser): dalej parser = MyParserWithoutDoctype() parser.feed(self.sample2) parser.close() def test_parse_string(self): parser = ET.XMLParser(target=ET.TreeBuilder()) parser.feed(self.sample3) e = parser.close() self.assertEqual(e.tag, 'money') self.assertEqual(e.attrib['value'], '$\xa3\u20ac\U0001017b') self.assertEqual(e.text, '$\xa3\u20ac\U0001017b') klasa NamespaceParseTest(unittest.TestCase): def test_find_with_namespace(self): nsmap = {'h': 'hello', 'f': 'foo'} doc = ET.fromstring(SAMPLE_XML_NS_ELEMS) self.assertEqual(len(doc.findall('{hello}table', nsmap)), 1) self.assertEqual(len(doc.findall('.//{hello}td', nsmap)), 2) self.assertEqual(len(doc.findall('.//{foo}name', nsmap)), 1) klasa ElementSlicingTest(unittest.TestCase): def _elem_tags(self, elemlist): zwróć [e.tag dla e w elemlist] def _subelem_tags(self, elem): zwróć self._elem_tags(list(elem)) def _make_elem_with_children(self, numchildren): """Create an Element przy a tag 'a', przy the given amount of children named 'a0', 'a1' ... oraz so on. """ e = ET.Element('a') dla i w range(numchildren): ET.SubElement(e, 'a%s' % i) zwróć e def test_getslice_single_index(self): e = self._make_elem_with_children(10) self.assertEqual(e[1].tag, 'a1') self.assertEqual(e[-2].tag, 'a8') self.assertRaises(IndexError, lambda: e[12]) def test_getslice_range(self): e = self._make_elem_with_children(6) self.assertEqual(self._elem_tags(e[3:]), ['a3', 'a4', 'a5']) self.assertEqual(self._elem_tags(e[3:6]), ['a3', 'a4', 'a5']) self.assertEqual(self._elem_tags(e[3:16]), ['a3', 'a4', 'a5']) self.assertEqual(self._elem_tags(e[3:5]), ['a3', 'a4']) self.assertEqual(self._elem_tags(e[3:-1]), ['a3', 'a4']) self.assertEqual(self._elem_tags(e[:2]), ['a0', 'a1']) def test_getslice_steps(self): e = self._make_elem_with_children(10) self.assertEqual(self._elem_tags(e[8:10:1]), ['a8', 'a9']) self.assertEqual(self._elem_tags(e[::3]), ['a0', 'a3', 'a6', 'a9']) self.assertEqual(self._elem_tags(e[::8]), ['a0', 'a8']) self.assertEqual(self._elem_tags(e[1::8]), ['a1', 'a9']) def test_getslice_negative_steps(self): e = self._make_elem_with_children(4) self.assertEqual(self._elem_tags(e[::-1]), ['a3', 'a2', 'a1', 'a0']) self.assertEqual(self._elem_tags(e[::-2]), ['a3', 'a1']) def test_delslice(self): e = self._make_elem_with_children(4) usuń e[0:2] self.assertEqual(self._subelem_tags(e), ['a2', 'a3']) e = self._make_elem_with_children(4) usuń e[0:] self.assertEqual(self._subelem_tags(e), []) e = self._make_elem_with_children(4) usuń e[::-1] self.assertEqual(self._subelem_tags(e), []) e = self._make_elem_with_children(4) usuń e[::-2] self.assertEqual(self._subelem_tags(e), ['a0', 'a2']) e = self._make_elem_with_children(4) usuń e[1::2] self.assertEqual(self._subelem_tags(e), ['a0', 'a2']) e = self._make_elem_with_children(2) usuń e[::2] self.assertEqual(self._subelem_tags(e), ['a1']) klasa IOTest(unittest.TestCase): def tearDown(self): support.unlink(TESTFN) def test_encoding(self): elem = ET.Element("tag") elem.text = "abc" self.assertEqual(serialize(elem), '<tag>abc</tag>') self.assertEqual(serialize(elem, encoding="utf-8"), b'<tag>abc</tag>') self.assertEqual(serialize(elem, encoding="us-ascii"), b'<tag>abc</tag>') dla enc w ("iso-8859-1", "utf-16", "utf-32"): self.assertEqual(serialize(elem, encoding=enc), ("<?xml version='1.0' encoding='%s'?>\n" "<tag>abc</tag>" % enc).encode(enc)) elem = ET.Element("tag") elem.text = "<&\"\'>" self.assertEqual(serialize(elem), '<tag>&lt;&amp;"\'&gt;</tag>') self.assertEqual(serialize(elem, encoding="utf-8"), b'<tag>&lt;&amp;"\'&gt;</tag>') self.assertEqual(serialize(elem, encoding="us-ascii"), b'<tag>&lt;&amp;"\'&gt;</tag>') dla enc w ("iso-8859-1", "utf-16", "utf-32"): self.assertEqual(serialize(elem, encoding=enc), ("<?xml version='1.0' encoding='%s'?>\n" "<tag>&lt;&amp;\"'&gt;</tag>" % enc).encode(enc)) elem = ET.Element("tag") elem.attrib["key"] = "<&\"\'>" self.assertEqual(serialize(elem), '<tag key="&lt;&amp;&quot;\'&gt;" />') self.assertEqual(serialize(elem, encoding="utf-8"), b'<tag key="&lt;&amp;&quot;\'&gt;" />') self.assertEqual(serialize(elem, encoding="us-ascii"), b'<tag key="&lt;&amp;&quot;\'&gt;" />') dla enc w ("iso-8859-1", "utf-16", "utf-32"): self.assertEqual(serialize(elem, encoding=enc), ("<?xml version='1.0' encoding='%s'?>\n" "<tag key=\"&lt;&amp;&quot;'&gt;\" />" % enc).encode(enc)) elem = ET.Element("tag") elem.text = '\xe5\xf6\xf6<>' self.assertEqual(serialize(elem), '<tag>\xe5\xf6\xf6&lt;&gt;</tag>') self.assertEqual(serialize(elem, encoding="utf-8"), b'<tag>\xc3\xa5\xc3\xb6\xc3\xb6&lt;&gt;</tag>') self.assertEqual(serialize(elem, encoding="us-ascii"), b'<tag>&#229;&#246;&#246;&lt;&gt;</tag>') dla enc w ("iso-8859-1", "utf-16", "utf-32"): self.assertEqual(serialize(elem, encoding=enc), ("<?xml version='1.0' encoding='%s'?>\n" "<tag>åöö&lt;&gt;</tag>" % enc).encode(enc)) elem = ET.Element("tag") elem.attrib["key"] = '\xe5\xf6\xf6<>' self.assertEqual(serialize(elem), '<tag key="\xe5\xf6\xf6&lt;&gt;" />') self.assertEqual(serialize(elem, encoding="utf-8"), b'<tag key="\xc3\xa5\xc3\xb6\xc3\xb6&lt;&gt;" />') self.assertEqual(serialize(elem, encoding="us-ascii"), b'<tag key="&#229;&#246;&#246;&lt;&gt;" />') dla enc w ("iso-8859-1", "utf-16", "utf-16le", "utf-16be", "utf-32"): self.assertEqual(serialize(elem, encoding=enc), ("<?xml version='1.0' encoding='%s'?>\n" "<tag key=\"åöö&lt;&gt;\" />" % enc).encode(enc)) def test_write_to_filename(self): tree = ET.ElementTree(ET.XML('''<site />''')) tree.write(TESTFN) przy open(TESTFN, 'rb') jako f: self.assertEqual(f.read(), b'''<site />''') def test_write_to_text_file(self): tree = ET.ElementTree(ET.XML('''<site />''')) przy open(TESTFN, 'w', encoding='utf-8') jako f: tree.write(f, encoding='unicode') self.assertNieprawda(f.closed) przy open(TESTFN, 'rb') jako f: self.assertEqual(f.read(), b'''<site />''') def test_write_to_binary_file(self): tree = ET.ElementTree(ET.XML('''<site />''')) przy open(TESTFN, 'wb') jako f: tree.write(f) self.assertNieprawda(f.closed) przy open(TESTFN, 'rb') jako f: self.assertEqual(f.read(), b'''<site />''') def test_write_to_binary_file_with_bom(self): tree = ET.ElementTree(ET.XML('''<site />''')) przy open(TESTFN, 'wb') jako f: tree.write(f, encoding='utf-16') self.assertNieprawda(f.closed) przy open(TESTFN, 'rb') jako f: self.assertEqual(f.read(), '''<?xml version='1.0' encoding='utf-16'?>\n''' '''<site />'''.encode("utf-16")) przy open(TESTFN, 'wb', buffering=0) jako f: tree.write(f, encoding='utf-16') self.assertNieprawda(f.closed) przy open(TESTFN, 'rb') jako f: self.assertEqual(f.read(), '''<?xml version='1.0' encoding='utf-16'?>\n''' '''<site />'''.encode("utf-16")) def test_read_from_stringio(self): tree = ET.ElementTree() stream = io.StringIO('''<?xml version="1.0"?><site></site>''') tree.parse(stream) self.assertEqual(tree.getroot().tag, 'site') def test_write_to_stringio(self): tree = ET.ElementTree(ET.XML('''<site />''')) stream = io.StringIO() tree.write(stream, encoding='unicode') self.assertEqual(stream.getvalue(), '''<site />''') def test_read_from_bytesio(self): tree = ET.ElementTree() raw = io.BytesIO(b'''<?xml version="1.0"?><site></site>''') tree.parse(raw) self.assertEqual(tree.getroot().tag, 'site') def test_write_to_bytesio(self): tree = ET.ElementTree(ET.XML('''<site />''')) raw = io.BytesIO() tree.write(raw) self.assertEqual(raw.getvalue(), b'''<site />''') klasa dummy: dalej def test_read_from_user_text_reader(self): stream = io.StringIO('''<?xml version="1.0"?><site></site>''') reader = self.dummy() reader.read = stream.read tree = ET.ElementTree() tree.parse(reader) self.assertEqual(tree.getroot().tag, 'site') def test_write_to_user_text_writer(self): tree = ET.ElementTree(ET.XML('''<site />''')) stream = io.StringIO() writer = self.dummy() writer.write = stream.write tree.write(writer, encoding='unicode') self.assertEqual(stream.getvalue(), '''<site />''') def test_read_from_user_binary_reader(self): raw = io.BytesIO(b'''<?xml version="1.0"?><site></site>''') reader = self.dummy() reader.read = raw.read tree = ET.ElementTree() tree.parse(reader) self.assertEqual(tree.getroot().tag, 'site') tree = ET.ElementTree() def test_write_to_user_binary_writer(self): tree = ET.ElementTree(ET.XML('''<site />''')) raw = io.BytesIO() writer = self.dummy() writer.write = raw.write tree.write(writer) self.assertEqual(raw.getvalue(), b'''<site />''') def test_write_to_user_binary_writer_with_bom(self): tree = ET.ElementTree(ET.XML('''<site />''')) raw = io.BytesIO() writer = self.dummy() writer.write = raw.write writer.seekable = lambda: Prawda writer.tell = raw.tell tree.write(writer, encoding="utf-16") self.assertEqual(raw.getvalue(), '''<?xml version='1.0' encoding='utf-16'?>\n''' '''<site />'''.encode("utf-16")) def test_tostringlist_invariant(self): root = ET.fromstring('<tag>foo</tag>') self.assertEqual( ET.tostring(root, 'unicode'), ''.join(ET.tostringlist(root, 'unicode'))) self.assertEqual( ET.tostring(root, 'utf-16'), b''.join(ET.tostringlist(root, 'utf-16'))) def test_short_empty_elements(self): root = ET.fromstring('<tag>a<x />b<y></y>c</tag>') self.assertEqual( ET.tostring(root, 'unicode'), '<tag>a<x />b<y />c</tag>') self.assertEqual( ET.tostring(root, 'unicode', short_empty_elements=Prawda), '<tag>a<x />b<y />c</tag>') self.assertEqual( ET.tostring(root, 'unicode', short_empty_elements=Nieprawda), '<tag>a<x></x>b<y></y>c</tag>') klasa ParseErrorTest(unittest.TestCase): def test_subclass(self): self.assertIsInstance(ET.ParseError(), SyntaxError) def _get_error(self, s): spróbuj: ET.fromstring(s) wyjąwszy ET.ParseError jako e: zwróć e def test_error_position(self): self.assertEqual(self._get_error('foo').position, (1, 0)) self.assertEqual(self._get_error('<tag>&foo;</tag>').position, (1, 5)) self.assertEqual(self._get_error('foobar<').position, (1, 6)) def test_error_code(self): zaimportuj xml.parsers.expat.errors jako ERRORS self.assertEqual(self._get_error('foo').code, ERRORS.codes[ERRORS.XML_ERROR_SYNTAX]) klasa KeywordArgsTest(unittest.TestCase): def test_issue14818(self): x = ET.XML("<a>foo</a>") self.assertEqual(x.find('a', Nic), x.find(path='a', namespaces=Nic)) self.assertEqual(x.findtext('a', Nic, Nic), x.findtext(path='a', default=Nic, namespaces=Nic)) self.assertEqual(x.findall('a', Nic), x.findall(path='a', namespaces=Nic)) self.assertEqual(list(x.iterfind('a', Nic)), list(x.iterfind(path='a', namespaces=Nic))) self.assertEqual(ET.Element('a').attrib, {}) elements = [ ET.Element('a', dict(href="#", id="foo")), ET.Element('a', attrib=dict(href="#", id="foo")), ET.Element('a', dict(href="#"), id="foo"), ET.Element('a', href="#", id="foo"), ET.Element('a', dict(href="#", id="foo"), href="#", id="foo"), ] dla e w elements: self.assertEqual(e.tag, 'a') self.assertEqual(e.attrib, dict(href="#", id="foo")) e2 = ET.SubElement(elements[0], 'foobar', attrib={'key1': 'value1'}) self.assertEqual(e2.attrib['key1'], 'value1') przy self.assertRaisesRegex(TypeError, 'must be dict, nie str'): ET.Element('a', "I'm nie a dict") przy self.assertRaisesRegex(TypeError, 'must be dict, nie str'): ET.Element('a', attrib="I'm nie a dict") klasa NoAcceleratorTest(unittest.TestCase): def setUp(self): jeżeli nie pyET: podnieś unittest.SkipTest('only dla the Python version') def test_correct_import_pyET(self): self.assertIsInstance(pyET.Element.__init__, types.FunctionType) self.assertIsInstance(pyET.XMLParser.__init__, types.FunctionType) klasa CleanContext(object): """Provide default namespace mapping oraz path cache.""" checkwarnings = Nic def __init__(self, quiet=Nieprawda): jeżeli sys.flags.optimize >= 2: quiet = Prawda deprecations = ( ("This search jest broken w 1.3 oraz earlier, oraz will be fixed " "in a future version. If you rely on the current behaviour, " "change it to '.+'", FutureWarning), ("This method will be removed w future versions. " "Use .+ instead.", DeprecationWarning), ("This method will be removed w future versions. " "Use .+ instead.", PendingDeprecationWarning)) self.checkwarnings = support.check_warnings(*deprecations, quiet=quiet) def __enter__(self): z xml.etree zaimportuj ElementPath self._nsmap = ET.register_namespace._namespace_map self._nsmap_copy = self._nsmap.copy() self._path_cache = ElementPath._cache ElementPath._cache = self._path_cache.copy() self.checkwarnings.__enter__() def __exit__(self, *args): z xml.etree zaimportuj ElementPath self._nsmap.clear() self._nsmap.update(self._nsmap_copy) ElementPath._cache = self._path_cache self.checkwarnings.__exit__(*args) def test_main(module=Nic): global pyET pyET = import_fresh_module('xml.etree.ElementTree', blocked=['_elementtree']) jeżeli module jest Nic: module = pyET global ET ET = module test_classes = [ ModuleTest, ElementSlicingTest, BasicElementTest, BadElementTest, BadElementPathTest, ElementTreeTest, IOTest, ParseErrorTest, XIncludeTest, ElementTreeTypeTest, ElementFindTest, ElementIterTest, TreeBuilderTest, XMLParserTest, XMLPullParserTest, BugsTest, ] # _elementtree. We can't use skipUnless here, because pyET jest filled w only jeżeli pyET jest nie ET: test_classes.extend([ NoAcceleratorTest, ]) spróbuj: przy CleanContext(quiet=(pyET jest nie ET)): support.run_unittest(*test_classes) w_końcu: ET = pyET = Nic jeżeli __name__ == '__main__': test_main()
false
true
f7f9ebacc9154a80a9c3c5665178f39bb3d0fe20
22,958
py
Python
datasets/common_voice/common_voice.py
matt-peters/datasets
b51cb81e736b86103089a584daa6e43db3c88bb5
[ "Apache-2.0" ]
1
2021-03-24T18:33:31.000Z
2021-03-24T18:33:31.000Z
datasets/common_voice/common_voice.py
pcyin/datasets
a03728637e24986bf7d47cd1ebffa6595093a557
[ "Apache-2.0" ]
null
null
null
datasets/common_voice/common_voice.py
pcyin/datasets
a03728637e24986bf7d47cd1ebffa6595093a557
[ "Apache-2.0" ]
1
2021-03-24T18:33:32.000Z
2021-03-24T18:33:32.000Z
# coding=utf-8 # Copyright 2021 The HuggingFace Datasets Authors and the current dataset script contributor. # # 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. """ Common Voice Dataset""" from __future__ import absolute_import, division, print_function import os import datasets _CITATION = """\ @inproceedings{commonvoice:2020, author = {Ardila, R. and Branson, M. and Davis, K. and Henretty, M. and Kohler, M. and Meyer, J. and Morais, R. and Saunders, L. and Tyers, F. M. and Weber, G.}, title = {Common Voice: A Massively-Multilingual Speech Corpus}, booktitle = {Proceedings of the 12th Conference on Language Resources and Evaluation (LREC 2020)}, pages = {4211--4215}, year = 2020 } """ _DESCRIPTION = """\ Common Voice is Mozilla's initiative to help teach machines how real people speak. The dataset currently consists of 7,335 validated hours of speech in 60 languages, but we’re always adding more voices and languages. """ _HOMEPAGE = "https://commonvoice.mozilla.org/en/datasets" _LICENSE = "https://github.com/common-voice/common-voice/blob/main/LICENSE" _LANGUAGES = { "ab": { "Language": "Abkhaz", "Date": "2020-12-11", "Size": "39 MB", "Version": "ab_1h_2020-12-11", "Validated_Hr_Total": 0.05, "Overall_Hr_Total": 1, "Number_Of_Voice": 14, }, "ar": { "Language": "Arabic", "Date": "2020-12-11", "Size": "2 GB", "Version": "ar_77h_2020-12-11", "Validated_Hr_Total": 49, "Overall_Hr_Total": 77, "Number_Of_Voice": 672, }, "as": { "Language": "Assamese", "Date": "2020-12-11", "Size": "21 MB", "Version": "as_0.78h_2020-12-11", "Validated_Hr_Total": 0.74, "Overall_Hr_Total": 0.78, "Number_Of_Voice": 17, }, "br": { "Language": "Breton", "Date": "2020-12-11", "Size": "444 MB", "Version": "br_16h_2020-12-11", "Validated_Hr_Total": 7, "Overall_Hr_Total": 16, "Number_Of_Voice": 157, }, "ca": { "Language": "Catalan", "Date": "2020-12-11", "Size": "19 GB", "Version": "ca_748h_2020-12-11", "Validated_Hr_Total": 623, "Overall_Hr_Total": 748, "Number_Of_Voice": 5376, }, "cnh": { "Language": "Hakha Chin", "Date": "2020-12-11", "Size": "39 MB", "Version": "ab_1h_2020-12-11", "Validated_Hr_Total": 0.05, "Overall_Hr_Total": 1, "Number_Of_Voice": 14, }, "cs": { "Language": "Czech", "Date": "2020-12-11", "Size": "39 MB", "Version": "ab_1h_2020-12-11", "Validated_Hr_Total": 0.05, "Overall_Hr_Total": 1, "Number_Of_Voice": 14, }, "cv": { "Language": "Chuvash", "Date": "2020-12-11", "Size": "419 MB", "Version": "cv_16h_2020-12-11", "Validated_Hr_Total": 4, "Overall_Hr_Total": 16, "Number_Of_Voice": 92, }, "cy": { "Language": "Welsh", "Date": "2020-12-11", "Size": "3 GB", "Version": "cy_124h_2020-12-11", "Validated_Hr_Total": 95, "Overall_Hr_Total": 124, "Number_Of_Voice": 1382, }, "de": { "Language": "German", "Date": "2020-12-11", "Size": "22 GB", "Version": "de_836h_2020-12-11", "Validated_Hr_Total": 777, "Overall_Hr_Total": 836, "Number_Of_Voice": 12659, }, "dv": { "Language": "Dhivehi", "Date": "2020-12-11", "Size": "515 MB", "Version": "dv_19h_2020-12-11", "Validated_Hr_Total": 18, "Overall_Hr_Total": 19, "Number_Of_Voice": 167, }, "el": { "Language": "Greek", "Date": "2020-12-11", "Size": "364 MB", "Version": "el_13h_2020-12-11", "Validated_Hr_Total": 6, "Overall_Hr_Total": 13, "Number_Of_Voice": 118, }, "en": { "Language": "English", "Date": "2020-12-11", "Size": "56 GB", "Version": "en_2181h_2020-12-11", "Validated_Hr_Total": 1686, "Overall_Hr_Total": 2181, "Number_Of_Voice": 66173, }, "eo": { "Language": "Esperanto", "Date": "2020-12-11", "Size": "3 GB", "Version": "eo_102h_2020-12-11", "Validated_Hr_Total": 90, "Overall_Hr_Total": 102, "Number_Of_Voice": 574, }, "es": { "Language": "Spanish", "Date": "2020-12-11", "Size": "15 GB", "Version": "es_579h_2020-12-11", "Validated_Hr_Total": 324, "Overall_Hr_Total": 579, "Number_Of_Voice": 19484, }, "et": { "Language": "Estonian", "Date": "2020-12-11", "Size": "732 MB", "Version": "et_27h_2020-12-11", "Validated_Hr_Total": 19, "Overall_Hr_Total": 27, "Number_Of_Voice": 543, }, "eu": { "Language": "Basque", "Date": "2020-12-11", "Size": "3 GB", "Version": "eu_131h_2020-12-11", "Validated_Hr_Total": 89, "Overall_Hr_Total": 131, "Number_Of_Voice": 1028, }, "fa": { "Language": "Persian", "Date": "2020-12-11", "Size": "8 GB", "Version": "fa_321h_2020-12-11", "Validated_Hr_Total": 282, "Overall_Hr_Total": 321, "Number_Of_Voice": 3655, }, "fi": { "Language": "Finnish", "Date": "2020-12-11", "Size": "48 MB", "Version": "fi_1h_2020-12-11", "Validated_Hr_Total": 1, "Overall_Hr_Total": 1, "Number_Of_Voice": 27, }, "fr": { "Language": "French", "Date": "2020-12-11", "Size": "18 GB", "Version": "fr_682h_2020-12-11", "Validated_Hr_Total": 623, "Overall_Hr_Total": 682, "Number_Of_Voice": 12953, }, "fy-NL": { "Language": "Frisian", "Date": "2020-12-11", "Size": "1 GB", "Version": "fy-NL_46h_2020-12-11", "Validated_Hr_Total": 14, "Overall_Hr_Total": 46, "Number_Of_Voice": 467, }, "ga-IE": { "Language": "Irish", "Date": "2020-12-11", "Size": "149 MB", "Version": "ga-IE_5h_2020-12-11", "Validated_Hr_Total": 3, "Overall_Hr_Total": 5, "Number_Of_Voice": 101, }, "hi": { "Language": "Hindi", "Date": "2020-12-11", "Size": "20 MB", "Version": "hi_0.8h_2020-12-11", "Validated_Hr_Total": 0.54, "Overall_Hr_Total": 0.8, "Number_Of_Voice": 31, }, "hsb": { "Language": "Sorbian, Upper", "Date": "2020-12-11", "Size": "76 MB", "Version": "hsb_2h_2020-12-11", "Validated_Hr_Total": 2, "Overall_Hr_Total": 2, "Number_Of_Voice": 19, }, "hu": { "Language": "Hungarian", "Date": "2020-12-11", "Size": "232 MB", "Version": "hu_8h_2020-12-11", "Validated_Hr_Total": 8, "Overall_Hr_Total": 8, "Number_Of_Voice": 47, }, "ia": { "Language": "InterLinguia", "Date": "2020-12-11", "Size": "216 MB", "Version": "ia_8h_2020-12-11", "Validated_Hr_Total": 6, "Overall_Hr_Total": 8, "Number_Of_Voice": 36, }, "id": { "Language": "Indonesian", "Date": "2020-12-11", "Size": "454 MB", "Version": "id_17h_2020-12-11", "Validated_Hr_Total": 9, "Overall_Hr_Total": 17, "Number_Of_Voice": 219, }, "it": { "Language": "Italian", "Date": "2020-12-11", "Size": "5 GB", "Version": "it_199h_2020-12-11", "Validated_Hr_Total": 158, "Overall_Hr_Total": 199, "Number_Of_Voice": 5729, }, "ja": { "Language": "Japanese", "Date": "2020-12-11", "Size": "146 MB", "Version": "ja_5h_2020-12-11", "Validated_Hr_Total": 3, "Overall_Hr_Total": 5, "Number_Of_Voice": 235, }, "ka": { "Language": "Georgian", "Date": "2020-12-11", "Size": "99 MB", "Version": "ka_3h_2020-12-11", "Validated_Hr_Total": 3, "Overall_Hr_Total": 3, "Number_Of_Voice": 44, }, "kab": { "Language": "Kabyle", "Date": "2020-12-11", "Size": "16 GB", "Version": "kab_622h_2020-12-11", "Validated_Hr_Total": 525, "Overall_Hr_Total": 622, "Number_Of_Voice": 1309, }, "ky": { "Language": "Kyrgyz", "Date": "2020-12-11", "Size": "553 MB", "Version": "ky_22h_2020-12-11", "Validated_Hr_Total": 11, "Overall_Hr_Total": 22, "Number_Of_Voice": 134, }, "lg": { "Language": "Luganda", "Date": "2020-12-11", "Size": "199 MB", "Version": "lg_8h_2020-12-11", "Validated_Hr_Total": 3, "Overall_Hr_Total": 8, "Number_Of_Voice": 76, }, "lt": { "Language": "Lithuanian", "Date": "2020-12-11", "Size": "129 MB", "Version": "lt_4h_2020-12-11", "Validated_Hr_Total": 2, "Overall_Hr_Total": 4, "Number_Of_Voice": 30, }, "lv": { "Language": "Latvian", "Date": "2020-12-11", "Size": "199 MB", "Version": "lv_7h_2020-12-11", "Validated_Hr_Total": 6, "Overall_Hr_Total": 7, "Number_Of_Voice": 99, }, "mn": { "Language": "Mongolian", "Date": "2020-12-11", "Size": "464 MB", "Version": "mn_17h_2020-12-11", "Validated_Hr_Total": 11, "Overall_Hr_Total": 17, "Number_Of_Voice": 376, }, "mt": { "Language": "Maltese", "Date": "2020-12-11", "Size": "405 MB", "Version": "mt_15h_2020-12-11", "Validated_Hr_Total": 7, "Overall_Hr_Total": 15, "Number_Of_Voice": 171, }, "nl": { "Language": "Dutch", "Date": "2020-12-11", "Size": "2 GB", "Version": "nl_63h_2020-12-11", "Validated_Hr_Total": 59, "Overall_Hr_Total": 63, "Number_Of_Voice": 1012, }, "or": { "Language": "Odia", "Date": "2020-12-11", "Size": "190 MB", "Version": "or_7h_2020-12-11", "Validated_Hr_Total": 0.87, "Overall_Hr_Total": 7, "Number_Of_Voice": 34, }, "pa-IN": { "Language": "Punjabi", "Date": "2020-12-11", "Size": "67 MB", "Version": "pa-IN_2h_2020-12-11", "Validated_Hr_Total": 0.5, "Overall_Hr_Total": 2, "Number_Of_Voice": 26, }, "pl": { "Language": "Polish", "Date": "2020-12-11", "Size": "3 GB", "Version": "pl_129h_2020-12-11", "Validated_Hr_Total": 108, "Overall_Hr_Total": 129, "Number_Of_Voice": 2647, }, "pt": { "Language": "Portuguese", "Date": "2020-12-11", "Size": "2 GB", "Version": "pt_63h_2020-12-11", "Validated_Hr_Total": 50, "Overall_Hr_Total": 63, "Number_Of_Voice": 1120, }, "rm-sursilv": { "Language": "Romansh Sursilvan", "Date": "2020-12-11", "Size": "263 MB", "Version": "rm-sursilv_9h_2020-12-11", "Validated_Hr_Total": 5, "Overall_Hr_Total": 9, "Number_Of_Voice": 78, }, "rm-vallader": { "Language": "Romansh Vallader", "Date": "2020-12-11", "Size": "103 MB", "Version": "rm-vallader_3h_2020-12-11", "Validated_Hr_Total": 2, "Overall_Hr_Total": 3, "Number_Of_Voice": 39, }, "ro": { "Language": "Romanian", "Date": "2020-12-11", "Size": "250 MB", "Version": "ro_9h_2020-12-11", "Validated_Hr_Total": 6, "Overall_Hr_Total": 9, "Number_Of_Voice": 130, }, "ru": { "Language": "Russian", "Date": "2020-12-11", "Size": "3 GB", "Version": "ru_130h_2020-12-11", "Validated_Hr_Total": 111, "Overall_Hr_Total": 130, "Number_Of_Voice": 1412, }, "rw": { "Language": "Kinyarwanda", "Date": "2020-12-11", "Size": "40 GB", "Version": "rw_1510h_2020-12-11", "Validated_Hr_Total": 1183, "Overall_Hr_Total": 1510, "Number_Of_Voice": 410, }, "sah": { "Language": "Sakha", "Date": "2020-12-11", "Size": "173 MB", "Version": "sah_6h_2020-12-11", "Validated_Hr_Total": 4, "Overall_Hr_Total": 6, "Number_Of_Voice": 42, }, "sl": { "Language": "Slovenian", "Date": "2020-12-11", "Size": "212 MB", "Version": "sl_7h_2020-12-11", "Validated_Hr_Total": 5, "Overall_Hr_Total": 7, "Number_Of_Voice": 82, }, "sv-SE": { "Language": "Swedish", "Date": "2020-12-11", "Size": "402 MB", "Version": "sv-SE_15h_2020-12-11", "Validated_Hr_Total": 12, "Overall_Hr_Total": 15, "Number_Of_Voice": 222, }, "ta": { "Language": "Tamil", "Date": "2020-12-11", "Size": "648 MB", "Version": "ta_24h_2020-12-11", "Validated_Hr_Total": 14, "Overall_Hr_Total": 24, "Number_Of_Voice": 266, }, "th": { "Language": "Thai", "Date": "2020-12-11", "Size": "325 MB", "Version": "th_12h_2020-12-11", "Validated_Hr_Total": 8, "Overall_Hr_Total": 12, "Number_Of_Voice": 182, }, "tr": { "Language": "Turkish", "Date": "2020-12-11", "Size": "592 MB", "Version": "tr_22h_2020-12-11", "Validated_Hr_Total": 20, "Overall_Hr_Total": 22, "Number_Of_Voice": 678, }, "tt": { "Language": "Tatar", "Date": "2020-12-11", "Size": "741 MB", "Version": "tt_28h_2020-12-11", "Validated_Hr_Total": 26, "Overall_Hr_Total": 28, "Number_Of_Voice": 185, }, "uk": { "Language": "Ukrainian", "Date": "2020-12-11", "Size": "1 GB", "Version": "uk_43h_2020-12-11", "Validated_Hr_Total": 30, "Overall_Hr_Total": 43, "Number_Of_Voice": 459, }, "vi": { "Language": "Vietnamese", "Date": "2020-12-11", "Size": "50 MB", "Version": "vi_1h_2020-12-11", "Validated_Hr_Total": 0.74, "Overall_Hr_Total": 1, "Number_Of_Voice": 62, }, "vot": { "Language": "Votic", "Date": "2020-12-11", "Size": "7 MB", "Version": "vot_0.28h_2020-12-11", "Validated_Hr_Total": 0, "Overall_Hr_Total": 0.28, "Number_Of_Voice": 3, }, "zh-CN": { "Language": "Chinese (China)", "Date": "2020-12-11", "Size": "2 GB", "Version": "zh-CN_78h_2020-12-11", "Validated_Hr_Total": 56, "Overall_Hr_Total": 78, "Number_Of_Voice": 3501, }, "zh-HK": { "Language": "Chinese (Hong Kong)", "Date": "2020-12-11", "Size": "3 GB", "Version": "zh-HK_100h_2020-12-11", "Validated_Hr_Total": 50, "Overall_Hr_Total": 100, "Number_Of_Voice": 2536, }, "zh-TW": { "Language": "Chinese (Taiwan)", "Date": "2020-12-11", "Size": "2 GB", "Version": "zh-TW_78h_2020-12-11", "Validated_Hr_Total": 55, "Overall_Hr_Total": 78, "Number_Of_Voice": 1444, }, } class CommonVoiceConfig(datasets.BuilderConfig): """BuilderConfig for CommonVoice.""" def __init__(self, name, sub_version, **kwargs): """ Args: data_dir: `string`, the path to the folder containing the files in the downloaded .tar citation: `string`, citation for the data set url: `string`, url for information about the data set **kwargs: keyword arguments forwarded to super. """ self.sub_version = sub_version self.language = kwargs.pop("language", None) self.date_of_snapshot = kwargs.pop("date", None) self.size = kwargs.pop("size", None) self.validated_hr_total = kwargs.pop("val_hrs", None) self.total_hr_total = kwargs.pop("total_hrs", None) self.num_of_voice = kwargs.pop("num_of_voice", None) description = f"Common Voice speech to text dataset in {self.language} version {self.sub_version} of {self.date_of_snapshot}. The dataset comprises {self.validated_hr_total} of validated transcribed speech data from {self.num_of_voice} speakers. The dataset has a size of {self.size}" super(CommonVoiceConfig, self).__init__( name=name, version=datasets.Version("6.1.0", ""), description=description, **kwargs ) class CommonVoice(datasets.GeneratorBasedBuilder): """TODO: Short description of my dataset.""" @property def manual_download_instructions(self): return """\ You need to go to https://commonvoice.mozilla.org/en/datasets, and manually download the dataset as a .tar file. Once it is completed, a folder will be made containing the files, validated.tsv, train.tsv, test.tsv, reported.tsv, other.tsv, invalidated.tsv, dev.tsv and the folder clips containing audiofiles sampled at 48khz. Each clip is around 3-4 seconds in duration with a size of around 20-50 khz The downloaded .tar file can be extracted using the `$ tar -xzvf <path/to/downloaded/file>` command. The extracted folder is usually called ``cv-corpus-6.1-2020-12-11`` and should contain a folder named after the language id, *e.g.* `en`. Make sure to pass the ``data_dir`` argument to process the Common Voice dataset. *E.g.*: ``` from datasets import load_dataset # here it is assumed that the folder `cv-corpus-6.1-2020-12-11` has `en` as a subfolder common_voice_ds = load_dataset("common_voice", "en", data_dir="./cv-corpus-6.1-2020-12-11") ``` """ BUILDER_CONFIGS = [ CommonVoiceConfig( name=lang_id, language=_LANGUAGES[lang_id]["Language"], sub_version=_LANGUAGES[lang_id]["Version"], date=_LANGUAGES[lang_id]["Date"], size=_LANGUAGES[lang_id]["Size"], val_hrs=_LANGUAGES[lang_id]["Validated_Hr_Total"], total_hrs=_LANGUAGES[lang_id]["Overall_Hr_Total"], num_of_voice=_LANGUAGES[lang_id]["Number_Of_Voice"], ) for lang_id in _LANGUAGES.keys() ] def _info(self): features = datasets.Features( { "client_id": datasets.Value("string"), "path": datasets.Value("string"), "sentence": datasets.Value("string"), "up_votes": datasets.Value("int64"), "down_votes": datasets.Value("int64"), "age": datasets.Value("string"), "gender": datasets.Value("string"), "accent": datasets.Value("string"), "locale": datasets.Value("string"), "segment": datasets.Value("string"), } ) return datasets.DatasetInfo( description=_DESCRIPTION, features=features, supervised_keys=None, homepage=_HOMEPAGE, license=_LICENSE, citation=_CITATION, ) def _split_generators(self, dl_manager): """Returns SplitGenerators.""" abs_path_to_data = os.path.abspath(os.path.join(dl_manager.manual_dir, self.config.name)) abs_path_to_clips = os.path.join(abs_path_to_data, "clips") return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={ "filepath": os.path.join(abs_path_to_data, "train.tsv"), "path_to_clips": abs_path_to_clips, }, ), datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={ "filepath": os.path.join(abs_path_to_data, "test.tsv"), "path_to_clips": abs_path_to_clips, }, ), datasets.SplitGenerator( name=datasets.Split.VALIDATION, gen_kwargs={ "filepath": os.path.join(abs_path_to_data, "dev.tsv"), "path_to_clips": abs_path_to_clips, }, ), datasets.SplitGenerator( name="other", gen_kwargs={ "filepath": os.path.join(abs_path_to_data, "other.tsv"), "path_to_clips": abs_path_to_clips, }, ), datasets.SplitGenerator( name="invalidated", gen_kwargs={ "filepath": os.path.join(abs_path_to_data, "invalidated.tsv"), "path_to_clips": abs_path_to_clips, }, ), ] def _generate_examples(self, filepath, path_to_clips): """ Yields examples. """ data_fields = list(self._info().features.keys()) path_idx = data_fields.index("path") with open(filepath, encoding="utf-8") as f: lines = f.readlines() headline = lines[0] column_names = headline.strip().split("\t") assert ( column_names == data_fields ), f"The file should have {data_fields} as column names, but has {column_names}" for id_, line in enumerate(lines[1:]): field_values = line.strip().split("\t") # set absolute path for mp3 audio file field_values[path_idx] = os.path.join(path_to_clips, field_values[path_idx]) # if data is incomplete, fill with empty values if len(field_values) < len(data_fields): field_values += (len(data_fields) - len(field_values)) * ["''"] yield id_, {key: value for key, value in zip(data_fields, field_values)}
30.857527
292
0.525612
from __future__ import absolute_import, division, print_function import os import datasets _CITATION = """\ @inproceedings{commonvoice:2020, author = {Ardila, R. and Branson, M. and Davis, K. and Henretty, M. and Kohler, M. and Meyer, J. and Morais, R. and Saunders, L. and Tyers, F. M. and Weber, G.}, title = {Common Voice: A Massively-Multilingual Speech Corpus}, booktitle = {Proceedings of the 12th Conference on Language Resources and Evaluation (LREC 2020)}, pages = {4211--4215}, year = 2020 } """ _DESCRIPTION = """\ Common Voice is Mozilla's initiative to help teach machines how real people speak. The dataset currently consists of 7,335 validated hours of speech in 60 languages, but we’re always adding more voices and languages. """ _HOMEPAGE = "https://commonvoice.mozilla.org/en/datasets" _LICENSE = "https://github.com/common-voice/common-voice/blob/main/LICENSE" _LANGUAGES = { "ab": { "Language": "Abkhaz", "Date": "2020-12-11", "Size": "39 MB", "Version": "ab_1h_2020-12-11", "Validated_Hr_Total": 0.05, "Overall_Hr_Total": 1, "Number_Of_Voice": 14, }, "ar": { "Language": "Arabic", "Date": "2020-12-11", "Size": "2 GB", "Version": "ar_77h_2020-12-11", "Validated_Hr_Total": 49, "Overall_Hr_Total": 77, "Number_Of_Voice": 672, }, "as": { "Language": "Assamese", "Date": "2020-12-11", "Size": "21 MB", "Version": "as_0.78h_2020-12-11", "Validated_Hr_Total": 0.74, "Overall_Hr_Total": 0.78, "Number_Of_Voice": 17, }, "br": { "Language": "Breton", "Date": "2020-12-11", "Size": "444 MB", "Version": "br_16h_2020-12-11", "Validated_Hr_Total": 7, "Overall_Hr_Total": 16, "Number_Of_Voice": 157, }, "ca": { "Language": "Catalan", "Date": "2020-12-11", "Size": "19 GB", "Version": "ca_748h_2020-12-11", "Validated_Hr_Total": 623, "Overall_Hr_Total": 748, "Number_Of_Voice": 5376, }, "cnh": { "Language": "Hakha Chin", "Date": "2020-12-11", "Size": "39 MB", "Version": "ab_1h_2020-12-11", "Validated_Hr_Total": 0.05, "Overall_Hr_Total": 1, "Number_Of_Voice": 14, }, "cs": { "Language": "Czech", "Date": "2020-12-11", "Size": "39 MB", "Version": "ab_1h_2020-12-11", "Validated_Hr_Total": 0.05, "Overall_Hr_Total": 1, "Number_Of_Voice": 14, }, "cv": { "Language": "Chuvash", "Date": "2020-12-11", "Size": "419 MB", "Version": "cv_16h_2020-12-11", "Validated_Hr_Total": 4, "Overall_Hr_Total": 16, "Number_Of_Voice": 92, }, "cy": { "Language": "Welsh", "Date": "2020-12-11", "Size": "3 GB", "Version": "cy_124h_2020-12-11", "Validated_Hr_Total": 95, "Overall_Hr_Total": 124, "Number_Of_Voice": 1382, }, "de": { "Language": "German", "Date": "2020-12-11", "Size": "22 GB", "Version": "de_836h_2020-12-11", "Validated_Hr_Total": 777, "Overall_Hr_Total": 836, "Number_Of_Voice": 12659, }, "dv": { "Language": "Dhivehi", "Date": "2020-12-11", "Size": "515 MB", "Version": "dv_19h_2020-12-11", "Validated_Hr_Total": 18, "Overall_Hr_Total": 19, "Number_Of_Voice": 167, }, "el": { "Language": "Greek", "Date": "2020-12-11", "Size": "364 MB", "Version": "el_13h_2020-12-11", "Validated_Hr_Total": 6, "Overall_Hr_Total": 13, "Number_Of_Voice": 118, }, "en": { "Language": "English", "Date": "2020-12-11", "Size": "56 GB", "Version": "en_2181h_2020-12-11", "Validated_Hr_Total": 1686, "Overall_Hr_Total": 2181, "Number_Of_Voice": 66173, }, "eo": { "Language": "Esperanto", "Date": "2020-12-11", "Size": "3 GB", "Version": "eo_102h_2020-12-11", "Validated_Hr_Total": 90, "Overall_Hr_Total": 102, "Number_Of_Voice": 574, }, "es": { "Language": "Spanish", "Date": "2020-12-11", "Size": "15 GB", "Version": "es_579h_2020-12-11", "Validated_Hr_Total": 324, "Overall_Hr_Total": 579, "Number_Of_Voice": 19484, }, "et": { "Language": "Estonian", "Date": "2020-12-11", "Size": "732 MB", "Version": "et_27h_2020-12-11", "Validated_Hr_Total": 19, "Overall_Hr_Total": 27, "Number_Of_Voice": 543, }, "eu": { "Language": "Basque", "Date": "2020-12-11", "Size": "3 GB", "Version": "eu_131h_2020-12-11", "Validated_Hr_Total": 89, "Overall_Hr_Total": 131, "Number_Of_Voice": 1028, }, "fa": { "Language": "Persian", "Date": "2020-12-11", "Size": "8 GB", "Version": "fa_321h_2020-12-11", "Validated_Hr_Total": 282, "Overall_Hr_Total": 321, "Number_Of_Voice": 3655, }, "fi": { "Language": "Finnish", "Date": "2020-12-11", "Size": "48 MB", "Version": "fi_1h_2020-12-11", "Validated_Hr_Total": 1, "Overall_Hr_Total": 1, "Number_Of_Voice": 27, }, "fr": { "Language": "French", "Date": "2020-12-11", "Size": "18 GB", "Version": "fr_682h_2020-12-11", "Validated_Hr_Total": 623, "Overall_Hr_Total": 682, "Number_Of_Voice": 12953, }, "fy-NL": { "Language": "Frisian", "Date": "2020-12-11", "Size": "1 GB", "Version": "fy-NL_46h_2020-12-11", "Validated_Hr_Total": 14, "Overall_Hr_Total": 46, "Number_Of_Voice": 467, }, "ga-IE": { "Language": "Irish", "Date": "2020-12-11", "Size": "149 MB", "Version": "ga-IE_5h_2020-12-11", "Validated_Hr_Total": 3, "Overall_Hr_Total": 5, "Number_Of_Voice": 101, }, "hi": { "Language": "Hindi", "Date": "2020-12-11", "Size": "20 MB", "Version": "hi_0.8h_2020-12-11", "Validated_Hr_Total": 0.54, "Overall_Hr_Total": 0.8, "Number_Of_Voice": 31, }, "hsb": { "Language": "Sorbian, Upper", "Date": "2020-12-11", "Size": "76 MB", "Version": "hsb_2h_2020-12-11", "Validated_Hr_Total": 2, "Overall_Hr_Total": 2, "Number_Of_Voice": 19, }, "hu": { "Language": "Hungarian", "Date": "2020-12-11", "Size": "232 MB", "Version": "hu_8h_2020-12-11", "Validated_Hr_Total": 8, "Overall_Hr_Total": 8, "Number_Of_Voice": 47, }, "ia": { "Language": "InterLinguia", "Date": "2020-12-11", "Size": "216 MB", "Version": "ia_8h_2020-12-11", "Validated_Hr_Total": 6, "Overall_Hr_Total": 8, "Number_Of_Voice": 36, }, "id": { "Language": "Indonesian", "Date": "2020-12-11", "Size": "454 MB", "Version": "id_17h_2020-12-11", "Validated_Hr_Total": 9, "Overall_Hr_Total": 17, "Number_Of_Voice": 219, }, "it": { "Language": "Italian", "Date": "2020-12-11", "Size": "5 GB", "Version": "it_199h_2020-12-11", "Validated_Hr_Total": 158, "Overall_Hr_Total": 199, "Number_Of_Voice": 5729, }, "ja": { "Language": "Japanese", "Date": "2020-12-11", "Size": "146 MB", "Version": "ja_5h_2020-12-11", "Validated_Hr_Total": 3, "Overall_Hr_Total": 5, "Number_Of_Voice": 235, }, "ka": { "Language": "Georgian", "Date": "2020-12-11", "Size": "99 MB", "Version": "ka_3h_2020-12-11", "Validated_Hr_Total": 3, "Overall_Hr_Total": 3, "Number_Of_Voice": 44, }, "kab": { "Language": "Kabyle", "Date": "2020-12-11", "Size": "16 GB", "Version": "kab_622h_2020-12-11", "Validated_Hr_Total": 525, "Overall_Hr_Total": 622, "Number_Of_Voice": 1309, }, "ky": { "Language": "Kyrgyz", "Date": "2020-12-11", "Size": "553 MB", "Version": "ky_22h_2020-12-11", "Validated_Hr_Total": 11, "Overall_Hr_Total": 22, "Number_Of_Voice": 134, }, "lg": { "Language": "Luganda", "Date": "2020-12-11", "Size": "199 MB", "Version": "lg_8h_2020-12-11", "Validated_Hr_Total": 3, "Overall_Hr_Total": 8, "Number_Of_Voice": 76, }, "lt": { "Language": "Lithuanian", "Date": "2020-12-11", "Size": "129 MB", "Version": "lt_4h_2020-12-11", "Validated_Hr_Total": 2, "Overall_Hr_Total": 4, "Number_Of_Voice": 30, }, "lv": { "Language": "Latvian", "Date": "2020-12-11", "Size": "199 MB", "Version": "lv_7h_2020-12-11", "Validated_Hr_Total": 6, "Overall_Hr_Total": 7, "Number_Of_Voice": 99, }, "mn": { "Language": "Mongolian", "Date": "2020-12-11", "Size": "464 MB", "Version": "mn_17h_2020-12-11", "Validated_Hr_Total": 11, "Overall_Hr_Total": 17, "Number_Of_Voice": 376, }, "mt": { "Language": "Maltese", "Date": "2020-12-11", "Size": "405 MB", "Version": "mt_15h_2020-12-11", "Validated_Hr_Total": 7, "Overall_Hr_Total": 15, "Number_Of_Voice": 171, }, "nl": { "Language": "Dutch", "Date": "2020-12-11", "Size": "2 GB", "Version": "nl_63h_2020-12-11", "Validated_Hr_Total": 59, "Overall_Hr_Total": 63, "Number_Of_Voice": 1012, }, "or": { "Language": "Odia", "Date": "2020-12-11", "Size": "190 MB", "Version": "or_7h_2020-12-11", "Validated_Hr_Total": 0.87, "Overall_Hr_Total": 7, "Number_Of_Voice": 34, }, "pa-IN": { "Language": "Punjabi", "Date": "2020-12-11", "Size": "67 MB", "Version": "pa-IN_2h_2020-12-11", "Validated_Hr_Total": 0.5, "Overall_Hr_Total": 2, "Number_Of_Voice": 26, }, "pl": { "Language": "Polish", "Date": "2020-12-11", "Size": "3 GB", "Version": "pl_129h_2020-12-11", "Validated_Hr_Total": 108, "Overall_Hr_Total": 129, "Number_Of_Voice": 2647, }, "pt": { "Language": "Portuguese", "Date": "2020-12-11", "Size": "2 GB", "Version": "pt_63h_2020-12-11", "Validated_Hr_Total": 50, "Overall_Hr_Total": 63, "Number_Of_Voice": 1120, }, "rm-sursilv": { "Language": "Romansh Sursilvan", "Date": "2020-12-11", "Size": "263 MB", "Version": "rm-sursilv_9h_2020-12-11", "Validated_Hr_Total": 5, "Overall_Hr_Total": 9, "Number_Of_Voice": 78, }, "rm-vallader": { "Language": "Romansh Vallader", "Date": "2020-12-11", "Size": "103 MB", "Version": "rm-vallader_3h_2020-12-11", "Validated_Hr_Total": 2, "Overall_Hr_Total": 3, "Number_Of_Voice": 39, }, "ro": { "Language": "Romanian", "Date": "2020-12-11", "Size": "250 MB", "Version": "ro_9h_2020-12-11", "Validated_Hr_Total": 6, "Overall_Hr_Total": 9, "Number_Of_Voice": 130, }, "ru": { "Language": "Russian", "Date": "2020-12-11", "Size": "3 GB", "Version": "ru_130h_2020-12-11", "Validated_Hr_Total": 111, "Overall_Hr_Total": 130, "Number_Of_Voice": 1412, }, "rw": { "Language": "Kinyarwanda", "Date": "2020-12-11", "Size": "40 GB", "Version": "rw_1510h_2020-12-11", "Validated_Hr_Total": 1183, "Overall_Hr_Total": 1510, "Number_Of_Voice": 410, }, "sah": { "Language": "Sakha", "Date": "2020-12-11", "Size": "173 MB", "Version": "sah_6h_2020-12-11", "Validated_Hr_Total": 4, "Overall_Hr_Total": 6, "Number_Of_Voice": 42, }, "sl": { "Language": "Slovenian", "Date": "2020-12-11", "Size": "212 MB", "Version": "sl_7h_2020-12-11", "Validated_Hr_Total": 5, "Overall_Hr_Total": 7, "Number_Of_Voice": 82, }, "sv-SE": { "Language": "Swedish", "Date": "2020-12-11", "Size": "402 MB", "Version": "sv-SE_15h_2020-12-11", "Validated_Hr_Total": 12, "Overall_Hr_Total": 15, "Number_Of_Voice": 222, }, "ta": { "Language": "Tamil", "Date": "2020-12-11", "Size": "648 MB", "Version": "ta_24h_2020-12-11", "Validated_Hr_Total": 14, "Overall_Hr_Total": 24, "Number_Of_Voice": 266, }, "th": { "Language": "Thai", "Date": "2020-12-11", "Size": "325 MB", "Version": "th_12h_2020-12-11", "Validated_Hr_Total": 8, "Overall_Hr_Total": 12, "Number_Of_Voice": 182, }, "tr": { "Language": "Turkish", "Date": "2020-12-11", "Size": "592 MB", "Version": "tr_22h_2020-12-11", "Validated_Hr_Total": 20, "Overall_Hr_Total": 22, "Number_Of_Voice": 678, }, "tt": { "Language": "Tatar", "Date": "2020-12-11", "Size": "741 MB", "Version": "tt_28h_2020-12-11", "Validated_Hr_Total": 26, "Overall_Hr_Total": 28, "Number_Of_Voice": 185, }, "uk": { "Language": "Ukrainian", "Date": "2020-12-11", "Size": "1 GB", "Version": "uk_43h_2020-12-11", "Validated_Hr_Total": 30, "Overall_Hr_Total": 43, "Number_Of_Voice": 459, }, "vi": { "Language": "Vietnamese", "Date": "2020-12-11", "Size": "50 MB", "Version": "vi_1h_2020-12-11", "Validated_Hr_Total": 0.74, "Overall_Hr_Total": 1, "Number_Of_Voice": 62, }, "vot": { "Language": "Votic", "Date": "2020-12-11", "Size": "7 MB", "Version": "vot_0.28h_2020-12-11", "Validated_Hr_Total": 0, "Overall_Hr_Total": 0.28, "Number_Of_Voice": 3, }, "zh-CN": { "Language": "Chinese (China)", "Date": "2020-12-11", "Size": "2 GB", "Version": "zh-CN_78h_2020-12-11", "Validated_Hr_Total": 56, "Overall_Hr_Total": 78, "Number_Of_Voice": 3501, }, "zh-HK": { "Language": "Chinese (Hong Kong)", "Date": "2020-12-11", "Size": "3 GB", "Version": "zh-HK_100h_2020-12-11", "Validated_Hr_Total": 50, "Overall_Hr_Total": 100, "Number_Of_Voice": 2536, }, "zh-TW": { "Language": "Chinese (Taiwan)", "Date": "2020-12-11", "Size": "2 GB", "Version": "zh-TW_78h_2020-12-11", "Validated_Hr_Total": 55, "Overall_Hr_Total": 78, "Number_Of_Voice": 1444, }, } class CommonVoiceConfig(datasets.BuilderConfig): def __init__(self, name, sub_version, **kwargs): self.sub_version = sub_version self.language = kwargs.pop("language", None) self.date_of_snapshot = kwargs.pop("date", None) self.size = kwargs.pop("size", None) self.validated_hr_total = kwargs.pop("val_hrs", None) self.total_hr_total = kwargs.pop("total_hrs", None) self.num_of_voice = kwargs.pop("num_of_voice", None) description = f"Common Voice speech to text dataset in {self.language} version {self.sub_version} of {self.date_of_snapshot}. The dataset comprises {self.validated_hr_total} of validated transcribed speech data from {self.num_of_voice} speakers. The dataset has a size of {self.size}" super(CommonVoiceConfig, self).__init__( name=name, version=datasets.Version("6.1.0", ""), description=description, **kwargs ) class CommonVoice(datasets.GeneratorBasedBuilder): @property def manual_download_instructions(self): return """\ You need to go to https://commonvoice.mozilla.org/en/datasets, and manually download the dataset as a .tar file. Once it is completed, a folder will be made containing the files, validated.tsv, train.tsv, test.tsv, reported.tsv, other.tsv, invalidated.tsv, dev.tsv and the folder clips containing audiofiles sampled at 48khz. Each clip is around 3-4 seconds in duration with a size of around 20-50 khz The downloaded .tar file can be extracted using the `$ tar -xzvf <path/to/downloaded/file>` command. The extracted folder is usually called ``cv-corpus-6.1-2020-12-11`` and should contain a folder named after the language id, *e.g.* `en`. Make sure to pass the ``data_dir`` argument to process the Common Voice dataset. *E.g.*: ``` from datasets import load_dataset # here it is assumed that the folder `cv-corpus-6.1-2020-12-11` has `en` as a subfolder common_voice_ds = load_dataset("common_voice", "en", data_dir="./cv-corpus-6.1-2020-12-11") ``` """ BUILDER_CONFIGS = [ CommonVoiceConfig( name=lang_id, language=_LANGUAGES[lang_id]["Language"], sub_version=_LANGUAGES[lang_id]["Version"], date=_LANGUAGES[lang_id]["Date"], size=_LANGUAGES[lang_id]["Size"], val_hrs=_LANGUAGES[lang_id]["Validated_Hr_Total"], total_hrs=_LANGUAGES[lang_id]["Overall_Hr_Total"], num_of_voice=_LANGUAGES[lang_id]["Number_Of_Voice"], ) for lang_id in _LANGUAGES.keys() ] def _info(self): features = datasets.Features( { "client_id": datasets.Value("string"), "path": datasets.Value("string"), "sentence": datasets.Value("string"), "up_votes": datasets.Value("int64"), "down_votes": datasets.Value("int64"), "age": datasets.Value("string"), "gender": datasets.Value("string"), "accent": datasets.Value("string"), "locale": datasets.Value("string"), "segment": datasets.Value("string"), } ) return datasets.DatasetInfo( description=_DESCRIPTION, features=features, supervised_keys=None, homepage=_HOMEPAGE, license=_LICENSE, citation=_CITATION, ) def _split_generators(self, dl_manager): abs_path_to_data = os.path.abspath(os.path.join(dl_manager.manual_dir, self.config.name)) abs_path_to_clips = os.path.join(abs_path_to_data, "clips") return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={ "filepath": os.path.join(abs_path_to_data, "train.tsv"), "path_to_clips": abs_path_to_clips, }, ), datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={ "filepath": os.path.join(abs_path_to_data, "test.tsv"), "path_to_clips": abs_path_to_clips, }, ), datasets.SplitGenerator( name=datasets.Split.VALIDATION, gen_kwargs={ "filepath": os.path.join(abs_path_to_data, "dev.tsv"), "path_to_clips": abs_path_to_clips, }, ), datasets.SplitGenerator( name="other", gen_kwargs={ "filepath": os.path.join(abs_path_to_data, "other.tsv"), "path_to_clips": abs_path_to_clips, }, ), datasets.SplitGenerator( name="invalidated", gen_kwargs={ "filepath": os.path.join(abs_path_to_data, "invalidated.tsv"), "path_to_clips": abs_path_to_clips, }, ), ] def _generate_examples(self, filepath, path_to_clips): data_fields = list(self._info().features.keys()) path_idx = data_fields.index("path") with open(filepath, encoding="utf-8") as f: lines = f.readlines() headline = lines[0] column_names = headline.strip().split("\t") assert ( column_names == data_fields ), f"The file should have {data_fields} as column names, but has {column_names}" for id_, line in enumerate(lines[1:]): field_values = line.strip().split("\t") # set absolute path for mp3 audio file field_values[path_idx] = os.path.join(path_to_clips, field_values[path_idx]) # if data is incomplete, fill with empty values if len(field_values) < len(data_fields): field_values += (len(data_fields) - len(field_values)) * ["''"] yield id_, {key: value for key, value in zip(data_fields, field_values)}
true
true
f7f9ec21c49e250c7256ce11431cab3ff27d95c8
7,288
py
Python
example_cases/1D_sodshocktube/input.py
ComputationalFlowPhysics/MFC-develop
901bff8d9e9d7519613cfcacc7a5463ab6295181
[ "MIT" ]
3
2021-05-20T23:42:47.000Z
2021-11-17T21:34:14.000Z
example_cases/1D_sodshocktube/input.py
ComputationalFlowPhysics/MFC-develop
901bff8d9e9d7519613cfcacc7a5463ab6295181
[ "MIT" ]
28
2021-11-02T00:40:40.000Z
2021-12-06T02:38:57.000Z
example_cases/1D_sodshocktube/input.py
ComputationalFlowPhysics/MFC-develop
901bff8d9e9d7519613cfcacc7a5463ab6295181
[ "MIT" ]
9
2021-10-02T04:37:25.000Z
2021-11-23T00:58:11.000Z
#!/usr/bin/env python3 import math #Numerical setup Nx = 399 dx = 1./(1.*(Nx+1)) Tend = 0.1 Nt = 1000 mydt = Tend/(1.*Nt) # Command to navigate between directories from os import chdir # Command to acquire directory path from os.path import dirname # Command to acquire script name and module search path from sys import argv, path # Navigating to script directory if len(dirname(argv[0])) != 0: chdir(dirname(argv[0])) # Adding master_scripts directory to module search path mfc_dir = '../../src'; path[:0] = [mfc_dir + '/master_scripts'] # Command to execute the MFC components from m_python_proxy import f_execute_mfc_component # Serial or parallel computational engine engine = 'serial' # ============================================================================== # Case Analysis Configuration ================================================== # Selecting MFC component comp_name = argv[1].strip() # Configuring case dictionary case_dict = \ { \ # Logistics ================================================ 'case_dir' : '\'.\'', \ 'run_time_info' : 'T', \ 'nodes' : 1, \ 'ppn' : 1, \ 'queue' : 'normal', \ 'walltime' : '24:00:00', \ 'mail_list' : '', \ # ========================================================== \ # Computational Domain Parameters ========================== 'x_domain%beg' : 0.E+00, \ 'x_domain%end' : 1.E+00, \ 'm' : Nx, \ 'n' : 0, \ 'p' : 0, \ 'dt' : mydt, \ 't_step_start' : 0, \ 't_step_stop' : int(Nt), \ 't_step_save' : int(math.ceil(Nt/10.)), \ # ========================================================== \ # Simulation Algorithm Parameters ========================== 'num_patches' : 2, \ 'model_eqns' : 2, \ 'alt_soundspeed' : 'F', \ 'num_fluids' : 1, \ 'adv_alphan' : 'T', \ 'mpp_lim' : 'F', \ 'mixture_err' : 'F', \ 'time_stepper' : 3, \ 'weno_vars' : 2, \ 'weno_order' : 5, \ 'weno_eps' : 1.E-16, \ 'char_decomp' : 'F', \ 'mapped_weno' : 'T', \ 'null_weights' : 'F', \ 'mp_weno' : 'F', \ 'riemann_solver' : 2, \ 'wave_speeds' : 1, \ 'avg_state' : 2, \ 'commute_err' : 'F', \ 'split_err' : 'F', \ 'bc_x%beg' : -3, \ 'bc_x%end' : -3, \ # ========================================================== \ # Formatted Database Files Structure Parameters ============ 'format' : 1, \ 'precision' : 2, \ 'prim_vars_wrt' :'T', \ 'parallel_io' :'F', \ # ========================================================== # Patch 1 L ================================================ 'patch_icpp(1)%geometry' : 1, \ 'patch_icpp(1)%x_centroid' : 0.25, \ 'patch_icpp(1)%length_x' : 0.5, \ 'patch_icpp(1)%vel(1)' : 0.0, \ 'patch_icpp(1)%pres' : 1.0, \ 'patch_icpp(1)%alpha_rho(1)' : 1.E+00, \ 'patch_icpp(1)%alpha(1)' : 1., \ # ========================================================== # Patch 2 R ================================================ 'patch_icpp(2)%geometry' : 1, \ 'patch_icpp(2)%x_centroid' : 0.75, \ 'patch_icpp(2)%length_x' : 0.5, \ 'patch_icpp(2)%vel(1)' : 0.0, \ 'patch_icpp(2)%pres' : 0.1, \ 'patch_icpp(2)%alpha_rho(1)' : 0.125E+00, \ 'patch_icpp(2)%alpha(1)' : 1., \ # ========================================================== # Fluids Physical Parameters =============================== 'fluid_pp(1)%gamma' : 1.E+00/(1.4-1.E+00), \ 'fluid_pp(1)%pi_inf' : 0.0, \ # ========================================================== } # Executing MFC component f_execute_mfc_component(comp_name, case_dict, mfc_dir, engine) # ==============================================================================
57.385827
86
0.221872
import math Nx = 399 dx = 1./(1.*(Nx+1)) Tend = 0.1 Nt = 1000 mydt = Tend/(1.*Nt) from os import chdir from os.path import dirname from sys import argv, path if len(dirname(argv[0])) != 0: chdir(dirname(argv[0])) mfc_dir = '../../src'; path[:0] = [mfc_dir + '/master_scripts'] from m_python_proxy import f_execute_mfc_component engine = 'serial' comp_name = argv[1].strip() case_dict = \ { \ 'case_dir' : '\'.\'', \ 'run_time_info' : 'T', \ 'nodes' : 1, \ 'ppn' : 1, \ 'queue' : 'normal', \ 'walltime' : '24:00:00', \ 'mail_list' : '', \ \ 'x_domain%beg' : 0.E+00, \ 'x_domain%end' : 1.E+00, \ 'm' : Nx, \ 'n' : 0, \ 'p' : 0, \ 'dt' : mydt, \ 't_step_start' : 0, \ 't_step_stop' : int(Nt), \ 't_step_save' : int(math.ceil(Nt/10.)), \ \ 'num_patches' : 2, \ 'model_eqns' : 2, \ 'alt_soundspeed' : 'F', \ 'num_fluids' : 1, \ 'adv_alphan' : 'T', \ 'mpp_lim' : 'F', \ 'mixture_err' : 'F', \ 'time_stepper' : 3, \ 'weno_vars' : 2, \ 'weno_order' : 5, \ 'weno_eps' : 1.E-16, \ 'char_decomp' : 'F', \ 'mapped_weno' : 'T', \ 'null_weights' : 'F', \ 'mp_weno' : 'F', \ 'riemann_solver' : 2, \ 'wave_speeds' : 1, \ 'avg_state' : 2, \ 'commute_err' : 'F', \ 'split_err' : 'F', \ 'bc_x%beg' : -3, \ 'bc_x%end' : -3, \ \ 'format' : 1, \ 'precision' : 2, \ 'prim_vars_wrt' :'T', \ 'parallel_io' :'F', \ 'patch_icpp(1)%geometry' : 1, \ 'patch_icpp(1)%x_centroid' : 0.25, \ 'patch_icpp(1)%length_x' : 0.5, \ 'patch_icpp(1)%vel(1)' : 0.0, \ 'patch_icpp(1)%pres' : 1.0, \ 'patch_icpp(1)%alpha_rho(1)' : 1.E+00, \ 'patch_icpp(1)%alpha(1)' : 1., \ 'patch_icpp(2)%geometry' : 1, \ 'patch_icpp(2)%x_centroid' : 0.75, \ 'patch_icpp(2)%length_x' : 0.5, \ 'patch_icpp(2)%vel(1)' : 0.0, \ 'patch_icpp(2)%pres' : 0.1, \ 'patch_icpp(2)%alpha_rho(1)' : 0.125E+00, \ 'patch_icpp(2)%alpha(1)' : 1., \ 'fluid_pp(1)%gamma' : 1.E+00/(1.4-1.E+00), \ 'fluid_pp(1)%pi_inf' : 0.0, \ } f_execute_mfc_component(comp_name, case_dict, mfc_dir, engine)
true
true
f7f9ed8864e7e9763a3d362d8651c82bf920bfab
2,046
py
Python
tensordata/report/p2peye/_p2peye.py
Hourout/tensordata
cbef6742ee0d3bfc4b886358fc01618bb5b63603
[ "Apache-2.0" ]
13
2019-01-08T10:22:39.000Z
2020-06-17T10:02:47.000Z
tensordata/report/p2peye/_p2peye.py
Hourout/tensordata
cbef6742ee0d3bfc4b886358fc01618bb5b63603
[ "Apache-2.0" ]
null
null
null
tensordata/report/p2peye/_p2peye.py
Hourout/tensordata
cbef6742ee0d3bfc4b886358fc01618bb5b63603
[ "Apache-2.0" ]
1
2020-06-17T10:02:49.000Z
2020-06-17T10:02:49.000Z
import io import time import datetime import requests import pandas as pd __all__ =['rating', 'problem_platform'] def rating(date=None): """P2peye comprehensive rating and display results. from https://www.p2peye.com Args: date: if None, download latest data, if like '201812', that download month data. Returns: DataFrame """ start = time.time() if date is None: date = str(pd.to_datetime(datetime.datetime.now())-pd.DateOffset(months=1))[:7].replace('-', '') assert (isinstance(date, str) and len(date)==6), "`date` shoule format '201812' or None" url_txt = 'https://raw.githubusercontent.com/Hourout/datasets/master/report/p2peye/rating/p2peye_rating'+date+'.txt' s = requests.get(url_txt).content data = pd.read_csv(io.StringIO(s.decode('utf-8'))) print('p2peye rating dataset download completed, run time %d min %.2f sec' %divmod((time.time()-start), 60)) return data def problem_platform(date=None, days=7): """P2peye problem platform and display results. from https://www.p2peye.com Args: date: if None, download latest data, if like '2018-12-01', that download month data. days: latest (date-days) day data. Returns: DataFrame """ start = time.time() if date is None: date = str(pd.to_datetime(datetime.datetime.now()).floor('d'))[:10] assert (isinstance(date, str) and len(date)==10), "`date` shoule format '2018-12-01' or None" date = pd.to_datetime(date) update = date-pd.DateOffset(days=days) url_txt = 'https://raw.githubusercontent.com/Hourout/datasets/master/report/p2peye/problem_platform/problem_platform.txt' s = requests.get(url_txt).content data = pd.read_csv(io.StringIO(s.decode('utf-8')), parse_dates=['问题发生时间']) data = data[(data['问题发生时间']<=date)&(data['问题发生时间']>update)].reset_index(drop=True) print('p2peye problem platform dataset download completed, run time %d min %.2f sec' %divmod((time.time()-start), 60)) return data
38.603774
125
0.669599
import io import time import datetime import requests import pandas as pd __all__ =['rating', 'problem_platform'] def rating(date=None): start = time.time() if date is None: date = str(pd.to_datetime(datetime.datetime.now())-pd.DateOffset(months=1))[:7].replace('-', '') assert (isinstance(date, str) and len(date)==6), "`date` shoule format '201812' or None" url_txt = 'https://raw.githubusercontent.com/Hourout/datasets/master/report/p2peye/rating/p2peye_rating'+date+'.txt' s = requests.get(url_txt).content data = pd.read_csv(io.StringIO(s.decode('utf-8'))) print('p2peye rating dataset download completed, run time %d min %.2f sec' %divmod((time.time()-start), 60)) return data def problem_platform(date=None, days=7): start = time.time() if date is None: date = str(pd.to_datetime(datetime.datetime.now()).floor('d'))[:10] assert (isinstance(date, str) and len(date)==10), "`date` shoule format '2018-12-01' or None" date = pd.to_datetime(date) update = date-pd.DateOffset(days=days) url_txt = 'https://raw.githubusercontent.com/Hourout/datasets/master/report/p2peye/problem_platform/problem_platform.txt' s = requests.get(url_txt).content data = pd.read_csv(io.StringIO(s.decode('utf-8')), parse_dates=['问题发生时间']) data = data[(data['问题发生时间']<=date)&(data['问题发生时间']>update)].reset_index(drop=True) print('p2peye problem platform dataset download completed, run time %d min %.2f sec' %divmod((time.time()-start), 60)) return data
true
true
f7f9ed8927fdd52bb75bb190d88a074e9be2fc2d
2,183
py
Python
apps/posts/migrations/0001_initial.py
aldwyn/effigia
eb456656949bf68934530bbec9c15ebc6d0236b8
[ "MIT" ]
1
2018-11-15T05:17:30.000Z
2018-11-15T05:17:30.000Z
apps/posts/migrations/0001_initial.py
aldwyn/effigia
eb456656949bf68934530bbec9c15ebc6d0236b8
[ "MIT" ]
5
2021-06-09T17:20:01.000Z
2022-03-11T23:18:06.000Z
apps/posts/migrations/0001_initial.py
aldwyn/effigia
eb456656949bf68934530bbec9c15ebc6d0236b8
[ "MIT" ]
1
2018-10-05T19:03:27.000Z
2018-10-05T19:03:27.000Z
# -*- coding: utf-8 -*- # Generated by Django 1.11.3 on 2017-07-16 06:34 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('groups', '0001_initial'), ] operations = [ migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('status', model_utils.fields.StatusField(choices=[('draft', 'draft'), ('published', 'published')], default='draft', max_length=100, no_check_for_status=True, verbose_name='status')), ('status_changed', model_utils.fields.MonitorField(default=django.utils.timezone.now, monitor='status', verbose_name='status changed')), ('is_removed', models.BooleanField(default=False)), ('name', models.CharField(max_length=255)), ('is_private', models.BooleanField(default=False)), ('description', models.TextField()), ('slug', models.SlugField(unique=True)), ('anonymous_visits_count', models.PositiveIntegerField(default=0)), ('created_by', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='posts', to='groups.Group')), ('likers', models.ManyToManyField(related_name='posts_liked', to=settings.AUTH_USER_MODEL)), ], options={ 'abstract': False, }, ), ]
48.511111
199
0.649107
from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('groups', '0001_initial'), ] operations = [ migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, editable=False, verbose_name='created')), ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, editable=False, verbose_name='modified')), ('status', model_utils.fields.StatusField(choices=[('draft', 'draft'), ('published', 'published')], default='draft', max_length=100, no_check_for_status=True, verbose_name='status')), ('status_changed', model_utils.fields.MonitorField(default=django.utils.timezone.now, monitor='status', verbose_name='status changed')), ('is_removed', models.BooleanField(default=False)), ('name', models.CharField(max_length=255)), ('is_private', models.BooleanField(default=False)), ('description', models.TextField()), ('slug', models.SlugField(unique=True)), ('anonymous_visits_count', models.PositiveIntegerField(default=0)), ('created_by', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ('group', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='posts', to='groups.Group')), ('likers', models.ManyToManyField(related_name='posts_liked', to=settings.AUTH_USER_MODEL)), ], options={ 'abstract': False, }, ), ]
true
true
f7f9eda4a1a5cfab9bb0fb14eb8ec37be8074b9e
403
py
Python
brus/liste/migrations/0003_auto_20160923_1401.py
webkom/brus
a1ffe0c03f78d6a8b301e4ae7554e625ed2e46a9
[ "MIT" ]
null
null
null
brus/liste/migrations/0003_auto_20160923_1401.py
webkom/brus
a1ffe0c03f78d6a8b301e4ae7554e625ed2e46a9
[ "MIT" ]
38
2016-04-30T16:07:09.000Z
2022-03-18T16:56:59.000Z
brus/liste/migrations/0003_auto_20160923_1401.py
webkom/brus
a1ffe0c03f78d6a8b301e4ae7554e625ed2e46a9
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-09-23 14:01 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("liste", "0002_auto_20160503_0953")] operations = [ migrations.AlterField( model_name="brus", name="cost", field=models.IntegerField(default=16) ) ]
23.705882
81
0.672457
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("liste", "0002_auto_20160503_0953")] operations = [ migrations.AlterField( model_name="brus", name="cost", field=models.IntegerField(default=16) ) ]
true
true
f7f9edda2a0d7177db793f60789f6f412439f341
371
py
Python
experiments/heat-3d/tmp_files/3120.py
LoopTilingBenchmark/benchmark
52a3d2e70216552a498fd91de02a2fa9cb62122c
[ "BSD-2-Clause" ]
null
null
null
experiments/heat-3d/tmp_files/3120.py
LoopTilingBenchmark/benchmark
52a3d2e70216552a498fd91de02a2fa9cb62122c
[ "BSD-2-Clause" ]
null
null
null
experiments/heat-3d/tmp_files/3120.py
LoopTilingBenchmark/benchmark
52a3d2e70216552a498fd91de02a2fa9cb62122c
[ "BSD-2-Clause" ]
null
null
null
from chill import * source('/uufs/chpc.utah.edu/common/home/u1142914/lib/ytopt_vinu/polybench/polybench-code/stencils/heat-3d/kernel.c') destination('/uufs/chpc.utah.edu/common/home/u1142914/lib/ytopt_vinu/experiments/heat-3d/tmp_files/3120.c') procedure('kernel_heat_3d') loop(0) tile(0,2,8,2) tile(0,4,8,4) tile(0,6,64,6) tile(1,2,8,2) tile(1,4,8,4) tile(1,6,64,6)
23.1875
116
0.743935
from chill import * source('/uufs/chpc.utah.edu/common/home/u1142914/lib/ytopt_vinu/polybench/polybench-code/stencils/heat-3d/kernel.c') destination('/uufs/chpc.utah.edu/common/home/u1142914/lib/ytopt_vinu/experiments/heat-3d/tmp_files/3120.c') procedure('kernel_heat_3d') loop(0) tile(0,2,8,2) tile(0,4,8,4) tile(0,6,64,6) tile(1,2,8,2) tile(1,4,8,4) tile(1,6,64,6)
true
true
f7f9eddab707610c784e27a6038ae7220ec190f4
6,106
py
Python
pyrender_render.py
trisct/DeepSDF
85e0cf413544244737fe2237f9549c0d4e946745
[ "MIT" ]
null
null
null
pyrender_render.py
trisct/DeepSDF
85e0cf413544244737fe2237f9549c0d4e946745
[ "MIT" ]
null
null
null
pyrender_render.py
trisct/DeepSDF
85e0cf413544244737fe2237f9549c0d4e946745
[ "MIT" ]
null
null
null
import numpy as np import trimesh import pyrender import matplotlib.pyplot as plt import math from tqdm import tqdm import os import torch import torchvision import glob def render_one(mesh_list, steps, save_name, save_path, resolution, need_video=False): """ mesh: pyrender.mesh.Mesh A pyrender.mesh.Mesh object steps: int number of steps in one horizontal revolution save_path: str path to save color and depth image (saved as numpy arrays). mode: str, either 'light' or 'albedo' if 'light', then render with light objects if 'albedo', then render with only ambient lights resolution: tuple of 2: (res_h, res_w) ---- file saving: This files save the color image, the depth image, the camera pose and the camera projection matrix color image: saved as [save_path]/[save_name]/[save_name]_[rotate_deg]_color.npy depth image: saved as [save_path]/[save_name]/[save_name]_[rotate_deg]_depth.npy camera pose: saved as [save_path]/[save_name]/[save_name]_[rotate_deg]_campose.npy projection matrix: saved as [save_path]/[save_name]/[save_name]_projection.npy """ print(f'Starting to render one, which will be saved to {os.path.join(save_path, save_name)}.') if not os.path.exists(os.path.join(save_path, save_name)): os.system(f'mkdir -p {os.path.join(save_path, save_name)}') # resolution res_h, res_w = resolution # creating nodes # mesh node_mesh_list = [] for mesh in mesh_list: #mesh = pyrender.Mesh.from_trimesh(mesh) node_mesh_list.append( pyrender.Node(mesh=mesh, matrix=np.eye(4)) ) # directional light dir_light = pyrender.DirectionalLight(color=[1.0, 1.0, 1.0], intensity=2.0) node_light = pyrender.Node(light=dir_light, matrix=np.eye(4)) # perspective cameras pers_cam = pyrender.PerspectiveCamera(yfov=np.pi / 3.0, aspectRatio=1) node_cam = pyrender.Node(camera=pers_cam, matrix=np.eye(4)) # scene scene = pyrender.Scene(ambient_light=[1., 1., 1.], bg_color=[1., 1., 1.]) for node_mesh in node_mesh_list: scene.add_node(node_mesh) scene.add_node(node_light) scene.add_node(node_cam) offscr_renderer = pyrender.OffscreenRenderer(viewport_width=res_h, viewport_height=res_w, point_size=3.) # for outputting video if need_video: color_video = torch.zeros(steps, res_h, res_w, 3, dtype=torch.uint8) depth_video = torch.zeros(steps, res_h, res_w, 3, dtype=torch.uint8) albedo_video = torch.zeros(steps, res_h, res_w, 3, dtype=torch.uint8) deg_interval = 720 / steps for i, angle_i in enumerate(range(steps)): print(f'Showing angle {angle_i}') angle_deg = int(deg_interval * angle_i) angle_rad = angle_deg * math.pi / 180 s = math.sin(angle_rad) c = math.cos(angle_rad) camera_pose = np.array([ [ c, 0.0, s, 2*s], [0.0, -1.0, 0.0, 0.0], [ s, 0.0, -c, -2*c], [0.0, 0.0, 0.0, 1.0]]) pitch_angle_rad = 30 * math.pi / 180 s_pitch = math.sin(pitch_angle_rad) c_pitch = math.cos(pitch_angle_rad) # rendering scene.set_pose(node_cam, pose=camera_pose) color, depth = offscr_renderer.render(scene) scene.remove_node(node_light) albedo, _ = offscr_renderer.render(scene) scene.add_node(node_light) #plt.imshow(color) #plt.show() # making video if need_video: color_video[i] = torch.from_numpy(color.copy()) depth_pt = torch.from_numpy(depth.copy()) depth_scaled = (depth_pt - depth_pt[depth_pt !=0].min()) / (depth_pt[depth_pt != 0].max() - depth_pt[depth_pt != 0].min()) * 255 depth_scaled = torch.where(depth_pt != 0., depth_scaled, torch.zeros_like(depth_scaled)) depth_video[i] = depth_scaled.int().unsqueeze(dim=-1).expand(-1, -1, 3) albedo_video[i] = torch.from_numpy(albedo.copy()) #np.save( os.path.join(save_path, save_name, f'{save_name}_{angle_deg}_color'), color) #np.save( os.path.join(save_path, save_name, f'{save_name}_{angle_deg}_depth'), depth) #np.save( os.path.join(save_path, save_name, f'{save_name}_{angle_deg}_albedo'), albedo) #np.save( os.path.join(save_path, save_name, f'{save_name}_{angle_deg}_campose'), camera_pose) #plt.imshow(color) #plt.savefig(f'{save_name}_color_{angle_i}.png', bbox_inches='tight') #plt.clf() #plt.show() #plt.imshow(depth) #plt.show() #plt.imshow(albedo) #plt.show() #np.save( os.path.join(save_path, save_name, f'{save_name}_projection'), node_cam.camera.get_projection_matrix()) #print(node_cam.camera.get_projection_matrix()) if need_video: final_video = torch.cat([color_video, depth_video], dim=2) torchvision.io.write_video( os.path.join(save_path, save_name, f'{save_name}_rendervideo_color.mp4'), color_video, fps=30) torchvision.io.write_video( os.path.join(save_path, save_name, f'{save_name}_rendervideo_depth.mp4'), depth_video, fps=30) if __name__ == '__main__': # headless rendering os.environ['PYOPENGL_PLATFORM']='egl' source_folder = '02691156' # steps steps = 180 file_list = ['0676', '0775', '1314', '0411', '0447', '1441', '0993', '0671'] for frame_id in file_list: file_name = glob.glob(f'*{frame_id}*.ply')[0] os.system(f'python ~/.dev_apps/simplemesh/simplemesh.py --input {file_name} -n.85 --output {file_name[:-4]+"_norm.ply"}') pcd = trimesh.load(file_name[:-4]+"_norm.ply") pcd_pyr = pyrender.Mesh.from_points(pcd.vertices, colors=pcd.colors) render_one([pcd_pyr], steps=steps, save_name=file_name[:-4]+'_render', save_path='videos', resolution=(512, 512), need_video=True)
36.562874
140
0.633803
import numpy as np import trimesh import pyrender import matplotlib.pyplot as plt import math from tqdm import tqdm import os import torch import torchvision import glob def render_one(mesh_list, steps, save_name, save_path, resolution, need_video=False): print(f'Starting to render one, which will be saved to {os.path.join(save_path, save_name)}.') if not os.path.exists(os.path.join(save_path, save_name)): os.system(f'mkdir -p {os.path.join(save_path, save_name)}') res_h, res_w = resolution node_mesh_list = [] for mesh in mesh_list: node_mesh_list.append( pyrender.Node(mesh=mesh, matrix=np.eye(4)) ) dir_light = pyrender.DirectionalLight(color=[1.0, 1.0, 1.0], intensity=2.0) node_light = pyrender.Node(light=dir_light, matrix=np.eye(4)) pers_cam = pyrender.PerspectiveCamera(yfov=np.pi / 3.0, aspectRatio=1) node_cam = pyrender.Node(camera=pers_cam, matrix=np.eye(4)) scene = pyrender.Scene(ambient_light=[1., 1., 1.], bg_color=[1., 1., 1.]) for node_mesh in node_mesh_list: scene.add_node(node_mesh) scene.add_node(node_light) scene.add_node(node_cam) offscr_renderer = pyrender.OffscreenRenderer(viewport_width=res_h, viewport_height=res_w, point_size=3.) if need_video: color_video = torch.zeros(steps, res_h, res_w, 3, dtype=torch.uint8) depth_video = torch.zeros(steps, res_h, res_w, 3, dtype=torch.uint8) albedo_video = torch.zeros(steps, res_h, res_w, 3, dtype=torch.uint8) deg_interval = 720 / steps for i, angle_i in enumerate(range(steps)): print(f'Showing angle {angle_i}') angle_deg = int(deg_interval * angle_i) angle_rad = angle_deg * math.pi / 180 s = math.sin(angle_rad) c = math.cos(angle_rad) camera_pose = np.array([ [ c, 0.0, s, 2*s], [0.0, -1.0, 0.0, 0.0], [ s, 0.0, -c, -2*c], [0.0, 0.0, 0.0, 1.0]]) pitch_angle_rad = 30 * math.pi / 180 s_pitch = math.sin(pitch_angle_rad) c_pitch = math.cos(pitch_angle_rad) scene.set_pose(node_cam, pose=camera_pose) color, depth = offscr_renderer.render(scene) scene.remove_node(node_light) albedo, _ = offscr_renderer.render(scene) scene.add_node(node_light) if need_video: color_video[i] = torch.from_numpy(color.copy()) depth_pt = torch.from_numpy(depth.copy()) depth_scaled = (depth_pt - depth_pt[depth_pt !=0].min()) / (depth_pt[depth_pt != 0].max() - depth_pt[depth_pt != 0].min()) * 255 depth_scaled = torch.where(depth_pt != 0., depth_scaled, torch.zeros_like(depth_scaled)) depth_video[i] = depth_scaled.int().unsqueeze(dim=-1).expand(-1, -1, 3) albedo_video[i] = torch.from_numpy(albedo.copy()) if need_video: final_video = torch.cat([color_video, depth_video], dim=2) torchvision.io.write_video( os.path.join(save_path, save_name, f'{save_name}_rendervideo_color.mp4'), color_video, fps=30) torchvision.io.write_video( os.path.join(save_path, save_name, f'{save_name}_rendervideo_depth.mp4'), depth_video, fps=30) if __name__ == '__main__': os.environ['PYOPENGL_PLATFORM']='egl' source_folder = '02691156' steps = 180 file_list = ['0676', '0775', '1314', '0411', '0447', '1441', '0993', '0671'] for frame_id in file_list: file_name = glob.glob(f'*{frame_id}*.ply')[0] os.system(f'python ~/.dev_apps/simplemesh/simplemesh.py --input {file_name} -n.85 --output {file_name[:-4]+"_norm.ply"}') pcd = trimesh.load(file_name[:-4]+"_norm.ply") pcd_pyr = pyrender.Mesh.from_points(pcd.vertices, colors=pcd.colors) render_one([pcd_pyr], steps=steps, save_name=file_name[:-4]+'_render', save_path='videos', resolution=(512, 512), need_video=True)
true
true
f7f9edf99c2bd10345a162cb1439130cfffc8be0
263
py
Python
airbyte-integrations/connectors/source-google-directory/source_google_directory/utils.py
OTRI-Unipd/OTRI-airbyte
50eeeb773f75246e86c6e167b0cd7d2dda6efe0d
[ "MIT" ]
6,215
2020-09-21T13:45:56.000Z
2022-03-31T21:21:45.000Z
airbyte-integrations/connectors/source-google-directory/source_google_directory/utils.py
OTRI-Unipd/OTRI-airbyte
50eeeb773f75246e86c6e167b0cd7d2dda6efe0d
[ "MIT" ]
8,448
2020-09-21T00:43:50.000Z
2022-03-31T23:56:06.000Z
airbyte-integrations/connectors/source-google-directory/source_google_directory/utils.py
OTRI-Unipd/OTRI-airbyte
50eeeb773f75246e86c6e167b0cd7d2dda6efe0d
[ "MIT" ]
1,251
2020-09-20T05:48:47.000Z
2022-03-31T10:41:29.000Z
# # Copyright (c) 2021 Airbyte, Inc., all rights reserved. # def rate_limit_handling(error): retried_cases = [ (403, "quotaExceeded"), (429, "rateLimitExceeded"), ] return (error.resp.status, error.resp.reason) not in retried_cases
20.230769
70
0.65019
def rate_limit_handling(error): retried_cases = [ (403, "quotaExceeded"), (429, "rateLimitExceeded"), ] return (error.resp.status, error.resp.reason) not in retried_cases
true
true
f7f9ee5ee71f4efc5aaf18062151307a3a14d026
941
py
Python
tests/sentry/management/commands/test_cleanup.py
vperron/sentry
4ea0c8cb120a3165f0e0b185c64213b69ab621ea
[ "BSD-3-Clause" ]
1
2017-08-30T06:55:25.000Z
2017-08-30T06:55:25.000Z
tests/sentry/management/commands/test_cleanup.py
tobetterman/sentry
fe85d3aee19dcdbfdd27921c4fb04529fc995a79
[ "BSD-3-Clause" ]
null
null
null
tests/sentry/management/commands/test_cleanup.py
tobetterman/sentry
fe85d3aee19dcdbfdd27921c4fb04529fc995a79
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- from __future__ import absolute_import from django.core.management import call_command from sentry.models import Event, Group, GroupTagValue, TagValue, TagKey from sentry.testutils import TestCase ALL_MODELS = (Event, Group, GroupTagValue, TagValue, TagKey) class SentryCleanupTest(TestCase): fixtures = ['tests/fixtures/cleanup.json'] def test_simple(self): call_command('cleanup', days=1) for model in ALL_MODELS: assert model.objects.count() == 0 def test_project(self): orig_counts = {} for model in ALL_MODELS: orig_counts[model] = model.objects.count() call_command('cleanup', days=1, project=2) for model in ALL_MODELS: assert model.objects.count() == orig_counts[model] call_command('cleanup', days=1, project=1) for model in ALL_MODELS: assert model.objects.count() == 0
26.138889
71
0.663124
from __future__ import absolute_import from django.core.management import call_command from sentry.models import Event, Group, GroupTagValue, TagValue, TagKey from sentry.testutils import TestCase ALL_MODELS = (Event, Group, GroupTagValue, TagValue, TagKey) class SentryCleanupTest(TestCase): fixtures = ['tests/fixtures/cleanup.json'] def test_simple(self): call_command('cleanup', days=1) for model in ALL_MODELS: assert model.objects.count() == 0 def test_project(self): orig_counts = {} for model in ALL_MODELS: orig_counts[model] = model.objects.count() call_command('cleanup', days=1, project=2) for model in ALL_MODELS: assert model.objects.count() == orig_counts[model] call_command('cleanup', days=1, project=1) for model in ALL_MODELS: assert model.objects.count() == 0
true
true
f7f9eeaf6d8636ba77648810e0df271e7fd84639
11,597
py
Python
Pilot2/P2B1/p2b1_baseline_keras2.py
j-woz/Benchmarks
d518162fdafb7cfa26071b6a30a3b456dad024f6
[ "MIT" ]
2
2021-02-06T06:47:19.000Z
2021-02-24T13:45:02.000Z
Pilot2/P2B1/p2b1_baseline_keras2.py
j-woz/Benchmarks
d518162fdafb7cfa26071b6a30a3b456dad024f6
[ "MIT" ]
null
null
null
Pilot2/P2B1/p2b1_baseline_keras2.py
j-woz/Benchmarks
d518162fdafb7cfa26071b6a30a3b456dad024f6
[ "MIT" ]
null
null
null
import numpy as np import scipy as sp import pickle import sys, os, json import argparse import h5py import logging try: reload # Python 2.7 except NameError: try: from importlib import reload # Python 3.4+ except ImportError: from imp import reload # Python 3.0 - 3.3 TIMEOUT=3600 # in sec; set this to -1 for no timeout file_path = os.path.dirname(os.path.realpath(__file__)) #lib_path = os.path.abspath(os.path.join(file_path, '..', 'common')) #sys.path.append(lib_path) lib_path2 = os.path.abspath(os.path.join(file_path, '..','..', 'common')) sys.path.append(lib_path2) from keras import backend as K import p2b1 import candle import p2b1_AE_models as AE_models HOME = os.environ['HOME'] logger = logging.getLogger(__name__) os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' def parse_list(option, opt, value, parser): setattr(parser.values, option.dest, value.split(',')) def str2bool(v): return v.lower() in ("yes", "true", "t", "1") def initialize_parameters(default_model = 'p2b1_default_model.txt'): # Build benchmark object p2b1Bmk = p2b1.BenchmarkP2B1(p2b1.file_path, default_model, 'keras', prog='p2b1_baseline', desc='Train Molecular Frame Autoencoder - Pilot 2 Benchmark 1') # Initialize parameters GP = candle.finalize_parameters(p2b1Bmk) #p2b1.logger.info('Params: {}'.format(gParameters)) print ('\nTraining parameters:') for key in sorted(GP): print ("\t%s: %s" % (key, GP[key])) # print json.dumps(GP, indent=4, skipkeys=True, sort_keys=True) if GP['backend'] != 'theano' and GP['backend'] != 'tensorflow': sys.exit('Invalid backend selected: %s' % GP['backend']) os.environ['KERAS_BACKEND'] = GP['backend'] reload(K) ''' if GP['backend'] == 'theano': K.set_image_dim_ordering('th') elif GP['backend'] == 'tensorflow': K.set_image_dim_ordering('tf') ''' K.set_image_data_format('channels_last') #"th" format means that the convolutional kernels will have the shape (depth, input_depth, rows, cols) #"tf" format means that the convolutional kernels will have the shape (rows, cols, input_depth, depth) print ("Image data format: ", K.image_data_format()) # print "Image ordering: ", K.image_dim_ordering() return GP def run(GP): # set the seed if GP['rng_seed']: np.random.seed(GP['rng_seed']) else: np.random.seed(np.random.randint(10000)) # Set paths if not os.path.isdir(GP['home_dir']): print ('Keras home directory not set') sys.exit(0) sys.path.append(GP['home_dir']) # Setup loggin args = candle.ArgumentStruct(**GP) # set_seed(args.rng_seed) # ext = extension_from_parameters(args) candle.verify_path(args.save_path) prefix = args.save_path # + ext logfile = args.logfile if args.logfile else prefix+'.log' candle.set_up_logger(logfile, logger, False) #args.verbose logger.info('Params: {}'.format(GP)) import p2b1 as hf reload(hf) #import keras_model_utils as KEU #reload(KEU) #reload(p2ck) #reload(p2ck.optimizers) maps = hf.autoencoder_preprocess() from keras.optimizers import SGD, RMSprop, Adam from keras.datasets import mnist from keras.callbacks import LearningRateScheduler, ModelCheckpoint from keras import callbacks from keras.layers.advanced_activations import ELU from keras.preprocessing.image import ImageDataGenerator # GP=hf.ReadConfig(opts.config_file) batch_size = GP['batch_size'] learning_rate = GP['learning_rate'] kerasDefaults = candle.keras_default_config() ##### Read Data ######## import helper (data_files, fields)=p2b1.get_list_of_data_files(GP) # Read from local directoy #(data_files, fields) = helper.get_local_files('/p/gscratchr/brainusr/datasets/cancer/pilot2/3k_run16_10us.35fs-DPPC.20-DIPC.60-CHOL.20.dir/') #(data_files, fields) = helper.get_local_files('3k_run16', '/p/lscratchf/brainusr/datasets/cancer/pilot2/') # Define datagenerator datagen = hf.ImageNoiseDataGenerator(corruption_level=GP['noise_factor']) # get data dimension ## num_samples = 0 for f in data_files: # Seperate different arrays from the data (X, nbrs, resnums) = helper.get_data_arrays(f) num_samples += X.shape[0] (X, nbrs, resnums) = helper.get_data_arrays(data_files[0]) print ('\nData chunk shape: ', X.shape) molecular_hidden_layers = GP['molecular_num_hidden'] if not molecular_hidden_layers: X_train = hf.get_data(X, case=GP['case']) input_dim = X_train.shape[1] else: # computing input dimension for outer AE input_dim = X.shape[1]*molecular_hidden_layers[-1] print ('\nState AE input/output dimension: ', input_dim) # get data dimension for molecular autoencoder molecular_nbrs = np.int(GP['molecular_nbrs']) num_molecules = X.shape[1] num_beads = X.shape[2] if GP['nbr_type'] == 'relative': # relative x, y, z positions num_loc_features = 3 loc_feat_vect = ['rel_x', 'rel_y', 'rel_z'] elif GP['nbr_type'] == 'invariant': # relative distance and angle num_loc_features = 2 loc_feat_vect = ['rel_dist', 'rel_angle'] else: print ('Invalid nbr_type!!') exit() if not GP['type_bool']: # only consider molecular location coordinates num_type_features = 0 type_feat_vect = [] else: num_type_features = 5 type_feat_vect = list(fields.keys())[3:8] num_features = num_loc_features + num_type_features + num_beads dim = np.prod([num_beads, num_features, molecular_nbrs+1]) bead_kernel_size = num_features molecular_input_dim = dim mol_kernel_size = num_beads feature_vector = loc_feat_vect + type_feat_vect + list(fields.keys())[8:] print ('\nMolecular AE input/output dimension: ', molecular_input_dim) print ('\nData Format:\n[Frames (%s), Molecules (%s), Beads (%s), %s (%s)]' % ( num_samples, num_molecules, num_beads, feature_vector, num_features)) ### Define Model, Solver and Compile ########## print ('\nDefine the model and compile') opt = candle.build_optimizer(GP['optimizer'], learning_rate, kerasDefaults) model_type = 'mlp' memo = '%s_%s' % (GP['base_memo'], model_type) ######## Define Molecular Model, Solver and Compile ######### molecular_nonlinearity = GP['molecular_nonlinearity'] len_molecular_hidden_layers = len(molecular_hidden_layers) conv_bool = GP['conv_bool'] full_conv_bool = GP['full_conv_bool'] if conv_bool: molecular_model, molecular_encoder = AE_models.conv_dense_mol_auto(bead_k_size=bead_kernel_size, mol_k_size=mol_kernel_size, weights_path=None, input_shape=(1, molecular_input_dim, 1), nonlinearity=molecular_nonlinearity, hidden_layers=molecular_hidden_layers, l2_reg=GP['l2_reg'], drop=float(GP['dropout'])) elif full_conv_bool: molecular_model, molecular_encoder = AE_models.full_conv_mol_auto(bead_k_size=bead_kernel_size, mol_k_size=mol_kernel_size, weights_path=None, input_shape=(1, molecular_input_dim, 1), nonlinearity=molecular_nonlinearity, hidden_layers=molecular_hidden_layers, l2_reg=GP['l2_reg'], drop=float(GP['dropout'])) else: molecular_model, molecular_encoder = AE_models.dense_auto(weights_path=None, input_shape=(molecular_input_dim,), nonlinearity=molecular_nonlinearity, hidden_layers=molecular_hidden_layers, l2_reg=GP['l2_reg'], drop=float(GP['dropout'])) if GP['loss'] == 'mse': loss_func = 'mse' elif GP['loss'] == 'custom': loss_func = helper.combined_loss molecular_model.compile(optimizer=opt, loss=loss_func, metrics=['mean_squared_error', 'mean_absolute_error']) print ('\nModel Summary: \n') molecular_model.summary() ##### set up callbacks and cooling for the molecular_model ########## drop = GP['dropout'] mb_epochs = GP['epochs'] initial_lrate = GP['learning_rate'] epochs_drop = 1+int(np.floor(mb_epochs/3)) def step_decay(epoch): global initial_lrate, epochs_drop, drop lrate = initial_lrate * np.power(drop, np.floor((1+epoch)/epochs_drop)) return lrate lr_scheduler = LearningRateScheduler(step_decay) history = callbacks.History() # callbacks=[history,lr_scheduler] history_logger = candle.LoggingCallback(logger.debug) candleRemoteMonitor = candle.CandleRemoteMonitor(params=GP) timeoutMonitor = candle.TerminateOnTimeOut(TIMEOUT) callbacks = [history, history_logger, candleRemoteMonitor, timeoutMonitor] loss = 0. #### Save the Model to disk if GP['save_path'] != None: save_path = GP['save_path'] if not os.path.exists(save_path): os.makedirs(save_path) else: save_path = '.' model_json = molecular_model.to_json() with open(save_path + '/model.json', "w") as json_file: json_file.write(model_json) encoder_json = molecular_encoder.to_json() with open(save_path + '/encoder.json', "w") as json_file: json_file.write(encoder_json) print('Saved model to disk') #### Train the Model if GP['train_bool']: ct = hf.Candle_Molecular_Train(molecular_model, molecular_encoder, data_files, mb_epochs, callbacks, batch_size=batch_size, nbr_type=GP['nbr_type'], save_path=GP['save_path'], len_molecular_hidden_layers=len_molecular_hidden_layers, molecular_nbrs=molecular_nbrs, conv_bool=conv_bool, full_conv_bool=full_conv_bool, type_bool=GP['type_bool'], sampling_density=GP['sampling_density']) frame_loss, frame_mse = ct.train_ac() else: frame_mse = [] frame_loss = [] return frame_loss, frame_mse def main(): gParameters = initialize_parameters() run(gParameters) if __name__ == '__main__': main() try: K.clear_session() except AttributeError: # theano does not have this function pass
37.775244
146
0.594378
import numpy as np import scipy as sp import pickle import sys, os, json import argparse import h5py import logging try: reload except NameError: try: from importlib import reload except ImportError: from imp import reload TIMEOUT=3600 file_path = os.path.dirname(os.path.realpath(__file__)) lib_path2 = os.path.abspath(os.path.join(file_path, '..','..', 'common')) sys.path.append(lib_path2) from keras import backend as K import p2b1 import candle import p2b1_AE_models as AE_models HOME = os.environ['HOME'] logger = logging.getLogger(__name__) os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' def parse_list(option, opt, value, parser): setattr(parser.values, option.dest, value.split(',')) def str2bool(v): return v.lower() in ("yes", "true", "t", "1") def initialize_parameters(default_model = 'p2b1_default_model.txt'): p2b1Bmk = p2b1.BenchmarkP2B1(p2b1.file_path, default_model, 'keras', prog='p2b1_baseline', desc='Train Molecular Frame Autoencoder - Pilot 2 Benchmark 1') GP = candle.finalize_parameters(p2b1Bmk) print ('\nTraining parameters:') for key in sorted(GP): print ("\t%s: %s" % (key, GP[key])) if GP['backend'] != 'theano' and GP['backend'] != 'tensorflow': sys.exit('Invalid backend selected: %s' % GP['backend']) os.environ['KERAS_BACKEND'] = GP['backend'] reload(K) K.set_image_data_format('channels_last') print ("Image data format: ", K.image_data_format()) return GP def run(GP): if GP['rng_seed']: np.random.seed(GP['rng_seed']) else: np.random.seed(np.random.randint(10000)) if not os.path.isdir(GP['home_dir']): print ('Keras home directory not set') sys.exit(0) sys.path.append(GP['home_dir']) args = candle.ArgumentStruct(**GP) candle.verify_path(args.save_path) prefix = args.save_path logfile = args.logfile if args.logfile else prefix+'.log' candle.set_up_logger(logfile, logger, False) logger.info('Params: {}'.format(GP)) import p2b1 as hf reload(hf) maps = hf.autoencoder_preprocess() from keras.optimizers import SGD, RMSprop, Adam from keras.datasets import mnist from keras.callbacks import LearningRateScheduler, ModelCheckpoint from keras import callbacks from keras.layers.advanced_activations import ELU from keras.preprocessing.image import ImageDataGenerator batch_size = GP['batch_size'] learning_rate = GP['learning_rate'] kerasDefaults = candle.keras_default_config() seDataGenerator(corruption_level=GP['noise_factor']) num_samples = 0 for f in data_files: (X, nbrs, resnums) = helper.get_data_arrays(f) num_samples += X.shape[0] (X, nbrs, resnums) = helper.get_data_arrays(data_files[0]) print ('\nData chunk shape: ', X.shape) molecular_hidden_layers = GP['molecular_num_hidden'] if not molecular_hidden_layers: X_train = hf.get_data(X, case=GP['case']) input_dim = X_train.shape[1] else: input_dim = X.shape[1]*molecular_hidden_layers[-1] print ('\nState AE input/output dimension: ', input_dim) molecular_nbrs = np.int(GP['molecular_nbrs']) num_molecules = X.shape[1] num_beads = X.shape[2] if GP['nbr_type'] == 'relative': num_loc_features = 3 loc_feat_vect = ['rel_x', 'rel_y', 'rel_z'] elif GP['nbr_type'] == 'invariant': num_loc_features = 2 loc_feat_vect = ['rel_dist', 'rel_angle'] else: print ('Invalid nbr_type!!') exit() if not GP['type_bool']: num_type_features = 0 type_feat_vect = [] else: num_type_features = 5 type_feat_vect = list(fields.keys())[3:8] num_features = num_loc_features + num_type_features + num_beads dim = np.prod([num_beads, num_features, molecular_nbrs+1]) bead_kernel_size = num_features molecular_input_dim = dim mol_kernel_size = num_beads feature_vector = loc_feat_vect + type_feat_vect + list(fields.keys())[8:] print ('\nMolecular AE input/output dimension: ', molecular_input_dim) print ('\nData Format:\n[Frames (%s), Molecules (%s), Beads (%s), %s (%s)]' % ( num_samples, num_molecules, num_beads, feature_vector, num_features)) p' memo = '%s_%s' % (GP['base_memo'], model_type) weights_path=None, input_shape=(1, molecular_input_dim, 1), nonlinearity=molecular_nonlinearity, hidden_layers=molecular_hidden_layers, l2_reg=GP['l2_reg'], drop=float(GP['dropout'])) elif full_conv_bool: molecular_model, molecular_encoder = AE_models.full_conv_mol_auto(bead_k_size=bead_kernel_size, mol_k_size=mol_kernel_size, weights_path=None, input_shape=(1, molecular_input_dim, 1), nonlinearity=molecular_nonlinearity, hidden_layers=molecular_hidden_layers, l2_reg=GP['l2_reg'], drop=float(GP['dropout'])) else: molecular_model, molecular_encoder = AE_models.dense_auto(weights_path=None, input_shape=(molecular_input_dim,), nonlinearity=molecular_nonlinearity, hidden_layers=molecular_hidden_layers, l2_reg=GP['l2_reg'], drop=float(GP['dropout'])) if GP['loss'] == 'mse': loss_func = 'mse' elif GP['loss'] == 'custom': loss_func = helper.combined_loss molecular_model.compile(optimizer=opt, loss=loss_func, metrics=['mean_squared_error', 'mean_absolute_error']) print ('\nModel Summary: \n') molecular_model.summary() lr_scheduler = LearningRateScheduler(step_decay) history = callbacks.History() history_logger = candle.LoggingCallback(logger.debug) candleRemoteMonitor = candle.CandleRemoteMonitor(params=GP) timeoutMonitor = candle.TerminateOnTimeOut(TIMEOUT) callbacks = [history, history_logger, candleRemoteMonitor, timeoutMonitor] loss = 0. if not os.path.exists(save_path): os.makedirs(save_path) else: save_path = '.' model_json = molecular_model.to_json() with open(save_path + '/model.json', "w") as json_file: json_file.write(model_json) encoder_json = molecular_encoder.to_json() with open(save_path + '/encoder.json', "w") as json_file: json_file.write(encoder_json) print('Saved model to disk') ular_Train(molecular_model, molecular_encoder, data_files, mb_epochs, callbacks, batch_size=batch_size, nbr_type=GP['nbr_type'], save_path=GP['save_path'], len_molecular_hidden_layers=len_molecular_hidden_layers, molecular_nbrs=molecular_nbrs, conv_bool=conv_bool, full_conv_bool=full_conv_bool, type_bool=GP['type_bool'], sampling_density=GP['sampling_density']) frame_loss, frame_mse = ct.train_ac() else: frame_mse = [] frame_loss = [] return frame_loss, frame_mse def main(): gParameters = initialize_parameters() run(gParameters) if __name__ == '__main__': main() try: K.clear_session() except AttributeError: pass
true
true
f7f9eec307e8014e88a0e5cea1baa407552b3713
305
py
Python
napari/utils/perf/_config.py
neuromusic/napari-gui
0adb11c53dbd29ae82fbf46b68c61bda63128775
[ "BSD-3-Clause" ]
1
2020-02-14T15:40:42.000Z
2020-02-14T15:40:42.000Z
napari/utils/perf/_config.py
willingc/napari
3b92d9cba5a178d04c5b5231192448cc316a9bfd
[ "BSD-3-Clause" ]
null
null
null
napari/utils/perf/_config.py
willingc/napari
3b92d9cba5a178d04c5b5231192448cc316a9bfd
[ "BSD-3-Clause" ]
null
null
null
"""Perf configuration flags. """ import os import sys # If USE_PERFMON is not set then performance timers will be 100% disabled with # hopefully zero run-time impact. USE_PERFMON = os.getenv("NAPARI_PERFMON", "0") != "0" # We have some pre-3.7 functionality. PYTHON_3_7 = sys.version_info[:2] >= (3, 7)
25.416667
78
0.718033
import os import sys USE_PERFMON = os.getenv("NAPARI_PERFMON", "0") != "0" PYTHON_3_7 = sys.version_info[:2] >= (3, 7)
true
true
f7f9ef0911013c5cc4b517a77a9b396d82989e3f
14,612
py
Python
pyclesperanto_prototype/_tier0/_pycl.py
tlambert-forks/pyclesperanto_prototype
aea964a75e691f19b7753040daa8b276d57ccf36
[ "BSD-3-Clause" ]
null
null
null
pyclesperanto_prototype/_tier0/_pycl.py
tlambert-forks/pyclesperanto_prototype
aea964a75e691f19b7753040daa8b276d57ccf36
[ "BSD-3-Clause" ]
1
2021-01-12T19:41:04.000Z
2021-01-12T19:41:04.000Z
pyclesperanto_prototype/_tier0/_pycl.py
tlambert-forks/pyclesperanto_prototype
aea964a75e691f19b7753040daa8b276d57ccf36
[ "BSD-3-Clause" ]
1
2021-06-18T14:45:20.000Z
2021-06-18T14:45:20.000Z
import os import sys import numpy as np import pyopencl as cl from pyopencl import characterize from pyopencl import array from ._device import get_device """ Below here, vendored from GPUtools Copyright (c) 2016, Martin Weigert 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 gputools 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 HOLDER 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. """ cl_image_datatype_dict = { cl.channel_type.FLOAT: np.float32, cl.channel_type.UNSIGNED_INT8: np.uint8, cl.channel_type.UNSIGNED_INT16: np.uint16, cl.channel_type.SIGNED_INT8: np.int8, cl.channel_type.SIGNED_INT16: np.int16, cl.channel_type.SIGNED_INT32: np.int32, } cl_image_datatype_dict.update( {dtype: cltype for cltype, dtype in list(cl_image_datatype_dict.items())} ) cl_buffer_datatype_dict = { np.bool: "bool", np.uint8: "uchar", np.uint16: "ushort", np.uint32: "uint", np.uint64: "ulong", np.int8: "char", np.int16: "short", np.int32: "int", np.int64: "long", np.float32: "float", np.complex64: "cfloat_t", } if characterize.has_double_support(get_device().device): cl_buffer_datatype_dict[np.float64] = "double" def abspath(myPath): """ Get absolute path to resource, works for dev and for PyInstaller """ try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS return os.path.join(base_path, os.path.basename(myPath)) except Exception: base_path = os.path.abspath(os.path.dirname(__file__)) return os.path.join(base_path, myPath) def assert_supported_ndarray_type(dtype): # make sure it works for e.g. np.float32 and np.dtype(np.float32) dtype = getattr(dtype, "type", dtype) if dtype not in cl_buffer_datatype_dict: raise KeyError("dtype %s not supported " % dtype) def assert_bufs_type(mytype, *bufs): if not all([b.dtype.type == mytype for b in bufs]): raise TypeError( "all data type of buffer(s) should be %s! but are %s" % (mytype, str([b.dtype.type for b in bufs])) ) def _wrap_OCLArray(cls): """ WRAPPER """ def prepare(arr): return np.require(arr, None, "C") @classmethod def from_array(cls, arr, *args, **kwargs): assert_supported_ndarray_type(arr.dtype.type) queue = get_device().queue return array.to_device(queue, prepare(arr), *args, **kwargs) @classmethod def empty(cls, shape, dtype=np.float32): assert_supported_ndarray_type(dtype) queue = get_device().queue return array.empty(queue, shape, dtype) @classmethod def empty_like(cls, arr): assert_supported_ndarray_type(arr.dtype.type) return cls.empty(arr.shape, arr.dtype.type) @classmethod def zeros(cls, shape, dtype=np.float32): assert_supported_ndarray_type(dtype) queue = get_device().queue return array.zeros(queue, shape, dtype) @classmethod def zeros_like(cls, arr): assert_supported_ndarray_type(arr.dtype.type) queue = get_device().queue return array.zeros(queue, arr.shape, arr.dtype.type) def copy_buffer(self, buf, **kwargs): queue = get_device().queue return cl.enqueue_copy(queue, self.data, buf.data, **kwargs) def write_array(self, arr, **kwargs): assert_supported_ndarray_type(arr.dtype.type) queue = get_device().queue return cl.enqueue_copy(queue, self.data, prepare(arr), **kwargs) def copy_image(self, img, **kwargs): queue = get_device().queue return cl.enqueue_copy( queue, self.data, img, offset=0, origin=(0,) * len(img.shape), region=img.shape, **kwargs, ) def wrap_module_func(mod, f): def func(self, *args, **kwargs): return getattr(mod, f)(self, *args, **kwargs) return func cls.from_array = from_array cls.empty = empty cls.empty_like = empty_like cls.zeros = zeros cls.zeros_like = zeros_like cls.copy_buffer = copy_buffer cls.copy_image = copy_image cls.write_array = write_array cls.__array__ = cls.get def add(x1, x2): if isinstance(x2, (int, float)) : from .._tier1 import add_image_and_scalar return add_image_and_scalar(x1, scalar=x2) else: from .._tier1 import add_images_weighted return add_images_weighted(x1, x2) cls.__add__ = add def iadd(x1, x2): from .._tier1 import copy temp = copy(x1) if isinstance(x2, (int, float)) : from .._tier1 import add_image_and_scalar return add_image_and_scalar(temp, x1, scalar=x2) else: from .._tier1 import add_images_weighted return add_images_weighted(temp, x2, x1) cls.__iadd__ = iadd def sub(x1, x2): if isinstance(x2, (int, float)): from .._tier1 import add_image_and_scalar return add_image_and_scalar(x1, scalar=-x2) else: from .._tier1 import add_images_weighted return add_images_weighted(x1, x2, factor2=-1) cls.__sub__ = sub def isub(x1, x2): from .._tier1 import copy temp = copy(x1) if isinstance(x2, (int, float)) : from .._tier1 import add_image_and_scalar return add_image_and_scalar(temp, x1, scalar=-x2) else: from .._tier1 import add_images_weighted return add_images_weighted(temp, x2, x1, factor2=-1) cls.__isub__ = isub def mul(x1, x2): if isinstance(x2, (int, float)): from .._tier1 import multiply_image_and_scalar return multiply_image_and_scalar(x1, scalar=x2) else: from .._tier1 import multiply_images return multiply_images(x1, x2) cls.__mul__ = mul def imul(x1, x2): from .._tier1 import copy temp = copy(x1) if isinstance(x2, (int, float)): from .._tier1 import multiply_image_and_scalar return multiply_image_and_scalar(temp, x1, scalar=x2) else: from .._tier1 import multiply_images return multiply_images(temp, x2, x1) cls.__imul__ = imul def div(x1, x2): if isinstance(x2, (int, float)): from .._tier1 import multiply_image_and_scalar return multiply_image_and_scalar(x1, scalar=1.0 / x2) else: from .._tier1 import divide_images return divide_images(x1, x2) cls.__div__ = div cls.__truediv__ = div def idiv(x1, x2): from .._tier1 import copy temp = copy(x1) if isinstance(x2, (int, float)): from .._tier1 import multiply_image_and_scalar return multiply_image_and_scalar(temp, x1, scalar=1.0 / x2) else: from .._tier1 import divide_images return divide_images(temp, x2, x1) cls.__idiv__ = idiv cls.__itruediv__ = idiv def gt(x1, x2): if isinstance(x2, (int, float)): from .._tier1 import greater_constant return greater_constant(x1, constant=x2) else: from .._tier1 import greater return greater(x1, x2) cls.__gt__ = gt def ge(x1, x2): if isinstance(x2, (int, float)): from .._tier1 import greater_or_equal_constant return greater_or_equal_constant(x1, constant=x2) else: from .._tier1 import greater_or_equal return greater_or_equal(x1, x2) cls.__ge__ = ge def lt(x1, x2): if isinstance(x2, (int, float)): from .._tier1 import smaller_constant return smaller_constant(x1, constant=x2) else: from .._tier1 import smaller return smaller(x1, x2) cls.__lt__ = lt def le(x1, x2): if isinstance(x2, (int, float)): from .._tier1 import smaller_or_equal_constant return smaller_or_equal_constant(x1, constant=x2) else: from .._tier1 import smaller_or_equal return smaller_or_equal(x1, x2) cls.__le__ = le def eq(x1, x2): if isinstance(x2, (int, float)): from .._tier1 import equal_constant return equal_constant(x1, constant=x2) else: from .._tier1 import equal return equal(x1, x2) cls.__eq__ = eq def ne(x1, x2): if isinstance(x2, (int, float)): from .._tier1 import not_equal_constant return not_equal_constant(x1, constant=x2) else: from .._tier1 import not_equal return not_equal(x1, x2) cls.__ne__ = ne def pos(x1): from .._tier1 import copy return copy(x1) cls.__pos__ = pos def neg(x1): from .._tier1 import subtract_image_from_scalar return subtract_image_from_scalar(x1, scalar=0) cls.__neg__ = neg def pow(x1, x2): if isinstance(x2, (int, float)): from .._tier1 import power return power(x1, exponent=x2) else: from .._tier1 import power_images return power_images(x1, x2) cls.__pow__ = pow def ipow(x1, x2): from .._tier1 import copy temp = copy(x1) if isinstance(x2, (int, float)): from .._tier1 import power return power(temp, x1, exponent=x2) else: from .._tier1 import power_images return power_images(temp, x2, x1) cls.__ipow__ = ipow def min(self, axis=None, out=None): from .._tier2 import minimum_of_all_pixels from .._tier1 import minimum_x_projection from .._tier1 import minimum_y_projection from .._tier1 import minimum_z_projection if axis==0: result = minimum_z_projection(self) elif axis==1: result = minimum_y_projection(self) elif axis==2: result = minimum_x_projection(self) elif axis is None: result = minimum_of_all_pixels(self) else: raise ValueError("Axis " + axis + " not supported") if out is not None: np.copyto(out, result.get().astype(out.dtype)) return result cls.min = min def max(self, axis=None, out=None): from .._tier2 import maximum_of_all_pixels from .._tier1 import maximum_x_projection from .._tier1 import maximum_y_projection from .._tier1 import maximum_z_projection if axis==0: result = maximum_z_projection(self) elif axis==1: result = maximum_y_projection(self) elif axis==2: result = maximum_x_projection(self) elif axis is None: result = maximum_of_all_pixels(self) else: raise ValueError("Axis " + axis + " not supported") if out is not None: np.copyto(out, result.get().astype(out.dtype)) return result cls.max = max def sum(self, axis=None, out=None): from .._tier2 import sum_of_all_pixels from .._tier1 import sum_x_projection from .._tier1 import sum_y_projection from .._tier1 import sum_z_projection if axis==0: result = sum_z_projection(self) elif axis==1: result = sum_y_projection(self) elif axis==2: result = sum_x_projection(self) elif axis is None: result = sum_of_all_pixels(self) else: raise ValueError("Axis " + axis + " not supported") if out is not None: np.copyto(out, result.get().astype(out.dtype)) return result cls.sum = sum cls._former_get = cls._get def _cust_get(self, queue=None, ary=None, async_=None, **kwargs): if not isinstance(queue, cl.CommandQueue): queue = None return self._former_get(queue, ary, async_, **kwargs) cls._get = _cust_get cls._former_get_item = cls.__getitem__ def _cust_get_item(self, index): try: return self._former_get_item(index) except IndexError: raise IndexError("Accessing individual GPU-backed pixels is not fully supported. If you work in napari, use the menu Plugins > clEsperanto > Make labels editable. If you work in python, use numpy.asarray(image) to retrieve a fully accessible copy of the image.") cls.__getitem__ = _cust_get_item # todo: # __floordiv__(x1, x2) # __mod__(x1, x2) # __matmul__(x1, x2) # __inv__(x1, x2) # __invert__(x1, x2) # __lshift__(x1, x2) # __rshift__(x1, x2) # and, or, xor for f in ["dot", "vdot"]: setattr(cls, f, wrap_module_func(array, f)) # for f in dir(cl_math): # if callable(getattr(cl.cl_math, f)): # setattr(cls, f, wrap_module_func(cl.cl_math, f)) # cls.sum = sum cls.__name__ = str("OCLArray") return cls OCLArray = _wrap_OCLArray(array.Array) class _OCLImage: def __init__(self, cl_image : cl.Image): self.data = cl_image self.shape = cl_image.shape[::-1] self.dtype = cl_image.dtype
32.256071
274
0.630304
import os import sys import numpy as np import pyopencl as cl from pyopencl import characterize from pyopencl import array from ._device import get_device cl_image_datatype_dict = { cl.channel_type.FLOAT: np.float32, cl.channel_type.UNSIGNED_INT8: np.uint8, cl.channel_type.UNSIGNED_INT16: np.uint16, cl.channel_type.SIGNED_INT8: np.int8, cl.channel_type.SIGNED_INT16: np.int16, cl.channel_type.SIGNED_INT32: np.int32, } cl_image_datatype_dict.update( {dtype: cltype for cltype, dtype in list(cl_image_datatype_dict.items())} ) cl_buffer_datatype_dict = { np.bool: "bool", np.uint8: "uchar", np.uint16: "ushort", np.uint32: "uint", np.uint64: "ulong", np.int8: "char", np.int16: "short", np.int32: "int", np.int64: "long", np.float32: "float", np.complex64: "cfloat_t", } if characterize.has_double_support(get_device().device): cl_buffer_datatype_dict[np.float64] = "double" def abspath(myPath): try: base_path = sys._MEIPASS return os.path.join(base_path, os.path.basename(myPath)) except Exception: base_path = os.path.abspath(os.path.dirname(__file__)) return os.path.join(base_path, myPath) def assert_supported_ndarray_type(dtype): dtype = getattr(dtype, "type", dtype) if dtype not in cl_buffer_datatype_dict: raise KeyError("dtype %s not supported " % dtype) def assert_bufs_type(mytype, *bufs): if not all([b.dtype.type == mytype for b in bufs]): raise TypeError( "all data type of buffer(s) should be %s! but are %s" % (mytype, str([b.dtype.type for b in bufs])) ) def _wrap_OCLArray(cls): def prepare(arr): return np.require(arr, None, "C") @classmethod def from_array(cls, arr, *args, **kwargs): assert_supported_ndarray_type(arr.dtype.type) queue = get_device().queue return array.to_device(queue, prepare(arr), *args, **kwargs) @classmethod def empty(cls, shape, dtype=np.float32): assert_supported_ndarray_type(dtype) queue = get_device().queue return array.empty(queue, shape, dtype) @classmethod def empty_like(cls, arr): assert_supported_ndarray_type(arr.dtype.type) return cls.empty(arr.shape, arr.dtype.type) @classmethod def zeros(cls, shape, dtype=np.float32): assert_supported_ndarray_type(dtype) queue = get_device().queue return array.zeros(queue, shape, dtype) @classmethod def zeros_like(cls, arr): assert_supported_ndarray_type(arr.dtype.type) queue = get_device().queue return array.zeros(queue, arr.shape, arr.dtype.type) def copy_buffer(self, buf, **kwargs): queue = get_device().queue return cl.enqueue_copy(queue, self.data, buf.data, **kwargs) def write_array(self, arr, **kwargs): assert_supported_ndarray_type(arr.dtype.type) queue = get_device().queue return cl.enqueue_copy(queue, self.data, prepare(arr), **kwargs) def copy_image(self, img, **kwargs): queue = get_device().queue return cl.enqueue_copy( queue, self.data, img, offset=0, origin=(0,) * len(img.shape), region=img.shape, **kwargs, ) def wrap_module_func(mod, f): def func(self, *args, **kwargs): return getattr(mod, f)(self, *args, **kwargs) return func cls.from_array = from_array cls.empty = empty cls.empty_like = empty_like cls.zeros = zeros cls.zeros_like = zeros_like cls.copy_buffer = copy_buffer cls.copy_image = copy_image cls.write_array = write_array cls.__array__ = cls.get def add(x1, x2): if isinstance(x2, (int, float)) : from .._tier1 import add_image_and_scalar return add_image_and_scalar(x1, scalar=x2) else: from .._tier1 import add_images_weighted return add_images_weighted(x1, x2) cls.__add__ = add def iadd(x1, x2): from .._tier1 import copy temp = copy(x1) if isinstance(x2, (int, float)) : from .._tier1 import add_image_and_scalar return add_image_and_scalar(temp, x1, scalar=x2) else: from .._tier1 import add_images_weighted return add_images_weighted(temp, x2, x1) cls.__iadd__ = iadd def sub(x1, x2): if isinstance(x2, (int, float)): from .._tier1 import add_image_and_scalar return add_image_and_scalar(x1, scalar=-x2) else: from .._tier1 import add_images_weighted return add_images_weighted(x1, x2, factor2=-1) cls.__sub__ = sub def isub(x1, x2): from .._tier1 import copy temp = copy(x1) if isinstance(x2, (int, float)) : from .._tier1 import add_image_and_scalar return add_image_and_scalar(temp, x1, scalar=-x2) else: from .._tier1 import add_images_weighted return add_images_weighted(temp, x2, x1, factor2=-1) cls.__isub__ = isub def mul(x1, x2): if isinstance(x2, (int, float)): from .._tier1 import multiply_image_and_scalar return multiply_image_and_scalar(x1, scalar=x2) else: from .._tier1 import multiply_images return multiply_images(x1, x2) cls.__mul__ = mul def imul(x1, x2): from .._tier1 import copy temp = copy(x1) if isinstance(x2, (int, float)): from .._tier1 import multiply_image_and_scalar return multiply_image_and_scalar(temp, x1, scalar=x2) else: from .._tier1 import multiply_images return multiply_images(temp, x2, x1) cls.__imul__ = imul def div(x1, x2): if isinstance(x2, (int, float)): from .._tier1 import multiply_image_and_scalar return multiply_image_and_scalar(x1, scalar=1.0 / x2) else: from .._tier1 import divide_images return divide_images(x1, x2) cls.__div__ = div cls.__truediv__ = div def idiv(x1, x2): from .._tier1 import copy temp = copy(x1) if isinstance(x2, (int, float)): from .._tier1 import multiply_image_and_scalar return multiply_image_and_scalar(temp, x1, scalar=1.0 / x2) else: from .._tier1 import divide_images return divide_images(temp, x2, x1) cls.__idiv__ = idiv cls.__itruediv__ = idiv def gt(x1, x2): if isinstance(x2, (int, float)): from .._tier1 import greater_constant return greater_constant(x1, constant=x2) else: from .._tier1 import greater return greater(x1, x2) cls.__gt__ = gt def ge(x1, x2): if isinstance(x2, (int, float)): from .._tier1 import greater_or_equal_constant return greater_or_equal_constant(x1, constant=x2) else: from .._tier1 import greater_or_equal return greater_or_equal(x1, x2) cls.__ge__ = ge def lt(x1, x2): if isinstance(x2, (int, float)): from .._tier1 import smaller_constant return smaller_constant(x1, constant=x2) else: from .._tier1 import smaller return smaller(x1, x2) cls.__lt__ = lt def le(x1, x2): if isinstance(x2, (int, float)): from .._tier1 import smaller_or_equal_constant return smaller_or_equal_constant(x1, constant=x2) else: from .._tier1 import smaller_or_equal return smaller_or_equal(x1, x2) cls.__le__ = le def eq(x1, x2): if isinstance(x2, (int, float)): from .._tier1 import equal_constant return equal_constant(x1, constant=x2) else: from .._tier1 import equal return equal(x1, x2) cls.__eq__ = eq def ne(x1, x2): if isinstance(x2, (int, float)): from .._tier1 import not_equal_constant return not_equal_constant(x1, constant=x2) else: from .._tier1 import not_equal return not_equal(x1, x2) cls.__ne__ = ne def pos(x1): from .._tier1 import copy return copy(x1) cls.__pos__ = pos def neg(x1): from .._tier1 import subtract_image_from_scalar return subtract_image_from_scalar(x1, scalar=0) cls.__neg__ = neg def pow(x1, x2): if isinstance(x2, (int, float)): from .._tier1 import power return power(x1, exponent=x2) else: from .._tier1 import power_images return power_images(x1, x2) cls.__pow__ = pow def ipow(x1, x2): from .._tier1 import copy temp = copy(x1) if isinstance(x2, (int, float)): from .._tier1 import power return power(temp, x1, exponent=x2) else: from .._tier1 import power_images return power_images(temp, x2, x1) cls.__ipow__ = ipow def min(self, axis=None, out=None): from .._tier2 import minimum_of_all_pixels from .._tier1 import minimum_x_projection from .._tier1 import minimum_y_projection from .._tier1 import minimum_z_projection if axis==0: result = minimum_z_projection(self) elif axis==1: result = minimum_y_projection(self) elif axis==2: result = minimum_x_projection(self) elif axis is None: result = minimum_of_all_pixels(self) else: raise ValueError("Axis " + axis + " not supported") if out is not None: np.copyto(out, result.get().astype(out.dtype)) return result cls.min = min def max(self, axis=None, out=None): from .._tier2 import maximum_of_all_pixels from .._tier1 import maximum_x_projection from .._tier1 import maximum_y_projection from .._tier1 import maximum_z_projection if axis==0: result = maximum_z_projection(self) elif axis==1: result = maximum_y_projection(self) elif axis==2: result = maximum_x_projection(self) elif axis is None: result = maximum_of_all_pixels(self) else: raise ValueError("Axis " + axis + " not supported") if out is not None: np.copyto(out, result.get().astype(out.dtype)) return result cls.max = max def sum(self, axis=None, out=None): from .._tier2 import sum_of_all_pixels from .._tier1 import sum_x_projection from .._tier1 import sum_y_projection from .._tier1 import sum_z_projection if axis==0: result = sum_z_projection(self) elif axis==1: result = sum_y_projection(self) elif axis==2: result = sum_x_projection(self) elif axis is None: result = sum_of_all_pixels(self) else: raise ValueError("Axis " + axis + " not supported") if out is not None: np.copyto(out, result.get().astype(out.dtype)) return result cls.sum = sum cls._former_get = cls._get def _cust_get(self, queue=None, ary=None, async_=None, **kwargs): if not isinstance(queue, cl.CommandQueue): queue = None return self._former_get(queue, ary, async_, **kwargs) cls._get = _cust_get cls._former_get_item = cls.__getitem__ def _cust_get_item(self, index): try: return self._former_get_item(index) except IndexError: raise IndexError("Accessing individual GPU-backed pixels is not fully supported. If you work in napari, use the menu Plugins > clEsperanto > Make labels editable. If you work in python, use numpy.asarray(image) to retrieve a fully accessible copy of the image.") cls.__getitem__ = _cust_get_item for f in ["dot", "vdot"]: setattr(cls, f, wrap_module_func(array, f)) cls.__name__ = str("OCLArray") return cls OCLArray = _wrap_OCLArray(array.Array) class _OCLImage: def __init__(self, cl_image : cl.Image): self.data = cl_image self.shape = cl_image.shape[::-1] self.dtype = cl_image.dtype
true
true
f7f9f0009c476d0aad3fe9fa8c2230b30322c93a
7,311
py
Python
django_faker/tests.py
rosscdh/django-faker
345e3eebcf636e2566d9890ae7b35788ebdb5173
[ "MIT" ]
211
2015-01-02T11:12:25.000Z
2021-11-08T10:54:01.000Z
django_faker/tests.py
rosscdh/django-faker
345e3eebcf636e2566d9890ae7b35788ebdb5173
[ "MIT" ]
21
2015-01-21T10:33:43.000Z
2020-04-12T17:57:20.000Z
django_faker/tests.py
rosscdh/django-faker
345e3eebcf636e2566d9890ae7b35788ebdb5173
[ "MIT" ]
50
2015-01-21T19:38:36.000Z
2021-09-29T08:01:28.000Z
from faker import Faker from django_faker.populator import Populator from django_faker import Faker as DjangoFaker from django.db import models from django.utils import unittest from django.template import Context, TemplateSyntaxError from django.template import Template fake = Faker() class Game(models.Model): title= models.CharField(max_length=200) slug= models.SlugField(max_length=200) description= models.TextField() created_at= models.DateTimeField() updated_date= models.DateField() updated_time= models.TimeField() active= models.BooleanField() max_score= models.BigIntegerField() class Player(models.Model): nickname= models.CharField(max_length=100) score= models.BigIntegerField() last_login_at= models.DateTimeField() game= models.ForeignKey(Game) class Action(models.Model): ACTION_FIRE='fire' ACTION_MOVE='move' ACTION_STOP='stop' ACTIONS = ( (ACTION_FIRE,'Fire'), (ACTION_MOVE,'Move'), (ACTION_STOP,'Stop'), ) name= models.CharField(max_length=4, choices=ACTIONS) executed_at= models.DateTimeField() actor= models.ForeignKey(Player,related_name='actions', null=True) target= models.ForeignKey(Player, related_name='enemy_actions+', null=True) class PopulatorTestCase(unittest.TestCase): def testPopulation(self): generator = fake populator = Populator(generator) populator.addEntity( Game, 10 ) self.assertEqual(len(populator.execute()[Game]), 10) def testGuesser(self): generator = fake def title_fake(arg): title_fake.count += 1 name = generator.company() return name title_fake.count = 0 populator = Populator(generator) populator.addEntity( Game, 10, { 'title': title_fake } ) self.assertEqual(len(populator.execute()[Game]), title_fake.count) def testFormatter(self): generator = fake populator = Populator( generator ) populator.addEntity(Game,5) populator.addEntity(Player, 10, { 'score': lambda x: fake.randomInt(0,1000), 'nickname': lambda x: fake.email() }) populator.addEntity(Action,30) insertedPks = populator.execute() self.assertTrue( len(insertedPks[Game]) == 5 ) self.assertTrue( len(insertedPks[Player]) == 10 ) self.assertTrue( any([0 <= p.score <= 1000 and '@' in p.nickname for p in Player.objects.all() ]) ) class TemplateTagsTestCase(unittest.TestCase): @staticmethod def render( template, context=None ): t = Template("{% load fakers %}"+template) c = Context(context or {}) text= t.render(c) return text # do_fake: fake def testSimpleFakeTag(self): self.assertNotEqual(self.render("{% fake 'name' as myname %}{{ myname }}"),"") def testSimpleFakeTagWithArguments(self): self.assertNotEqual(self.render("{% fake 'dateTimeBetween' '-10d' as mydate %}{{ mydate }}"),"") def testSimpleFakeTagFormatterNotFoundRaisesException(self): with self.assertRaises(AttributeError): self.render("{% fake 'notFoundedFake' as foo %}") def testSimpleFakeTagOptionalAssignment(self): self.assertNotEqual(self.render("{% fake 'name' %}"),"") self.assertEqual(len(self.render("{% fake 'md5' %}")),32) # do_fake_filter: fake def testFakeFilterTag(self): self.assertIn(self.render("{{ 'randomElement'|fake:'testString' }}"),'testString') def testFakeFilterWithValueFromContext(self): mylist = [100,200,300] rendered = self.render("{{ 'randomElement'|fake:mylist }}", {'mylist': mylist}) self.assertIn(rendered, [unicode(el) for el in mylist]) def testFakeFilterFormatterNotFoundRaisesException(self): with self.assertRaises(AttributeError): self.render("{{ 'notFoundedFake'|fake:mylist }}", {'mylist': [100,200,300]}) def testFakeFilterAsIfCondition(self): self.assertEqual(self.render("{% if 'boolean'|fake:100 %}True forever{% endif %}"), "True forever") self.assertEqual(self.render("{% if 'boolean'|fake:0 %}{% else %}False forever{% endif %}"), "False forever") def testFakeFilterAsForInRange(self): times = 10 rendered = self.render("{% for word in 'words'|fake:times %}{{ word }}\n{% endfor %}",{'times':times}) words = [word for word in rendered.split('\n') if word.strip()] self.assertEqual( len(words) , times) # do_or_fake_filter: or_fake def testOrFakeFilterTag(self): self.assertEqual(len(self.render("{{ unknown_var|or_fake:'md5' }}")), 32) def testFullXmlContact(self): self.assertTrue(self.render("""<?xml version="1.0" encoding="UTF-8"?> <contacts> {% fake 'randomInt' 10 20 as times %} {% for i in 10|get_range %} <contact firstName="{% fake 'firstName' %}" lastName="{% fake 'lastName' %}" email="{% fake 'email' %}"/> <phone number="{% fake 'phoneNumber' %}"/> {% if 'boolean'|fake:25 %} <birth date="{{ 'dateTimeThisCentury'|fake|date:"D d M Y" }}" place="{% fake 'city' %}"/> {% endif %} <address> <street>{% fake 'streetAddress' %}</street> <city>{% fake 'city' %}</city> <postcode>{% fake 'postcode' %}</postcode> <state>{% fake 'state' %}</state> </address> <company name="{% fake 'company' %}" catchPhrase="{% fake 'catchPhrase' %}"> {% if 'boolean'|fake:25 %} <offer>{% fake 'bs' %}</offer> {% endif %} {% if 'boolean'|fake:33 %} <director name="{% fake 'name' %}" /> {% endif %} </company> {% if 'boolean'|fake:15 %} <details> <![CDATA[ {% fake 'text' 500 %} ]]> </details> {% endif %} </contact> {% endfor %} </contacts> """)) class APIDjangoFakerTestCase(unittest.TestCase): def testDjangoFakerSingleton(self): self.assertEqual( DjangoFaker() , DjangoFaker() ) self.assertIs( DjangoFaker() , DjangoFaker() ) def testFakerCacheGenerator(self): self.assertEqual( DjangoFaker().getGenerator(), DjangoFaker().getGenerator() ) self.assertIs( DjangoFaker().getGenerator(), DjangoFaker().getGenerator() ) self.assertIs( DjangoFaker().getGenerator(codename='default'), DjangoFaker().getGenerator(codename='default') ) self.assertEqual( DjangoFaker().getGenerator(locale='it_IT'), DjangoFaker().getGenerator(locale='it_IT') ) self.assertIs( DjangoFaker().getGenerator(locale='it_IT'), DjangoFaker().getGenerator(locale='it_IT') ) def testFakerCachePopulator(self): self.assertEqual( DjangoFaker().getPopulator(), DjangoFaker().getPopulator() ) self.assertIs( DjangoFaker().getPopulator(), DjangoFaker().getPopulator() ) self.assertIs( DjangoFaker().getPopulator().generator, DjangoFaker().getPopulator().generator ) self.assertEqual( DjangoFaker().getPopulator(locale='it_IT'), DjangoFaker().getPopulator(locale='it_IT') ) self.assertIs( DjangoFaker().getPopulator(locale='it_IT'), DjangoFaker().getPopulator(locale='it_IT') )
34.485849
119
0.63083
from faker import Faker from django_faker.populator import Populator from django_faker import Faker as DjangoFaker from django.db import models from django.utils import unittest from django.template import Context, TemplateSyntaxError from django.template import Template fake = Faker() class Game(models.Model): title= models.CharField(max_length=200) slug= models.SlugField(max_length=200) description= models.TextField() created_at= models.DateTimeField() updated_date= models.DateField() updated_time= models.TimeField() active= models.BooleanField() max_score= models.BigIntegerField() class Player(models.Model): nickname= models.CharField(max_length=100) score= models.BigIntegerField() last_login_at= models.DateTimeField() game= models.ForeignKey(Game) class Action(models.Model): ACTION_FIRE='fire' ACTION_MOVE='move' ACTION_STOP='stop' ACTIONS = ( (ACTION_FIRE,'Fire'), (ACTION_MOVE,'Move'), (ACTION_STOP,'Stop'), ) name= models.CharField(max_length=4, choices=ACTIONS) executed_at= models.DateTimeField() actor= models.ForeignKey(Player,related_name='actions', null=True) target= models.ForeignKey(Player, related_name='enemy_actions+', null=True) class PopulatorTestCase(unittest.TestCase): def testPopulation(self): generator = fake populator = Populator(generator) populator.addEntity( Game, 10 ) self.assertEqual(len(populator.execute()[Game]), 10) def testGuesser(self): generator = fake def title_fake(arg): title_fake.count += 1 name = generator.company() return name title_fake.count = 0 populator = Populator(generator) populator.addEntity( Game, 10, { 'title': title_fake } ) self.assertEqual(len(populator.execute()[Game]), title_fake.count) def testFormatter(self): generator = fake populator = Populator( generator ) populator.addEntity(Game,5) populator.addEntity(Player, 10, { 'score': lambda x: fake.randomInt(0,1000), 'nickname': lambda x: fake.email() }) populator.addEntity(Action,30) insertedPks = populator.execute() self.assertTrue( len(insertedPks[Game]) == 5 ) self.assertTrue( len(insertedPks[Player]) == 10 ) self.assertTrue( any([0 <= p.score <= 1000 and '@' in p.nickname for p in Player.objects.all() ]) ) class TemplateTagsTestCase(unittest.TestCase): @staticmethod def render( template, context=None ): t = Template("{% load fakers %}"+template) c = Context(context or {}) text= t.render(c) return text def testSimpleFakeTag(self): self.assertNotEqual(self.render("{% fake 'name' as myname %}{{ myname }}"),"") def testSimpleFakeTagWithArguments(self): self.assertNotEqual(self.render("{% fake 'dateTimeBetween' '-10d' as mydate %}{{ mydate }}"),"") def testSimpleFakeTagFormatterNotFoundRaisesException(self): with self.assertRaises(AttributeError): self.render("{% fake 'notFoundedFake' as foo %}") def testSimpleFakeTagOptionalAssignment(self): self.assertNotEqual(self.render("{% fake 'name' %}"),"") self.assertEqual(len(self.render("{% fake 'md5' %}")),32) def testFakeFilterTag(self): self.assertIn(self.render("{{ 'randomElement'|fake:'testString' }}"),'testString') def testFakeFilterWithValueFromContext(self): mylist = [100,200,300] rendered = self.render("{{ 'randomElement'|fake:mylist }}", {'mylist': mylist}) self.assertIn(rendered, [unicode(el) for el in mylist]) def testFakeFilterFormatterNotFoundRaisesException(self): with self.assertRaises(AttributeError): self.render("{{ 'notFoundedFake'|fake:mylist }}", {'mylist': [100,200,300]}) def testFakeFilterAsIfCondition(self): self.assertEqual(self.render("{% if 'boolean'|fake:100 %}True forever{% endif %}"), "True forever") self.assertEqual(self.render("{% if 'boolean'|fake:0 %}{% else %}False forever{% endif %}"), "False forever") def testFakeFilterAsForInRange(self): times = 10 rendered = self.render("{% for word in 'words'|fake:times %}{{ word }}\n{% endfor %}",{'times':times}) words = [word for word in rendered.split('\n') if word.strip()] self.assertEqual( len(words) , times) def testOrFakeFilterTag(self): self.assertEqual(len(self.render("{{ unknown_var|or_fake:'md5' }}")), 32) def testFullXmlContact(self): self.assertTrue(self.render("""<?xml version="1.0" encoding="UTF-8"?> <contacts> {% fake 'randomInt' 10 20 as times %} {% for i in 10|get_range %} <contact firstName="{% fake 'firstName' %}" lastName="{% fake 'lastName' %}" email="{% fake 'email' %}"/> <phone number="{% fake 'phoneNumber' %}"/> {% if 'boolean'|fake:25 %} <birth date="{{ 'dateTimeThisCentury'|fake|date:"D d M Y" }}" place="{% fake 'city' %}"/> {% endif %} <address> <street>{% fake 'streetAddress' %}</street> <city>{% fake 'city' %}</city> <postcode>{% fake 'postcode' %}</postcode> <state>{% fake 'state' %}</state> </address> <company name="{% fake 'company' %}" catchPhrase="{% fake 'catchPhrase' %}"> {% if 'boolean'|fake:25 %} <offer>{% fake 'bs' %}</offer> {% endif %} {% if 'boolean'|fake:33 %} <director name="{% fake 'name' %}" /> {% endif %} </company> {% if 'boolean'|fake:15 %} <details> <![CDATA[ {% fake 'text' 500 %} ]]> </details> {% endif %} </contact> {% endfor %} </contacts> """)) class APIDjangoFakerTestCase(unittest.TestCase): def testDjangoFakerSingleton(self): self.assertEqual( DjangoFaker() , DjangoFaker() ) self.assertIs( DjangoFaker() , DjangoFaker() ) def testFakerCacheGenerator(self): self.assertEqual( DjangoFaker().getGenerator(), DjangoFaker().getGenerator() ) self.assertIs( DjangoFaker().getGenerator(), DjangoFaker().getGenerator() ) self.assertIs( DjangoFaker().getGenerator(codename='default'), DjangoFaker().getGenerator(codename='default') ) self.assertEqual( DjangoFaker().getGenerator(locale='it_IT'), DjangoFaker().getGenerator(locale='it_IT') ) self.assertIs( DjangoFaker().getGenerator(locale='it_IT'), DjangoFaker().getGenerator(locale='it_IT') ) def testFakerCachePopulator(self): self.assertEqual( DjangoFaker().getPopulator(), DjangoFaker().getPopulator() ) self.assertIs( DjangoFaker().getPopulator(), DjangoFaker().getPopulator() ) self.assertIs( DjangoFaker().getPopulator().generator, DjangoFaker().getPopulator().generator ) self.assertEqual( DjangoFaker().getPopulator(locale='it_IT'), DjangoFaker().getPopulator(locale='it_IT') ) self.assertIs( DjangoFaker().getPopulator(locale='it_IT'), DjangoFaker().getPopulator(locale='it_IT') )
true
true
f7f9f0321b032e73bc4529c029db24c1debcfe05
700
py
Python
tests/templatetags/test_django_htmx.py
felixxm/django-htmx
06a2b430c6ec573d9b04319bae299e5e03c35713
[ "MIT" ]
452
2020-10-18T17:48:17.000Z
2022-03-31T09:23:01.000Z
tests/templatetags/test_django_htmx.py
felixxm/django-htmx
06a2b430c6ec573d9b04319bae299e5e03c35713
[ "MIT" ]
101
2020-12-18T01:18:08.000Z
2022-03-14T08:05:34.000Z
tests/templatetags/test_django_htmx.py
felixxm/django-htmx
06a2b430c6ec573d9b04319bae299e5e03c35713
[ "MIT" ]
47
2020-11-24T20:32:09.000Z
2022-03-29T20:25:47.000Z
from django.template import Context, Template from django.test import SimpleTestCase, override_settings class DjangoHtmxScriptTests(SimpleTestCase): def test_non_debug_empty(self): result = Template("{% load django_htmx %}{% django_htmx_script %}").render( Context() ) assert result == "" def test_debug_success(self): with override_settings(DEBUG=True): result = Template("{% load django_htmx %}{% django_htmx_script %}").render( Context() ) assert result == ( '<script type="text/javascript" src="django-htmx.js" ' + 'data-debug="True" async defer></script>' )
30.434783
87
0.605714
from django.template import Context, Template from django.test import SimpleTestCase, override_settings class DjangoHtmxScriptTests(SimpleTestCase): def test_non_debug_empty(self): result = Template("{% load django_htmx %}{% django_htmx_script %}").render( Context() ) assert result == "" def test_debug_success(self): with override_settings(DEBUG=True): result = Template("{% load django_htmx %}{% django_htmx_script %}").render( Context() ) assert result == ( '<script type="text/javascript" src="django-htmx.js" ' + 'data-debug="True" async defer></script>' )
true
true
f7f9f03230751a9ba1d767a5c2e41c3db2cb3ef9
5,422
py
Python
flexget/components/seen/seen.py
Jeremiad/Flexget
73e6e062eeb126eaec8737a6d6c94ccf3d250b03
[ "MIT" ]
1,322
2015-01-01T22:00:25.000Z
2022-03-30T05:37:46.000Z
flexget/components/seen/seen.py
Jeremiad/Flexget
73e6e062eeb126eaec8737a6d6c94ccf3d250b03
[ "MIT" ]
2,384
2015-01-01T04:23:15.000Z
2022-03-31T01:06:43.000Z
flexget/components/seen/seen.py
Jeremiad/Flexget
73e6e062eeb126eaec8737a6d6c94ccf3d250b03
[ "MIT" ]
617
2015-01-02T15:15:07.000Z
2022-03-15T12:29:31.000Z
from loguru import logger from flexget import plugin from flexget.event import event from . import db logger = logger.bind(name='seen') class FilterSeen: """ Remembers previously downloaded content and rejects them in subsequent executions. Without this plugin FlexGet would download all matching content on every execution. This plugin is enabled on all tasks by default. See wiki for more information. """ schema = { 'oneOf': [ {'type': 'boolean'}, {'type': 'string', 'enum': ['global', 'local']}, { 'type': 'object', 'properties': { 'local': {'type': 'boolean'}, 'fields': { 'type': 'array', 'items': {'type': 'string'}, "minItems": 1, "uniqueItems": True, }, }, }, ] } def __init__(self): # remember and filter by these fields self.fields = ['title', 'url', 'original_url'] self.keyword = 'seen' def prepare_config(self, config): if config is None: config = {} elif isinstance(config, bool): if config is False: return config else: config = {'local': False} elif isinstance(config, str): config = {'local': config == 'local'} config.setdefault('local', False) config.setdefault('fields', self.fields) return config @plugin.priority(plugin.PRIORITY_FIRST) def on_task_filter(self, task, config, remember_rejected=False): """Filter entries already accepted on previous runs.""" config = self.prepare_config(config) if config is False: logger.debug('{} is disabled', self.keyword) return fields = config.get('fields') local = config.get('local') for entry in task.entries: # construct list of values looked values = [] for field in fields: if field not in entry: continue if entry[field] not in values and entry[field]: values.append(str(entry[field])) if values: logger.trace('querying for: {}', ', '.join(values)) # check if SeenField.value is any of the values found = db.search_by_field_values( field_value_list=values, task_name=task.name, local=local, session=task.session ) if found: logger.debug( "Rejecting '{}' '{}' because of seen '{}'", entry['url'], entry['title'], found.value, ) se = ( task.session.query(db.SeenEntry) .filter(db.SeenEntry.id == found.seen_entry_id) .one() ) entry.reject( 'Entry with %s `%s` is already marked seen in the task %s at %s' % (found.field, found.value, se.task, se.added.strftime('%Y-%m-%d %H:%M')), remember=remember_rejected, ) def on_task_learn(self, task, config): """Remember succeeded entries""" config = self.prepare_config(config) if config is False: logger.debug('disabled') return fields = config.get('fields') local = config.get('local') if isinstance(config, list): fields.extend(config) for entry in task.accepted: self.learn(task, entry, fields=fields, local=local) # verbose if in learning mode if task.options.learn: logger.info("Learned '{}' (will skip this in the future)", entry['title']) def learn(self, task, entry, fields=None, reason=None, local=False): """Marks entry as seen""" # no explicit fields given, use default if not fields: fields = self.fields se = db.SeenEntry(entry['title'], str(task.name), reason, local) remembered = [] for field in fields: if field not in entry: continue # removes duplicate values (eg. url, original_url are usually same) if entry[field] in remembered: continue remembered.append(entry[field]) sf = db.SeenField(str(field), str(entry[field])) se.fields.append(sf) logger.debug("Learned '{}' (field: {}, local: {})", entry[field], field, local) # Only add the entry to the session if it has one of the required fields if se.fields: task.session.add(se) def forget(self, task, title): """Forget SeenEntry with :title:. Return True if forgotten.""" se = task.session.query(db.SeenEntry).filter(db.SeenEntry.title == title).first() if se: logger.debug("Forgotten '{}' ({} fields)", title, len(se.fields)) task.session.delete(se) return True @event('plugin.register') def register_plugin(): plugin.register(FilterSeen, 'seen', builtin=True, api_ver=2)
34.980645
99
0.514201
from loguru import logger from flexget import plugin from flexget.event import event from . import db logger = logger.bind(name='seen') class FilterSeen: schema = { 'oneOf': [ {'type': 'boolean'}, {'type': 'string', 'enum': ['global', 'local']}, { 'type': 'object', 'properties': { 'local': {'type': 'boolean'}, 'fields': { 'type': 'array', 'items': {'type': 'string'}, "minItems": 1, "uniqueItems": True, }, }, }, ] } def __init__(self): self.fields = ['title', 'url', 'original_url'] self.keyword = 'seen' def prepare_config(self, config): if config is None: config = {} elif isinstance(config, bool): if config is False: return config else: config = {'local': False} elif isinstance(config, str): config = {'local': config == 'local'} config.setdefault('local', False) config.setdefault('fields', self.fields) return config @plugin.priority(plugin.PRIORITY_FIRST) def on_task_filter(self, task, config, remember_rejected=False): config = self.prepare_config(config) if config is False: logger.debug('{} is disabled', self.keyword) return fields = config.get('fields') local = config.get('local') for entry in task.entries: values = [] for field in fields: if field not in entry: continue if entry[field] not in values and entry[field]: values.append(str(entry[field])) if values: logger.trace('querying for: {}', ', '.join(values)) found = db.search_by_field_values( field_value_list=values, task_name=task.name, local=local, session=task.session ) if found: logger.debug( "Rejecting '{}' '{}' because of seen '{}'", entry['url'], entry['title'], found.value, ) se = ( task.session.query(db.SeenEntry) .filter(db.SeenEntry.id == found.seen_entry_id) .one() ) entry.reject( 'Entry with %s `%s` is already marked seen in the task %s at %s' % (found.field, found.value, se.task, se.added.strftime('%Y-%m-%d %H:%M')), remember=remember_rejected, ) def on_task_learn(self, task, config): config = self.prepare_config(config) if config is False: logger.debug('disabled') return fields = config.get('fields') local = config.get('local') if isinstance(config, list): fields.extend(config) for entry in task.accepted: self.learn(task, entry, fields=fields, local=local) if task.options.learn: logger.info("Learned '{}' (will skip this in the future)", entry['title']) def learn(self, task, entry, fields=None, reason=None, local=False): if not fields: fields = self.fields se = db.SeenEntry(entry['title'], str(task.name), reason, local) remembered = [] for field in fields: if field not in entry: continue if entry[field] in remembered: continue remembered.append(entry[field]) sf = db.SeenField(str(field), str(entry[field])) se.fields.append(sf) logger.debug("Learned '{}' (field: {}, local: {})", entry[field], field, local) if se.fields: task.session.add(se) def forget(self, task, title): se = task.session.query(db.SeenEntry).filter(db.SeenEntry.title == title).first() if se: logger.debug("Forgotten '{}' ({} fields)", title, len(se.fields)) task.session.delete(se) return True @event('plugin.register') def register_plugin(): plugin.register(FilterSeen, 'seen', builtin=True, api_ver=2)
true
true
f7f9f13000e86c4fc5bd537b79f20e41d8fca340
3,251
py
Python
gamestonk_terminal/jupyter/dashboards/dashboards_controller.py
GarnixJu2015/GamestonkTerminal
ec400e46ddce4ac934af836b863528f14a13d865
[ "MIT" ]
null
null
null
gamestonk_terminal/jupyter/dashboards/dashboards_controller.py
GarnixJu2015/GamestonkTerminal
ec400e46ddce4ac934af836b863528f14a13d865
[ "MIT" ]
null
null
null
gamestonk_terminal/jupyter/dashboards/dashboards_controller.py
GarnixJu2015/GamestonkTerminal
ec400e46ddce4ac934af836b863528f14a13d865
[ "MIT" ]
null
null
null
"""Dashboards Module""" __docformat__ = "numpy" import os import argparse import subprocess from typing import List from prompt_toolkit.completion import NestedCompleter from gamestonk_terminal.rich_config import console from gamestonk_terminal.parent_classes import BaseController from gamestonk_terminal import feature_flags as gtff from gamestonk_terminal.helper_funcs import ( EXPORT_ONLY_RAW_DATA_ALLOWED, parse_known_args_and_warn, ) from gamestonk_terminal.menu import session # pylint: disable=consider-using-with class DashboardsController(BaseController): """Dashboards Controller class""" CHOICES_COMMANDS = ["stocks", "correlation", "vsurf", "chains"] PATH = "/jupyter/dashboard/" def __init__(self, queue: List[str] = None): """Constructor""" super().__init__(queue) if session and gtff.USE_PROMPT_TOOLKIT: choices: dict = {c: {} for c in self.controller_choices} self.completer = NestedCompleter.from_nested_dict(choices) def print_help(self): """Print help""" help_text = """[cmds] stocks historic stock information correlation stock correlations vsurf options volatility surface chains options chain analysis[/cmds] """ console.print(text=help_text, menu="Jupyter - Dashboards") def call_stocks(self, other_args: List[str]): """Process stocks command""" create_call(other_args, "stocks", "stocks") def call_correlation(self, other_args: List[str]): """Process correlation command""" create_call(other_args, "correlation", "correlation") def call_vsurf(self, other_args: List[str]): """Process vsurf command""" create_call(other_args, "vsurf", "") def call_chains(self, other_args: List[str]): """Process vsurf command""" create_call(other_args, "chains", "") def create_call(other_args: List[str], name: str, filename: str = None) -> None: filename = filename if filename else name parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog=name, description="""Shows correlations between stocks""", ) parser.add_argument( "-j", "--jupyter", action="store_true", default=False, dest="jupyter", help="Shows dashboard in jupyter-lab.", ) ns_parser = parse_known_args_and_warn( parser, other_args, EXPORT_ONLY_RAW_DATA_ALLOWED ) if ns_parser: cmd = "jupyter-lab" if ns_parser.jupyter else "voila" file = os.path.join( os.path.abspath(os.path.dirname(__file__)), f"{filename}.ipynb" ) console.print(f"Warning: opens a port on your computer to run a {cmd} server.") response = input("Would you like us to run the server for you? y/n\n") if response.lower() == "y": subprocess.Popen( f"{cmd} {file}", stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, ) else: console.print(f"Type: {cmd} {file}\ninto a terminal to run.") console.print("")
31.872549
87
0.645955
__docformat__ = "numpy" import os import argparse import subprocess from typing import List from prompt_toolkit.completion import NestedCompleter from gamestonk_terminal.rich_config import console from gamestonk_terminal.parent_classes import BaseController from gamestonk_terminal import feature_flags as gtff from gamestonk_terminal.helper_funcs import ( EXPORT_ONLY_RAW_DATA_ALLOWED, parse_known_args_and_warn, ) from gamestonk_terminal.menu import session class DashboardsController(BaseController): CHOICES_COMMANDS = ["stocks", "correlation", "vsurf", "chains"] PATH = "/jupyter/dashboard/" def __init__(self, queue: List[str] = None): super().__init__(queue) if session and gtff.USE_PROMPT_TOOLKIT: choices: dict = {c: {} for c in self.controller_choices} self.completer = NestedCompleter.from_nested_dict(choices) def print_help(self): help_text = """[cmds] stocks historic stock information correlation stock correlations vsurf options volatility surface chains options chain analysis[/cmds] """ console.print(text=help_text, menu="Jupyter - Dashboards") def call_stocks(self, other_args: List[str]): create_call(other_args, "stocks", "stocks") def call_correlation(self, other_args: List[str]): create_call(other_args, "correlation", "correlation") def call_vsurf(self, other_args: List[str]): create_call(other_args, "vsurf", "") def call_chains(self, other_args: List[str]): create_call(other_args, "chains", "") def create_call(other_args: List[str], name: str, filename: str = None) -> None: filename = filename if filename else name parser = argparse.ArgumentParser( add_help=False, formatter_class=argparse.ArgumentDefaultsHelpFormatter, prog=name, description="""Shows correlations between stocks""", ) parser.add_argument( "-j", "--jupyter", action="store_true", default=False, dest="jupyter", help="Shows dashboard in jupyter-lab.", ) ns_parser = parse_known_args_and_warn( parser, other_args, EXPORT_ONLY_RAW_DATA_ALLOWED ) if ns_parser: cmd = "jupyter-lab" if ns_parser.jupyter else "voila" file = os.path.join( os.path.abspath(os.path.dirname(__file__)), f"{filename}.ipynb" ) console.print(f"Warning: opens a port on your computer to run a {cmd} server.") response = input("Would you like us to run the server for you? y/n\n") if response.lower() == "y": subprocess.Popen( f"{cmd} {file}", stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True, ) else: console.print(f"Type: {cmd} {file}\ninto a terminal to run.") console.print("")
true
true
f7f9f2c30c2a5a2c1cb3385eb335648d3066ef3f
48,534
py
Python
cogs/Mod.py
JakeWasChosen/edoC
fda4285878a76987761d0ff81e761d10d90bb046
[ "MIT" ]
1
2021-09-23T15:42:35.000Z
2021-09-23T15:42:35.000Z
cogs/Mod.py
JakeWasChosen/edoC
fda4285878a76987761d0ff81e761d10d90bb046
[ "MIT" ]
null
null
null
cogs/Mod.py
JakeWasChosen/edoC
fda4285878a76987761d0ff81e761d10d90bb046
[ "MIT" ]
2
2021-08-29T20:45:53.000Z
2021-09-01T16:20:38.000Z
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # Copyright (c) 2021. Jason Cameron + # All rights reserved. + # This file is part of the edoC discord bot project , + # and is released under the "MIT License Agreement". Please see the LICENSE + # file that should have been included as part of this package. + # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ import argparse import asyncio import copy import datetime import logging import re import shlex from collections import Counter from io import BytesIO import discord from discord import NotFound, Object from discord.ext import commands from discord.ext.commands import Converter, BadArgument from discord.utils import find from cogs.Discordinfo import format_relative, plural # from lib.db import db from utils import checks, default from utils.checks import MemberConverterr from utils.default import mod_or_permissions from utils.vars import * log = logging.getLogger('mod') class Arguments(argparse.ArgumentParser): def error(self, message): raise RuntimeError(message) class BannedUser(Converter): async def convert(self, ctx, arg): if ctx.guild.me.guild_permissions.ban_members: if arg.isdigit(): try: return (await ctx.guild.fetch_ban(Object(id=int(arg)))).user except NotFound: raise BadArgument banned = [e.user for e in await ctx.guild.bans()] if banned: if (user := find(lambda u: str(u) == arg, banned)) is not None: return user else: raise BadArgument class MemberID(commands.Converter): async def convert(self, ctx, argument): try: m = await commands.MemberConverter().convert(ctx, argument) except commands.BadArgument: try: return int(argument, base=10) except ValueError: raise commands.BadArgument(f"{argument} is not a valid member or member ID.") from None else: return m.id class ActionReason(commands.Converter): async def convert(self, ctx, argument): ret = argument if len(ret) > 512: reason_max = 512 - len(ret) - len(argument) raise commands.BadArgument(f"reason is too long ({len(argument)}/{reason_max})") return ret BannedUsers = {} async def Get_Banned_Users(bot): bans = bot.db.field("SELECT id FROM users WHERE banned = ?", "True") for UserID in bans: BannedUsers + UserID async def BannedU(ctx): if ctx.author in BannedUsers: print(f"Command by {ctx.author} blocked!") async def pred(ctx): if ctx.author in BannedUsers: return ctx.send("You are banned from using commands") return pred async def BanUser(ctx, userid: MemberID, reason): BannedUsers + userid ctx.bot.db.execute("INSERT INTO users (?, ?)", (userid, reason,)) # db.execute("INSERT INTO users (Reason)", reason) ctx.bot.db.commit() return await ctx.send(f'{userid} Was banned from using the bot') def can_execute_action(ctx, user, target): return user.id == ctx.bot.owner_id or \ user == ctx.guild.owner or \ user.top_role > target.top_role class NoMuteRole(commands.CommandError): def __init__(self): super().__init__('This server does not have a mute role set up.') def can_mute(): async def predicate(ctx): is_owner = await ctx.bot.is_owner(ctx.author) if ctx.guild is None: return False if not ctx.author.guild_permissions.manage_roles and not is_owner: return False # This will only be used within this cog. role = discord.utils.get(ctx.guild.roles, name='Muted') for channel in ctx.guild.text_channels: await channel.set_permissions(role, overwrite=discord.PermissionOverwrite(send_messages=False, add_reactions=False)) for channel in ctx.guild.voice_channels: await channel.set_permissions(role, overwrite=discord.PermissionOverwrite(speak=False)) if role is None: perms = ctx.guild.default_role.permissions role = await ctx.guild.create_role(name="Muted", permissions=perms) return ctx.author.top_role > role return commands.check(predicate) class Mod(commands.Cog, description='Moderator go brrrrrrrr ~ban'): def __init__(self, bot): self.bot = bot self.config = bot.config async def _basic_cleanup_strategy(self, ctx, search): count = 0 async for msg in ctx.history(limit=search, before=ctx.message): if msg.author == ctx.me and not (msg.mentions or msg.role_mentions): await msg.delete() count += 1 return {'Bot': count} async def _complex_cleanup_strategy(self, ctx, search): prefixes = tuple(self.bot.get_guild_prefixes(ctx.guild)) # thanks startswith todo update this bc it wont work rn def check(m): return m.author == ctx.me or m.content.startswith(prefixes) deleted = await ctx.channel.purge(limit=search, check=check, before=ctx.message) return Counter(m.author.display_name for m in deleted) async def _regular_user_cleanup_strategy(self, ctx, search): prefixes = tuple(self.bot.get_guild_prefixes(ctx.guild)) def check(m): return (m.author == ctx.me or m.content.startswith(prefixes)) and not (m.mentions or m.role_mentions) deleted = await ctx.channel.purge(limit=search, check=check, before=ctx.message) return Counter(m.author.display_name for m in deleted) @commands.command() async def cleanup(self, ctx, search=100): """Cleans up the bot's messages from the channel. If a search number is specified, it searches that many messages to delete. If the bot has Manage Messages permissions then it will try to delete messages that look like they invoked the bot as well. After the cleanup is completed, the bot will send you a message with which people got their messages deleted and their count. This is useful to see which users are spammers. Members with Manage Messages can search up to 1000 messages. Members without can search up to 25 messages. """ strategy = self._basic_cleanup_strategy is_mod = ctx.channel.permissions_for(ctx.author).manage_messages if ctx.channel.permissions_for(ctx.me).manage_messages: if is_mod: strategy = self._complex_cleanup_strategy else: strategy = self._regular_user_cleanup_strategy if is_mod: search = min(max(2, search), 1000) else: search = min(max(2, search), 25) spammers = await strategy(ctx, search) deleted = sum(spammers.values()) messages = [f'{deleted} message{" was" if deleted == 1 else "s were"} removed.'] if deleted: messages.append('') spammers = sorted(spammers.items(), key=lambda t: t[1], reverse=True) messages.extend(f'- **{author}**: {count}' for author, count in spammers) await ctx.send('\n'.join(messages), delete_after=10) @commands.command(aliases=['newmembers', 'nu']) @commands.guild_only() async def newusers(self, ctx, *, count=5): """Tells you the newest members of the server. This is useful to check if any suspicious members have joined. The count parameter can only be up to 25. """ count = max(min(count, 25), 5) if not ctx.guild.chunked: members = await ctx.guild.chunk(cache=True) members = sorted(ctx.guild.members, key=lambda m: m.joined_at, reverse=True)[:count] e = discord.Embed(title='New Members', colour=green) for member in members: body = f'Joined {format_relative(member.joined_at)}\nCreated {format_relative(member.created_at)}' e.add_field(name=f'{member} (ID: {member.id})', value=body, inline=False) await ctx.send(embed=e) @commands.command() @commands.guild_only() @commands.has_permissions(manage_emojis=True) async def emoji(self, ctx, emoji: discord.PartialEmoji, *roles: discord.Role): """This clones a specified emoji that only specified roles are allowed to use. """ # fetch the emoji asset and read it as bytes. emoji_bytes = await emoji.read() # the key parameter here is `roles`, which controls # what roles are able to use the emoji. await ctx.guild.create_custom_emoji( name=emoji.name, image=emoji_bytes, roles=roles, reason='Very secret business.' ) @commands.command() @commands.guild_only() @mod_or_permissions(kick_members=True) async def kick(self, ctx, member: MemberConverterr, *, reason: ActionReason = None): """Kicks a member from the server. In order for this to work, the bot must have Kick Member permissions. To use this command you must have Kick Members permission. """ if reason is None: reason = f'Action done by {ctx.author} (ID: {ctx.author.id})' await ctx.guild.kick(member, reason=reason) await ctx.send('\N{OK HAND SIGN}') # @commands.command(name="delprofanity", aliases=["delswears", "delcurses"]) # @commands.guild_only # @commands.has_permissions(manage_guild=True) # async def remove_profanity(self, ctx, *words): # with open("./data/profanity.txt", "r", encoding="utf-8") as f: # stored = [w.strip() for w in f.readlines()] # # with open("./data/profanity.txt", "w", encoding="utf-8") as f: # f.write("".join([f"{w}\n" for w in stored if w not in words])) # # profanity.load_censor_words_from_file("./data/profanity.txt") # await ctx.send("Action complete.") # await ctx.send("Action complete.") @commands.command(aliases=["nick"]) @commands.guild_only() @commands.has_permissions(manage_nicknames=True) async def nickname(self, ctx, member: MemberConverterr, *, name: str = None): """ Nicknames a user from the current server. """ if await checks.check_priv(ctx, member): return try: await member.edit(nick=name, reason=default.responsible(ctx.author, "Changed by command")) message = f"Changed **{member.name}'s** nickname to **{name}**" if name is None: message = f"Reset **{member.name}'s** nickname" await ctx.send(message) except Exception as e: await ctx.send(e) @commands.command(aliases=["massnick"]) @commands.guild_only() @commands.has_permissions(manage_nicknames=True) async def massnickname(self, ctx, *, name: str = None): """ Nicknames all the users from the current server. """ for member in ctx.guild.members: if await checks.check_priv(ctx, member): return else: if member.id == 845186772698923029 or 511724576674414600: continue else: try: await member.edit(nick=name, reason=default.responsible(ctx.author, "Changed by command")) message = f"Changed **{member.name}'s** nickname to **{name}**" if name is None: message = f"Reset **{member.name}'s** nickname" await ctx.send(message) except Exception as e: await ctx.send(e) @commands.command() @commands.guild_only() @mod_or_permissions(ban_members=True) async def ban(self, ctx, member: MemberID, *, reason: ActionReason = None): """Bans a member from the server. You can also ban from ID to ban regardless whether they're in the server or not. In order for this to work, the bot must have Ban Member permissions. To use this command you must have Ban Members permission. """ if reason is None: reason = f'Action done by {ctx.author} (ID: {ctx.author.id})' await ctx.guild.ban(member, reason=reason) await ctx.send('\N{OK HAND SIGN}') @commands.command() @commands.guild_only() @mod_or_permissions(ban_members=True) async def multiban(self, ctx, members: commands.Greedy[MemberID], *, reason: ActionReason = None): """Bans multiple members from the server. This only works through banning via ID. In order for this to work, the bot must have Ban Member permissions. To use this command you must have Ban Members permission. """ if reason is None: reason = f'Action done by {ctx.author} (ID: {ctx.author.id})' total_members = len(members) if total_members == 0: return await ctx.send('Missing members to ban.') confirm = await ctx.prompt(f'This will ban **{plural(total_members):member}**. Are you sure?', reacquire=False) if not confirm: return await ctx.send('Aborting.') failed = 0 for member in members: try: await ctx.guild.ban(member, reason=reason) except discord.HTTPException: failed += 1 await ctx.send(f'Banned {total_members - failed}/{total_members} members.') @commands.command() @commands.guild_only() @mod_or_permissions(kick_members=True) async def softban(self, ctx, member: MemberID, *, reason: ActionReason = None): """Soft bans a member from the server. A softban is basically banning the member from the server but then unbanning the member as well. This allows you to essentially kick the member while removing their messages. In order for this to work, the bot must have Ban Member permissions. To use this command you must have Kick Members permissions. """ if reason is None: reason = f'Action done by {ctx.author} (ID: {ctx.author.id})' await ctx.guild.ban(member, reason=reason) await ctx.guild.unban(member, reason=reason) await ctx.send('\N{OK HAND SIGN}') @commands.command() @commands.guild_only() @mod_or_permissions(ban_members=True) async def massban(self, ctx, *, args): """Mass bans multiple members from the server. This command has a powerful "command line" syntax. To use this command you and the bot must both have Ban Members permission. **Every option is optional.** Users are only banned **if and only if** all conditions are met. The following options are valid. `--channel` or `-c`: Channel to search for message history. `--reason` or `-r`: The reason for the ban. `--regex`: Regex that usernames must match. `--created`: Matches users whose accounts were created less than specified minutes ago. `--joined`: Matches users that joined less than specified minutes ago. `--joined-before`: Matches users who joined before the member ID given. `--joined-after`: Matches users who joined after the member ID given. `--no-avatar`: Matches users who have no avatar. (no arguments) `--no-roles`: Matches users that have no role. (no arguments) `--show`: Show members instead of banning them (no arguments). Message history filters (Requires `--channel`): `--contains`: A substring to search for in the message. `--starts`: A substring to search if the message starts with. `--ends`: A substring to search if the message ends with. `--match`: A regex to match the message content to. `--search`: How many messages to search. Default 100. Max 2000. `--after`: Messages must come after this message ID. `--before`: Messages must come before this message ID. `--files`: Checks if the message has attachments (no arguments). `--embeds`: Checks if the message has embeds (no arguments). """ # For some reason there are cases due to caching that ctx.author # can be a User even in a guild only context # Rather than trying to work out the kink with it # Just upgrade the member itself. if not isinstance(ctx.author, MemberConverterr): try: author = await ctx.guild.fetch_member(ctx.author.id) except discord.HTTPException: return await ctx.send('Somehow, Discord does not seem to think you are in this server.') else: author = ctx.author parser = Arguments(add_help=False, allow_abbrev=False) parser.add_argument('--channel', '-c') parser.add_argument('--reason', '-r') parser.add_argument('--search', type=int, default=100) parser.add_argument('--regex') parser.add_argument('--no-avatar', action='store_true') parser.add_argument('--no-roles', action='store_true') parser.add_argument('--created', type=int) parser.add_argument('--joined', type=int) parser.add_argument('--joined-before', type=int) parser.add_argument('--joined-after', type=int) parser.add_argument('--contains') parser.add_argument('--starts') parser.add_argument('--ends') parser.add_argument('--match') parser.add_argument('--show', action='store_true') parser.add_argument('--embeds', action='store_const', const=lambda m: len(m.embeds)) parser.add_argument('--files', action='store_const', const=lambda m: len(m.attachments)) parser.add_argument('--after', type=int) parser.add_argument('--before', type=int) try: args = parser.parse_args(shlex.split(args)) except Exception as e: return await ctx.send(str(e)) members = [] if args.channel: channel = await commands.TextChannelConverter().convert(ctx, args.channel) before = args.before and discord.Object(id=args.before) after = args.after and discord.Object(id=args.after) predicates = [] if args.contains: predicates.append(lambda m: args.contains in m.content) if args.starts: predicates.append(lambda m: m.content.startswith(args.starts)) if args.ends: predicates.append(lambda m: m.content.endswith(args.ends)) if args.match: try: _match = re.compile(args.match) except re.error as e: return await ctx.send(f'Invalid regex passed to `--match`: {e}') else: predicates.append(lambda m, x=_match: x.match(m.content)) if args.embeds: predicates.append(args.embeds) if args.files: predicates.append(args.files) async for message in channel.history(limit=min(max(1, args.search), 2000), before=before, after=after): if all(p(message) for p in predicates): members.append(message.author) else: if ctx.guild.chunked: members = ctx.guild.members else: async with ctx.typing(): await ctx.guild.chunk(cache=True) members = ctx.guild.members # member filters predicates = [ lambda m: isinstance(m, MemberConverterr) and can_execute_action(ctx, author, m), # Only if applicable lambda m: not m.bot, # No bots lambda m: m.discriminator != '0000', # No deleted users ] converter = commands.MemberConverter() if args.regex: try: _regex = re.compile(args.regex) except re.error as e: return await ctx.send(f'Invalid regex passed to `--regex`: {e}') else: predicates.append(lambda m, x=_regex: x.match(m.name)) if args.no_avatar: predicates.append(lambda m: m.avatar == m.default_avatar) if args.no_roles: predicates.append(lambda m: len(getattr(m, 'roles', [])) <= 1) now = discord.utils.utcnow() if args.created: def created(member, *, offset=now - datetime.timedelta(minutes=args.created)): return member.created_at > offset predicates.append(created) if args.joined: def joined(member, *, offset=now - datetime.timedelta(minutes=args.joined)): if isinstance(member, discord.User): # If the member is a user then they left already return True return member.joined_at and member.joined_at > offset predicates.append(joined) if args.joined_after: _joined_after_member = await converter.convert(ctx, str(args.joined_after)) def joined_after(member, *, _other=_joined_after_member): return member.joined_at and _other.joined_at and member.joined_at > _other.joined_at predicates.append(joined_after) if args.joined_before: _joined_before_member = await converter.convert(ctx, str(args.joined_before)) def joined_before(member, *, _other=_joined_before_member): return member.joined_at and _other.joined_at and member.joined_at < _other.joined_at predicates.append(joined_before) members = {m for m in members if all(p(m) for p in predicates)} if len(members) == 0: return await ctx.send('No members found matching criteria.') if args.show: members = sorted(members, key=lambda m: m.joined_at or now) fmt = "\n".join(f'{m.id}\tJoined: {m.joined_at}\tCreated: {m.created_at}\t{m}' for m in members) content = f'Current Time: {discord.utils.utcnow()}\nTotal members: {len(members)}\n{fmt}' file = discord.File(BytesIO(content.encode('utf-8')), filename='members.txt') return await ctx.send(file=file) if args.reason is None: return await ctx.send('--reason flag is required.') else: reason = await ActionReason().convert(ctx, args.reason) confirm = await ctx.prompt(f'This will ban **{plural(len(members)):member}**. Are you sure?') if not confirm: return await ctx.send('Aborting.') count = 0 for member in members: try: await ctx.guild.ban(member, reason=reason) except discord.HTTPException: pass else: count += 1 await ctx.send(f'Banned {count}/{len(members)}') @commands.command() @commands.guild_only() @commands.max_concurrency(1, per=commands.BucketType.user) @commands.has_permissions(ban_members=True) async def massunban(self, ctx, *members: MemberID): """ Mass unbans multiple members from the server. """ try: for member_id in members: await ctx.guild.unban(discord.Object(id=str(member_id))) await ctx.send(default.actionmessage("massunbans", mass=True)) except Exception as e: await ctx.send(e) @commands.command() @commands.guild_only() @commands.max_concurrency(1, per=commands.BucketType.user) @commands.has_permissions(kick_members=True) async def masskick(self, ctx, reason: ActionReason, *members: MemberID): """ Mass kicks multiple members from the server. """ try: for member_id in members: await ctx.guild.kick(discord.Object(id=str(member_id)), reason=default.responsible(ctx.author, reason)) await ctx.send(default.actionmessage("masskickd", mass=True)) except Exception as e: await ctx.send(e) @commands.command() @commands.guild_only() @commands.has_permissions(ban_members=True) async def unban(self, ctx, member: MemberID, *, reason: str = None): """ Unbans a user from the current server. """ try: await ctx.guild.unban(discord.Object(id=str(member)), reason=default.responsible(ctx.author, reason)) await ctx.send(default.actionmessage("unbanned")) except Exception as e: await ctx.send(e) @commands.group(invoke_without_command=True) @can_mute() async def mute(self, ctx, members: commands.Greedy[discord.Member], *, reason: ActionReason = None): """Mutes members using the configured mute role. The bot must have Manage Roles permission and be above the muted role in the hierarchy. To use this command you need to be higher than the mute role in the hierarchy and have Manage Roles permission at the server level.""" if reason is None: reason = f'Action done by {ctx.author} (ID: {ctx.author.id})' guild = ctx.guild total = len(members) if total == 0: return await ctx.warn('Missing members to mute.') elif total > 20: return await ctx.error('You may only mute 20 people at a time') role = discord.utils.get(guild.roles, name='Muted') failed = 0 em = discord.Embed(colour=invis, description='') for member in members: if role not in member.roles: try: await member.add_roles(role, reason=reason) em.description += f'{self.bot.icons["greenTick"]} {member.name} Sucsessfully muted' except discord.HTTPException: failed += 1 em.description += f'{self.bot.icons["RedTick"]} {member.name} Failed to mute muted' em.set_footer(text=f'Muted [{total - failed}/{total}]') await ctx.try_reply(embed=em) """"# Mute a Member @commands.command(aliases=['Unmute']) @commands.has_permissions(manage_roles=True) @commands.guild_only() async def unmute(self, ctx, mem: str): member = getUser(ctx, mem) if member: role = utils.find(lambda r: "mute" in r.name.lower(), member.roles) if role: roles = member.roles roles.remove(role) asyncio.sleep(0.5) await member.edit(roles=roles) log.info(f'Unmuted {member}') e = discord.Embed(color=embedColor(self)) e.set_author(name="\N{SPEAKER} Unmuted " + str(member)) await edit(ctx, embed=e) else: await edit(ctx, content="\N{HEAVY EXCLAMATION MARK SYMBOL} Member is not muted", ttl=5) # SoftBan a Member (ban, delelte messagea and unban) @commands.command(aliases=['Softban']) @commands.has_permissions(ban_members=True) @commands.guild_only() async def softban(self, ctx, member: str, *, reason: str=None): Softban a Member(Kick and delete Messages member = getUser(ctx, member) if member: try: await ctx.guild.ban(member, reason=reason) await ctx.guild.unban(member) except discord.Forbidden: await edit(ctx, content="\N{HEAVY EXCLAMATION MARK SYMBOL} Missing permissions to ban this Member", ttl=5) except discord.HTTPException: await edit(ctx, content="\N{HEAVY EXCLAMATION MARK SYMBOL} Something went wrong while trying to ban...", ttl=5) else: e = discord.Embed(color=embedColor(self)) e.set_author(icon_url="https://cdn.discordapp.com/attachments/278603491520544768/301087009408024580/273910007857414147.png", name="Soft Banned: " + str(member)) await edit(ctx, embed=e)""" @commands.command() @commands.is_owner() async def do(self, ctx, times: int, *, command): """Repeats a command a specified number of times.""" msg = copy.copy(ctx.message) msg.content = ctx.prefix + command new_ctx = await self.bot.get_context(msg, cls=type(ctx)) for i in range(times): await new_ctx.reinvoke() #@commands.group(name='mute', invoke_without_command=True) #@can_mute() #async def _mute(self, ctx, members: commands.Greedy[MemberConverterr], *, reason: ActionReason = None): # """Mutes members using the configured mute role. # The bot must have Manage Roles permission and be # above the muted role in the hierarchy. # To use this command you need to be higher than the # mute role in the hierarchy and have Manage Roles # permission at the server level. # """ # # if reason is None: # reason = f'Action done by {ctx.author} (ID: {ctx.author.id})' # # role = next((g for g in ctx.guild.roles if g.name == "Muted"), None) # total = len(members) # if total == 0: # return await ctx.send('Missing members to mute.') # # failed = 0 # for member in members: # try: # await member.add_roles(role, reason=reason) # except discord.HTTPException: # failed += 1 # # if failed == 0: # await ctx.send('\N{THUMBS UP SIGN}') # else: # await ctx.send(f'Muted [{total - failed}/{total}]') # @commands.command(name='unmute') @can_mute() async def _unmute(self, ctx, members: commands.Greedy[MemberConverterr], *, reason: ActionReason = None): """Unmutes members using the configured mute role. The bot must have Manage Roles permission and be above the muted role in the hierarchy. To use this command you need to be higher than the mute role in the hierarchy and have Manage Roles permission at the server level. """ if reason is None: reason = f'Action done by {ctx.author} (ID: {ctx.author.id})' role = next((g for g in ctx.guild.roles if g.name == "Muted"), None) total = len(members) if total == 0: return await ctx.send('Missing members to unmute.') failed = 0 for member in members: try: await member.remove_roles(role, reason=reason) except discord.HTTPException: failed += 1 if failed == 0: await ctx.send('\N{THUMBS UP SIGN}') else: await ctx.send(f'Unmuted [{total - failed}/{total}]') @commands.command(aliases=["ar"]) @commands.guild_only() @commands.has_permissions(manage_roles=True) async def announcerole(self, ctx, *, role: discord.Role): """ Makes a role mentionable and removes it whenever you mention the role """ if role == ctx.guild.default_role: return await ctx.warn("To prevent abuse, I won't allow mentionable role for everyone/here role.") if ctx.author.top_role.position <= role.position: return await ctx.warn( "It seems like the role you attempt to mention is over your permissions, therefore I won't allow you.") if ctx.me.top_role.position <= role.position: return await ctx.error("This role is above my permissions, I can't make it mentionable ;-;") await role.edit(mentionable=True, reason=f"[ {ctx.author} ] announcerole command") msg = await ctx.success( f"**{role.name}** is now mentionable, if you don't mention it within 30 seconds, I will revert the changes.") while True: def role_checker(m): if role.mention in m.content: return True return False try: checker = await self.bot.wait_for("message", timeout=30.0, check=role_checker) if checker.author.id == ctx.author.id: await role.edit(mentionable=False, reason=f"[ {ctx.author} ] announcerole command") return await msg.edit( content=f"**{role.name}** mentioned by **{ctx.author}** in {checker.channel.mention}") else: await checker.delete() except asyncio.TimeoutError: await role.edit(mentionable=False, reason=f"[ {ctx.author} ] announcerole command") return await msg.edit(content=f"**{role.name}** was never mentioned by **{ctx.author}**...") @commands.group() @commands.guild_only() @commands.has_permissions(manage_messages=True) async def find(self, ctx): """ Finds a user within your search term """ if ctx.invoked_subcommand is None: await ctx.send_help(str(ctx.command)) @find.command(name="playing") async def find_playing(self, ctx, *, search: str): loop = [] for i in ctx.guild.members: if i.activities and (not i.bot): for g in i.activities: if g.name and (search.lower() in g.name.lower()): loop.append(f"{i} | {type(g).__name__}: {g.name} ({i.id})") await default.prettyResults( ctx, "playing", f"Found **{len(loop)}** on your search for **{search}**", loop ) @find.command(name="username", aliases=["name"]) async def find_name(self, ctx, *, search: str): loop = [f"{i} ({i.id})" for i in ctx.guild.members if search.lower() in i.name.lower() and not i.bot] await default.prettyResults( ctx, "name", f"Found **{len(loop)}** on your search for **{search}**", loop ) @find.command(name="nickname", aliases=["nick"]) async def find_nickname(self, ctx, *, search: str): loop = [f"{i.nick} | {i} ({i.id})" for i in ctx.guild.members if i.nick if (search.lower() in i.nick.lower()) and not i.bot] await default.prettyResults( ctx, "name", f"Found **{len(loop)}** on your search for **{search}**", loop ) @find.command(name="id") async def find_id(self, ctx, *, search: int): loop = [f"{i} | {i} ({i.id})" for i in ctx.guild.members if (str(search) in str(i.id)) and not i.bot] await default.prettyResults( ctx, "name", f"Found **{len(loop)}** on your search for **{search}**", loop ) @find.command(name="discriminator", aliases=["discrim"]) async def find_discriminator(self, ctx, *, search: str): if not len(search) == 4 or not re.compile("^[0-9]*$").search(search): return await ctx.send("You must provide exactly 4 digits") loop = [f"{i} ({i.id})" for i in ctx.guild.members if search == i.discriminator] await default.prettyResults( ctx, "discriminator", f"Found **{len(loop)}** on your search for **{search}**", loop ) @commands.command() @commands.guild_only() @commands.has_permissions(manage_roles=True) async def lock(self, ctx): channel = ctx.channel overwrite = channel.overwrites_for(ctx.guild.default_role) if not overwrite.send_messages: embed = discord.Embed(colour=magenta, description=f"{channel.mention} is already a locked channel") embed.set_author(name='Invalid usage', icon_url=picture("Warning")) try: await ctx.send(embed=embed) return except: try: await ctx.author.send(embed=embed) return except: return embed = discord.Embed(colour=magenta, description=f":lock: **Locked channel** {ctx.channel.mention}") await ctx.send(embed=embed) await channel.set_permissions(ctx.guild.default_role, send_messages=False) @commands.command() @commands.guild_only() @commands.has_permissions(manage_roles=True) async def unlock(self, ctx): channel = ctx.channel overwrite = channel.overwrites_for(ctx.guild.default_role) if overwrite.send_messages: embed = discord.Embed(colour=magenta, description=f"{channel.mention} is not a locked channel") embed.set_author(name='Invalid usage', icon_url=picture("Warning")) try: await ctx.send(embed=embed) return except: try: await ctx.author.send(embed=embed) return except: return await channel.set_permissions(ctx.guild.default_role, send_messages=True) embed = discord.Embed(colour=0xFF004D, description=f":unlock: **Unlocked channel** {ctx.channel.mention}") try: await ctx.send(embed=embed) except: try: await ctx.author.send(embed=embed) except: pass @commands.command() @commands.has_permissions(manage_messages=True) async def cls(self, ctx, amount: int): amount2 = amount + 1 await ctx.channel.purge(limit=amount2) @commands.group(aliases=["purge", "clr", "clear"]) @commands.guild_only() @commands.max_concurrency(1, per=commands.BucketType.guild) @commands.has_permissions(manage_messages=True) async def prune(self, ctx): """ Removes messages from the current server. """ if ctx.invoked_subcommand is None: await ctx.send_help(str(ctx.command)) async def do_removal(self, ctx, limit, predicate, *, before=None, after=None): if limit > 2000: return await ctx.send(f'Too many messages to search given ({limit}/2000)') if before is None: before = ctx.message else: before = discord.Object(id=before) if after is not None: after = discord.Object(id=after) try: deleted = await ctx.channel.purge(limit=limit, before=before, after=after, check=predicate) except discord.Forbidden as e: return await ctx.send('I do not have permissions to delete messages.') except discord.HTTPException as e: return await ctx.send(f'Error: {e} (try a smaller search?)') spammers = Counter(m.author.display_name for m in deleted) deleted = len(deleted) messages = [f'{deleted} message{" was" if deleted == 1 else "s were"} removed.'] if deleted: messages.append('') spammers = sorted(spammers.items(), key=lambda t: t[1], reverse=True) messages.extend(f'**{name}**: {count}' for name, count in spammers) to_send = '\n'.join(messages) if len(to_send) > 2000: await ctx.send(f'Successfully removed {deleted} messages.', delete_after=10) else: await ctx.send(to_send, delete_after=10) @prune.command() async def embeds(self, ctx, search=100): """Removes messages that have embeds in them.""" await self.do_removal(ctx, search, lambda e: len(e.embeds)) @prune.command() async def files(self, ctx, search=100): """Removes messages that have attachments in them.""" await self.do_removal(ctx, search, lambda e: len(e.attachments)) @prune.command() async def mentions(self, ctx, search=100): """Removes messages that have mentions in them.""" await self.do_removal(ctx, search, lambda e: len(e.mentions) or len(e.role_mentions)) @prune.command() async def images(self, ctx, search=100): """Removes messages that have embeds or attachments.""" await self.do_removal(ctx, search, lambda e: len(e.embeds) or len(e.attachments)) @prune.command(name="all") async def _remove_all(self, ctx, search=100): """Removes all messages.""" await self.do_removal(ctx, search, lambda e: True) @prune.command() async def user(self, ctx, member: MemberConverterr, search=100): """Removes all messages by the member.""" await self.do_removal(ctx, search, lambda e: e.author == member) @prune.command() async def contains(self, ctx, *, substr: str): """Removes all messages containing a substring. The substring must be at least 3 characters long. """ if len(substr) < 3: await ctx.send("The substring length must be at least 3 characters.") else: await self.do_removal(ctx, 100, lambda e: substr in e.content) @prune.command(name="bot", aliases=['bots']) async def _bots(self, ctx, prefix, search=100): """Removes a bot user's messages and messages with their optional prefix.""" def predicate(m): return (m.webhook_id is None and m.author.bot) or m.content.startswith(tuple(prefix)) await self.do_removal(ctx, search, predicate) @prune.command(name="users") async def _users(self, ctx, search=100): """Removes only user messages. """ def predicate(m): return m.author.bot is False await self.do_removal(ctx, search, predicate) @prune.command(name="emojis") async def _emojis(self, ctx, search=100): """Removes all messages containing custom emoji.""" custom_emoji = re.compile(r"<a?:(.*?):(\d{17,21})>|[\u263a-\U0001f645]") def predicate(m): return custom_emoji.search(m.content) await self.do_removal(ctx, search, predicate) @prune.command(name="reactions") async def _reactions(self, ctx, search=100): """Removes all reactions from messages that have them.""" if search > 2000: return await ctx.send(f"Too many messages to search for ({search}/2000)") total_reactions = 0 async for message in ctx.history(limit=search, before=ctx.message): if len(message.reactions): total_reactions += sum(r.count for r in message.reactions) await message.clear_reactions() await ctx.send(f"Successfully removed {total_reactions} reactions.") @prune.command() async def custom(self, ctx, *, args: str): """A more advanced purge command. This command uses a powerful "command line" syntax. Most options support multiple values to indicate 'any' match. If the value has spaces it must be quoted. The messages are only deleted if all options are met unless the `--or` flag is passed, in which case only if any is met. The following options are valid. `--user`: A mention or name of the user to remove. `--contains`: A substring to search for in the message. `--starts`: A substring to search if the message starts with. `--ends`: A substring to search if the message ends with. `--search`: How many messages to search. Default 100. Max 2000. `--after`: Messages must come after this message ID. `--before`: Messages must come before this message ID. Flag options (no arguments): `--bot`: Check if it's a bot user. `--embeds`: Check if the message has embeds. `--files`: Check if the message has attachments. `--emoji`: Check if the message has custom emoji. `--reactions`: Check if the message has reactions `--or`: Use logical OR for all options. `--not`: Use logical NOT for all options. """ parser = Arguments(add_help=False, allow_abbrev=False) parser.add_argument('--user', nargs='+') parser.add_argument('--contains', nargs='+') parser.add_argument('--starts', nargs='+') parser.add_argument('--ends', nargs='+') parser.add_argument('--or', action='store_true', dest='_or') parser.add_argument('--not', action='store_true', dest='_not') parser.add_argument('--emoji', action='store_true') parser.add_argument('--bot', action='store_const', const=lambda m: m.author.bot) parser.add_argument('--embeds', action='store_const', const=lambda m: len(m.embeds)) parser.add_argument('--files', action='store_const', const=lambda m: len(m.attachments)) parser.add_argument('--reactions', action='store_const', const=lambda m: len(m.reactions)) parser.add_argument('--search', type=int) parser.add_argument('--after', type=int) parser.add_argument('--before', type=int) try: args = parser.parse_args(shlex.split(args)) except Exception as e: await ctx.send(str(e)) return predicates = [] if args.bot: predicates.append(args.bot) if args.embeds: predicates.append(args.embeds) if args.files: predicates.append(args.files) if args.reactions: predicates.append(args.reactions) if args.emoji: custom_emoji = re.compile(r'<:(\w+):(\d+)>') predicates.append(lambda m: custom_emoji.search(m.content)) if args.user: users = [] converter = commands.MemberConverter() for u in args.user: try: user = await converter.convert(ctx, u) users.append(user) except Exception as e: await ctx.send(str(e)) return predicates.append(lambda m: m.author in users) if args.contains: predicates.append(lambda m: any(sub in m.content for sub in args.contains)) if args.starts: predicates.append(lambda m: any(m.content.startswith(s) for s in args.starts)) if args.ends: predicates.append(lambda m: any(m.content.endswith(s) for s in args.ends)) op = all if not args._or else any def predicate(m): r = op(p(m) for p in predicates) if args._not: return not r return r if args.after: if args.search is None: args.search = 2000 if args.search is None: args.search = 100 args.search = max(0, min(2000, args.search)) # clamp from 0-2000 await self.do_removal(ctx, args.search, predicate, before=args.before, after=args.after) # Mute related stuff async def update_mute_role(self, ctx, config, role, *, merge=False): guild = ctx.guild if config and merge: members = config.muted_members # If the roles are being merged then the old members should get the new role reason = f'Action done by {ctx.author} (ID: {ctx.author.id}): Merging mute roles' async for member in self.bot.resolve_member_ids(guild, members): if not member._roles.has(role.id): try: await member.add_roles(role, reason=reason) except discord.HTTPException: pass else: members = set() members.update(map(lambda m: m.id, role.members)) #query = """INSERT INTO guild_mod_config (id, mute_role_id, muted_members) # VALUES ($1, $2, $3::bigint[]) ON CONFLICT (id) # DO UPDATE SET # mute_role_id = EXCLUDED.mute_role_id, # muted_members = EXCLUDED.muted_members # """ #await self.bot.pool.execute(query, guild.id, role.id, list(members)) #self.get_guild_config.invalidate(self, guild.id) def setup(bot): bot.add_cog(Mod(bot))
41.660086
140
0.597004
import argparse import asyncio import copy import datetime import logging import re import shlex from collections import Counter from io import BytesIO import discord from discord import NotFound, Object from discord.ext import commands from discord.ext.commands import Converter, BadArgument from discord.utils import find from cogs.Discordinfo import format_relative, plural from utils import checks, default from utils.checks import MemberConverterr from utils.default import mod_or_permissions from utils.vars import * log = logging.getLogger('mod') class Arguments(argparse.ArgumentParser): def error(self, message): raise RuntimeError(message) class BannedUser(Converter): async def convert(self, ctx, arg): if ctx.guild.me.guild_permissions.ban_members: if arg.isdigit(): try: return (await ctx.guild.fetch_ban(Object(id=int(arg)))).user except NotFound: raise BadArgument banned = [e.user for e in await ctx.guild.bans()] if banned: if (user := find(lambda u: str(u) == arg, banned)) is not None: return user else: raise BadArgument class MemberID(commands.Converter): async def convert(self, ctx, argument): try: m = await commands.MemberConverter().convert(ctx, argument) except commands.BadArgument: try: return int(argument, base=10) except ValueError: raise commands.BadArgument(f"{argument} is not a valid member or member ID.") from None else: return m.id class ActionReason(commands.Converter): async def convert(self, ctx, argument): ret = argument if len(ret) > 512: reason_max = 512 - len(ret) - len(argument) raise commands.BadArgument(f"reason is too long ({len(argument)}/{reason_max})") return ret BannedUsers = {} async def Get_Banned_Users(bot): bans = bot.db.field("SELECT id FROM users WHERE banned = ?", "True") for UserID in bans: BannedUsers + UserID async def BannedU(ctx): if ctx.author in BannedUsers: print(f"Command by {ctx.author} blocked!") async def pred(ctx): if ctx.author in BannedUsers: return ctx.send("You are banned from using commands") return pred async def BanUser(ctx, userid: MemberID, reason): BannedUsers + userid ctx.bot.db.execute("INSERT INTO users (?, ?)", (userid, reason,)) ctx.bot.db.commit() return await ctx.send(f'{userid} Was banned from using the bot') def can_execute_action(ctx, user, target): return user.id == ctx.bot.owner_id or \ user == ctx.guild.owner or \ user.top_role > target.top_role class NoMuteRole(commands.CommandError): def __init__(self): super().__init__('This server does not have a mute role set up.') def can_mute(): async def predicate(ctx): is_owner = await ctx.bot.is_owner(ctx.author) if ctx.guild is None: return False if not ctx.author.guild_permissions.manage_roles and not is_owner: return False role = discord.utils.get(ctx.guild.roles, name='Muted') for channel in ctx.guild.text_channels: await channel.set_permissions(role, overwrite=discord.PermissionOverwrite(send_messages=False, add_reactions=False)) for channel in ctx.guild.voice_channels: await channel.set_permissions(role, overwrite=discord.PermissionOverwrite(speak=False)) if role is None: perms = ctx.guild.default_role.permissions role = await ctx.guild.create_role(name="Muted", permissions=perms) return ctx.author.top_role > role return commands.check(predicate) class Mod(commands.Cog, description='Moderator go brrrrrrrr ~ban'): def __init__(self, bot): self.bot = bot self.config = bot.config async def _basic_cleanup_strategy(self, ctx, search): count = 0 async for msg in ctx.history(limit=search, before=ctx.message): if msg.author == ctx.me and not (msg.mentions or msg.role_mentions): await msg.delete() count += 1 return {'Bot': count} async def _complex_cleanup_strategy(self, ctx, search): prefixes = tuple(self.bot.get_guild_prefixes(ctx.guild)) def check(m): return m.author == ctx.me or m.content.startswith(prefixes) deleted = await ctx.channel.purge(limit=search, check=check, before=ctx.message) return Counter(m.author.display_name for m in deleted) async def _regular_user_cleanup_strategy(self, ctx, search): prefixes = tuple(self.bot.get_guild_prefixes(ctx.guild)) def check(m): return (m.author == ctx.me or m.content.startswith(prefixes)) and not (m.mentions or m.role_mentions) deleted = await ctx.channel.purge(limit=search, check=check, before=ctx.message) return Counter(m.author.display_name for m in deleted) @commands.command() async def cleanup(self, ctx, search=100): strategy = self._basic_cleanup_strategy is_mod = ctx.channel.permissions_for(ctx.author).manage_messages if ctx.channel.permissions_for(ctx.me).manage_messages: if is_mod: strategy = self._complex_cleanup_strategy else: strategy = self._regular_user_cleanup_strategy if is_mod: search = min(max(2, search), 1000) else: search = min(max(2, search), 25) spammers = await strategy(ctx, search) deleted = sum(spammers.values()) messages = [f'{deleted} message{" was" if deleted == 1 else "s were"} removed.'] if deleted: messages.append('') spammers = sorted(spammers.items(), key=lambda t: t[1], reverse=True) messages.extend(f'- **{author}**: {count}' for author, count in spammers) await ctx.send('\n'.join(messages), delete_after=10) @commands.command(aliases=['newmembers', 'nu']) @commands.guild_only() async def newusers(self, ctx, *, count=5): count = max(min(count, 25), 5) if not ctx.guild.chunked: members = await ctx.guild.chunk(cache=True) members = sorted(ctx.guild.members, key=lambda m: m.joined_at, reverse=True)[:count] e = discord.Embed(title='New Members', colour=green) for member in members: body = f'Joined {format_relative(member.joined_at)}\nCreated {format_relative(member.created_at)}' e.add_field(name=f'{member} (ID: {member.id})', value=body, inline=False) await ctx.send(embed=e) @commands.command() @commands.guild_only() @commands.has_permissions(manage_emojis=True) async def emoji(self, ctx, emoji: discord.PartialEmoji, *roles: discord.Role): emoji_bytes = await emoji.read() await ctx.guild.create_custom_emoji( name=emoji.name, image=emoji_bytes, roles=roles, reason='Very secret business.' ) @commands.command() @commands.guild_only() @mod_or_permissions(kick_members=True) async def kick(self, ctx, member: MemberConverterr, *, reason: ActionReason = None): if reason is None: reason = f'Action done by {ctx.author} (ID: {ctx.author.id})' await ctx.guild.kick(member, reason=reason) await ctx.send('\N{OK HAND SIGN}') @commands.command(aliases=["nick"]) @commands.guild_only() @commands.has_permissions(manage_nicknames=True) async def nickname(self, ctx, member: MemberConverterr, *, name: str = None): if await checks.check_priv(ctx, member): return try: await member.edit(nick=name, reason=default.responsible(ctx.author, "Changed by command")) message = f"Changed **{member.name}'s** nickname to **{name}**" if name is None: message = f"Reset **{member.name}'s** nickname" await ctx.send(message) except Exception as e: await ctx.send(e) @commands.command(aliases=["massnick"]) @commands.guild_only() @commands.has_permissions(manage_nicknames=True) async def massnickname(self, ctx, *, name: str = None): for member in ctx.guild.members: if await checks.check_priv(ctx, member): return else: if member.id == 845186772698923029 or 511724576674414600: continue else: try: await member.edit(nick=name, reason=default.responsible(ctx.author, "Changed by command")) message = f"Changed **{member.name}'s** nickname to **{name}**" if name is None: message = f"Reset **{member.name}'s** nickname" await ctx.send(message) except Exception as e: await ctx.send(e) @commands.command() @commands.guild_only() @mod_or_permissions(ban_members=True) async def ban(self, ctx, member: MemberID, *, reason: ActionReason = None): if reason is None: reason = f'Action done by {ctx.author} (ID: {ctx.author.id})' await ctx.guild.ban(member, reason=reason) await ctx.send('\N{OK HAND SIGN}') @commands.command() @commands.guild_only() @mod_or_permissions(ban_members=True) async def multiban(self, ctx, members: commands.Greedy[MemberID], *, reason: ActionReason = None): if reason is None: reason = f'Action done by {ctx.author} (ID: {ctx.author.id})' total_members = len(members) if total_members == 0: return await ctx.send('Missing members to ban.') confirm = await ctx.prompt(f'This will ban **{plural(total_members):member}**. Are you sure?', reacquire=False) if not confirm: return await ctx.send('Aborting.') failed = 0 for member in members: try: await ctx.guild.ban(member, reason=reason) except discord.HTTPException: failed += 1 await ctx.send(f'Banned {total_members - failed}/{total_members} members.') @commands.command() @commands.guild_only() @mod_or_permissions(kick_members=True) async def softban(self, ctx, member: MemberID, *, reason: ActionReason = None): if reason is None: reason = f'Action done by {ctx.author} (ID: {ctx.author.id})' await ctx.guild.ban(member, reason=reason) await ctx.guild.unban(member, reason=reason) await ctx.send('\N{OK HAND SIGN}') @commands.command() @commands.guild_only() @mod_or_permissions(ban_members=True) async def massban(self, ctx, *, args): if not isinstance(ctx.author, MemberConverterr): try: author = await ctx.guild.fetch_member(ctx.author.id) except discord.HTTPException: return await ctx.send('Somehow, Discord does not seem to think you are in this server.') else: author = ctx.author parser = Arguments(add_help=False, allow_abbrev=False) parser.add_argument('--channel', '-c') parser.add_argument('--reason', '-r') parser.add_argument('--search', type=int, default=100) parser.add_argument('--regex') parser.add_argument('--no-avatar', action='store_true') parser.add_argument('--no-roles', action='store_true') parser.add_argument('--created', type=int) parser.add_argument('--joined', type=int) parser.add_argument('--joined-before', type=int) parser.add_argument('--joined-after', type=int) parser.add_argument('--contains') parser.add_argument('--starts') parser.add_argument('--ends') parser.add_argument('--match') parser.add_argument('--show', action='store_true') parser.add_argument('--embeds', action='store_const', const=lambda m: len(m.embeds)) parser.add_argument('--files', action='store_const', const=lambda m: len(m.attachments)) parser.add_argument('--after', type=int) parser.add_argument('--before', type=int) try: args = parser.parse_args(shlex.split(args)) except Exception as e: return await ctx.send(str(e)) members = [] if args.channel: channel = await commands.TextChannelConverter().convert(ctx, args.channel) before = args.before and discord.Object(id=args.before) after = args.after and discord.Object(id=args.after) predicates = [] if args.contains: predicates.append(lambda m: args.contains in m.content) if args.starts: predicates.append(lambda m: m.content.startswith(args.starts)) if args.ends: predicates.append(lambda m: m.content.endswith(args.ends)) if args.match: try: _match = re.compile(args.match) except re.error as e: return await ctx.send(f'Invalid regex passed to `--match`: {e}') else: predicates.append(lambda m, x=_match: x.match(m.content)) if args.embeds: predicates.append(args.embeds) if args.files: predicates.append(args.files) async for message in channel.history(limit=min(max(1, args.search), 2000), before=before, after=after): if all(p(message) for p in predicates): members.append(message.author) else: if ctx.guild.chunked: members = ctx.guild.members else: async with ctx.typing(): await ctx.guild.chunk(cache=True) members = ctx.guild.members predicates = [ lambda m: isinstance(m, MemberConverterr) and can_execute_action(ctx, author, m), lambda m: not m.bot, lambda m: m.discriminator != '0000', ] converter = commands.MemberConverter() if args.regex: try: _regex = re.compile(args.regex) except re.error as e: return await ctx.send(f'Invalid regex passed to `--regex`: {e}') else: predicates.append(lambda m, x=_regex: x.match(m.name)) if args.no_avatar: predicates.append(lambda m: m.avatar == m.default_avatar) if args.no_roles: predicates.append(lambda m: len(getattr(m, 'roles', [])) <= 1) now = discord.utils.utcnow() if args.created: def created(member, *, offset=now - datetime.timedelta(minutes=args.created)): return member.created_at > offset predicates.append(created) if args.joined: def joined(member, *, offset=now - datetime.timedelta(minutes=args.joined)): if isinstance(member, discord.User): return True return member.joined_at and member.joined_at > offset predicates.append(joined) if args.joined_after: _joined_after_member = await converter.convert(ctx, str(args.joined_after)) def joined_after(member, *, _other=_joined_after_member): return member.joined_at and _other.joined_at and member.joined_at > _other.joined_at predicates.append(joined_after) if args.joined_before: _joined_before_member = await converter.convert(ctx, str(args.joined_before)) def joined_before(member, *, _other=_joined_before_member): return member.joined_at and _other.joined_at and member.joined_at < _other.joined_at predicates.append(joined_before) members = {m for m in members if all(p(m) for p in predicates)} if len(members) == 0: return await ctx.send('No members found matching criteria.') if args.show: members = sorted(members, key=lambda m: m.joined_at or now) fmt = "\n".join(f'{m.id}\tJoined: {m.joined_at}\tCreated: {m.created_at}\t{m}' for m in members) content = f'Current Time: {discord.utils.utcnow()}\nTotal members: {len(members)}\n{fmt}' file = discord.File(BytesIO(content.encode('utf-8')), filename='members.txt') return await ctx.send(file=file) if args.reason is None: return await ctx.send('--reason flag is required.') else: reason = await ActionReason().convert(ctx, args.reason) confirm = await ctx.prompt(f'This will ban **{plural(len(members)):member}**. Are you sure?') if not confirm: return await ctx.send('Aborting.') count = 0 for member in members: try: await ctx.guild.ban(member, reason=reason) except discord.HTTPException: pass else: count += 1 await ctx.send(f'Banned {count}/{len(members)}') @commands.command() @commands.guild_only() @commands.max_concurrency(1, per=commands.BucketType.user) @commands.has_permissions(ban_members=True) async def massunban(self, ctx, *members: MemberID): try: for member_id in members: await ctx.guild.unban(discord.Object(id=str(member_id))) await ctx.send(default.actionmessage("massunbans", mass=True)) except Exception as e: await ctx.send(e) @commands.command() @commands.guild_only() @commands.max_concurrency(1, per=commands.BucketType.user) @commands.has_permissions(kick_members=True) async def masskick(self, ctx, reason: ActionReason, *members: MemberID): try: for member_id in members: await ctx.guild.kick(discord.Object(id=str(member_id)), reason=default.responsible(ctx.author, reason)) await ctx.send(default.actionmessage("masskickd", mass=True)) except Exception as e: await ctx.send(e) @commands.command() @commands.guild_only() @commands.has_permissions(ban_members=True) async def unban(self, ctx, member: MemberID, *, reason: str = None): try: await ctx.guild.unban(discord.Object(id=str(member)), reason=default.responsible(ctx.author, reason)) await ctx.send(default.actionmessage("unbanned")) except Exception as e: await ctx.send(e) @commands.group(invoke_without_command=True) @can_mute() async def mute(self, ctx, members: commands.Greedy[discord.Member], *, reason: ActionReason = None): if reason is None: reason = f'Action done by {ctx.author} (ID: {ctx.author.id})' guild = ctx.guild total = len(members) if total == 0: return await ctx.warn('Missing members to mute.') elif total > 20: return await ctx.error('You may only mute 20 people at a time') role = discord.utils.get(guild.roles, name='Muted') failed = 0 em = discord.Embed(colour=invis, description='') for member in members: if role not in member.roles: try: await member.add_roles(role, reason=reason) em.description += f'{self.bot.icons["greenTick"]} {member.name} Sucsessfully muted' except discord.HTTPException: failed += 1 em.description += f'{self.bot.icons["RedTick"]} {member.name} Failed to mute muted' em.set_footer(text=f'Muted [{total - failed}/{total}]') await ctx.try_reply(embed=em) @commands.command() @commands.is_owner() async def do(self, ctx, times: int, *, command): msg = copy.copy(ctx.message) msg.content = ctx.prefix + command new_ctx = await self.bot.get_context(msg, cls=type(ctx)) for i in range(times): await new_ctx.reinvoke() # The bot must have Manage Roles permission and be # above the muted role in the hierarchy. # To use this command you need to be higher than the # mute role in the hierarchy and have Manage Roles # permission at the server level. # """ @commands.command(name='unmute') @can_mute() async def _unmute(self, ctx, members: commands.Greedy[MemberConverterr], *, reason: ActionReason = None): if reason is None: reason = f'Action done by {ctx.author} (ID: {ctx.author.id})' role = next((g for g in ctx.guild.roles if g.name == "Muted"), None) total = len(members) if total == 0: return await ctx.send('Missing members to unmute.') failed = 0 for member in members: try: await member.remove_roles(role, reason=reason) except discord.HTTPException: failed += 1 if failed == 0: await ctx.send('\N{THUMBS UP SIGN}') else: await ctx.send(f'Unmuted [{total - failed}/{total}]') @commands.command(aliases=["ar"]) @commands.guild_only() @commands.has_permissions(manage_roles=True) async def announcerole(self, ctx, *, role: discord.Role): if role == ctx.guild.default_role: return await ctx.warn("To prevent abuse, I won't allow mentionable role for everyone/here role.") if ctx.author.top_role.position <= role.position: return await ctx.warn( "It seems like the role you attempt to mention is over your permissions, therefore I won't allow you.") if ctx.me.top_role.position <= role.position: return await ctx.error("This role is above my permissions, I can't make it mentionable ;-;") await role.edit(mentionable=True, reason=f"[ {ctx.author} ] announcerole command") msg = await ctx.success( f"**{role.name}** is now mentionable, if you don't mention it within 30 seconds, I will revert the changes.") while True: def role_checker(m): if role.mention in m.content: return True return False try: checker = await self.bot.wait_for("message", timeout=30.0, check=role_checker) if checker.author.id == ctx.author.id: await role.edit(mentionable=False, reason=f"[ {ctx.author} ] announcerole command") return await msg.edit( content=f"**{role.name}** mentioned by **{ctx.author}** in {checker.channel.mention}") else: await checker.delete() except asyncio.TimeoutError: await role.edit(mentionable=False, reason=f"[ {ctx.author} ] announcerole command") return await msg.edit(content=f"**{role.name}** was never mentioned by **{ctx.author}**...") @commands.group() @commands.guild_only() @commands.has_permissions(manage_messages=True) async def find(self, ctx): if ctx.invoked_subcommand is None: await ctx.send_help(str(ctx.command)) @find.command(name="playing") async def find_playing(self, ctx, *, search: str): loop = [] for i in ctx.guild.members: if i.activities and (not i.bot): for g in i.activities: if g.name and (search.lower() in g.name.lower()): loop.append(f"{i} | {type(g).__name__}: {g.name} ({i.id})") await default.prettyResults( ctx, "playing", f"Found **{len(loop)}** on your search for **{search}**", loop ) @find.command(name="username", aliases=["name"]) async def find_name(self, ctx, *, search: str): loop = [f"{i} ({i.id})" for i in ctx.guild.members if search.lower() in i.name.lower() and not i.bot] await default.prettyResults( ctx, "name", f"Found **{len(loop)}** on your search for **{search}**", loop ) @find.command(name="nickname", aliases=["nick"]) async def find_nickname(self, ctx, *, search: str): loop = [f"{i.nick} | {i} ({i.id})" for i in ctx.guild.members if i.nick if (search.lower() in i.nick.lower()) and not i.bot] await default.prettyResults( ctx, "name", f"Found **{len(loop)}** on your search for **{search}**", loop ) @find.command(name="id") async def find_id(self, ctx, *, search: int): loop = [f"{i} | {i} ({i.id})" for i in ctx.guild.members if (str(search) in str(i.id)) and not i.bot] await default.prettyResults( ctx, "name", f"Found **{len(loop)}** on your search for **{search}**", loop ) @find.command(name="discriminator", aliases=["discrim"]) async def find_discriminator(self, ctx, *, search: str): if not len(search) == 4 or not re.compile("^[0-9]*$").search(search): return await ctx.send("You must provide exactly 4 digits") loop = [f"{i} ({i.id})" for i in ctx.guild.members if search == i.discriminator] await default.prettyResults( ctx, "discriminator", f"Found **{len(loop)}** on your search for **{search}**", loop ) @commands.command() @commands.guild_only() @commands.has_permissions(manage_roles=True) async def lock(self, ctx): channel = ctx.channel overwrite = channel.overwrites_for(ctx.guild.default_role) if not overwrite.send_messages: embed = discord.Embed(colour=magenta, description=f"{channel.mention} is already a locked channel") embed.set_author(name='Invalid usage', icon_url=picture("Warning")) try: await ctx.send(embed=embed) return except: try: await ctx.author.send(embed=embed) return except: return embed = discord.Embed(colour=magenta, description=f":lock: **Locked channel** {ctx.channel.mention}") await ctx.send(embed=embed) await channel.set_permissions(ctx.guild.default_role, send_messages=False) @commands.command() @commands.guild_only() @commands.has_permissions(manage_roles=True) async def unlock(self, ctx): channel = ctx.channel overwrite = channel.overwrites_for(ctx.guild.default_role) if overwrite.send_messages: embed = discord.Embed(colour=magenta, description=f"{channel.mention} is not a locked channel") embed.set_author(name='Invalid usage', icon_url=picture("Warning")) try: await ctx.send(embed=embed) return except: try: await ctx.author.send(embed=embed) return except: return await channel.set_permissions(ctx.guild.default_role, send_messages=True) embed = discord.Embed(colour=0xFF004D, description=f":unlock: **Unlocked channel** {ctx.channel.mention}") try: await ctx.send(embed=embed) except: try: await ctx.author.send(embed=embed) except: pass @commands.command() @commands.has_permissions(manage_messages=True) async def cls(self, ctx, amount: int): amount2 = amount + 1 await ctx.channel.purge(limit=amount2) @commands.group(aliases=["purge", "clr", "clear"]) @commands.guild_only() @commands.max_concurrency(1, per=commands.BucketType.guild) @commands.has_permissions(manage_messages=True) async def prune(self, ctx): if ctx.invoked_subcommand is None: await ctx.send_help(str(ctx.command)) async def do_removal(self, ctx, limit, predicate, *, before=None, after=None): if limit > 2000: return await ctx.send(f'Too many messages to search given ({limit}/2000)') if before is None: before = ctx.message else: before = discord.Object(id=before) if after is not None: after = discord.Object(id=after) try: deleted = await ctx.channel.purge(limit=limit, before=before, after=after, check=predicate) except discord.Forbidden as e: return await ctx.send('I do not have permissions to delete messages.') except discord.HTTPException as e: return await ctx.send(f'Error: {e} (try a smaller search?)') spammers = Counter(m.author.display_name for m in deleted) deleted = len(deleted) messages = [f'{deleted} message{" was" if deleted == 1 else "s were"} removed.'] if deleted: messages.append('') spammers = sorted(spammers.items(), key=lambda t: t[1], reverse=True) messages.extend(f'**{name}**: {count}' for name, count in spammers) to_send = '\n'.join(messages) if len(to_send) > 2000: await ctx.send(f'Successfully removed {deleted} messages.', delete_after=10) else: await ctx.send(to_send, delete_after=10) @prune.command() async def embeds(self, ctx, search=100): await self.do_removal(ctx, search, lambda e: len(e.embeds)) @prune.command() async def files(self, ctx, search=100): await self.do_removal(ctx, search, lambda e: len(e.attachments)) @prune.command() async def mentions(self, ctx, search=100): await self.do_removal(ctx, search, lambda e: len(e.mentions) or len(e.role_mentions)) @prune.command() async def images(self, ctx, search=100): await self.do_removal(ctx, search, lambda e: len(e.embeds) or len(e.attachments)) @prune.command(name="all") async def _remove_all(self, ctx, search=100): await self.do_removal(ctx, search, lambda e: True) @prune.command() async def user(self, ctx, member: MemberConverterr, search=100): await self.do_removal(ctx, search, lambda e: e.author == member) @prune.command() async def contains(self, ctx, *, substr: str): if len(substr) < 3: await ctx.send("The substring length must be at least 3 characters.") else: await self.do_removal(ctx, 100, lambda e: substr in e.content) @prune.command(name="bot", aliases=['bots']) async def _bots(self, ctx, prefix, search=100): def predicate(m): return (m.webhook_id is None and m.author.bot) or m.content.startswith(tuple(prefix)) await self.do_removal(ctx, search, predicate) @prune.command(name="users") async def _users(self, ctx, search=100): def predicate(m): return m.author.bot is False await self.do_removal(ctx, search, predicate) @prune.command(name="emojis") async def _emojis(self, ctx, search=100): custom_emoji = re.compile(r"<a?:(.*?):(\d{17,21})>|[\u263a-\U0001f645]") def predicate(m): return custom_emoji.search(m.content) await self.do_removal(ctx, search, predicate) @prune.command(name="reactions") async def _reactions(self, ctx, search=100): if search > 2000: return await ctx.send(f"Too many messages to search for ({search}/2000)") total_reactions = 0 async for message in ctx.history(limit=search, before=ctx.message): if len(message.reactions): total_reactions += sum(r.count for r in message.reactions) await message.clear_reactions() await ctx.send(f"Successfully removed {total_reactions} reactions.") @prune.command() async def custom(self, ctx, *, args: str): parser = Arguments(add_help=False, allow_abbrev=False) parser.add_argument('--user', nargs='+') parser.add_argument('--contains', nargs='+') parser.add_argument('--starts', nargs='+') parser.add_argument('--ends', nargs='+') parser.add_argument('--or', action='store_true', dest='_or') parser.add_argument('--not', action='store_true', dest='_not') parser.add_argument('--emoji', action='store_true') parser.add_argument('--bot', action='store_const', const=lambda m: m.author.bot) parser.add_argument('--embeds', action='store_const', const=lambda m: len(m.embeds)) parser.add_argument('--files', action='store_const', const=lambda m: len(m.attachments)) parser.add_argument('--reactions', action='store_const', const=lambda m: len(m.reactions)) parser.add_argument('--search', type=int) parser.add_argument('--after', type=int) parser.add_argument('--before', type=int) try: args = parser.parse_args(shlex.split(args)) except Exception as e: await ctx.send(str(e)) return predicates = [] if args.bot: predicates.append(args.bot) if args.embeds: predicates.append(args.embeds) if args.files: predicates.append(args.files) if args.reactions: predicates.append(args.reactions) if args.emoji: custom_emoji = re.compile(r'<:(\w+):(\d+)>') predicates.append(lambda m: custom_emoji.search(m.content)) if args.user: users = [] converter = commands.MemberConverter() for u in args.user: try: user = await converter.convert(ctx, u) users.append(user) except Exception as e: await ctx.send(str(e)) return predicates.append(lambda m: m.author in users) if args.contains: predicates.append(lambda m: any(sub in m.content for sub in args.contains)) if args.starts: predicates.append(lambda m: any(m.content.startswith(s) for s in args.starts)) if args.ends: predicates.append(lambda m: any(m.content.endswith(s) for s in args.ends)) op = all if not args._or else any def predicate(m): r = op(p(m) for p in predicates) if args._not: return not r return r if args.after: if args.search is None: args.search = 2000 if args.search is None: args.search = 100 args.search = max(0, min(2000, args.search)) await self.do_removal(ctx, args.search, predicate, before=args.before, after=args.after) async def update_mute_role(self, ctx, config, role, *, merge=False): guild = ctx.guild if config and merge: members = config.muted_members reason = f'Action done by {ctx.author} (ID: {ctx.author.id}): Merging mute roles' async for member in self.bot.resolve_member_ids(guild, members): if not member._roles.has(role.id): try: await member.add_roles(role, reason=reason) except discord.HTTPException: pass else: members = set() members.update(map(lambda m: m.id, role.members)) # VALUES ($1, $2, $3::bigint[]) ON CONFLICT (id) # DO UPDATE SET # mute_role_id = EXCLUDED.mute_role_id, # muted_members = EXCLUDED.muted_members # """ def setup(bot): bot.add_cog(Mod(bot))
true
true
f7f9f3cc52418089bf9334dff470ab446f48fffb
2,672
py
Python
src/nodes/corenodes/blend/alpha_over_node/alpha_over_node.py
yonMaor/GimelStudio
7ed7db429e61e0413791ad261583c7018f888953
[ "Apache-2.0" ]
null
null
null
src/nodes/corenodes/blend/alpha_over_node/alpha_over_node.py
yonMaor/GimelStudio
7ed7db429e61e0413791ad261583c7018f888953
[ "Apache-2.0" ]
null
null
null
src/nodes/corenodes/blend/alpha_over_node/alpha_over_node.py
yonMaor/GimelStudio
7ed7db429e61e0413791ad261583c7018f888953
[ "Apache-2.0" ]
null
null
null
# ---------------------------------------------------------------------------- # Gimel Studio Copyright 2019-2022 by the Gimel Studio project contributors # # 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 gimelstudio import api class AlphaOverNode(api.Node): def __init__(self, nodegraph, id): api.Node.__init__(self, nodegraph, id) @property def NodeMeta(self): meta_info = { "label": "Alpha Over", "author": "Gimel Studio", "version": (0, 4, 0), "category": "BLEND", "description": "Alpha over two images together based on the factor.", } return meta_info def NodeInitProps(self): image1 = api.ImageProp( idname="image_1", ) image2 = api.ImageProp( idname="image_2", ) factor = api.IntegerProp( idname="factor", default=100, min_val=0, max_val=100, fpb_label="Factor" ) self.NodeAddProp(image1) self.NodeAddProp(image2) self.NodeAddProp(factor) def NodeInitOutputs(self): self.outputs = { "image": api.Output(idname="image", datatype="IMAGE", label="Image"), } def MutedNodeEvaluation(self, eval_info): return self.EvalMutedNode(eval_info) def NodeEvaluation(self, eval_info): image1 = self.EvalProperty(eval_info, "image_1") image2 = self.EvalProperty(eval_info, "image_2") factor = self.EvalProperty(eval_info, "factor") render_image = api.Image() # Make correction for slider range of 1-100 factor = (factor * 0.01) props = { "factor": factor } shader_src = "nodes/corenodes/blend/alpha_over_node/alpha_over.glsl" result = self.RenderGLSL(shader_src, props, image1, image2) render_image.SetAsImage(result) self.NodeUpdateThumb(render_image) return { "image": render_image } api.RegisterNode(AlphaOverNode, "corenode_alpha_over")
31.435294
81
0.587201
from gimelstudio import api class AlphaOverNode(api.Node): def __init__(self, nodegraph, id): api.Node.__init__(self, nodegraph, id) @property def NodeMeta(self): meta_info = { "label": "Alpha Over", "author": "Gimel Studio", "version": (0, 4, 0), "category": "BLEND", "description": "Alpha over two images together based on the factor.", } return meta_info def NodeInitProps(self): image1 = api.ImageProp( idname="image_1", ) image2 = api.ImageProp( idname="image_2", ) factor = api.IntegerProp( idname="factor", default=100, min_val=0, max_val=100, fpb_label="Factor" ) self.NodeAddProp(image1) self.NodeAddProp(image2) self.NodeAddProp(factor) def NodeInitOutputs(self): self.outputs = { "image": api.Output(idname="image", datatype="IMAGE", label="Image"), } def MutedNodeEvaluation(self, eval_info): return self.EvalMutedNode(eval_info) def NodeEvaluation(self, eval_info): image1 = self.EvalProperty(eval_info, "image_1") image2 = self.EvalProperty(eval_info, "image_2") factor = self.EvalProperty(eval_info, "factor") render_image = api.Image() factor = (factor * 0.01) props = { "factor": factor } shader_src = "nodes/corenodes/blend/alpha_over_node/alpha_over.glsl" result = self.RenderGLSL(shader_src, props, image1, image2) render_image.SetAsImage(result) self.NodeUpdateThumb(render_image) return { "image": render_image } api.RegisterNode(AlphaOverNode, "corenode_alpha_over")
true
true
f7f9f536978a46cbd0cd0d7c3ba4c7f3ff816ceb
1,815
py
Python
test/test_optimal_transport.py
vlkit/vlk
0fc79b39972356af1ca921eab5fce5d671366725
[ "MIT" ]
null
null
null
test/test_optimal_transport.py
vlkit/vlk
0fc79b39972356af1ca921eab5fce5d671366725
[ "MIT" ]
null
null
null
test/test_optimal_transport.py
vlkit/vlk
0fc79b39972356af1ca921eab5fce5d671366725
[ "MIT" ]
null
null
null
import os.path as osp TEST_DIR = osp.dirname(__file__) import sys, os sys.path.insert(0, osp.abspath(osp.join(TEST_DIR, "../"))) from vlkit.optimal_transport import sinkhorn import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from matplotlib import gridspec import torch import numpy as np import ot import ot.plot from ot.datasets import make_1D_gauss as gauss savedir = osp.join(osp.dirname(__file__), "../data/test") os.makedirs(savedir, exist_ok=True) n = 100 # nb bins # bin positions x = np.arange(n, dtype=np.float64) # Gaussian distributions a = gauss(n, m=20, s=5) # m= mean, s= std b = gauss(n, m=60, s=8) d1, d2 = a.shape[0], b.shape[0] # loss matrix M = ot.dist(x.reshape((n, 1)), x.reshape((n, 1))) M /= M.max() lambd = 1e-3 T_ot = ot.sinkhorn(a, b, M, lambd, verbose=False) T = sinkhorn( torch.from_numpy(a).view(1, -1), torch.from_numpy(b).view(1, -1), torch.from_numpy(M).unsqueeze(dim=0), num_iters=1000, error_thres=1e-9, reg=lambd, ) plt.figure(figsize=(20, 10)) gs = gridspec.GridSpec(3, 6) ax1 = plt.subplot(gs[0, 1:3]) plt.plot(np.arange(b.size), b, 'r', label='Target distribution') ax2 = plt.subplot(gs[1:, 0]) plt.plot(b, x, 'b', label='Source distribution') plt.gca().invert_xaxis() plt.gca().invert_yaxis() plt.subplot(gs[1:3, 1:3], sharex=ax1, sharey=ax2) plt.imshow(T_ot) plt.axis('off') ax1 = plt.subplot(gs[0, 4:]) plt.plot(np.arange(b.size), b, 'r', label='Target distribution') ax2 = plt.subplot(gs[1:, 3]) plt.plot(b, x, 'b', label='Source distribution') plt.gca().invert_xaxis() plt.gca().invert_yaxis() plt.subplot(gs[1:3, 4:], sharex=ax1, sharey=ax2) plt.imshow(T.squeeze(dim=0).numpy()) plt.axis('off') plt.tight_layout() plt.subplots_adjust(wspace=0., hspace=0.2) plt.savefig(osp.join(savedir, 'pth_sinkhorm.pdf'))
24.2
64
0.685399
import os.path as osp TEST_DIR = osp.dirname(__file__) import sys, os sys.path.insert(0, osp.abspath(osp.join(TEST_DIR, "../"))) from vlkit.optimal_transport import sinkhorn import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from matplotlib import gridspec import torch import numpy as np import ot import ot.plot from ot.datasets import make_1D_gauss as gauss savedir = osp.join(osp.dirname(__file__), "../data/test") os.makedirs(savedir, exist_ok=True) n = 100 x = np.arange(n, dtype=np.float64) a = gauss(n, m=20, s=5) b = gauss(n, m=60, s=8) d1, d2 = a.shape[0], b.shape[0] M = ot.dist(x.reshape((n, 1)), x.reshape((n, 1))) M /= M.max() lambd = 1e-3 T_ot = ot.sinkhorn(a, b, M, lambd, verbose=False) T = sinkhorn( torch.from_numpy(a).view(1, -1), torch.from_numpy(b).view(1, -1), torch.from_numpy(M).unsqueeze(dim=0), num_iters=1000, error_thres=1e-9, reg=lambd, ) plt.figure(figsize=(20, 10)) gs = gridspec.GridSpec(3, 6) ax1 = plt.subplot(gs[0, 1:3]) plt.plot(np.arange(b.size), b, 'r', label='Target distribution') ax2 = plt.subplot(gs[1:, 0]) plt.plot(b, x, 'b', label='Source distribution') plt.gca().invert_xaxis() plt.gca().invert_yaxis() plt.subplot(gs[1:3, 1:3], sharex=ax1, sharey=ax2) plt.imshow(T_ot) plt.axis('off') ax1 = plt.subplot(gs[0, 4:]) plt.plot(np.arange(b.size), b, 'r', label='Target distribution') ax2 = plt.subplot(gs[1:, 3]) plt.plot(b, x, 'b', label='Source distribution') plt.gca().invert_xaxis() plt.gca().invert_yaxis() plt.subplot(gs[1:3, 4:], sharex=ax1, sharey=ax2) plt.imshow(T.squeeze(dim=0).numpy()) plt.axis('off') plt.tight_layout() plt.subplots_adjust(wspace=0., hspace=0.2) plt.savefig(osp.join(savedir, 'pth_sinkhorm.pdf'))
true
true
f7f9f673f4107768045a7d316366915609a1158f
10,330
py
Python
eth2/beacon/state_machines/forks/serenity/validation.py
kushagrasharma/trinity
0dd33ee304630b93192861626ac5e9eca6fc4d92
[ "MIT" ]
null
null
null
eth2/beacon/state_machines/forks/serenity/validation.py
kushagrasharma/trinity
0dd33ee304630b93192861626ac5e9eca6fc4d92
[ "MIT" ]
null
null
null
eth2/beacon/state_machines/forks/serenity/validation.py
kushagrasharma/trinity
0dd33ee304630b93192861626ac5e9eca6fc4d92
[ "MIT" ]
null
null
null
from eth_typing import ( Hash32 ) from eth_utils import ( ValidationError, ) import rlp from eth.constants import ( ZERO_HASH32, ) from eth2._utils import bls as bls from eth2.beacon._utils.hash import ( hash_eth2, ) from eth2.beacon.enums import ( SignatureDomain, ) from eth2.beacon.helpers import ( get_attestation_participants, get_beacon_proposer_index, get_block_root, get_domain, ) from eth2.beacon.types.blocks import BaseBeaconBlock # noqa: F401 from eth2.beacon.types.states import BeaconState # noqa: F401 from eth2.beacon.types.attestations import Attestation # noqa: F401 from eth2.beacon.types.attestation_data import AttestationData # noqa: F401 from eth2.beacon.types.proposal_signed_data import ProposalSignedData from eth2.beacon.typing import ( ShardNumber, ) # # Proposer signature validation # def validate_serenity_proposer_signature(state: BeaconState, block: BaseBeaconBlock, beacon_chain_shard_number: ShardNumber, epoch_length: int) -> None: block_without_signature_root = block.block_without_signature_root # TODO: Replace this root with tree hash root proposal_root = ProposalSignedData( state.slot, beacon_chain_shard_number, block_without_signature_root, ).root # Get the public key of proposer beacon_proposer_index = get_beacon_proposer_index(state, state.slot, epoch_length) proposer_pubkey = state.validator_registry[beacon_proposer_index].pubkey is_valid_signature = bls.verify( pubkey=proposer_pubkey, message=proposal_root, signature=block.signature, domain=get_domain(state.fork_data, state.slot, SignatureDomain.DOMAIN_PROPOSAL), ) if not is_valid_signature: raise ValidationError("Invalid Proposer Signature on block") # # Attestation validation # def validate_serenity_attestation(state: BeaconState, attestation: Attestation, epoch_length: int, min_attestation_inclusion_delay: int, latest_block_roots_length: int) -> None: """ Validate the given ``attestation``. Raise ``ValidationError`` if it's invalid. """ validate_serenity_attestation_slot( attestation.data, state.slot, epoch_length, min_attestation_inclusion_delay, ) validate_serenity_attestation_justified_slot( attestation.data, state.slot, state.previous_justified_slot, state.justified_slot, epoch_length, ) validate_serenity_attestation_justified_block_root( attestation.data, justified_block_root=get_block_root( state=state, slot=attestation.data.justified_slot, latest_block_roots_length=latest_block_roots_length, ), ) validate_serenity_attestation_latest_crosslink_root( attestation.data, latest_crosslink_root=state.latest_crosslinks[attestation.data.shard].shard_block_root, ) validate_serenity_attestation_shard_block_root(attestation.data) validate_serenity_attestation_aggregate_signature( state, attestation, epoch_length, ) def validate_serenity_attestation_slot(attestation_data: AttestationData, current_slot: int, epoch_length: int, min_attestation_inclusion_delay: int) -> None: """ Validate ``slot`` field of ``attestation_data``. Raise ``ValidationError`` if it's invalid. """ if attestation_data.slot + min_attestation_inclusion_delay > current_slot: raise ValidationError( "Attestation slot plus min inclusion delay is too high:\n" "\tFound: %s (%s + %s), Needed less than or equal to %s" % ( attestation_data.slot + min_attestation_inclusion_delay, attestation_data.slot, min_attestation_inclusion_delay, current_slot, ) ) if attestation_data.slot + epoch_length < current_slot: raise ValidationError( "Attestation slot plus epoch length is too low:\n" "\tFound: %s (%s + %s), Needed greater than or equal to: %s" % ( attestation_data.slot + epoch_length, attestation_data.slot, epoch_length, current_slot, ) ) def validate_serenity_attestation_justified_slot(attestation_data: AttestationData, current_slot: int, previous_justified_slot: int, justified_slot: int, epoch_length: int) -> None: """ Validate ``justified_slot`` field of ``attestation_data``. Raise ``ValidationError`` if it's invalid. """ if attestation_data.slot >= current_slot - (current_slot % epoch_length): if attestation_data.justified_slot != justified_slot: raise ValidationError( "Attestation ``slot`` is after recent epoch transition but attestation" "``justified_slot`` is not targeting the ``justified_slot``:\n" "\tFound: %s, Expected %s" % (attestation_data.justified_slot, justified_slot) ) else: if attestation_data.justified_slot != previous_justified_slot: raise ValidationError( "Attestation ``slot`` is before recent epoch transition but attestation" "``justified_slot`` is not targeting the ``previous_justified_slot:\n" "\tFound: %s, Expected %s" % (attestation_data.justified_slot, previous_justified_slot) ) def validate_serenity_attestation_justified_block_root(attestation_data: AttestationData, justified_block_root: Hash32) -> None: """ Validate ``justified_block_root`` field of ``attestation_data``. Raise ``ValidationError`` if it's invalid. """ if attestation_data.justified_block_root != justified_block_root: raise ValidationError( "Attestation ``justified_block_root`` is not equal to the " "``justified_block_root`` at the ``justified_slot``:\n" "\tFound: %s, Expected %s at slot %s" % ( attestation_data.justified_block_root, justified_block_root, attestation_data.justified_slot, ) ) def validate_serenity_attestation_latest_crosslink_root(attestation_data: AttestationData, latest_crosslink_root: Hash32) -> None: """ Validate that either the attestation ``latest_crosslink_root`` or ``shard_block_root`` field of ``attestation_data`` is the provided ``latest_crosslink_root``. Raise ``ValidationError`` if it's invalid. """ acceptable_shard_block_roots = { attestation_data.latest_crosslink_root, attestation_data.shard_block_root, } if latest_crosslink_root not in acceptable_shard_block_roots: raise ValidationError( "Neither the attestation ``latest_crosslink_root`` nor the attestation " "``shard_block_root`` are equal to the ``latest_crosslink_root``.\n" "\tFound: %s and %s, Expected %s" % ( attestation_data.latest_crosslink_root, attestation_data.shard_block_root, latest_crosslink_root, ) ) def validate_serenity_attestation_shard_block_root(attestation_data: AttestationData) -> None: """ Validate ``shard_block_root`` field of `attestation_data`. Raise ``ValidationError`` if it's invalid. Note: This is the Phase 0 version of ``shard_block_root`` validation. This is a built-in stub and will be changed in phase 1. """ if attestation_data.shard_block_root != ZERO_HASH32: raise ValidationError( "Attestation ``shard_block_root`` is not ZERO_HASH32.\n" "\tFound: %s, Expected %s" % ( attestation_data.shard_block_root, ZERO_HASH32, ) ) def validate_serenity_attestation_aggregate_signature(state: BeaconState, attestation: Attestation, epoch_length: int) -> None: """ Validate ``aggregate_signature`` field of ``attestation``. Raise ``ValidationError`` if it's invalid. Note: This is the phase 0 version of `aggregate_signature`` validation. All proof of custody bits are assumed to be 0 within the signed data. This will change to reflect real proof of custody bits in the Phase 1. """ participant_indices = get_attestation_participants( state=state, slot=attestation.data.slot, shard=attestation.data.shard, participation_bitfield=attestation.participation_bitfield, epoch_length=epoch_length, ) pubkeys = tuple( state.validator_registry[validator_index].pubkey for validator_index in participant_indices ) group_public_key = bls.aggregate_pubkeys(pubkeys) # TODO: change to tree hashing when we have SSZ # TODO: Replace with AttestationAndCustodyBit data structure message = hash_eth2( rlp.encode(attestation.data) + (0).to_bytes(1, "big") ) is_valid_signature = bls.verify( message=message, pubkey=group_public_key, signature=attestation.aggregate_signature, domain=get_domain( fork_data=state.fork_data, slot=attestation.data.slot, domain_type=SignatureDomain.DOMAIN_ATTESTATION, ), ) if not is_valid_signature: raise ValidationError( "Attestation ``aggregate_signature`` is invalid." )
35.993031
95
0.626137
from eth_typing import ( Hash32 ) from eth_utils import ( ValidationError, ) import rlp from eth.constants import ( ZERO_HASH32, ) from eth2._utils import bls as bls from eth2.beacon._utils.hash import ( hash_eth2, ) from eth2.beacon.enums import ( SignatureDomain, ) from eth2.beacon.helpers import ( get_attestation_participants, get_beacon_proposer_index, get_block_root, get_domain, ) from eth2.beacon.types.blocks import BaseBeaconBlock from eth2.beacon.types.states import BeaconState from eth2.beacon.types.attestations import Attestation from eth2.beacon.types.attestation_data import AttestationData from eth2.beacon.types.proposal_signed_data import ProposalSignedData from eth2.beacon.typing import ( ShardNumber, ) def validate_serenity_proposer_signature(state: BeaconState, block: BaseBeaconBlock, beacon_chain_shard_number: ShardNumber, epoch_length: int) -> None: block_without_signature_root = block.block_without_signature_root proposal_root = ProposalSignedData( state.slot, beacon_chain_shard_number, block_without_signature_root, ).root beacon_proposer_index = get_beacon_proposer_index(state, state.slot, epoch_length) proposer_pubkey = state.validator_registry[beacon_proposer_index].pubkey is_valid_signature = bls.verify( pubkey=proposer_pubkey, message=proposal_root, signature=block.signature, domain=get_domain(state.fork_data, state.slot, SignatureDomain.DOMAIN_PROPOSAL), ) if not is_valid_signature: raise ValidationError("Invalid Proposer Signature on block") def validate_serenity_attestation(state: BeaconState, attestation: Attestation, epoch_length: int, min_attestation_inclusion_delay: int, latest_block_roots_length: int) -> None: validate_serenity_attestation_slot( attestation.data, state.slot, epoch_length, min_attestation_inclusion_delay, ) validate_serenity_attestation_justified_slot( attestation.data, state.slot, state.previous_justified_slot, state.justified_slot, epoch_length, ) validate_serenity_attestation_justified_block_root( attestation.data, justified_block_root=get_block_root( state=state, slot=attestation.data.justified_slot, latest_block_roots_length=latest_block_roots_length, ), ) validate_serenity_attestation_latest_crosslink_root( attestation.data, latest_crosslink_root=state.latest_crosslinks[attestation.data.shard].shard_block_root, ) validate_serenity_attestation_shard_block_root(attestation.data) validate_serenity_attestation_aggregate_signature( state, attestation, epoch_length, ) def validate_serenity_attestation_slot(attestation_data: AttestationData, current_slot: int, epoch_length: int, min_attestation_inclusion_delay: int) -> None: if attestation_data.slot + min_attestation_inclusion_delay > current_slot: raise ValidationError( "Attestation slot plus min inclusion delay is too high:\n" "\tFound: %s (%s + %s), Needed less than or equal to %s" % ( attestation_data.slot + min_attestation_inclusion_delay, attestation_data.slot, min_attestation_inclusion_delay, current_slot, ) ) if attestation_data.slot + epoch_length < current_slot: raise ValidationError( "Attestation slot plus epoch length is too low:\n" "\tFound: %s (%s + %s), Needed greater than or equal to: %s" % ( attestation_data.slot + epoch_length, attestation_data.slot, epoch_length, current_slot, ) ) def validate_serenity_attestation_justified_slot(attestation_data: AttestationData, current_slot: int, previous_justified_slot: int, justified_slot: int, epoch_length: int) -> None: if attestation_data.slot >= current_slot - (current_slot % epoch_length): if attestation_data.justified_slot != justified_slot: raise ValidationError( "Attestation ``slot`` is after recent epoch transition but attestation" "``justified_slot`` is not targeting the ``justified_slot``:\n" "\tFound: %s, Expected %s" % (attestation_data.justified_slot, justified_slot) ) else: if attestation_data.justified_slot != previous_justified_slot: raise ValidationError( "Attestation ``slot`` is before recent epoch transition but attestation" "``justified_slot`` is not targeting the ``previous_justified_slot:\n" "\tFound: %s, Expected %s" % (attestation_data.justified_slot, previous_justified_slot) ) def validate_serenity_attestation_justified_block_root(attestation_data: AttestationData, justified_block_root: Hash32) -> None: if attestation_data.justified_block_root != justified_block_root: raise ValidationError( "Attestation ``justified_block_root`` is not equal to the " "``justified_block_root`` at the ``justified_slot``:\n" "\tFound: %s, Expected %s at slot %s" % ( attestation_data.justified_block_root, justified_block_root, attestation_data.justified_slot, ) ) def validate_serenity_attestation_latest_crosslink_root(attestation_data: AttestationData, latest_crosslink_root: Hash32) -> None: acceptable_shard_block_roots = { attestation_data.latest_crosslink_root, attestation_data.shard_block_root, } if latest_crosslink_root not in acceptable_shard_block_roots: raise ValidationError( "Neither the attestation ``latest_crosslink_root`` nor the attestation " "``shard_block_root`` are equal to the ``latest_crosslink_root``.\n" "\tFound: %s and %s, Expected %s" % ( attestation_data.latest_crosslink_root, attestation_data.shard_block_root, latest_crosslink_root, ) ) def validate_serenity_attestation_shard_block_root(attestation_data: AttestationData) -> None: if attestation_data.shard_block_root != ZERO_HASH32: raise ValidationError( "Attestation ``shard_block_root`` is not ZERO_HASH32.\n" "\tFound: %s, Expected %s" % ( attestation_data.shard_block_root, ZERO_HASH32, ) ) def validate_serenity_attestation_aggregate_signature(state: BeaconState, attestation: Attestation, epoch_length: int) -> None: participant_indices = get_attestation_participants( state=state, slot=attestation.data.slot, shard=attestation.data.shard, participation_bitfield=attestation.participation_bitfield, epoch_length=epoch_length, ) pubkeys = tuple( state.validator_registry[validator_index].pubkey for validator_index in participant_indices ) group_public_key = bls.aggregate_pubkeys(pubkeys) message = hash_eth2( rlp.encode(attestation.data) + (0).to_bytes(1, "big") ) is_valid_signature = bls.verify( message=message, pubkey=group_public_key, signature=attestation.aggregate_signature, domain=get_domain( fork_data=state.fork_data, slot=attestation.data.slot, domain_type=SignatureDomain.DOMAIN_ATTESTATION, ), ) if not is_valid_signature: raise ValidationError( "Attestation ``aggregate_signature`` is invalid." )
true
true
f7f9f77256d26b0c3cdef69a0fe2fde6a8fd02db
42,579
py
Python
perfrunner/helpers/local.py
bochun/perfrunner
e215c73240381cf82fddc40856f560369c9b75a8
[ "Apache-2.0" ]
null
null
null
perfrunner/helpers/local.py
bochun/perfrunner
e215c73240381cf82fddc40856f560369c9b75a8
[ "Apache-2.0" ]
null
null
null
perfrunner/helpers/local.py
bochun/perfrunner
e215c73240381cf82fddc40856f560369c9b75a8
[ "Apache-2.0" ]
null
null
null
import os import shutil import socket import time import urllib.parse from datetime import date from glob import glob from sys import platform from typing import List from fabric.api import hide, lcd, local, quiet, settings, shell_env from mc_bin_client.mc_bin_client import MemcachedClient, MemcachedError from logger import logger from perfrunner.settings import ClusterSpec def extract_cb(filename: str): cmd = 'rpm2cpio ./{} | cpio -idm'.format(filename) with quiet(): local(cmd) def extract_cb_deb(filename: str): cmd = 'ar p {} data.tar.xz | unxz | tar x'.format(filename) with quiet(): local(cmd) def extract_cb_any(filename: str): if os.path.exists("{}.deb".format(filename)): extract_cb_deb("{}.deb".format(filename)) else: extract_cb("{}.rpm".format(filename)) def cleanup(backup_dir: str): logger.info("Cleaning the disk before backup/export") # Remove files from the directory, if any. local('rm -fr {}/*'.format(backup_dir)) # Discard unused blocks. Twice. if not os.path.exists(backup_dir): os.makedirs(backup_dir) # Otherwise fstrim won't find the device if platform == "linux2": local('fstrim -v {0} && fstrim -v {0}'.format(backup_dir)) def drop_caches(): logger.info('Dropping memory cache') local('sync && echo 3 > /proc/sys/vm/drop_caches') def backup(master_node: str, cluster_spec: ClusterSpec, threads: int, wrapper: bool = False, mode: str = None, compression: bool = False, storage_type: str = None, sink_type: str = None, shards: int = None, include_data: str = None): logger.info('Creating a new backup: {}'.format(cluster_spec.backup)) if not mode: cleanup(cluster_spec.backup) if wrapper: cbbackupwrapper(master_node, cluster_spec, 16, mode) else: cbbackupmgr_backup(master_node, cluster_spec, threads, mode, compression, storage_type, sink_type, shards, include_data) def compact(cluster_spec: ClusterSpec, snapshots: List[str], threads, wrapper: bool = False): if wrapper: return cbbackupmgr_compact(cluster_spec, snapshots, threads) def cbbackupwrapper(master_node: str, cluster_spec: ClusterSpec, threads: int, mode: str): postfix = '' if mode: postfix = '-m {}'.format(mode) cmd = './cbbackupwrapper http://{}:8091 {} -u {} -p {} -P {} {}'.format( master_node, cluster_spec.backup, cluster_spec.rest_credentials[0], cluster_spec.rest_credentials[1], threads, postfix, ) logger.info('Running: {}'.format(cmd)) with lcd('./opt/couchbase/bin'): local(cmd) def cbbackupmgr_backup(master_node: str, cluster_spec: ClusterSpec, threads: int, mode: str, compression: bool, storage_type: str, sink_type: str, shards: int, include_data: str): if not mode: if include_data: logger.info('running ./opt/couchbase/bin/cbbackupmgr config ' '--archive {} --repo default --include-data {}'.format(cluster_spec.backup, include_data)) local('./opt/couchbase/bin/cbbackupmgr config ' '--archive {} --repo default --include-data {}'.format(cluster_spec.backup, include_data)) else: logger.info('running ./opt/couchbase/bin/cbbackupmgr config ' '--archive {} --repo default'.format(cluster_spec.backup)) local('./opt/couchbase/bin/cbbackupmgr config ' '--archive {} --repo default'.format(cluster_spec.backup)) flags = ['--archive {}'.format(cluster_spec.backup), '--repo default', '--host http://{}'.format(master_node), '--username {}'.format(cluster_spec.rest_credentials[0]), '--password {}'.format(cluster_spec.rest_credentials[1]), '--threads {}'.format(threads) if threads else None, '--storage {}'.format(storage_type) if storage_type else None, '--sink {}'.format(sink_type) if sink_type else None, '--value-compression compressed' if compression else None, '--shards {}'.format(shards) if shards else None] cmd = './opt/couchbase/bin/cbbackupmgr backup {}'.format( ' '.join(filter(None, flags))) logger.info('Running: {}'.format(cmd)) local(cmd) def cbbackupmgr_collectinfo(cluster_spec: ClusterSpec, archive: str = ''): logger.info('Running cbbackumgr cbcollect_info on local/host ') cmd = ('./opt/couchbase/bin/cbbackupmgr collect-logs --archive {} ' '--output-dir {}'.format(archive or cluster_spec.backup, '.')) logger.info('Running: {}'.format(cmd)) local(cmd) def get_backup_snapshots(cluster_spec: ClusterSpec) -> List[str]: logger.info('running cbbackupmgr list/info command ') cmd_type = 'list' cmd = \ './opt/couchbase/bin/cbbackupmgr list ' \ '--archive {} --repo default '.format(cluster_spec.backup) for line in local(cmd, capture=True).split('\n'): if 'list is deprecated' in line: cmd_type = 'info' cmd = \ './opt/couchbase/bin/cbbackupmgr {} ' \ '--archive {} --repo default '.format(cmd_type, cluster_spec.backup, ) snapshots = [] if cmd_type == 'info': pattern = '+ {}-'.format(date.today().year) for line in local(cmd, capture=True).split('\n'): if pattern in line: snapshot = line.strip().split()[1] snapshots.append(snapshot) return snapshots elif cmd_type == 'list': pattern = '+ {}-'.format(date.today().year) for line in local(cmd, capture=True).split('\n'): if pattern in line: snapshot = line.strip().split()[-1] snapshots.append(snapshot) return snapshots def cbbackupmgr_merge(cluster_spec: ClusterSpec, snapshots: List[str], storage_type: str, threads: int): flags = ['--archive {}'.format(cluster_spec.backup), '--repo default', '--start {}'.format(snapshots[0]), '--end {}'.format(snapshots[1]), '--storage {}'.format(storage_type) if storage_type else None, '--threads {}'.format(threads) if threads else None] cmd = './opt/couchbase/bin/cbbackupmgr merge {}'.format( ' '.join(filter(None, flags))) logger.info('Running: {}'.format(cmd)) local(cmd) def calc_backup_size(cluster_spec: ClusterSpec, rounded: bool = True) -> float: backup_size = local('du -sb0 {}'.format(cluster_spec.backup), capture=True) backup_size = backup_size.split()[0] backup_size = float(backup_size) / 2 ** 30 # B -> GB return round(backup_size) if rounded else backup_size def restore(master_node: str, cluster_spec: ClusterSpec, threads: int, wrapper: bool = False, include_data: str = None): logger.info('Restore from {}'.format(cluster_spec.backup)) if wrapper: cbrestorewrapper(master_node, cluster_spec) else: cbbackupmgr_restore(master_node, cluster_spec, threads, include_data) def cbrestorewrapper(master_node: str, cluster_spec: ClusterSpec): cmd = './cbrestorewrapper {} http://{}:8091 -u {} -p {}'.format( cluster_spec.backup, master_node, cluster_spec.rest_credentials[0], cluster_spec.rest_credentials[1], ) logger.info('Running: {}'.format(cmd)) with lcd('./opt/couchbase/bin'): local(cmd) def cbbackupmgr_restore(master_node: str, cluster_spec: ClusterSpec, threads: int, include_data: str, archive: str = '', repo: str = 'default', map_data: str = None): flags = ['--archive {}'.format(archive or cluster_spec.backup), '--repo {}'.format(repo), '--include-data {}'.format(include_data) if include_data else None, '--threads {}'.format(threads), '--host http://{}'.format(master_node), '--username {}'.format(cluster_spec.rest_credentials[0]), '--password {}'.format(cluster_spec.rest_credentials[1]), '--map-data {}'.format(map_data) if map_data else None] cmd = './opt/couchbase/bin/cbbackupmgr restore --force-updates {}'.format( ' '.join(filter(None, flags))) logger.info('Running: {}'.format(cmd)) local(cmd) def cbbackupmgr_compact(cluster_spec: ClusterSpec, snapshots: List[str], threads: int): flags = ['--archive {}'.format(cluster_spec.backup), '--repo default', '--backup {}'.format(snapshots[0]), '--threads {}'.format(threads) if threads else None] cmd = './opt/couchbase/bin/cbbackupmgr compact {}'.format( ' '.join(filter(None, flags))) logger.info('Running: {}'.format(cmd)) local(cmd) def cbbackupmgr_list(cluster_spec: ClusterSpec, snapshots: List[str], bucket: str = None): flags = ['--archive {}'.format(cluster_spec.backup), '--repo default', '--backup {}'.format(snapshots[0]), '--bucket {}'.format(bucket) if bucket else None] cmd = './opt/couchbase/bin/cbbackupmgr list {}'.format( ' '.join(filter(None, flags))) logger.info('Running: {}'.format(cmd)) local(cmd) def cbexport(master_node: str, cluster_spec: ClusterSpec, bucket: str, data_format: str, threads: int, collection_field: str, scope_field: str, key_field: str = None, log_file: str = None): export_path = os.path.join(cluster_spec.backup, 'data.json') cleanup(cluster_spec.backup) if collection_field and scope_field: flags = ['--format {}'.format(data_format), '--output {}'.format(export_path), '--cluster http://{}'.format(master_node), '--bucket {}'.format(bucket), '--username {}'.format(cluster_spec.rest_credentials[0]), '--password {}'.format(cluster_spec.rest_credentials[1]), '--collection-field {}'.format(collection_field), '--scope-field {}'.format(scope_field), '--threads {}'.format(threads) if threads else None, '--include-key key', '--log-file {}'.format(log_file) if log_file else None] else: flags = ['--format {}'.format(data_format), '--output {}'.format(export_path), '--cluster http://{}'.format(master_node), '--bucket {}'.format(bucket), '--username {}'.format(cluster_spec.rest_credentials[0]), '--password {}'.format(cluster_spec.rest_credentials[1]), '--threads {}'.format(threads) if threads else None, '--include-key {}'.format(key_field) if key_field else None, '--log-file {}'.format(log_file) if log_file else None] cmd = './opt/couchbase/bin/cbexport json {}'.format( ' '.join(filter(None, flags))) logger.info('Running: {}'.format(cmd)) local(cmd) def cbimport(master_node: str, cluster_spec: ClusterSpec, bucket: str, data_type: str, data_format: str, import_file: str, threads: int, scope_collection_exp: str, field_separator: str = None, limit_rows: int = None, skip_rows: int = None, infer_types: int = None, omit_empty: int = None, errors_log: str = None, log_file: str = None): if not scope_collection_exp: flags = ['--format {}'.format(data_format) if data_type == 'json' else None, '--dataset {}'.format(import_file), '--cluster http://{}'.format(master_node), '--bucket {}'.format(bucket), '--username {}'.format(cluster_spec.rest_credentials[0]), '--password {}'.format(cluster_spec.rest_credentials[1]), '--generate-key "#MONO_INCR#"', '--threads {}'.format(threads) if threads else None, '--field-separator {}'.format(field_separator) if field_separator else None, '--limit-rows {}'.format(limit_rows) if limit_rows else None, '--skip-rows {}'.format(skip_rows) if skip_rows else None, '--infer-types' if infer_types else None, '--omit-empty' if omit_empty else None, '--errors-log {}'.format(errors_log) if errors_log else None, '--log-file {}'.format(log_file) if log_file else None] else: flags = ['--format {}'.format(data_format) if data_type == 'json' else None, '--dataset {}'.format(import_file), '--cluster http://{}'.format(master_node), '--bucket {}'.format(bucket), '--username {}'.format(cluster_spec.rest_credentials[0]), '--password {}'.format(cluster_spec.rest_credentials[1]), '--generate-key "#MONO_INCR#"', '--threads {}'.format(threads) if threads else None, '--field-separator {}'.format(field_separator) if field_separator else None, '--limit-rows {}'.format(limit_rows) if limit_rows else None, '--skip-rows {}'.format(skip_rows) if skip_rows else None, '--infer-types' if infer_types else None, '--omit-empty' if omit_empty else None, '--errors-log {}'.format(errors_log) if errors_log else None, '--log-file {}'.format(log_file) if log_file else None, '--scope-collection-exp {}'.format(scope_collection_exp)] cmd = './opt/couchbase/bin/cbimport {} {}'.format( data_type, ' '.join(filter(None, flags))) logger.info('Running: {}'.format(cmd)) local(cmd) def run_cbc_pillowfight(host: str, bucket: str, password: str, num_items: int, num_threads: int, num_cycles: int, size: int, batch_size: int, writes: int, persist_to: int, replicate_to: int, connstr_params: dict, durability: int, doc_gen: str = 'binary', ssl_mode: str = 'none', populate: bool = False, collections: dict = None, custom_pillowfight: bool = False): cmd = 'cbc-pillowfight ' \ '--password {password} ' \ '--batch-size {batch_size} ' \ '--num-items {num_items} ' \ '--num-threads {num_threads} ' \ '--min-size {size} ' \ '--max-size {size} ' \ '--persist-to {persist_to} ' \ '--replicate-to {replicate_to} ' if custom_pillowfight: cmd = '/tmp/libcouchbase_custom/libcouchbase/build/bin/'+cmd if collections: target_scope_collections = collections[bucket] for scope in target_scope_collections.keys(): for collection in target_scope_collections[scope].keys(): if populate: if target_scope_collections[scope][collection]['load'] == 1: cmd += "--collection " + scope+"."+collection + " " else: if target_scope_collections[scope][collection]['access'] == 1: cmd += "--collection " + scope+"."+collection + " " if doc_gen == 'json': cmd += '--json ' elif doc_gen == 'json_snappy': cmd += '--json --compress --compress ' if ssl_mode == 'data': cmd += '--spec "couchbases://{host}/{bucket}?{params}" --certpath root.pem ' else: cmd += '--spec "couchbase://{host}/{bucket}?{params}" ' if populate: cmd += '--populate-only ' else: cmd += \ '--set-pct {writes} ' \ '--num-cycles {num_cycles} ' \ '--no-population ' durability_options = { 0: 'none', 1: 'majority', 2: 'majority_and_persist_to_active', 3: 'persist_to_majority'} if durability: cmd += '--durability {durability} ' cmd += ' > /dev/null 2>&1' params = urllib.parse.urlencode(connstr_params) cmd = cmd.format(host=host, bucket=bucket, password=password, params=params, num_items=num_items, num_threads=num_threads, num_cycles=num_cycles, size=size, batch_size=batch_size, persist_to=persist_to, replicate_to=replicate_to, writes=writes, durability=durability_options[durability] if durability else None) logger.info('Running: {}'.format(cmd)) local(cmd, shell='/bin/bash') def run_dcptest(host: str, username: str, password: str, bucket: str, num_items: int, num_connections: int): cmd = './dcptest ' \ '-kvaddrs {host}:11210 ' \ '-buckets {bucket} ' \ '-nummessages {num_items} ' \ '-numconnections {num_connections} ' \ '-outputfile dcpstatsfile ' \ '{host}:8091 > dcptest.log 2>&1' cmd = cmd.format(host=host, bucket=bucket, num_items=num_items, num_connections=num_connections) cbauth = 'http://{user}:{password}@{host}:8091'.format(host=host, user=username, password=password) logger.info('Running: {}'.format(cmd)) with shell_env(CBAUTH_REVRPC_URL=cbauth): local(cmd) def run_kvgen(hostname: str, num_docs: int, prefix: str): cmd = './kvgen -hostname {} -docs {} -prefix {}'.format(hostname, num_docs, prefix) logger.info('Running: {}'.format(cmd)) with shell_env(GOGC='300'): local(cmd) def run_ycsb(host: str, bucket: str, password: str, action: str, ycsb_client: str, workload: str, items: int, workers: int, target: int, epoll: str, boost: int, persist_to: int, replicate_to: int, num_atrs: int, documentsintransaction: int, transactionreadproportion: str, transactionupdateproportion: str, transactioninsertproportion: str, requestdistribution: str, ssl_keystore_file: str = '', ssl_keystore_password: str = '', ssl_mode: str = 'none', certificate_file: str = '', soe_params: dict = None, ops: int = None, execution_time: int = None, cbcollect: int = 0, timeseries: int = 0, transactionsenabled: int = 0, instance: int = 0, fieldlength: int = 1024, fieldcount: int = 10, durability: int = None, kv_endpoints: int = 1, enable_mutation_token: str = None, retry_strategy: str = 'default', retry_lower: int = 1, retry_upper: int = 500, retry_factor: int = 2, ycsb_jvm_args: str = None, collections_map: dict = None, out_of_order: int = 0, phase_params: dict = None, insert_test_params: dict = None, cloud: bool = None): cmd = 'bin/ycsb {action} {ycsb_client} ' \ '-P {workload} ' \ '-p writeallfields=true ' \ '-threads {workers} ' \ '-p target={target} ' \ '-p fieldlength={fieldlength} ' \ '-p fieldcount={fieldcount} ' \ '-p requestdistribution={requestdistribution} ' \ '-p couchbase.host={host} ' \ '-p couchbase.bucket={bucket} ' \ '-p couchbase.upsert=true ' \ '-p couchbase.epoll={epoll} ' \ '-p couchbase.boost={boost} ' \ '-p couchbase.kvEndpoints={kv_endpoints} ' \ '-p couchbase.sslMode={ssl_mode} ' \ '-p couchbase.certKeystoreFile=../{ssl_keystore_file} ' \ '-p couchbase.certKeystorePassword={ssl_keystore_password} ' \ '-p couchbase.certificateFile=../{certificate_file} ' \ '-p couchbase.password={password} ' \ '-p exportfile=ycsb_{action}_{instance}.log ' \ '-p couchbase.retryStrategy={retry_strategy} ' \ '-p couchbase.retryLower={retry_lower} ' \ '-p couchbase.retryUpper={retry_upper} ' \ '-p couchbase.retryFactor={retry_factor} ' cmd = 'pyenv local system && ' + cmd if durability is None: cmd += '-p couchbase.persistTo={persist_to} ' cmd += '-p couchbase.replicateTo={replicate_to} ' else: cmd += '-p couchbase.durability={durability} ' if enable_mutation_token is not None: cmd += '-p couchbase.enableMutationToken={enable_mutation_token} ' if ops is not None: cmd += ' -p operationcount={ops} ' if execution_time is not None: cmd += ' -p maxexecutiontime={execution_time} ' if timeseries or cbcollect: cmd += '-p measurementtype=timeseries ' if transactionsenabled: cmd += ' -p couchbase.transactionsEnabled=true ' cmd += ' -p couchbase.atrs={num_atrs} ' cmd += ' -p documentsintransaction={documentsintransaction} ' cmd += ' -p transactionreadproportion={transactionreadproportion} ' cmd += ' -p transactionupdateproportion={transactionupdateproportion} ' cmd += ' -p transactioninsertproportion={transactioninsertproportion} ' if ycsb_jvm_args is not None: cmd += ' -jvm-args=\'{ycsb_jvm_args}\' ' cmd = cmd.format(host=host, bucket=bucket, action=action, ycsb_client=ycsb_client, workload=workload, items=items, ops=ops, workers=workers, target=target, execution_time=execution_time, epoll=epoll, documentsintransaction=documentsintransaction, transactionreadproportion=transactionreadproportion, transactionupdateproportion=transactionupdateproportion, transactioninsertproportion=transactioninsertproportion, requestdistribution=requestdistribution, boost=boost, persist_to=persist_to, replicate_to=replicate_to, num_atrs=num_atrs, instance=instance, ssl_mode=ssl_mode, password=password, ssl_keystore_file=ssl_keystore_file, ssl_keystore_password=ssl_keystore_password, certificate_file=certificate_file, fieldlength=fieldlength, fieldcount=fieldcount, durability=durability, kv_endpoints=kv_endpoints, enable_mutation_token=enable_mutation_token, retry_strategy=retry_strategy, retry_lower=retry_lower, retry_upper=retry_upper, retry_factor=retry_factor, ycsb_jvm_args=ycsb_jvm_args) if soe_params is None: if phase_params: cmd += ' -p totalrecordcount={totalrecordcount} '.format(totalrecordcount=items) cmd += ' -p recordcount={items} '.format( items=phase_params['inserts_per_workerinstance']) cmd += ' -p insertstart={insertstart} '.format(insertstart=phase_params['insertstart']) elif insert_test_params: cmd += ' -p recordcount={items} '.format(items=insert_test_params['recordcount']) cmd += ' -p insertstart={insertstart} '.format( insertstart=insert_test_params['insertstart']) else: cmd += ' -p recordcount={items} '.format(items=items) else: cmd += ' -p totalrecordcount={totalrecordcount} '.format(totalrecordcount=items) cmd += ' -p recordcount={items} '.format(items=soe_params['recorded_load_cache_size']) cmd += ' -p insertstart={insertstart} '.format(insertstart=soe_params['insertstart']) if out_of_order: cmd += ' -p couchbase.outOfOrderExecution=true ' if collections_map: target_scope_collections = collections_map[bucket] target_scopes = set() target_collections = set() for scope in target_scope_collections.keys(): for collection in target_scope_collections[scope].keys(): if target_scope_collections[scope][collection]['load'] == 1 \ and target_scope_collections[scope][collection]['access'] == 1: target_scopes.add(scope) target_collections.add(collection) records_per_collection = items // len(target_collections) cmd += ' -p recordspercollection={recordspercollection} '\ .format(recordspercollection=records_per_collection) cmd += ' -p collectioncount={num_of_collections} '\ .format(num_of_collections=len(target_collections)) cmd += ' -p scopecount={num_of_scopes} '\ .format(num_of_scopes=len(target_scopes)) collection_string = '' for coll in list(target_collections): collection_string += coll + "," collections_param = collection_string[:-1] cmd += ' -p collectionsparam={collectionsparam} '.format(collectionsparam=collections_param) scope_string = '' for scope in list(target_scopes): scope_string += scope + "," scopes_param = scope_string[:-1] cmd += ' -p scopesparam={scopesparam} '.format(scopesparam=scopes_param) cmd += ' 2>ycsb_{action}_{instance}_stderr.log '.format(action=action, instance=instance) logger.info('Running: {}'.format(cmd)) with lcd('YCSB'): local(cmd) def run_tpcds_loader(host: str, bucket: str, password: str, partitions: int, instance: int, scale_factor: int): cmd = "java -jar tpcds.jar" \ " partitions={partitions}" \ " partition={partition}" \ " scalefactor={scalefactor}" \ " hostname={host}" \ " bucketname={bucket}" \ " username={user}" \ " password={password}" cmd = cmd.format( partitions=partitions, partition=instance+1, scalefactor=scale_factor, host=host, bucket=bucket, user="Administrator", password=password) with lcd("cbas-perf-support"), lcd("tpcds-couchbase-loader"), lcd("target"): local(cmd) def run_custom_cmd(path: str, binary: str, params: str): logger.info("Executing command {} {}".format(binary, params)) cmd = "{} {}".format(binary, params) with lcd(path): local(cmd) def get_jts_logs(jts_home: str, local_dir: str): logger.info("Collecting remote JTS logs") source_dir = "{}/logs".format(jts_home) for file in glob("{}".format(source_dir)): local("cp -r {} {}/".format(file, local_dir)) def restart_memcached(mem_limit: int = 10000, port: int = 8000): cmd1 = 'killall -9 memcached' logger.info('Running: {}'.format(cmd1)) with settings(warn_only=True): local(cmd1, capture=True) for counter in range(5): time.sleep(2) with settings(warn_only=True): result = local('pgrep memcached', capture=True) if result.return_code == 1: break else: logger.info('memcached still running') else: raise Exception('memcached was not killed properly') cmd2 = 'memcached -u root -m {mem_limit} -l localhost -p {port} -d' cmd2 = cmd2.format(mem_limit=mem_limit, port=port) logger.info('Running: {}'.format(cmd2)) local(cmd2, capture=True) for counter in range(5): try: time.sleep(2) mc = MemcachedClient(host='localhost', port=port) mc.stats() mc.close() break except (EOFError, socket.error, MemcachedError): logger.info('Can not connect to memcached') else: raise Exception('memcached did not start properly') logger.info('memcached restarted') def run_cbindexperf(path_to_tool: str, node: str, rest_username: str, rest_password: str, configfile: str, run_in_background: bool = False, collect_profile: bool = True): logger.info('Initiating scan workload') cmdstr = "{} -cluster {}:8091 -auth=\"{}:{}\" -configfile {} -resultfile result.json " \ "-statsfile /root/statsfile" \ .format(path_to_tool, node, rest_username, rest_password, configfile) if collect_profile: cmdstr += " -cpuprofile cpuprofile.prof -memprofile memprofile.prof " if run_in_background: cmdstr += " &" logger.info('To be applied: {}'.format(cmdstr)) ret = local(cmdstr) return ret.return_code def kill_process(process: str): logger.info('Killing the following process: {}'.format(process)) with quiet(): local("killall -9 {}".format(process)) def start_celery_worker(queue: str): with shell_env(PYTHONOPTIMIZE='1', PYTHONWARNINGS='ignore', C_FORCE_ROOT='1'): local('WORKER_TYPE=local ' 'BROKER_URL=sqla+sqlite:///perfrunner.db ' 'nohup env/bin/celery worker ' '-A perfrunner.helpers.worker -l INFO -Q {} > worker.log &'.format(queue)) def clone_git_repo(repo: str, branch: str, commit: str = None): repo_name = repo.split("/")[-1].split(".")[0] logger.info('checking if repo {} exists...'.format(repo_name)) if os.path.exists("{}".format(repo_name)): logger.info('repo {} exists...removing...'.format(repo_name)) shutil.rmtree(repo_name, ignore_errors=True) logger.info('Cloning repository: {} branch: {}'.format(repo, branch)) local('git clone -q -b {} {}'.format(branch, repo)) if commit: with lcd(repo_name): local('git checkout {}'.format(commit)) def init_tpcds_couchbase_loader(repo: str, branch: str): clone_git_repo(repo, branch) with lcd("cbas-perf-support"), lcd("tpcds-couchbase-loader"): local('mvn install') def init_jts(repo: str, branch: str, jts_home: str): clone_git_repo(repo, branch) with lcd(jts_home): local('mvn install') def generate_bigfun_data(user_docs: int): logger.info('Generating socialGen documents for {} users'.format(user_docs)) with lcd('socialGen'): cmd = \ "./scripts/initb.sh data 1 0 {users} " \ "-f JSON -k STRING#%015d > socialGen.log".format( users=user_docs) local('mvn clean package') local(cmd) def run_loader(hostname: str, bucket: str, password: str, workers: int, table: str, path: str = 'socialGen/data/p1'): logger.info('Loading socialGen documents ("{}" table)'.format(table)) cmd = \ "./loader -hostname {hostname} -bucket {bucket} -password {password} " \ "-workers {workers} -table {table} -path {path} > loader.log".format( hostname=hostname, bucket=bucket, password=password, workers=workers, table=table, path=path) local(cmd) def load_bigfun_data(hostname: str, bucket: str, password: str, workers: int): for table in 'gbook_users', 'gbook_messages', 'chirp_messages': run_loader(hostname, bucket, password, workers, table) def get_indexer_heap_profile(indexer: str, user: str, password: str) -> str: cmd = 'go tool pprof --text http://{}:{}@{}:9102/debug/pprof/heap'.format(user, password, indexer) logger.info('Running: {}'.format(cmd)) for counter in range(10): time.sleep(2) with settings(warn_only=True): result = local(cmd, capture=True) if result.succeeded: break else: logger.info('Error: {}'.format(result.stderr)) else: raise Exception('Command failed: {}'.format(cmd)) return result def govendor_fetch(path: str, revision: str, package: str): logger.info('Fetching: {} with revision {} and package as {}'.format(path, revision, package)) local('govendor fetch {}/{}@{}'.format(path, package, revision)) def generate_ssl_keystore(root_certificate: str, keystore_file: str, storepass: str): logger.info('Generating SSL keystore') with quiet(): local("keytool -delete -keystore {} -alias couchbase -storepass storepass" .format(keystore_file)) local("keytool -importcert -file {} -storepass {} -trustcacerts " "-noprompt -keystore {} -alias couchbase" .format(root_certificate, storepass, keystore_file)) def build_java_dcp_client(): with lcd('java-dcp-client'): local('perf/build.sh') def run_java_dcp_client(connection_string: str, messages: int, config_file: str, instance: int = None, collections: list = None): cmd = 'perf/run.sh {} {} {} '.format(connection_string, messages, config_file) if collections: for collection in collections: cmd += collection+"," cmd = cmd[:-1] if instance: cmd += ' > java_dcp_{}.log'.format(str(instance)) else: cmd += ' > java_dcp.log' with lcd('java-dcp-client'): logger.info('Running: {}'.format(cmd)) local(cmd) def detect_ubuntu_release(): return local('lsb_release -sr', capture=True).strip() def get_cbstats(server: str, port: int, command: str, cluster_spec: ClusterSpec): cmd = "./opt/couchbase/bin/cbstats -a {}:{} -u {} -p {} {} -j" \ .format(server, port, cluster_spec.rest_credentials[0], cluster_spec.rest_credentials[1], command) with hide('warnings'), settings(warn_only=True): result = local(cmd, capture=True) if result.return_code == 0: return result else: return False def read_aws_credential(credential_path: str): logger.info("Reading AWS credential") cmd = 'cat {}/aws_credential'.format(credential_path) credential = local(cmd, capture=True) cmd = 'rm {}/aws_credential'.format(credential_path) local(cmd) return credential def cbepctl(master_node: str, cluster_spec: ClusterSpec, bucket: str, option: str, value: int): flags = ['{}:11209'.format(master_node), '-u {}'.format(cluster_spec.rest_credentials[0]), '-p {}'.format(cluster_spec.rest_credentials[1]), '-b {}'.format(bucket), 'set flush_param {} {}'.format(option, value)] cmd = './opt/couchbase/bin/cbepctl {}'.format( ' '.join(flags)) logger.info('Running: {}'.format(cmd)) local(cmd) def create_remote_link(analytics_link, data_node, analytics_node): logger.info('Create analytics remote ink') cmd = "curl -v -u Administrator:password " \ "-X POST http://{}:8095/analytics/link " \ "-d dataverse=Default " \ "-d name={} " \ "-d type=couchbase " \ "-d hostname={}:8091 " \ "-d username=Administrator " \ "-d password=password " \ "-d encryption=none ".format(analytics_node, analytics_link, data_node) local(cmd) def download_pytppc(repo: str, branch: str): cmd = 'git clone -q -b {} {}'.format(branch, repo) local(cmd) def pytpcc_create_collections(collection_config: str, master_node: str): cmd = 'cp py-tpcc/pytpcc/constants.py.collections py-tpcc/pytpcc/constants.py' logger.info("Copyied constants.py.collections {}".format(cmd)) local(cmd) cmd = './py-tpcc/pytpcc/util/{} {}'.format(collection_config, master_node) logger.info("Creating Collections : {}".format(cmd)) local(cmd) def pytpcc_create_indexes(master_node: str, run_sql_shell: str, cbrindex_sql: str, port: str, index_replica: int): cmd = './py-tpcc/pytpcc/util/{} {}:{} {} ' \ '< ./py-tpcc/pytpcc/util/{} '.format(run_sql_shell, master_node, port, index_replica, cbrindex_sql) logger.info("Creating pytpcc Indexes : {}".format(cmd)) local(cmd) def pytpcc_load_data(warehouse: int, client_threads: int, master_node: str, port: str, cluster_spec: ClusterSpec, multi_query_node: bool, driver: str, nodes: list): if multi_query_node: nodes_length = len(nodes) multi_query_url = master_node + ':' + port for node in range(1, nodes_length): multi_query_url = multi_query_url + ',' + nodes[node] + ':' + port cmd = './tpcc.py --warehouses {}' \ ' --clients {} {} --no-execute --query-url {}:{}' \ ' --multi-query-url {}' \ ' --userid {} --password {}'.format(warehouse, client_threads, driver, master_node, port, multi_query_url, cluster_spec.rest_credentials[0], cluster_spec.rest_credentials[1]) else: cmd = './tpcc.py --warehouses {}' \ ' --clients {} {} --no-execute --query-url {}:{}' \ ' --userid {} --password {}'.format(warehouse, client_threads, driver, master_node, port, cluster_spec.rest_credentials[0], cluster_spec.rest_credentials[1]) logger.info("Loading Docs : {}".format(cmd)) with lcd('py-tpcc/pytpcc/'): for line in local(cmd, capture=True).split('\n'): print(line) def pytpcc_run_task(warehouse: int, duration: int, client_threads: int, driver: str, master_node: str, multi_query_node: bool, cluster_spec: ClusterSpec, port: str, nodes: list, durability_level: str, scan_consistency: str, txtimeout: str): if multi_query_node: nodes_length = len(nodes) multi_query_url = master_node + ':' + port for node in range(1, nodes_length): multi_query_url = multi_query_url + ',' + nodes[node] + ':' + port cmd = './tpcc.py --warehouses {} --duration {} ' \ '--clients {} {} --query-url {}:{} ' \ '--multi-query-url {} --userid {} --no-load --durability_level {} ' \ '--password {} --scan_consistency {}' \ ' --txtimeout {} > pytpcc_run_result.log'.format(warehouse, duration, client_threads, driver, master_node, port, multi_query_url, cluster_spec.rest_credentials[0], durability_level, cluster_spec.rest_credentials[1], scan_consistency, txtimeout) else: cmd = './tpcc.py --warehouses {} --duration {} ' \ '--clients {} {} --query-url {}:{} ' \ '--no-load --userid {} --password {} --durability_level {} ' \ '--scan_consistency {} ' \ '--txtimeout {} > pytpcc_run_result.log'.format(warehouse, duration, client_threads, driver, master_node, port, cluster_spec.rest_credentials[0], cluster_spec.rest_credentials[1], durability_level, scan_consistency, txtimeout) logger.info("Running : {}".format(cmd)) with lcd('py-tpcc/pytpcc/'): for line in local(cmd, capture=True).split('\n'): print(line) def copy_pytpcc_run_output(): cmd = 'cp py-tpcc/pytpcc/pytpcc_run_result.log .' local(cmd)
38.4287
100
0.546795
import os import shutil import socket import time import urllib.parse from datetime import date from glob import glob from sys import platform from typing import List from fabric.api import hide, lcd, local, quiet, settings, shell_env from mc_bin_client.mc_bin_client import MemcachedClient, MemcachedError from logger import logger from perfrunner.settings import ClusterSpec def extract_cb(filename: str): cmd = 'rpm2cpio ./{} | cpio -idm'.format(filename) with quiet(): local(cmd) def extract_cb_deb(filename: str): cmd = 'ar p {} data.tar.xz | unxz | tar x'.format(filename) with quiet(): local(cmd) def extract_cb_any(filename: str): if os.path.exists("{}.deb".format(filename)): extract_cb_deb("{}.deb".format(filename)) else: extract_cb("{}.rpm".format(filename)) def cleanup(backup_dir: str): logger.info("Cleaning the disk before backup/export") local('rm -fr {}/*'.format(backup_dir)) if not os.path.exists(backup_dir): os.makedirs(backup_dir) if platform == "linux2": local('fstrim -v {0} && fstrim -v {0}'.format(backup_dir)) def drop_caches(): logger.info('Dropping memory cache') local('sync && echo 3 > /proc/sys/vm/drop_caches') def backup(master_node: str, cluster_spec: ClusterSpec, threads: int, wrapper: bool = False, mode: str = None, compression: bool = False, storage_type: str = None, sink_type: str = None, shards: int = None, include_data: str = None): logger.info('Creating a new backup: {}'.format(cluster_spec.backup)) if not mode: cleanup(cluster_spec.backup) if wrapper: cbbackupwrapper(master_node, cluster_spec, 16, mode) else: cbbackupmgr_backup(master_node, cluster_spec, threads, mode, compression, storage_type, sink_type, shards, include_data) def compact(cluster_spec: ClusterSpec, snapshots: List[str], threads, wrapper: bool = False): if wrapper: return cbbackupmgr_compact(cluster_spec, snapshots, threads) def cbbackupwrapper(master_node: str, cluster_spec: ClusterSpec, threads: int, mode: str): postfix = '' if mode: postfix = '-m {}'.format(mode) cmd = './cbbackupwrapper http://{}:8091 {} -u {} -p {} -P {} {}'.format( master_node, cluster_spec.backup, cluster_spec.rest_credentials[0], cluster_spec.rest_credentials[1], threads, postfix, ) logger.info('Running: {}'.format(cmd)) with lcd('./opt/couchbase/bin'): local(cmd) def cbbackupmgr_backup(master_node: str, cluster_spec: ClusterSpec, threads: int, mode: str, compression: bool, storage_type: str, sink_type: str, shards: int, include_data: str): if not mode: if include_data: logger.info('running ./opt/couchbase/bin/cbbackupmgr config ' '--archive {} --repo default --include-data {}'.format(cluster_spec.backup, include_data)) local('./opt/couchbase/bin/cbbackupmgr config ' '--archive {} --repo default --include-data {}'.format(cluster_spec.backup, include_data)) else: logger.info('running ./opt/couchbase/bin/cbbackupmgr config ' '--archive {} --repo default'.format(cluster_spec.backup)) local('./opt/couchbase/bin/cbbackupmgr config ' '--archive {} --repo default'.format(cluster_spec.backup)) flags = ['--archive {}'.format(cluster_spec.backup), '--repo default', '--host http://{}'.format(master_node), '--username {}'.format(cluster_spec.rest_credentials[0]), '--password {}'.format(cluster_spec.rest_credentials[1]), '--threads {}'.format(threads) if threads else None, '--storage {}'.format(storage_type) if storage_type else None, '--sink {}'.format(sink_type) if sink_type else None, '--value-compression compressed' if compression else None, '--shards {}'.format(shards) if shards else None] cmd = './opt/couchbase/bin/cbbackupmgr backup {}'.format( ' '.join(filter(None, flags))) logger.info('Running: {}'.format(cmd)) local(cmd) def cbbackupmgr_collectinfo(cluster_spec: ClusterSpec, archive: str = ''): logger.info('Running cbbackumgr cbcollect_info on local/host ') cmd = ('./opt/couchbase/bin/cbbackupmgr collect-logs --archive {} ' '--output-dir {}'.format(archive or cluster_spec.backup, '.')) logger.info('Running: {}'.format(cmd)) local(cmd) def get_backup_snapshots(cluster_spec: ClusterSpec) -> List[str]: logger.info('running cbbackupmgr list/info command ') cmd_type = 'list' cmd = \ './opt/couchbase/bin/cbbackupmgr list ' \ '--archive {} --repo default '.format(cluster_spec.backup) for line in local(cmd, capture=True).split('\n'): if 'list is deprecated' in line: cmd_type = 'info' cmd = \ './opt/couchbase/bin/cbbackupmgr {} ' \ '--archive {} --repo default '.format(cmd_type, cluster_spec.backup, ) snapshots = [] if cmd_type == 'info': pattern = '+ {}-'.format(date.today().year) for line in local(cmd, capture=True).split('\n'): if pattern in line: snapshot = line.strip().split()[1] snapshots.append(snapshot) return snapshots elif cmd_type == 'list': pattern = '+ {}-'.format(date.today().year) for line in local(cmd, capture=True).split('\n'): if pattern in line: snapshot = line.strip().split()[-1] snapshots.append(snapshot) return snapshots def cbbackupmgr_merge(cluster_spec: ClusterSpec, snapshots: List[str], storage_type: str, threads: int): flags = ['--archive {}'.format(cluster_spec.backup), '--repo default', '--start {}'.format(snapshots[0]), '--end {}'.format(snapshots[1]), '--storage {}'.format(storage_type) if storage_type else None, '--threads {}'.format(threads) if threads else None] cmd = './opt/couchbase/bin/cbbackupmgr merge {}'.format( ' '.join(filter(None, flags))) logger.info('Running: {}'.format(cmd)) local(cmd) def calc_backup_size(cluster_spec: ClusterSpec, rounded: bool = True) -> float: backup_size = local('du -sb0 {}'.format(cluster_spec.backup), capture=True) backup_size = backup_size.split()[0] backup_size = float(backup_size) / 2 ** 30 # B -> GB return round(backup_size) if rounded else backup_size def restore(master_node: str, cluster_spec: ClusterSpec, threads: int, wrapper: bool = False, include_data: str = None): logger.info('Restore from {}'.format(cluster_spec.backup)) if wrapper: cbrestorewrapper(master_node, cluster_spec) else: cbbackupmgr_restore(master_node, cluster_spec, threads, include_data) def cbrestorewrapper(master_node: str, cluster_spec: ClusterSpec): cmd = './cbrestorewrapper {} http://{}:8091 -u {} -p {}'.format( cluster_spec.backup, master_node, cluster_spec.rest_credentials[0], cluster_spec.rest_credentials[1], ) logger.info('Running: {}'.format(cmd)) with lcd('./opt/couchbase/bin'): local(cmd) def cbbackupmgr_restore(master_node: str, cluster_spec: ClusterSpec, threads: int, include_data: str, archive: str = '', repo: str = 'default', map_data: str = None): flags = ['--archive {}'.format(archive or cluster_spec.backup), '--repo {}'.format(repo), '--include-data {}'.format(include_data) if include_data else None, '--threads {}'.format(threads), '--host http://{}'.format(master_node), '--username {}'.format(cluster_spec.rest_credentials[0]), '--password {}'.format(cluster_spec.rest_credentials[1]), '--map-data {}'.format(map_data) if map_data else None] cmd = './opt/couchbase/bin/cbbackupmgr restore --force-updates {}'.format( ' '.join(filter(None, flags))) logger.info('Running: {}'.format(cmd)) local(cmd) def cbbackupmgr_compact(cluster_spec: ClusterSpec, snapshots: List[str], threads: int): flags = ['--archive {}'.format(cluster_spec.backup), '--repo default', '--backup {}'.format(snapshots[0]), '--threads {}'.format(threads) if threads else None] cmd = './opt/couchbase/bin/cbbackupmgr compact {}'.format( ' '.join(filter(None, flags))) logger.info('Running: {}'.format(cmd)) local(cmd) def cbbackupmgr_list(cluster_spec: ClusterSpec, snapshots: List[str], bucket: str = None): flags = ['--archive {}'.format(cluster_spec.backup), '--repo default', '--backup {}'.format(snapshots[0]), '--bucket {}'.format(bucket) if bucket else None] cmd = './opt/couchbase/bin/cbbackupmgr list {}'.format( ' '.join(filter(None, flags))) logger.info('Running: {}'.format(cmd)) local(cmd) def cbexport(master_node: str, cluster_spec: ClusterSpec, bucket: str, data_format: str, threads: int, collection_field: str, scope_field: str, key_field: str = None, log_file: str = None): export_path = os.path.join(cluster_spec.backup, 'data.json') cleanup(cluster_spec.backup) if collection_field and scope_field: flags = ['--format {}'.format(data_format), '--output {}'.format(export_path), '--cluster http://{}'.format(master_node), '--bucket {}'.format(bucket), '--username {}'.format(cluster_spec.rest_credentials[0]), '--password {}'.format(cluster_spec.rest_credentials[1]), '--collection-field {}'.format(collection_field), '--scope-field {}'.format(scope_field), '--threads {}'.format(threads) if threads else None, '--include-key key', '--log-file {}'.format(log_file) if log_file else None] else: flags = ['--format {}'.format(data_format), '--output {}'.format(export_path), '--cluster http://{}'.format(master_node), '--bucket {}'.format(bucket), '--username {}'.format(cluster_spec.rest_credentials[0]), '--password {}'.format(cluster_spec.rest_credentials[1]), '--threads {}'.format(threads) if threads else None, '--include-key {}'.format(key_field) if key_field else None, '--log-file {}'.format(log_file) if log_file else None] cmd = './opt/couchbase/bin/cbexport json {}'.format( ' '.join(filter(None, flags))) logger.info('Running: {}'.format(cmd)) local(cmd) def cbimport(master_node: str, cluster_spec: ClusterSpec, bucket: str, data_type: str, data_format: str, import_file: str, threads: int, scope_collection_exp: str, field_separator: str = None, limit_rows: int = None, skip_rows: int = None, infer_types: int = None, omit_empty: int = None, errors_log: str = None, log_file: str = None): if not scope_collection_exp: flags = ['--format {}'.format(data_format) if data_type == 'json' else None, '--dataset {}'.format(import_file), '--cluster http://{}'.format(master_node), '--bucket {}'.format(bucket), '--username {}'.format(cluster_spec.rest_credentials[0]), '--password {}'.format(cluster_spec.rest_credentials[1]), '--generate-key "#MONO_INCR#"', '--threads {}'.format(threads) if threads else None, '--field-separator {}'.format(field_separator) if field_separator else None, '--limit-rows {}'.format(limit_rows) if limit_rows else None, '--skip-rows {}'.format(skip_rows) if skip_rows else None, '--infer-types' if infer_types else None, '--omit-empty' if omit_empty else None, '--errors-log {}'.format(errors_log) if errors_log else None, '--log-file {}'.format(log_file) if log_file else None] else: flags = ['--format {}'.format(data_format) if data_type == 'json' else None, '--dataset {}'.format(import_file), '--cluster http://{}'.format(master_node), '--bucket {}'.format(bucket), '--username {}'.format(cluster_spec.rest_credentials[0]), '--password {}'.format(cluster_spec.rest_credentials[1]), '--generate-key "#MONO_INCR#"', '--threads {}'.format(threads) if threads else None, '--field-separator {}'.format(field_separator) if field_separator else None, '--limit-rows {}'.format(limit_rows) if limit_rows else None, '--skip-rows {}'.format(skip_rows) if skip_rows else None, '--infer-types' if infer_types else None, '--omit-empty' if omit_empty else None, '--errors-log {}'.format(errors_log) if errors_log else None, '--log-file {}'.format(log_file) if log_file else None, '--scope-collection-exp {}'.format(scope_collection_exp)] cmd = './opt/couchbase/bin/cbimport {} {}'.format( data_type, ' '.join(filter(None, flags))) logger.info('Running: {}'.format(cmd)) local(cmd) def run_cbc_pillowfight(host: str, bucket: str, password: str, num_items: int, num_threads: int, num_cycles: int, size: int, batch_size: int, writes: int, persist_to: int, replicate_to: int, connstr_params: dict, durability: int, doc_gen: str = 'binary', ssl_mode: str = 'none', populate: bool = False, collections: dict = None, custom_pillowfight: bool = False): cmd = 'cbc-pillowfight ' \ '--password {password} ' \ '--batch-size {batch_size} ' \ '--num-items {num_items} ' \ '--num-threads {num_threads} ' \ '--min-size {size} ' \ '--max-size {size} ' \ '--persist-to {persist_to} ' \ '--replicate-to {replicate_to} ' if custom_pillowfight: cmd = '/tmp/libcouchbase_custom/libcouchbase/build/bin/'+cmd if collections: target_scope_collections = collections[bucket] for scope in target_scope_collections.keys(): for collection in target_scope_collections[scope].keys(): if populate: if target_scope_collections[scope][collection]['load'] == 1: cmd += "--collection " + scope+"."+collection + " " else: if target_scope_collections[scope][collection]['access'] == 1: cmd += "--collection " + scope+"."+collection + " " if doc_gen == 'json': cmd += '--json ' elif doc_gen == 'json_snappy': cmd += '--json --compress --compress ' if ssl_mode == 'data': cmd += '--spec "couchbases://{host}/{bucket}?{params}" --certpath root.pem ' else: cmd += '--spec "couchbase://{host}/{bucket}?{params}" ' if populate: cmd += '--populate-only ' else: cmd += \ '--set-pct {writes} ' \ '--num-cycles {num_cycles} ' \ '--no-population ' durability_options = { 0: 'none', 1: 'majority', 2: 'majority_and_persist_to_active', 3: 'persist_to_majority'} if durability: cmd += '--durability {durability} ' cmd += ' > /dev/null 2>&1' params = urllib.parse.urlencode(connstr_params) cmd = cmd.format(host=host, bucket=bucket, password=password, params=params, num_items=num_items, num_threads=num_threads, num_cycles=num_cycles, size=size, batch_size=batch_size, persist_to=persist_to, replicate_to=replicate_to, writes=writes, durability=durability_options[durability] if durability else None) logger.info('Running: {}'.format(cmd)) local(cmd, shell='/bin/bash') def run_dcptest(host: str, username: str, password: str, bucket: str, num_items: int, num_connections: int): cmd = './dcptest ' \ '-kvaddrs {host}:11210 ' \ '-buckets {bucket} ' \ '-nummessages {num_items} ' \ '-numconnections {num_connections} ' \ '-outputfile dcpstatsfile ' \ '{host}:8091 > dcptest.log 2>&1' cmd = cmd.format(host=host, bucket=bucket, num_items=num_items, num_connections=num_connections) cbauth = 'http://{user}:{password}@{host}:8091'.format(host=host, user=username, password=password) logger.info('Running: {}'.format(cmd)) with shell_env(CBAUTH_REVRPC_URL=cbauth): local(cmd) def run_kvgen(hostname: str, num_docs: int, prefix: str): cmd = './kvgen -hostname {} -docs {} -prefix {}'.format(hostname, num_docs, prefix) logger.info('Running: {}'.format(cmd)) with shell_env(GOGC='300'): local(cmd) def run_ycsb(host: str, bucket: str, password: str, action: str, ycsb_client: str, workload: str, items: int, workers: int, target: int, epoll: str, boost: int, persist_to: int, replicate_to: int, num_atrs: int, documentsintransaction: int, transactionreadproportion: str, transactionupdateproportion: str, transactioninsertproportion: str, requestdistribution: str, ssl_keystore_file: str = '', ssl_keystore_password: str = '', ssl_mode: str = 'none', certificate_file: str = '', soe_params: dict = None, ops: int = None, execution_time: int = None, cbcollect: int = 0, timeseries: int = 0, transactionsenabled: int = 0, instance: int = 0, fieldlength: int = 1024, fieldcount: int = 10, durability: int = None, kv_endpoints: int = 1, enable_mutation_token: str = None, retry_strategy: str = 'default', retry_lower: int = 1, retry_upper: int = 500, retry_factor: int = 2, ycsb_jvm_args: str = None, collections_map: dict = None, out_of_order: int = 0, phase_params: dict = None, insert_test_params: dict = None, cloud: bool = None): cmd = 'bin/ycsb {action} {ycsb_client} ' \ '-P {workload} ' \ '-p writeallfields=true ' \ '-threads {workers} ' \ '-p target={target} ' \ '-p fieldlength={fieldlength} ' \ '-p fieldcount={fieldcount} ' \ '-p requestdistribution={requestdistribution} ' \ '-p couchbase.host={host} ' \ '-p couchbase.bucket={bucket} ' \ '-p couchbase.upsert=true ' \ '-p couchbase.epoll={epoll} ' \ '-p couchbase.boost={boost} ' \ '-p couchbase.kvEndpoints={kv_endpoints} ' \ '-p couchbase.sslMode={ssl_mode} ' \ '-p couchbase.certKeystoreFile=../{ssl_keystore_file} ' \ '-p couchbase.certKeystorePassword={ssl_keystore_password} ' \ '-p couchbase.certificateFile=../{certificate_file} ' \ '-p couchbase.password={password} ' \ '-p exportfile=ycsb_{action}_{instance}.log ' \ '-p couchbase.retryStrategy={retry_strategy} ' \ '-p couchbase.retryLower={retry_lower} ' \ '-p couchbase.retryUpper={retry_upper} ' \ '-p couchbase.retryFactor={retry_factor} ' cmd = 'pyenv local system && ' + cmd if durability is None: cmd += '-p couchbase.persistTo={persist_to} ' cmd += '-p couchbase.replicateTo={replicate_to} ' else: cmd += '-p couchbase.durability={durability} ' if enable_mutation_token is not None: cmd += '-p couchbase.enableMutationToken={enable_mutation_token} ' if ops is not None: cmd += ' -p operationcount={ops} ' if execution_time is not None: cmd += ' -p maxexecutiontime={execution_time} ' if timeseries or cbcollect: cmd += '-p measurementtype=timeseries ' if transactionsenabled: cmd += ' -p couchbase.transactionsEnabled=true ' cmd += ' -p couchbase.atrs={num_atrs} ' cmd += ' -p documentsintransaction={documentsintransaction} ' cmd += ' -p transactionreadproportion={transactionreadproportion} ' cmd += ' -p transactionupdateproportion={transactionupdateproportion} ' cmd += ' -p transactioninsertproportion={transactioninsertproportion} ' if ycsb_jvm_args is not None: cmd += ' -jvm-args=\'{ycsb_jvm_args}\' ' cmd = cmd.format(host=host, bucket=bucket, action=action, ycsb_client=ycsb_client, workload=workload, items=items, ops=ops, workers=workers, target=target, execution_time=execution_time, epoll=epoll, documentsintransaction=documentsintransaction, transactionreadproportion=transactionreadproportion, transactionupdateproportion=transactionupdateproportion, transactioninsertproportion=transactioninsertproportion, requestdistribution=requestdistribution, boost=boost, persist_to=persist_to, replicate_to=replicate_to, num_atrs=num_atrs, instance=instance, ssl_mode=ssl_mode, password=password, ssl_keystore_file=ssl_keystore_file, ssl_keystore_password=ssl_keystore_password, certificate_file=certificate_file, fieldlength=fieldlength, fieldcount=fieldcount, durability=durability, kv_endpoints=kv_endpoints, enable_mutation_token=enable_mutation_token, retry_strategy=retry_strategy, retry_lower=retry_lower, retry_upper=retry_upper, retry_factor=retry_factor, ycsb_jvm_args=ycsb_jvm_args) if soe_params is None: if phase_params: cmd += ' -p totalrecordcount={totalrecordcount} '.format(totalrecordcount=items) cmd += ' -p recordcount={items} '.format( items=phase_params['inserts_per_workerinstance']) cmd += ' -p insertstart={insertstart} '.format(insertstart=phase_params['insertstart']) elif insert_test_params: cmd += ' -p recordcount={items} '.format(items=insert_test_params['recordcount']) cmd += ' -p insertstart={insertstart} '.format( insertstart=insert_test_params['insertstart']) else: cmd += ' -p recordcount={items} '.format(items=items) else: cmd += ' -p totalrecordcount={totalrecordcount} '.format(totalrecordcount=items) cmd += ' -p recordcount={items} '.format(items=soe_params['recorded_load_cache_size']) cmd += ' -p insertstart={insertstart} '.format(insertstart=soe_params['insertstart']) if out_of_order: cmd += ' -p couchbase.outOfOrderExecution=true ' if collections_map: target_scope_collections = collections_map[bucket] target_scopes = set() target_collections = set() for scope in target_scope_collections.keys(): for collection in target_scope_collections[scope].keys(): if target_scope_collections[scope][collection]['load'] == 1 \ and target_scope_collections[scope][collection]['access'] == 1: target_scopes.add(scope) target_collections.add(collection) records_per_collection = items // len(target_collections) cmd += ' -p recordspercollection={recordspercollection} '\ .format(recordspercollection=records_per_collection) cmd += ' -p collectioncount={num_of_collections} '\ .format(num_of_collections=len(target_collections)) cmd += ' -p scopecount={num_of_scopes} '\ .format(num_of_scopes=len(target_scopes)) collection_string = '' for coll in list(target_collections): collection_string += coll + "," collections_param = collection_string[:-1] cmd += ' -p collectionsparam={collectionsparam} '.format(collectionsparam=collections_param) scope_string = '' for scope in list(target_scopes): scope_string += scope + "," scopes_param = scope_string[:-1] cmd += ' -p scopesparam={scopesparam} '.format(scopesparam=scopes_param) cmd += ' 2>ycsb_{action}_{instance}_stderr.log '.format(action=action, instance=instance) logger.info('Running: {}'.format(cmd)) with lcd('YCSB'): local(cmd) def run_tpcds_loader(host: str, bucket: str, password: str, partitions: int, instance: int, scale_factor: int): cmd = "java -jar tpcds.jar" \ " partitions={partitions}" \ " partition={partition}" \ " scalefactor={scalefactor}" \ " hostname={host}" \ " bucketname={bucket}" \ " username={user}" \ " password={password}" cmd = cmd.format( partitions=partitions, partition=instance+1, scalefactor=scale_factor, host=host, bucket=bucket, user="Administrator", password=password) with lcd("cbas-perf-support"), lcd("tpcds-couchbase-loader"), lcd("target"): local(cmd) def run_custom_cmd(path: str, binary: str, params: str): logger.info("Executing command {} {}".format(binary, params)) cmd = "{} {}".format(binary, params) with lcd(path): local(cmd) def get_jts_logs(jts_home: str, local_dir: str): logger.info("Collecting remote JTS logs") source_dir = "{}/logs".format(jts_home) for file in glob("{}".format(source_dir)): local("cp -r {} {}/".format(file, local_dir)) def restart_memcached(mem_limit: int = 10000, port: int = 8000): cmd1 = 'killall -9 memcached' logger.info('Running: {}'.format(cmd1)) with settings(warn_only=True): local(cmd1, capture=True) for counter in range(5): time.sleep(2) with settings(warn_only=True): result = local('pgrep memcached', capture=True) if result.return_code == 1: break else: logger.info('memcached still running') else: raise Exception('memcached was not killed properly') cmd2 = 'memcached -u root -m {mem_limit} -l localhost -p {port} -d' cmd2 = cmd2.format(mem_limit=mem_limit, port=port) logger.info('Running: {}'.format(cmd2)) local(cmd2, capture=True) for counter in range(5): try: time.sleep(2) mc = MemcachedClient(host='localhost', port=port) mc.stats() mc.close() break except (EOFError, socket.error, MemcachedError): logger.info('Can not connect to memcached') else: raise Exception('memcached did not start properly') logger.info('memcached restarted') def run_cbindexperf(path_to_tool: str, node: str, rest_username: str, rest_password: str, configfile: str, run_in_background: bool = False, collect_profile: bool = True): logger.info('Initiating scan workload') cmdstr = "{} -cluster {}:8091 -auth=\"{}:{}\" -configfile {} -resultfile result.json " \ "-statsfile /root/statsfile" \ .format(path_to_tool, node, rest_username, rest_password, configfile) if collect_profile: cmdstr += " -cpuprofile cpuprofile.prof -memprofile memprofile.prof " if run_in_background: cmdstr += " &" logger.info('To be applied: {}'.format(cmdstr)) ret = local(cmdstr) return ret.return_code def kill_process(process: str): logger.info('Killing the following process: {}'.format(process)) with quiet(): local("killall -9 {}".format(process)) def start_celery_worker(queue: str): with shell_env(PYTHONOPTIMIZE='1', PYTHONWARNINGS='ignore', C_FORCE_ROOT='1'): local('WORKER_TYPE=local ' 'BROKER_URL=sqla+sqlite:///perfrunner.db ' 'nohup env/bin/celery worker ' '-A perfrunner.helpers.worker -l INFO -Q {} > worker.log &'.format(queue)) def clone_git_repo(repo: str, branch: str, commit: str = None): repo_name = repo.split("/")[-1].split(".")[0] logger.info('checking if repo {} exists...'.format(repo_name)) if os.path.exists("{}".format(repo_name)): logger.info('repo {} exists...removing...'.format(repo_name)) shutil.rmtree(repo_name, ignore_errors=True) logger.info('Cloning repository: {} branch: {}'.format(repo, branch)) local('git clone -q -b {} {}'.format(branch, repo)) if commit: with lcd(repo_name): local('git checkout {}'.format(commit)) def init_tpcds_couchbase_loader(repo: str, branch: str): clone_git_repo(repo, branch) with lcd("cbas-perf-support"), lcd("tpcds-couchbase-loader"): local('mvn install') def init_jts(repo: str, branch: str, jts_home: str): clone_git_repo(repo, branch) with lcd(jts_home): local('mvn install') def generate_bigfun_data(user_docs: int): logger.info('Generating socialGen documents for {} users'.format(user_docs)) with lcd('socialGen'): cmd = \ "./scripts/initb.sh data 1 0 {users} " \ "-f JSON -k STRING#%015d > socialGen.log".format( users=user_docs) local('mvn clean package') local(cmd) def run_loader(hostname: str, bucket: str, password: str, workers: int, table: str, path: str = 'socialGen/data/p1'): logger.info('Loading socialGen documents ("{}" table)'.format(table)) cmd = \ "./loader -hostname {hostname} -bucket {bucket} -password {password} " \ "-workers {workers} -table {table} -path {path} > loader.log".format( hostname=hostname, bucket=bucket, password=password, workers=workers, table=table, path=path) local(cmd) def load_bigfun_data(hostname: str, bucket: str, password: str, workers: int): for table in 'gbook_users', 'gbook_messages', 'chirp_messages': run_loader(hostname, bucket, password, workers, table) def get_indexer_heap_profile(indexer: str, user: str, password: str) -> str: cmd = 'go tool pprof --text http://{}:{}@{}:9102/debug/pprof/heap'.format(user, password, indexer) logger.info('Running: {}'.format(cmd)) for counter in range(10): time.sleep(2) with settings(warn_only=True): result = local(cmd, capture=True) if result.succeeded: break else: logger.info('Error: {}'.format(result.stderr)) else: raise Exception('Command failed: {}'.format(cmd)) return result def govendor_fetch(path: str, revision: str, package: str): logger.info('Fetching: {} with revision {} and package as {}'.format(path, revision, package)) local('govendor fetch {}/{}@{}'.format(path, package, revision)) def generate_ssl_keystore(root_certificate: str, keystore_file: str, storepass: str): logger.info('Generating SSL keystore') with quiet(): local("keytool -delete -keystore {} -alias couchbase -storepass storepass" .format(keystore_file)) local("keytool -importcert -file {} -storepass {} -trustcacerts " "-noprompt -keystore {} -alias couchbase" .format(root_certificate, storepass, keystore_file)) def build_java_dcp_client(): with lcd('java-dcp-client'): local('perf/build.sh') def run_java_dcp_client(connection_string: str, messages: int, config_file: str, instance: int = None, collections: list = None): cmd = 'perf/run.sh {} {} {} '.format(connection_string, messages, config_file) if collections: for collection in collections: cmd += collection+"," cmd = cmd[:-1] if instance: cmd += ' > java_dcp_{}.log'.format(str(instance)) else: cmd += ' > java_dcp.log' with lcd('java-dcp-client'): logger.info('Running: {}'.format(cmd)) local(cmd) def detect_ubuntu_release(): return local('lsb_release -sr', capture=True).strip() def get_cbstats(server: str, port: int, command: str, cluster_spec: ClusterSpec): cmd = "./opt/couchbase/bin/cbstats -a {}:{} -u {} -p {} {} -j" \ .format(server, port, cluster_spec.rest_credentials[0], cluster_spec.rest_credentials[1], command) with hide('warnings'), settings(warn_only=True): result = local(cmd, capture=True) if result.return_code == 0: return result else: return False def read_aws_credential(credential_path: str): logger.info("Reading AWS credential") cmd = 'cat {}/aws_credential'.format(credential_path) credential = local(cmd, capture=True) cmd = 'rm {}/aws_credential'.format(credential_path) local(cmd) return credential def cbepctl(master_node: str, cluster_spec: ClusterSpec, bucket: str, option: str, value: int): flags = ['{}:11209'.format(master_node), '-u {}'.format(cluster_spec.rest_credentials[0]), '-p {}'.format(cluster_spec.rest_credentials[1]), '-b {}'.format(bucket), 'set flush_param {} {}'.format(option, value)] cmd = './opt/couchbase/bin/cbepctl {}'.format( ' '.join(flags)) logger.info('Running: {}'.format(cmd)) local(cmd) def create_remote_link(analytics_link, data_node, analytics_node): logger.info('Create analytics remote ink') cmd = "curl -v -u Administrator:password " \ "-X POST http://{}:8095/analytics/link " \ "-d dataverse=Default " \ "-d name={} " \ "-d type=couchbase " \ "-d hostname={}:8091 " \ "-d username=Administrator " \ "-d password=password " \ "-d encryption=none ".format(analytics_node, analytics_link, data_node) local(cmd) def download_pytppc(repo: str, branch: str): cmd = 'git clone -q -b {} {}'.format(branch, repo) local(cmd) def pytpcc_create_collections(collection_config: str, master_node: str): cmd = 'cp py-tpcc/pytpcc/constants.py.collections py-tpcc/pytpcc/constants.py' logger.info("Copyied constants.py.collections {}".format(cmd)) local(cmd) cmd = './py-tpcc/pytpcc/util/{} {}'.format(collection_config, master_node) logger.info("Creating Collections : {}".format(cmd)) local(cmd) def pytpcc_create_indexes(master_node: str, run_sql_shell: str, cbrindex_sql: str, port: str, index_replica: int): cmd = './py-tpcc/pytpcc/util/{} {}:{} {} ' \ '< ./py-tpcc/pytpcc/util/{} '.format(run_sql_shell, master_node, port, index_replica, cbrindex_sql) logger.info("Creating pytpcc Indexes : {}".format(cmd)) local(cmd) def pytpcc_load_data(warehouse: int, client_threads: int, master_node: str, port: str, cluster_spec: ClusterSpec, multi_query_node: bool, driver: str, nodes: list): if multi_query_node: nodes_length = len(nodes) multi_query_url = master_node + ':' + port for node in range(1, nodes_length): multi_query_url = multi_query_url + ',' + nodes[node] + ':' + port cmd = './tpcc.py --warehouses {}' \ ' --clients {} {} --no-execute --query-url {}:{}' \ ' --multi-query-url {}' \ ' --userid {} --password {}'.format(warehouse, client_threads, driver, master_node, port, multi_query_url, cluster_spec.rest_credentials[0], cluster_spec.rest_credentials[1]) else: cmd = './tpcc.py --warehouses {}' \ ' --clients {} {} --no-execute --query-url {}:{}' \ ' --userid {} --password {}'.format(warehouse, client_threads, driver, master_node, port, cluster_spec.rest_credentials[0], cluster_spec.rest_credentials[1]) logger.info("Loading Docs : {}".format(cmd)) with lcd('py-tpcc/pytpcc/'): for line in local(cmd, capture=True).split('\n'): print(line) def pytpcc_run_task(warehouse: int, duration: int, client_threads: int, driver: str, master_node: str, multi_query_node: bool, cluster_spec: ClusterSpec, port: str, nodes: list, durability_level: str, scan_consistency: str, txtimeout: str): if multi_query_node: nodes_length = len(nodes) multi_query_url = master_node + ':' + port for node in range(1, nodes_length): multi_query_url = multi_query_url + ',' + nodes[node] + ':' + port cmd = './tpcc.py --warehouses {} --duration {} ' \ '--clients {} {} --query-url {}:{} ' \ '--multi-query-url {} --userid {} --no-load --durability_level {} ' \ '--password {} --scan_consistency {}' \ ' --txtimeout {} > pytpcc_run_result.log'.format(warehouse, duration, client_threads, driver, master_node, port, multi_query_url, cluster_spec.rest_credentials[0], durability_level, cluster_spec.rest_credentials[1], scan_consistency, txtimeout) else: cmd = './tpcc.py --warehouses {} --duration {} ' \ '--clients {} {} --query-url {}:{} ' \ '--no-load --userid {} --password {} --durability_level {} ' \ '--scan_consistency {} ' \ '--txtimeout {} > pytpcc_run_result.log'.format(warehouse, duration, client_threads, driver, master_node, port, cluster_spec.rest_credentials[0], cluster_spec.rest_credentials[1], durability_level, scan_consistency, txtimeout) logger.info("Running : {}".format(cmd)) with lcd('py-tpcc/pytpcc/'): for line in local(cmd, capture=True).split('\n'): print(line) def copy_pytpcc_run_output(): cmd = 'cp py-tpcc/pytpcc/pytpcc_run_result.log .' local(cmd)
true
true
f7f9f77555ad33ebf0ef7c8b3a992fb72fc28df0
1,746
py
Python
vise/tests/analyzer/vasp/test_make_diele_func.py
kumagai-group/vise
8adfe61ad8f31767ec562f02f271e2495f357cd4
[ "MIT" ]
16
2020-07-14T13:14:05.000Z
2022-03-04T13:39:30.000Z
vise/tests/analyzer/vasp/test_make_diele_func.py
kumagai-group/vise
8adfe61ad8f31767ec562f02f271e2495f357cd4
[ "MIT" ]
10
2021-03-15T20:47:45.000Z
2021-08-19T00:47:12.000Z
vise/tests/analyzer/vasp/test_make_diele_func.py
kumagai-group/vise
8adfe61ad8f31767ec562f02f271e2495f357cd4
[ "MIT" ]
6
2020-03-03T00:42:39.000Z
2022-02-22T02:34:47.000Z
# -*- coding: utf-8 -*- # Copyright (c) 2020. Distributed under the terms of the MIT License. from pymatgen.io.vasp import Vasprun, Outcar from vise.analyzer.dielectric_function import make_shifted_diele_func from vise.analyzer.vasp.band_edge_properties import VaspBandEdgeProperties from vise.analyzer.vasp.make_diele_func import make_diele_func def test_make_diele_func(test_data_files): v = Vasprun(test_data_files / "MgSe_absorption_vasprun_gamma.xml") o = Outcar(test_data_files / "MgSe_absorption_OUTCAR_gamma") actual = make_diele_func(v, o) # print(VaspBandEdgeProperties(v, o)) print(actual.diele_func_real) assert actual.energies[1] == 0.0407 def test_make_diele_func_calc_real(test_data_files): v = Vasprun(test_data_files / "MgSe_absorption_vasprun_gamma.xml") o = Outcar(test_data_files / "MgSe_absorption_OUTCAR_gamma") actual = make_diele_func(v, o, use_vasp_real=False) print(actual.diele_func_real) assert actual.energies[1] == 0.0407 def test_make_diele_func_2(test_data_files): v = Vasprun(test_data_files / "MgSe_absorption_vasprun_gamma.xml") o = Outcar(test_data_files / "MgSe_absorption_OUTCAR_gamma") actual = make_shifted_diele_func(make_diele_func(v, o), original_band_gap=1.997, shift=1.0) assert isinstance(actual.diele_func_imag[0], list) assert isinstance(actual.diele_func_imag[0][0], float) # print(type(actual.diele_func_imag[0])) # print(type(actual.diele_func_imag[0][0])) # print(actual.diele_func_real) # print(actual.diele_func_imag[1000]) # plotter = AbsorptionCoeffPlotlyPlotter(actual) # fig = plotter.create_figure() # fig.show()
41.571429
74
0.730813
from pymatgen.io.vasp import Vasprun, Outcar from vise.analyzer.dielectric_function import make_shifted_diele_func from vise.analyzer.vasp.band_edge_properties import VaspBandEdgeProperties from vise.analyzer.vasp.make_diele_func import make_diele_func def test_make_diele_func(test_data_files): v = Vasprun(test_data_files / "MgSe_absorption_vasprun_gamma.xml") o = Outcar(test_data_files / "MgSe_absorption_OUTCAR_gamma") actual = make_diele_func(v, o) print(actual.diele_func_real) assert actual.energies[1] == 0.0407 def test_make_diele_func_calc_real(test_data_files): v = Vasprun(test_data_files / "MgSe_absorption_vasprun_gamma.xml") o = Outcar(test_data_files / "MgSe_absorption_OUTCAR_gamma") actual = make_diele_func(v, o, use_vasp_real=False) print(actual.diele_func_real) assert actual.energies[1] == 0.0407 def test_make_diele_func_2(test_data_files): v = Vasprun(test_data_files / "MgSe_absorption_vasprun_gamma.xml") o = Outcar(test_data_files / "MgSe_absorption_OUTCAR_gamma") actual = make_shifted_diele_func(make_diele_func(v, o), original_band_gap=1.997, shift=1.0) assert isinstance(actual.diele_func_imag[0], list) assert isinstance(actual.diele_func_imag[0][0], float)
true
true
f7f9f7b9b4f9671012ab558a81d6781c1f64eefc
4,166
py
Python
benchmark/startQiskit_Class2221.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
benchmark/startQiskit_Class2221.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
benchmark/startQiskit_Class2221.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
# qubit number=4 # total number=40 import cirq import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer, execute, transpile from pprint import pprint from qiskit.test.mock import FakeVigo from math import log2 import numpy as np import networkx as nx def bitwise_xor(s: str, t: str) -> str: length = len(s) res = [] for i in range(length): res.append(str(int(s[i]) ^ int(t[i]))) return ''.join(res[::-1]) def bitwise_dot(s: str, t: str) -> str: length = len(s) res = 0 for i in range(length): res += int(s[i]) * int(t[i]) return str(res % 2) def build_oracle(n: int, f) -> QuantumCircuit: # implement the oracle O_f # NOTE: use multi_control_toffoli_gate ('noancilla' mode) # https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html # https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates # https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate controls = QuantumRegister(n, "ofc") target = QuantumRegister(1, "oft") oracle = QuantumCircuit(controls, target, name="Of") for i in range(2 ** n): rep = np.binary_repr(i, n) if f(rep) == "1": for j in range(n): if rep[j] == "0": oracle.x(controls[j]) oracle.mct(controls, target[0], None, mode='noancilla') for j in range(n): if rep[j] == "0": oracle.x(controls[j]) # oracle.barrier() return oracle def make_circuit(n:int,f) -> QuantumCircuit: # circuit begin input_qubit = QuantumRegister(n,"qc") classical = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classical) prog.h(input_qubit[3]) # number=24 prog.cz(input_qubit[0],input_qubit[3]) # number=25 prog.h(input_qubit[3]) # number=26 prog.h(input_qubit[3]) # number=21 prog.cz(input_qubit[0],input_qubit[3]) # number=22 prog.h(input_qubit[3]) # number=23 prog.h(input_qubit[3]) # number=27 prog.cz(input_qubit[0],input_qubit[3]) # number=28 prog.h(input_qubit[3]) # number=29 prog.cx(input_qubit[0],input_qubit[3]) # number=30 prog.x(input_qubit[3]) # number=31 prog.h(input_qubit[3]) # number=33 prog.cz(input_qubit[0],input_qubit[3]) # number=34 prog.h(input_qubit[3]) # number=35 prog.cx(input_qubit[0],input_qubit[3]) # number=18 prog.rx(-0.364424747816416,input_qubit[3]) # number=36 prog.y(input_qubit[3]) # number=20 prog.h(input_qubit[3]) # number=37 prog.cz(input_qubit[0],input_qubit[3]) # number=38 prog.h(input_qubit[3]) # number=39 prog.cx(input_qubit[0],input_qubit[3]) # number=12 prog.h(input_qubit[1]) # number=2 prog.h(input_qubit[2]) # number=3 prog.h(input_qubit[3]) # number=4 prog.h(input_qubit[0]) # number=5 oracle = build_oracle(n-1, f) prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]]) prog.h(input_qubit[1]) # number=6 prog.h(input_qubit[2]) # number=7 prog.h(input_qubit[3]) # number=19 prog.h(input_qubit[3]) # number=8 prog.h(input_qubit[0]) # number=9 # circuit end return prog if __name__ == '__main__': a = "111" b = "0" f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b) prog = make_circuit(4,f) backend = BasicAer.get_backend('statevector_simulator') sample_shot =8000 info = execute(prog, backend=backend).result().get_statevector() qubits = round(log2(len(info))) info = { np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3) for i in range(2 ** qubits) } backend = FakeVigo() circuit1 = transpile(prog,backend,optimization_level=2) writefile = open("../data/startQiskit_Class2221.csv","w") print(info,file=writefile) print("results end", file=writefile) print(circuit1.__len__(),file=writefile) print(circuit1,file=writefile) writefile.close()
34.429752
140
0.647144
import cirq import qiskit from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer, execute, transpile from pprint import pprint from qiskit.test.mock import FakeVigo from math import log2 import numpy as np import networkx as nx def bitwise_xor(s: str, t: str) -> str: length = len(s) res = [] for i in range(length): res.append(str(int(s[i]) ^ int(t[i]))) return ''.join(res[::-1]) def bitwise_dot(s: str, t: str) -> str: length = len(s) res = 0 for i in range(length): res += int(s[i]) * int(t[i]) return str(res % 2) def build_oracle(n: int, f) -> QuantumCircuit: controls = QuantumRegister(n, "ofc") target = QuantumRegister(1, "oft") oracle = QuantumCircuit(controls, target, name="Of") for i in range(2 ** n): rep = np.binary_repr(i, n) if f(rep) == "1": for j in range(n): if rep[j] == "0": oracle.x(controls[j]) oracle.mct(controls, target[0], None, mode='noancilla') for j in range(n): if rep[j] == "0": oracle.x(controls[j]) return oracle def make_circuit(n:int,f) -> QuantumCircuit: input_qubit = QuantumRegister(n,"qc") classical = ClassicalRegister(n, "qm") prog = QuantumCircuit(input_qubit, classical) prog.h(input_qubit[3]) prog.cz(input_qubit[0],input_qubit[3]) prog.h(input_qubit[3]) prog.h(input_qubit[3]) prog.cz(input_qubit[0],input_qubit[3]) prog.h(input_qubit[3]) prog.h(input_qubit[3]) prog.cz(input_qubit[0],input_qubit[3]) prog.h(input_qubit[3]) prog.cx(input_qubit[0],input_qubit[3]) prog.x(input_qubit[3]) prog.h(input_qubit[3]) prog.cz(input_qubit[0],input_qubit[3]) prog.h(input_qubit[3]) prog.cx(input_qubit[0],input_qubit[3]) prog.rx(-0.364424747816416,input_qubit[3]) prog.y(input_qubit[3]) prog.h(input_qubit[3]) prog.cz(input_qubit[0],input_qubit[3]) prog.h(input_qubit[3]) prog.cx(input_qubit[0],input_qubit[3]) prog.h(input_qubit[1]) prog.h(input_qubit[2]) prog.h(input_qubit[3]) prog.h(input_qubit[0]) oracle = build_oracle(n-1, f) prog.append(oracle.to_gate(),[input_qubit[i] for i in range(n-1)]+[input_qubit[n-1]]) prog.h(input_qubit[1]) prog.h(input_qubit[2]) prog.h(input_qubit[3]) prog.h(input_qubit[3]) prog.h(input_qubit[0]) return prog if __name__ == '__main__': a = "111" b = "0" f = lambda rep: bitwise_xor(bitwise_dot(a, rep), b) prog = make_circuit(4,f) backend = BasicAer.get_backend('statevector_simulator') sample_shot =8000 info = execute(prog, backend=backend).result().get_statevector() qubits = round(log2(len(info))) info = { np.binary_repr(i, qubits): round((info[i]*(info[i].conjugate())).real,3) for i in range(2 ** qubits) } backend = FakeVigo() circuit1 = transpile(prog,backend,optimization_level=2) writefile = open("../data/startQiskit_Class2221.csv","w") print(info,file=writefile) print("results end", file=writefile) print(circuit1.__len__(),file=writefile) print(circuit1,file=writefile) writefile.close()
true
true
f7f9f853bb35f1ce699cc0d72855a75f9c14669f
1,704
py
Python
tools/gt_map_visualization/angular_velocity_from_bag.py
kirkscheper/mvsec
ee9b7ac0c20ad6f8e48a6dbe337587ca184926e2
[ "MIT" ]
37
2017-09-12T02:07:00.000Z
2022-03-29T13:18:44.000Z
tools/gt_map_visualization/angular_velocity_from_bag.py
kirkscheper/mvsec
ee9b7ac0c20ad6f8e48a6dbe337587ca184926e2
[ "MIT" ]
13
2018-12-14T13:19:12.000Z
2022-03-21T09:11:28.000Z
tools/gt_map_visualization/angular_velocity_from_bag.py
kirkscheper/mvsec
ee9b7ac0c20ad6f8e48a6dbe337587ca184926e2
[ "MIT" ]
9
2018-10-02T04:36:34.000Z
2022-01-08T18:17:08.000Z
#!/usr/bin/env python # # import rosbag, rospy, numpy as np import sys, os, glob import argparse import numpy.linalg import math import tf import tf.transformations if __name__ == '__main__': parser = argparse.ArgumentParser(description='get angular velocity from bag.') parser.add_argument('--start', '-s', action='store', default=rospy.Time(0), type=rospy.Time, help='where to start in the bag.') parser.add_argument('--end', '-e', action='store', default=1e10, type=float, help='where to stop in the bag.') parser.add_argument('bagfile') args = parser.parse_args() t0 = -1 integration_time = 1.0 # in seconds w_avg = np.array([0, 0, 0]) w_max = 0 cnt =0 for bagfile in glob.glob(args.bagfile): bag = rosbag.Bag(bagfile, 'r') topics = ["/davis/right/imu"] # topics = ["/davis/left/imu"] # topics = ["/imu0"] iterator = bag.read_messages(topics=topics, start_time=args.start) for (topic, msg, time) in iterator: tstamp = msg.header.stamp.to_sec() if (t0 < 0): t0 = tstamp #print msg w = msg.angular_velocity w_vec = np.array([w.x, w.y, w.z]) t = tstamp - t0 if (t > args.end): break; w_len = np.linalg.norm(w_vec) if w_len > w_max: w_max = w_len w_avg = w_avg + w_vec cnt = cnt + 1 # print "%f %f %f %f %f" % (t, w_vec[0], w_vec[1], w_vec[2], w_len) print "avg ang velocity: " + str(w_avg / cnt) print "max ang velocity: %f" % (w_max)
28.881356
114
0.538146
import rosbag, rospy, numpy as np import sys, os, glob import argparse import numpy.linalg import math import tf import tf.transformations if __name__ == '__main__': parser = argparse.ArgumentParser(description='get angular velocity from bag.') parser.add_argument('--start', '-s', action='store', default=rospy.Time(0), type=rospy.Time, help='where to start in the bag.') parser.add_argument('--end', '-e', action='store', default=1e10, type=float, help='where to stop in the bag.') parser.add_argument('bagfile') args = parser.parse_args() t0 = -1 integration_time = 1.0 w_avg = np.array([0, 0, 0]) w_max = 0 cnt =0 for bagfile in glob.glob(args.bagfile): bag = rosbag.Bag(bagfile, 'r') topics = ["/davis/right/imu"] iterator = bag.read_messages(topics=topics, start_time=args.start) for (topic, msg, time) in iterator: tstamp = msg.header.stamp.to_sec() if (t0 < 0): t0 = tstamp w = msg.angular_velocity w_vec = np.array([w.x, w.y, w.z]) t = tstamp - t0 if (t > args.end): break; w_len = np.linalg.norm(w_vec) if w_len > w_max: w_max = w_len w_avg = w_avg + w_vec cnt = cnt + 1 print "avg ang velocity: " + str(w_avg / cnt) print "max ang velocity: %f" % (w_max)
false
true
f7f9f967f923b880c6bc9efd359fb8f026ee5aeb
246
py
Python
minterest/accountapp/views.py
Dohwee-Kim/minterest
f6a52ccee6e5900ce1f1140f05d68c8a6b494117
[ "MIT" ]
null
null
null
minterest/accountapp/views.py
Dohwee-Kim/minterest
f6a52ccee6e5900ce1f1140f05d68c8a6b494117
[ "MIT" ]
null
null
null
minterest/accountapp/views.py
Dohwee-Kim/minterest
f6a52ccee6e5900ce1f1140f05d68c8a6b494117
[ "MIT" ]
null
null
null
from django.shortcuts import render from django.http.response import HttpResponse # Create your views here. def hello_world(request): # 왜 바로 안 읽어지냐면 , root app 의 setting.py 에서 추가해줘야한다 return render(request, 'accountapp/hello_world.html')
35.142857
57
0.772358
from django.shortcuts import render from django.http.response import HttpResponse def hello_world(request): return render(request, 'accountapp/hello_world.html')
true
true
f7f9f9df29333c2d27564830cba79534770403e1
1,329
py
Python
nipype/algorithms/tests/test_overlap.py
Conxz/nipype
1281723ae56eacd103597ff4081a205583706e62
[ "Apache-2.0" ]
null
null
null
nipype/algorithms/tests/test_overlap.py
Conxz/nipype
1281723ae56eacd103597ff4081a205583706e62
[ "Apache-2.0" ]
2
2017-10-05T21:08:38.000Z
2018-10-09T23:01:23.000Z
nipype/algorithms/tests/test_overlap.py
Conxz/nipype
1281723ae56eacd103597ff4081a205583706e62
[ "Apache-2.0" ]
1
2016-10-11T19:18:53.000Z
2016-10-11T19:18:53.000Z
#!/usr/bin/env python # -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: import os from shutil import rmtree from tempfile import mkdtemp from nipype.testing import (example_data) import numpy as np def test_overlap(): from nipype.algorithms.metrics import Overlap def check_close(val1, val2): import numpy.testing as npt return npt.assert_almost_equal(val1, val2, decimal=3) tempdir = mkdtemp() in1 = example_data('segmentation0.nii.gz') in2 = example_data('segmentation1.nii.gz') cwd = os.getcwd() os.chdir(tempdir) overlap = Overlap() overlap.inputs.volume1 = in1 overlap.inputs.volume2 = in1 res = overlap.run() yield check_close, res.outputs.jaccard, 1.0 overlap = Overlap() overlap.inputs.volume1 = in1 overlap.inputs.volume2 = in2 res = overlap.run() yield check_close, res.outputs.jaccard, 0.99705 overlap = Overlap() overlap.inputs.volume1 = in1 overlap.inputs.volume2 = in2 overlap.inputs.vol_units = 'mm' res = overlap.run() yield check_close, res.outputs.jaccard, 0.99705 yield (check_close, res.outputs.roi_voldiff, np.array([0.0063086, -0.0025506, 0.0])) os.chdir(cwd) rmtree(tempdir)
25.557692
73
0.671181
import os from shutil import rmtree from tempfile import mkdtemp from nipype.testing import (example_data) import numpy as np def test_overlap(): from nipype.algorithms.metrics import Overlap def check_close(val1, val2): import numpy.testing as npt return npt.assert_almost_equal(val1, val2, decimal=3) tempdir = mkdtemp() in1 = example_data('segmentation0.nii.gz') in2 = example_data('segmentation1.nii.gz') cwd = os.getcwd() os.chdir(tempdir) overlap = Overlap() overlap.inputs.volume1 = in1 overlap.inputs.volume2 = in1 res = overlap.run() yield check_close, res.outputs.jaccard, 1.0 overlap = Overlap() overlap.inputs.volume1 = in1 overlap.inputs.volume2 = in2 res = overlap.run() yield check_close, res.outputs.jaccard, 0.99705 overlap = Overlap() overlap.inputs.volume1 = in1 overlap.inputs.volume2 = in2 overlap.inputs.vol_units = 'mm' res = overlap.run() yield check_close, res.outputs.jaccard, 0.99705 yield (check_close, res.outputs.roi_voldiff, np.array([0.0063086, -0.0025506, 0.0])) os.chdir(cwd) rmtree(tempdir)
true
true
f7f9fa4ef1d0e0ffe5592fc7666a73807aefa5a9
372
py
Python
wordcount_file.py
filkuzmanovski/creditspark
d94ee21e19f6c790d9c31f391d9e005fb809acaa
[ "MIT" ]
null
null
null
wordcount_file.py
filkuzmanovski/creditspark
d94ee21e19f6c790d9c31f391d9e005fb809acaa
[ "MIT" ]
null
null
null
wordcount_file.py
filkuzmanovski/creditspark
d94ee21e19f6c790d9c31f391d9e005fb809acaa
[ "MIT" ]
null
null
null
import sys from pyspark import SparkContext sc = SparkContext("local", "My App") text_file = sc.textFile("file:///home/ma1306/creditspark/"+sys.argv[1]) counts = text_file.flatMap(lambda line: line.split(" ")) \ .map(lambda word: (word, 1)) \ .reduceByKey(lambda a, b: a + b) counts.saveAsTextFile("file:///home/ma1306/creditspark/output")
24.8
71
0.658602
import sys from pyspark import SparkContext sc = SparkContext("local", "My App") text_file = sc.textFile("file:///home/ma1306/creditspark/"+sys.argv[1]) counts = text_file.flatMap(lambda line: line.split(" ")) \ .map(lambda word: (word, 1)) \ .reduceByKey(lambda a, b: a + b) counts.saveAsTextFile("file:///home/ma1306/creditspark/output")
true
true
f7f9fa507c47a6fad463050a43d09185cf90b1e6
1,645
py
Python
setup.py
ailove-dev/django-event
2d82cee0b3b86209850cbb6e382d597d2624251d
[ "MIT" ]
3
2015-08-31T00:46:12.000Z
2017-12-13T01:32:32.000Z
setup.py
ailove-dev/django-event
2d82cee0b3b86209850cbb6e382d597d2624251d
[ "MIT" ]
8
2015-01-20T12:27:24.000Z
2015-05-29T12:29:53.000Z
setup.py
ailove-dev/django-event
2d82cee0b3b86209850cbb6e382d597d2624251d
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os import sys from setuptools import setup from setuptools import find_packages from django_event import __version__ from django_event import __release_tag__ requirments = [ 'django>=1.7', 'celery>=3.1.16', 'tornado>=4.0.2', 'sockjs-tornado>=1.0.1', ] if sys.version < '3': requirments.extend([ 'futures>=2.2.0' # 2.7 backport of concurrent package ]) extras = { 'rest_framework': ['djangorestframework>=3.1.1', ], 'rabbit_mq': ['pika>=0.9.14', ], 'redis': ['django-redis==3.8.3', ], } on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if on_rtd: for extra_requirements in extras.itervalues(): requirments.extend(extra_requirements) setup_options = dict( name='django-event', version='%s-%s' % ( __version__, __release_tag__ ) if __release_tag__ else __version__, url='https://github.com/ailove-dev/django-event', license='MIT', author='Dmitry Panchenko', author_email='d.panchenko@ailove.com', description='Event notification system for django project', packages=find_packages(), zip_safe=False, include_package_data=True, platforms='any', install_requires=requirments, tests_require=['Django'], classifiers=[ 'Development Status :: 4 - Beta', 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Utilities', ], ) setup(**setup_options)
24.552239
63
0.648024
from __future__ import unicode_literals import os import sys from setuptools import setup from setuptools import find_packages from django_event import __version__ from django_event import __release_tag__ requirments = [ 'django>=1.7', 'celery>=3.1.16', 'tornado>=4.0.2', 'sockjs-tornado>=1.0.1', ] if sys.version < '3': requirments.extend([ 'futures>=2.2.0' ]) extras = { 'rest_framework': ['djangorestframework>=3.1.1', ], 'rabbit_mq': ['pika>=0.9.14', ], 'redis': ['django-redis==3.8.3', ], } on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if on_rtd: for extra_requirements in extras.itervalues(): requirments.extend(extra_requirements) setup_options = dict( name='django-event', version='%s-%s' % ( __version__, __release_tag__ ) if __release_tag__ else __version__, url='https://github.com/ailove-dev/django-event', license='MIT', author='Dmitry Panchenko', author_email='d.panchenko@ailove.com', description='Event notification system for django project', packages=find_packages(), zip_safe=False, include_package_data=True, platforms='any', install_requires=requirments, tests_require=['Django'], classifiers=[ 'Development Status :: 4 - Beta', 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Utilities', ], ) setup(**setup_options)
true
true
f7f9fa62dc9100fd1155cece12f7f9915406bd4a
12,625
py
Python
conda_build/inspect_pkg.py
grlee77/conda-build
ea99e2dc2fa473039dbeb73d92b3f5d5c59548fe
[ "BSD-3-Clause" ]
1
2019-01-15T10:51:38.000Z
2019-01-15T10:51:38.000Z
conda_build/inspect_pkg.py
grlee77/conda-build
ea99e2dc2fa473039dbeb73d92b3f5d5c59548fe
[ "BSD-3-Clause" ]
null
null
null
conda_build/inspect_pkg.py
grlee77/conda-build
ea99e2dc2fa473039dbeb73d92b3f5d5c59548fe
[ "BSD-3-Clause" ]
null
null
null
# (c) Continuum Analytics, Inc. / http://continuum.io # All Rights Reserved # # conda is distributed under the terms of the BSD 3-clause license. # Consult LICENSE.txt or http://opensource.org/licenses/BSD-3-Clause. from __future__ import absolute_import, division, print_function from collections import defaultdict import json from operator import itemgetter from os.path import abspath, join, dirname, exists, basename import os import re import sys import tempfile from conda_build.os_utils.ldd import get_linkages, get_package_obj_files, get_untracked_obj_files from conda_build.os_utils.macho import get_rpaths, human_filetype from conda_build.utils import (groupby, getter, comma_join, rm_rf, package_has_file, get_logger, ensure_list) from conda_build.conda_interface import (iteritems, specs_from_args, is_linked, linked_data, linked, get_index) from conda_build.conda_interface import display_actions, install_actions from conda_build.conda_interface import memoized @memoized def dist_files(prefix, dist): meta = is_linked(prefix, dist) return set(meta['files']) def which_package(in_prefix_path, prefix): """ given the path of a conda installed file iterate over the conda packages the file came from. Usually the iteration yields only one package. """ for dist in linked(prefix): if in_prefix_path.replace(os.sep, '/') in dist_files(prefix, dist): yield dist def print_object_info(info, key): output_string = "" gb = groupby(key, info) for header in sorted(gb, key=str): output_string += header + "\n" for f_info in sorted(gb[header], key=getter('filename')): for data in sorted(f_info): if data == key: continue if f_info[data] is None: continue output_string += ' %s: %s\n' % (data, f_info[data]) if len([i for i in f_info if f_info[i] is not None and i != key]) > 1: output_string += '\n' output_string += '\n' return output_string class _untracked_package: def __str__(self): return "<untracked>" untracked_package = _untracked_package() def check_install(packages, platform=None, channel_urls=(), prepend=True, minimal_hint=False): prefix = tempfile.mkdtemp('conda') try: specs = specs_from_args(packages) index = get_index(channel_urls=channel_urls, prepend=prepend, platform=platform, prefix=prefix) actions = install_actions(prefix, index, specs, pinned=False, minimal_hint=minimal_hint) display_actions(actions, index) return actions finally: rm_rf(prefix) return None def print_linkages(depmap, show_files=False): # Print system and not found last dist_depmap = {} for k, v in depmap.items(): if hasattr(k, 'dist_name'): k = k.dist_name dist_depmap[k] = v depmap = dist_depmap k = sorted(set(depmap.keys()) - {'system', 'not found'}) all_deps = k if 'not found' not in depmap.keys() else k + ['system', 'not found'] output_string = "" for dep in all_deps: output_string += "%s:\n" % dep if show_files: for lib, path, binary in sorted(depmap[dep]): output_string += " %s (%s) from %s\n" % (lib, path, binary) else: for lib, path in sorted(set(map(itemgetter(0, 1), depmap[dep]))): output_string += " %s (%s)\n" % (lib, path) output_string += "\n" return output_string def replace_path(binary, path, prefix): if sys.platform.startswith('linux'): return abspath(path) elif sys.platform.startswith('darwin'): if path == basename(binary): return abspath(join(prefix, binary)) if '@rpath' in path: rpaths = get_rpaths(join(prefix, binary)) if not rpaths: return "NO LC_RPATH FOUND" else: for rpath in rpaths: path1 = path.replace("@rpath", rpath) path1 = path1.replace('@loader_path', join(prefix, dirname(binary))) if exists(abspath(join(prefix, path1))): path = path1 break else: return 'not found' path = path.replace('@loader_path', join(prefix, dirname(binary))) if path.startswith('/'): return abspath(path) return 'not found' def test_installable(channel='defaults'): success = True log = get_logger(__name__) has_py = re.compile(r'py(\d)(\d)') for platform in ['osx-64', 'linux-32', 'linux-64', 'win-32', 'win-64']: log.info("######## Testing platform %s ########", platform) channels = [channel] index = get_index(channel_urls=channels, prepend=False, platform=platform) for _, rec in iteritems(index): # If we give channels at the command line, only look at # packages from those channels (not defaults). if channel != 'defaults' and rec.get('schannel', 'defaults') == 'defaults': continue name = rec['name'] if name in {'conda', 'conda-build'}: # conda can only be installed in the root environment continue if name.endswith('@'): # this is a 'virtual' feature record that conda adds to the index for the solver # and should be ignored here continue # Don't fail just because the package is a different version of Python # than the default. We should probably check depends rather than the # build string. build = rec['build'] match = has_py.search(build) assert match if 'py' in build else True, build if match: additional_packages = ['python=%s.%s' % (match.group(1), match.group(2))] else: additional_packages = [] version = rec['version'] log.info('Testing %s=%s', name, version) try: install_steps = check_install([name + '=' + version] + additional_packages, channel_urls=channels, prepend=False, platform=platform) success &= bool(install_steps) except KeyboardInterrupt: raise # sys.exit raises an exception that doesn't subclass from Exception except BaseException as e: success = False log.error("FAIL: %s %s on %s with %s (%s)", name, version, platform, additional_packages, e) return success def _installed(prefix): installed = linked_data(prefix) installed = {rec['name']: dist for dist, rec in iteritems(installed)} return installed def _underlined_text(text): return str(text) + '\n' + '-' * len(str(text)) + '\n\n' def inspect_linkages(packages, prefix=sys.prefix, untracked=False, all_packages=False, show_files=False, groupby="package", sysroot=""): pkgmap = {} installed = _installed(prefix) if not packages and not untracked and not all_packages: raise ValueError("At least one package or --untracked or --all must be provided") if all_packages: packages = sorted(installed.keys()) if untracked: packages.append(untracked_package) for pkg in ensure_list(packages): if pkg == untracked_package: dist = untracked_package elif pkg not in installed: sys.exit("Package %s is not installed in %s" % (pkg, prefix)) else: dist = installed[pkg] if not sys.platform.startswith(('linux', 'darwin')): sys.exit("Error: conda inspect linkages is only implemented in Linux and OS X") if dist == untracked_package: obj_files = get_untracked_obj_files(prefix) else: obj_files = get_package_obj_files(dist, prefix) linkages = get_linkages(obj_files, prefix, sysroot) depmap = defaultdict(list) pkgmap[pkg] = depmap depmap['not found'] = [] depmap['system'] = [] for binary in linkages: for lib, path in linkages[binary]: path = replace_path(binary, path, prefix) if path not in {'', 'not found'} else path if path.startswith(prefix): in_prefix_path = re.sub('^' + prefix + '/', '', path) deps = list(which_package(in_prefix_path, prefix)) if len(deps) > 1: deps_str = [str(dep) for dep in deps] get_logger(__name__).warn("Warning: %s comes from multiple " "packages: %s", path, comma_join(deps_str)) if not deps: if exists(path): depmap['untracked'].append((lib, path.split(prefix + '/', 1)[-1], binary)) else: depmap['not found'].append((lib, path.split(prefix + '/', 1)[-1], binary)) for d in deps: depmap[d].append((lib, path.split(prefix + '/', 1)[-1], binary)) elif path == 'not found': depmap['not found'].append((lib, path, binary)) else: depmap['system'].append((lib, path, binary)) output_string = "" if groupby == 'package': for pkg in packages: output_string += _underlined_text(pkg) output_string += print_linkages(pkgmap[pkg], show_files=show_files) elif groupby == 'dependency': # {pkg: {dep: [files]}} -> {dep: {pkg: [files]}} inverted_map = defaultdict(lambda: defaultdict(list)) for pkg in pkgmap: for dep in pkgmap[pkg]: if pkgmap[pkg][dep]: inverted_map[dep][pkg] = pkgmap[pkg][dep] # print system and not found last k = sorted(set(inverted_map.keys()) - {'system', 'not found'}) for dep in k + ['system', 'not found']: output_string += _underlined_text(dep) output_string += print_linkages(inverted_map[dep], show_files=show_files) else: raise ValueError("Unrecognized groupby: %s" % groupby) if hasattr(output_string, 'decode'): output_string = output_string.decode('utf-8') return output_string def inspect_objects(packages, prefix=sys.prefix, groupby='package'): installed = _installed(prefix) output_string = "" for pkg in ensure_list(packages): if pkg == untracked_package: dist = untracked_package elif pkg not in installed: raise ValueError("Package %s is not installed in %s" % (pkg, prefix)) else: dist = installed[pkg] output_string += _underlined_text(pkg) if not sys.platform.startswith('darwin'): sys.exit("Error: conda inspect objects is only implemented in OS X") if dist == untracked_package: obj_files = get_untracked_obj_files(prefix) else: obj_files = get_package_obj_files(dist, prefix) info = [] for f in obj_files: f_info = {} path = join(prefix, f) f_info['filetype'] = human_filetype(path) f_info['rpath'] = ':'.join(get_rpaths(path)) f_info['filename'] = f info.append(f_info) output_string += print_object_info(info, groupby) if hasattr(output_string, 'decode'): output_string = output_string.decode('utf-8') return output_string def get_hash_input(packages): hash_inputs = {} for pkg in ensure_list(packages): pkgname = os.path.basename(pkg)[:-8] hash_inputs[pkgname] = {} hash_input = package_has_file(pkg, 'info/hash_input.json') if hash_input: hash_inputs[pkgname]['recipe'] = json.loads(hash_input.decode()) else: hash_inputs[pkgname] = "<no hash_input.json in file>" return hash_inputs
37.799401
100
0.569901
from __future__ import absolute_import, division, print_function from collections import defaultdict import json from operator import itemgetter from os.path import abspath, join, dirname, exists, basename import os import re import sys import tempfile from conda_build.os_utils.ldd import get_linkages, get_package_obj_files, get_untracked_obj_files from conda_build.os_utils.macho import get_rpaths, human_filetype from conda_build.utils import (groupby, getter, comma_join, rm_rf, package_has_file, get_logger, ensure_list) from conda_build.conda_interface import (iteritems, specs_from_args, is_linked, linked_data, linked, get_index) from conda_build.conda_interface import display_actions, install_actions from conda_build.conda_interface import memoized @memoized def dist_files(prefix, dist): meta = is_linked(prefix, dist) return set(meta['files']) def which_package(in_prefix_path, prefix): for dist in linked(prefix): if in_prefix_path.replace(os.sep, '/') in dist_files(prefix, dist): yield dist def print_object_info(info, key): output_string = "" gb = groupby(key, info) for header in sorted(gb, key=str): output_string += header + "\n" for f_info in sorted(gb[header], key=getter('filename')): for data in sorted(f_info): if data == key: continue if f_info[data] is None: continue output_string += ' %s: %s\n' % (data, f_info[data]) if len([i for i in f_info if f_info[i] is not None and i != key]) > 1: output_string += '\n' output_string += '\n' return output_string class _untracked_package: def __str__(self): return "<untracked>" untracked_package = _untracked_package() def check_install(packages, platform=None, channel_urls=(), prepend=True, minimal_hint=False): prefix = tempfile.mkdtemp('conda') try: specs = specs_from_args(packages) index = get_index(channel_urls=channel_urls, prepend=prepend, platform=platform, prefix=prefix) actions = install_actions(prefix, index, specs, pinned=False, minimal_hint=minimal_hint) display_actions(actions, index) return actions finally: rm_rf(prefix) return None def print_linkages(depmap, show_files=False): dist_depmap = {} for k, v in depmap.items(): if hasattr(k, 'dist_name'): k = k.dist_name dist_depmap[k] = v depmap = dist_depmap k = sorted(set(depmap.keys()) - {'system', 'not found'}) all_deps = k if 'not found' not in depmap.keys() else k + ['system', 'not found'] output_string = "" for dep in all_deps: output_string += "%s:\n" % dep if show_files: for lib, path, binary in sorted(depmap[dep]): output_string += " %s (%s) from %s\n" % (lib, path, binary) else: for lib, path in sorted(set(map(itemgetter(0, 1), depmap[dep]))): output_string += " %s (%s)\n" % (lib, path) output_string += "\n" return output_string def replace_path(binary, path, prefix): if sys.platform.startswith('linux'): return abspath(path) elif sys.platform.startswith('darwin'): if path == basename(binary): return abspath(join(prefix, binary)) if '@rpath' in path: rpaths = get_rpaths(join(prefix, binary)) if not rpaths: return "NO LC_RPATH FOUND" else: for rpath in rpaths: path1 = path.replace("@rpath", rpath) path1 = path1.replace('@loader_path', join(prefix, dirname(binary))) if exists(abspath(join(prefix, path1))): path = path1 break else: return 'not found' path = path.replace('@loader_path', join(prefix, dirname(binary))) if path.startswith('/'): return abspath(path) return 'not found' def test_installable(channel='defaults'): success = True log = get_logger(__name__) has_py = re.compile(r'py(\d)(\d)') for platform in ['osx-64', 'linux-32', 'linux-64', 'win-32', 'win-64']: log.info("######## Testing platform %s ########", platform) channels = [channel] index = get_index(channel_urls=channels, prepend=False, platform=platform) for _, rec in iteritems(index): if channel != 'defaults' and rec.get('schannel', 'defaults') == 'defaults': continue name = rec['name'] if name in {'conda', 'conda-build'}: continue if name.endswith('@'): continue # than the default. We should probably check depends rather than the # build string. build = rec['build'] match = has_py.search(build) assert match if 'py' in build else True, build if match: additional_packages = ['python=%s.%s' % (match.group(1), match.group(2))] else: additional_packages = [] version = rec['version'] log.info('Testing %s=%s', name, version) try: install_steps = check_install([name + '=' + version] + additional_packages, channel_urls=channels, prepend=False, platform=platform) success &= bool(install_steps) except KeyboardInterrupt: raise # sys.exit raises an exception that doesn't subclass from Exception except BaseException as e: success = False log.error("FAIL: %s %s on %s with %s (%s)", name, version, platform, additional_packages, e) return success def _installed(prefix): installed = linked_data(prefix) installed = {rec['name']: dist for dist, rec in iteritems(installed)} return installed def _underlined_text(text): return str(text) + '\n' + '-' * len(str(text)) + '\n\n' def inspect_linkages(packages, prefix=sys.prefix, untracked=False, all_packages=False, show_files=False, groupby="package", sysroot=""): pkgmap = {} installed = _installed(prefix) if not packages and not untracked and not all_packages: raise ValueError("At least one package or --untracked or --all must be provided") if all_packages: packages = sorted(installed.keys()) if untracked: packages.append(untracked_package) for pkg in ensure_list(packages): if pkg == untracked_package: dist = untracked_package elif pkg not in installed: sys.exit("Package %s is not installed in %s" % (pkg, prefix)) else: dist = installed[pkg] if not sys.platform.startswith(('linux', 'darwin')): sys.exit("Error: conda inspect linkages is only implemented in Linux and OS X") if dist == untracked_package: obj_files = get_untracked_obj_files(prefix) else: obj_files = get_package_obj_files(dist, prefix) linkages = get_linkages(obj_files, prefix, sysroot) depmap = defaultdict(list) pkgmap[pkg] = depmap depmap['not found'] = [] depmap['system'] = [] for binary in linkages: for lib, path in linkages[binary]: path = replace_path(binary, path, prefix) if path not in {'', 'not found'} else path if path.startswith(prefix): in_prefix_path = re.sub('^' + prefix + '/', '', path) deps = list(which_package(in_prefix_path, prefix)) if len(deps) > 1: deps_str = [str(dep) for dep in deps] get_logger(__name__).warn("Warning: %s comes from multiple " "packages: %s", path, comma_join(deps_str)) if not deps: if exists(path): depmap['untracked'].append((lib, path.split(prefix + '/', 1)[-1], binary)) else: depmap['not found'].append((lib, path.split(prefix + '/', 1)[-1], binary)) for d in deps: depmap[d].append((lib, path.split(prefix + '/', 1)[-1], binary)) elif path == 'not found': depmap['not found'].append((lib, path, binary)) else: depmap['system'].append((lib, path, binary)) output_string = "" if groupby == 'package': for pkg in packages: output_string += _underlined_text(pkg) output_string += print_linkages(pkgmap[pkg], show_files=show_files) elif groupby == 'dependency': inverted_map = defaultdict(lambda: defaultdict(list)) for pkg in pkgmap: for dep in pkgmap[pkg]: if pkgmap[pkg][dep]: inverted_map[dep][pkg] = pkgmap[pkg][dep] k = sorted(set(inverted_map.keys()) - {'system', 'not found'}) for dep in k + ['system', 'not found']: output_string += _underlined_text(dep) output_string += print_linkages(inverted_map[dep], show_files=show_files) else: raise ValueError("Unrecognized groupby: %s" % groupby) if hasattr(output_string, 'decode'): output_string = output_string.decode('utf-8') return output_string def inspect_objects(packages, prefix=sys.prefix, groupby='package'): installed = _installed(prefix) output_string = "" for pkg in ensure_list(packages): if pkg == untracked_package: dist = untracked_package elif pkg not in installed: raise ValueError("Package %s is not installed in %s" % (pkg, prefix)) else: dist = installed[pkg] output_string += _underlined_text(pkg) if not sys.platform.startswith('darwin'): sys.exit("Error: conda inspect objects is only implemented in OS X") if dist == untracked_package: obj_files = get_untracked_obj_files(prefix) else: obj_files = get_package_obj_files(dist, prefix) info = [] for f in obj_files: f_info = {} path = join(prefix, f) f_info['filetype'] = human_filetype(path) f_info['rpath'] = ':'.join(get_rpaths(path)) f_info['filename'] = f info.append(f_info) output_string += print_object_info(info, groupby) if hasattr(output_string, 'decode'): output_string = output_string.decode('utf-8') return output_string def get_hash_input(packages): hash_inputs = {} for pkg in ensure_list(packages): pkgname = os.path.basename(pkg)[:-8] hash_inputs[pkgname] = {} hash_input = package_has_file(pkg, 'info/hash_input.json') if hash_input: hash_inputs[pkgname]['recipe'] = json.loads(hash_input.decode()) else: hash_inputs[pkgname] = "<no hash_input.json in file>" return hash_inputs
true
true
f7f9faefe441c222cc97bcc160b16b48b42a8190
134,876
py
Python
tests/unit/gapic/compute_v1/test_security_policies.py
LaudateCorpus1/python-compute
a36c637f153c7b4ef49bb6a78c8b09f3746e7af1
[ "Apache-2.0" ]
null
null
null
tests/unit/gapic/compute_v1/test_security_policies.py
LaudateCorpus1/python-compute
a36c637f153c7b4ef49bb6a78c8b09f3746e7af1
[ "Apache-2.0" ]
null
null
null
tests/unit/gapic/compute_v1/test_security_policies.py
LaudateCorpus1/python-compute
a36c637f153c7b4ef49bb6a78c8b09f3746e7af1
[ "Apache-2.0" ]
null
null
null
# -*- 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 os import mock import grpc from grpc.experimental import aio import json import math import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule from requests import Response from requests import Request, PreparedRequest from requests.sessions import Session from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.compute_v1.services.security_policies import SecurityPoliciesClient from google.cloud.compute_v1.services.security_policies import pagers from google.cloud.compute_v1.services.security_policies import transports from google.cloud.compute_v1.types import compute from google.oauth2 import service_account import google.auth def client_cert_source_callback(): return b"cert bytes", b"key bytes" # If default endpoint is localhost, then default mtls endpoint will be the same. # This method modifies the default endpoint so the client can produce a different # mtls endpoint for endpoint testing purposes. def modify_default_endpoint(client): return ( "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT ) def test__get_default_mtls_endpoint(): api_endpoint = "example.googleapis.com" api_mtls_endpoint = "example.mtls.googleapis.com" sandbox_endpoint = "example.sandbox.googleapis.com" sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" non_googleapi = "api.example.com" assert SecurityPoliciesClient._get_default_mtls_endpoint(None) is None assert ( SecurityPoliciesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint ) assert ( SecurityPoliciesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint ) assert ( SecurityPoliciesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint ) assert ( SecurityPoliciesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint ) assert ( SecurityPoliciesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi ) @pytest.mark.parametrize("client_class", [SecurityPoliciesClient,]) def test_security_policies_client_from_service_account_info(client_class): creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: factory.return_value = creds info = {"valid": True} client = client_class.from_service_account_info(info) assert client.transport._credentials == creds assert isinstance(client, client_class) assert client.transport._host == "compute.googleapis.com:443" @pytest.mark.parametrize( "transport_class,transport_name", [(transports.SecurityPoliciesRestTransport, "rest"),], ) def test_security_policies_client_service_account_always_use_jwt( transport_class, transport_name ): with mock.patch.object( service_account.Credentials, "with_always_use_jwt_access", create=True ) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) with mock.patch.object( service_account.Credentials, "with_always_use_jwt_access", create=True ) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=False) use_jwt.assert_not_called() @pytest.mark.parametrize("client_class", [SecurityPoliciesClient,]) def test_security_policies_client_from_service_account_file(client_class): creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: factory.return_value = creds client = client_class.from_service_account_file("dummy/file/path.json") assert client.transport._credentials == creds assert isinstance(client, client_class) client = client_class.from_service_account_json("dummy/file/path.json") assert client.transport._credentials == creds assert isinstance(client, client_class) assert client.transport._host == "compute.googleapis.com:443" def test_security_policies_client_get_transport_class(): transport = SecurityPoliciesClient.get_transport_class() available_transports = [ transports.SecurityPoliciesRestTransport, ] assert transport in available_transports transport = SecurityPoliciesClient.get_transport_class("rest") assert transport == transports.SecurityPoliciesRestTransport @pytest.mark.parametrize( "client_class,transport_class,transport_name", [(SecurityPoliciesClient, transports.SecurityPoliciesRestTransport, "rest"),], ) @mock.patch.object( SecurityPoliciesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityPoliciesClient), ) def test_security_policies_client_client_options( client_class, transport_class, transport_name ): # Check that if channel is provided we won't create a new one. with mock.patch.object(SecurityPoliciesClient, "get_transport_class") as gtc: transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() # Check that if channel is provided via str we will create a new one. with mock.patch.object(SecurityPoliciesClient, "get_transport_class") as gtc: client = client_class(transport=transport_name) gtc.assert_called() # Check the case api_endpoint is provided. options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, host="squid.clam.whelk", scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "always". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, host=client.DEFAULT_MTLS_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has # unsupported value. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError): client = client_class(transport=transport_name) # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} ): with pytest.raises(ValueError): client = client_class(transport=transport_name) # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) @pytest.mark.parametrize( "client_class,transport_class,transport_name,use_client_cert_env", [ ( SecurityPoliciesClient, transports.SecurityPoliciesRestTransport, "rest", "true", ), ( SecurityPoliciesClient, transports.SecurityPoliciesRestTransport, "rest", "false", ), ], ) @mock.patch.object( SecurityPoliciesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityPoliciesClient), ) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) def test_security_policies_client_mtls_env_auto( client_class, transport_class, transport_name, use_client_cert_env ): # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. # Check the case client_cert_source is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} ): options = client_options.ClientOptions( client_cert_source=client_cert_source_callback ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None expected_host = client.DEFAULT_ENDPOINT else: expected_client_cert_source = client_cert_source_callback expected_host = client.DEFAULT_MTLS_ENDPOINT patched.assert_called_once_with( credentials=None, credentials_file=None, host=expected_host, scopes=None, client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) # Check the case ADC client cert is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} ): with mock.patch.object(transport_class, "__init__") as patched: with mock.patch( "google.auth.transport.mtls.has_default_client_cert_source", return_value=True, ): with mock.patch( "google.auth.transport.mtls.default_client_cert_source", return_value=client_cert_source_callback, ): if use_client_cert_env == "false": expected_host = client.DEFAULT_ENDPOINT expected_client_cert_source = None else: expected_host = client.DEFAULT_MTLS_ENDPOINT expected_client_cert_source = client_cert_source_callback patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, host=expected_host, scopes=None, client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) # Check the case client_cert_source and ADC client cert are not provided. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} ): with mock.patch.object(transport_class, "__init__") as patched: with mock.patch( "google.auth.transport.mtls.has_default_client_cert_source", return_value=False, ): patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) @pytest.mark.parametrize("client_class", [SecurityPoliciesClient]) @mock.patch.object( SecurityPoliciesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityPoliciesClient), ) def test_security_policies_client_get_mtls_endpoint_and_cert_source(client_class): mock_client_cert_source = mock.Mock() # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): mock_api_endpoint = "foo" options = client_options.ClientOptions( client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint ) api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( options ) assert api_endpoint == mock_api_endpoint assert cert_source == mock_client_cert_source # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" options = client_options.ClientOptions( client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint ) api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( options ) assert api_endpoint == mock_api_endpoint assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): with mock.patch( "google.auth.transport.mtls.has_default_client_cert_source", return_value=False, ): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert exists. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): with mock.patch( "google.auth.transport.mtls.has_default_client_cert_source", return_value=True, ): with mock.patch( "google.auth.transport.mtls.default_client_cert_source", return_value=mock_client_cert_source, ): ( api_endpoint, cert_source, ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @pytest.mark.parametrize( "client_class,transport_class,transport_name", [(SecurityPoliciesClient, transports.SecurityPoliciesRestTransport, "rest"),], ) def test_security_policies_client_client_options_scopes( client_class, transport_class, transport_name ): # Check the case scopes are provided. options = client_options.ClientOptions(scopes=["1", "2"],) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=["1", "2"], client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) @pytest.mark.parametrize( "client_class,transport_class,transport_name", [(SecurityPoliciesClient, transports.SecurityPoliciesRestTransport, "rest"),], ) def test_security_policies_client_client_options_credentials_file( client_class, transport_class, transport_name ): # Check the case credentials file is provided. options = client_options.ClientOptions(credentials_file="credentials.json") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", host=client.DEFAULT_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) @pytest.mark.parametrize("request_type", [compute.AddRuleSecurityPolicyRequest, dict,]) def test_add_rule_unary_rest(request_type): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "security_policy": "sample2"} request_init["security_policy_rule_resource"] = { "action": "action_value", "description": "description_value", "kind": "kind_value", "match": { "config": { "src_ip_ranges": ["src_ip_ranges_value_1", "src_ip_ranges_value_2"] }, "expr": { "description": "description_value", "expression": "expression_value", "location": "location_value", "title": "title_value", }, "versioned_expr": "versioned_expr_value", }, "preview": True, "priority": 898, } request = request_type(request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.Operation( client_operation_id="client_operation_id_value", creation_timestamp="creation_timestamp_value", description="description_value", end_time="end_time_value", http_error_message="http_error_message_value", http_error_status_code=2374, id=205, insert_time="insert_time_value", kind="kind_value", name="name_value", operation_group_id="operation_group_id_value", operation_type="operation_type_value", progress=885, region="region_value", self_link="self_link_value", start_time="start_time_value", status=compute.Operation.Status.DONE, status_message="status_message_value", target_id=947, target_link="target_link_value", user="user_value", zone="zone_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.add_rule_unary(request) # Establish that the response is the type that we expect. assert isinstance(response, compute.Operation) assert response.client_operation_id == "client_operation_id_value" assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" assert response.end_time == "end_time_value" assert response.http_error_message == "http_error_message_value" assert response.http_error_status_code == 2374 assert response.id == 205 assert response.insert_time == "insert_time_value" assert response.kind == "kind_value" assert response.name == "name_value" assert response.operation_group_id == "operation_group_id_value" assert response.operation_type == "operation_type_value" assert response.progress == 885 assert response.region == "region_value" assert response.self_link == "self_link_value" assert response.start_time == "start_time_value" assert response.status == compute.Operation.Status.DONE assert response.status_message == "status_message_value" assert response.target_id == 947 assert response.target_link == "target_link_value" assert response.user == "user_value" assert response.zone == "zone_value" def test_add_rule_unary_rest_required_fields( request_type=compute.AddRuleSecurityPolicyRequest, ): transport_class = transports.SecurityPoliciesRestTransport request_init = {} request_init["project"] = "" request_init["security_policy"] = "" request = request_type(request_init) jsonified_request = json.loads( request_type.to_json( request, including_default_value_fields=False, use_integers_for_enums=False ) ) # verify fields with default values are dropped unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).add_rule._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["project"] = "project_value" jsonified_request["securityPolicy"] = "security_policy_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).add_rule._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" assert "securityPolicy" in jsonified_request assert jsonified_request["securityPolicy"] == "security_policy_value" client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type(request_init) # Designate an appropriate value for the returned response. return_value = compute.Operation() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. transcode_result = { "uri": "v1/sample_method", "method": "post", "query_params": request_init, } transcode_result["body"] = {} transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.add_rule_unary(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_add_rule_unary_rest_unset_required_fields(): transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = transport.add_rule._get_unset_required_fields({}) assert set(unset_fields) == ( set(()) & set(("project", "securityPolicy", "securityPolicyRuleResource",)) ) def test_add_rule_unary_rest_bad_request( transport: str = "rest", request_type=compute.AddRuleSecurityPolicyRequest ): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "security_policy": "sample2"} request_init["security_policy_rule_resource"] = { "action": "action_value", "description": "description_value", "kind": "kind_value", "match": { "config": { "src_ip_ranges": ["src_ip_ranges_value_1", "src_ip_ranges_value_2"] }, "expr": { "description": "description_value", "expression": "expression_value", "location": "location_value", "title": "title_value", }, "versioned_expr": "versioned_expr_value", }, "preview": True, "priority": 898, } request = request_type(request_init) # Mock the http request call within the method and fake a BadRequest error. with mock.patch.object(Session, "request") as req, pytest.raises( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 response_value.request = Request() req.return_value = response_value client.add_rule_unary(request) def test_add_rule_unary_rest_flattened(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.Operation() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value # get arguments that satisfy an http rule for this method sample_request = {"project": "sample1", "security_policy": "sample2"} # get truthy value for each flattened field mock_args = dict( project="project_value", security_policy="security_policy_value", security_policy_rule_resource=compute.SecurityPolicyRule( action="action_value" ), ) mock_args.update(sample_request) client.add_rule_unary(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( "https://%s/compute/v1/projects/{project}/global/securityPolicies/{security_policy}/addRule" % client.transport._host, args[1], ) def test_add_rule_unary_rest_flattened_error(transport: str = "rest"): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.add_rule_unary( compute.AddRuleSecurityPolicyRequest(), project="project_value", security_policy="security_policy_value", security_policy_rule_resource=compute.SecurityPolicyRule( action="action_value" ), ) def test_add_rule_unary_rest_error(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @pytest.mark.parametrize("request_type", [compute.DeleteSecurityPolicyRequest, dict,]) def test_delete_unary_rest(request_type): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "security_policy": "sample2"} request = request_type(request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.Operation( client_operation_id="client_operation_id_value", creation_timestamp="creation_timestamp_value", description="description_value", end_time="end_time_value", http_error_message="http_error_message_value", http_error_status_code=2374, id=205, insert_time="insert_time_value", kind="kind_value", name="name_value", operation_group_id="operation_group_id_value", operation_type="operation_type_value", progress=885, region="region_value", self_link="self_link_value", start_time="start_time_value", status=compute.Operation.Status.DONE, status_message="status_message_value", target_id=947, target_link="target_link_value", user="user_value", zone="zone_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.delete_unary(request) # Establish that the response is the type that we expect. assert isinstance(response, compute.Operation) assert response.client_operation_id == "client_operation_id_value" assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" assert response.end_time == "end_time_value" assert response.http_error_message == "http_error_message_value" assert response.http_error_status_code == 2374 assert response.id == 205 assert response.insert_time == "insert_time_value" assert response.kind == "kind_value" assert response.name == "name_value" assert response.operation_group_id == "operation_group_id_value" assert response.operation_type == "operation_type_value" assert response.progress == 885 assert response.region == "region_value" assert response.self_link == "self_link_value" assert response.start_time == "start_time_value" assert response.status == compute.Operation.Status.DONE assert response.status_message == "status_message_value" assert response.target_id == 947 assert response.target_link == "target_link_value" assert response.user == "user_value" assert response.zone == "zone_value" def test_delete_unary_rest_required_fields( request_type=compute.DeleteSecurityPolicyRequest, ): transport_class = transports.SecurityPoliciesRestTransport request_init = {} request_init["project"] = "" request_init["security_policy"] = "" request = request_type(request_init) jsonified_request = json.loads( request_type.to_json( request, including_default_value_fields=False, use_integers_for_enums=False ) ) # verify fields with default values are dropped unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).delete._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["project"] = "project_value" jsonified_request["securityPolicy"] = "security_policy_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).delete._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" assert "securityPolicy" in jsonified_request assert jsonified_request["securityPolicy"] == "security_policy_value" client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type(request_init) # Designate an appropriate value for the returned response. return_value = compute.Operation() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. transcode_result = { "uri": "v1/sample_method", "method": "delete", "query_params": request_init, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.delete_unary(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_delete_unary_rest_unset_required_fields(): transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = transport.delete._get_unset_required_fields({}) assert set(unset_fields) == ( set(("requestId",)) & set(("project", "securityPolicy",)) ) def test_delete_unary_rest_bad_request( transport: str = "rest", request_type=compute.DeleteSecurityPolicyRequest ): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "security_policy": "sample2"} request = request_type(request_init) # Mock the http request call within the method and fake a BadRequest error. with mock.patch.object(Session, "request") as req, pytest.raises( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 response_value.request = Request() req.return_value = response_value client.delete_unary(request) def test_delete_unary_rest_flattened(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.Operation() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value # get arguments that satisfy an http rule for this method sample_request = {"project": "sample1", "security_policy": "sample2"} # get truthy value for each flattened field mock_args = dict( project="project_value", security_policy="security_policy_value", ) mock_args.update(sample_request) client.delete_unary(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( "https://%s/compute/v1/projects/{project}/global/securityPolicies/{security_policy}" % client.transport._host, args[1], ) def test_delete_unary_rest_flattened_error(transport: str = "rest"): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.delete_unary( compute.DeleteSecurityPolicyRequest(), project="project_value", security_policy="security_policy_value", ) def test_delete_unary_rest_error(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @pytest.mark.parametrize("request_type", [compute.GetSecurityPolicyRequest, dict,]) def test_get_rest(request_type): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "security_policy": "sample2"} request = request_type(request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.SecurityPolicy( creation_timestamp="creation_timestamp_value", description="description_value", fingerprint="fingerprint_value", id=205, kind="kind_value", name="name_value", self_link="self_link_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.SecurityPolicy.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.get(request) # Establish that the response is the type that we expect. assert isinstance(response, compute.SecurityPolicy) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" assert response.fingerprint == "fingerprint_value" assert response.id == 205 assert response.kind == "kind_value" assert response.name == "name_value" assert response.self_link == "self_link_value" def test_get_rest_required_fields(request_type=compute.GetSecurityPolicyRequest): transport_class = transports.SecurityPoliciesRestTransport request_init = {} request_init["project"] = "" request_init["security_policy"] = "" request = request_type(request_init) jsonified_request = json.loads( request_type.to_json( request, including_default_value_fields=False, use_integers_for_enums=False ) ) # verify fields with default values are dropped unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).get._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["project"] = "project_value" jsonified_request["securityPolicy"] = "security_policy_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).get._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" assert "securityPolicy" in jsonified_request assert jsonified_request["securityPolicy"] == "security_policy_value" client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type(request_init) # Designate an appropriate value for the returned response. return_value = compute.SecurityPolicy() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. transcode_result = { "uri": "v1/sample_method", "method": "get", "query_params": request_init, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = compute.SecurityPolicy.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.get(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_rest_unset_required_fields(): transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = transport.get._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("project", "securityPolicy",))) def test_get_rest_bad_request( transport: str = "rest", request_type=compute.GetSecurityPolicyRequest ): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "security_policy": "sample2"} request = request_type(request_init) # Mock the http request call within the method and fake a BadRequest error. with mock.patch.object(Session, "request") as req, pytest.raises( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 response_value.request = Request() req.return_value = response_value client.get(request) def test_get_rest_flattened(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.SecurityPolicy() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.SecurityPolicy.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value # get arguments that satisfy an http rule for this method sample_request = {"project": "sample1", "security_policy": "sample2"} # get truthy value for each flattened field mock_args = dict( project="project_value", security_policy="security_policy_value", ) mock_args.update(sample_request) client.get(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( "https://%s/compute/v1/projects/{project}/global/securityPolicies/{security_policy}" % client.transport._host, args[1], ) def test_get_rest_flattened_error(transport: str = "rest"): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.get( compute.GetSecurityPolicyRequest(), project="project_value", security_policy="security_policy_value", ) def test_get_rest_error(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @pytest.mark.parametrize("request_type", [compute.GetRuleSecurityPolicyRequest, dict,]) def test_get_rule_rest(request_type): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "security_policy": "sample2"} request = request_type(request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.SecurityPolicyRule( action="action_value", description="description_value", kind="kind_value", preview=True, priority=898, ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.SecurityPolicyRule.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.get_rule(request) # Establish that the response is the type that we expect. assert isinstance(response, compute.SecurityPolicyRule) assert response.action == "action_value" assert response.description == "description_value" assert response.kind == "kind_value" assert response.preview is True assert response.priority == 898 def test_get_rule_rest_required_fields( request_type=compute.GetRuleSecurityPolicyRequest, ): transport_class = transports.SecurityPoliciesRestTransport request_init = {} request_init["project"] = "" request_init["security_policy"] = "" request = request_type(request_init) jsonified_request = json.loads( request_type.to_json( request, including_default_value_fields=False, use_integers_for_enums=False ) ) # verify fields with default values are dropped unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).get_rule._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["project"] = "project_value" jsonified_request["securityPolicy"] = "security_policy_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).get_rule._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set(("priority",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" assert "securityPolicy" in jsonified_request assert jsonified_request["securityPolicy"] == "security_policy_value" client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type(request_init) # Designate an appropriate value for the returned response. return_value = compute.SecurityPolicyRule() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. transcode_result = { "uri": "v1/sample_method", "method": "get", "query_params": request_init, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = compute.SecurityPolicyRule.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.get_rule(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_rule_rest_unset_required_fields(): transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = transport.get_rule._get_unset_required_fields({}) assert set(unset_fields) == ( set(("priority",)) & set(("project", "securityPolicy",)) ) def test_get_rule_rest_bad_request( transport: str = "rest", request_type=compute.GetRuleSecurityPolicyRequest ): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "security_policy": "sample2"} request = request_type(request_init) # Mock the http request call within the method and fake a BadRequest error. with mock.patch.object(Session, "request") as req, pytest.raises( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 response_value.request = Request() req.return_value = response_value client.get_rule(request) def test_get_rule_rest_flattened(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.SecurityPolicyRule() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.SecurityPolicyRule.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value # get arguments that satisfy an http rule for this method sample_request = {"project": "sample1", "security_policy": "sample2"} # get truthy value for each flattened field mock_args = dict( project="project_value", security_policy="security_policy_value", ) mock_args.update(sample_request) client.get_rule(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( "https://%s/compute/v1/projects/{project}/global/securityPolicies/{security_policy}/getRule" % client.transport._host, args[1], ) def test_get_rule_rest_flattened_error(transport: str = "rest"): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.get_rule( compute.GetRuleSecurityPolicyRequest(), project="project_value", security_policy="security_policy_value", ) def test_get_rule_rest_error(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @pytest.mark.parametrize("request_type", [compute.InsertSecurityPolicyRequest, dict,]) def test_insert_unary_rest(request_type): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding request_init = {"project": "sample1"} request_init["security_policy_resource"] = { "adaptive_protection_config": { "layer7_ddos_defense_config": { "enable": True, "rule_visibility": "rule_visibility_value", } }, "advanced_options_config": { "json_parsing": "json_parsing_value", "log_level": "log_level_value", }, "creation_timestamp": "creation_timestamp_value", "description": "description_value", "fingerprint": "fingerprint_value", "id": 205, "kind": "kind_value", "name": "name_value", "rules": [ { "action": "action_value", "description": "description_value", "kind": "kind_value", "match": { "config": { "src_ip_ranges": [ "src_ip_ranges_value_1", "src_ip_ranges_value_2", ] }, "expr": { "description": "description_value", "expression": "expression_value", "location": "location_value", "title": "title_value", }, "versioned_expr": "versioned_expr_value", }, "preview": True, "priority": 898, } ], "self_link": "self_link_value", } request = request_type(request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.Operation( client_operation_id="client_operation_id_value", creation_timestamp="creation_timestamp_value", description="description_value", end_time="end_time_value", http_error_message="http_error_message_value", http_error_status_code=2374, id=205, insert_time="insert_time_value", kind="kind_value", name="name_value", operation_group_id="operation_group_id_value", operation_type="operation_type_value", progress=885, region="region_value", self_link="self_link_value", start_time="start_time_value", status=compute.Operation.Status.DONE, status_message="status_message_value", target_id=947, target_link="target_link_value", user="user_value", zone="zone_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.insert_unary(request) # Establish that the response is the type that we expect. assert isinstance(response, compute.Operation) assert response.client_operation_id == "client_operation_id_value" assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" assert response.end_time == "end_time_value" assert response.http_error_message == "http_error_message_value" assert response.http_error_status_code == 2374 assert response.id == 205 assert response.insert_time == "insert_time_value" assert response.kind == "kind_value" assert response.name == "name_value" assert response.operation_group_id == "operation_group_id_value" assert response.operation_type == "operation_type_value" assert response.progress == 885 assert response.region == "region_value" assert response.self_link == "self_link_value" assert response.start_time == "start_time_value" assert response.status == compute.Operation.Status.DONE assert response.status_message == "status_message_value" assert response.target_id == 947 assert response.target_link == "target_link_value" assert response.user == "user_value" assert response.zone == "zone_value" def test_insert_unary_rest_required_fields( request_type=compute.InsertSecurityPolicyRequest, ): transport_class = transports.SecurityPoliciesRestTransport request_init = {} request_init["project"] = "" request = request_type(request_init) jsonified_request = json.loads( request_type.to_json( request, including_default_value_fields=False, use_integers_for_enums=False ) ) # verify fields with default values are dropped unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).insert._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["project"] = "project_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).insert._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type(request_init) # Designate an appropriate value for the returned response. return_value = compute.Operation() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. transcode_result = { "uri": "v1/sample_method", "method": "post", "query_params": request_init, } transcode_result["body"] = {} transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.insert_unary(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_insert_unary_rest_unset_required_fields(): transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = transport.insert._get_unset_required_fields({}) assert set(unset_fields) == ( set(("requestId",)) & set(("project", "securityPolicyResource",)) ) def test_insert_unary_rest_bad_request( transport: str = "rest", request_type=compute.InsertSecurityPolicyRequest ): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding request_init = {"project": "sample1"} request_init["security_policy_resource"] = { "adaptive_protection_config": { "layer7_ddos_defense_config": { "enable": True, "rule_visibility": "rule_visibility_value", } }, "advanced_options_config": { "json_parsing": "json_parsing_value", "log_level": "log_level_value", }, "creation_timestamp": "creation_timestamp_value", "description": "description_value", "fingerprint": "fingerprint_value", "id": 205, "kind": "kind_value", "name": "name_value", "rules": [ { "action": "action_value", "description": "description_value", "kind": "kind_value", "match": { "config": { "src_ip_ranges": [ "src_ip_ranges_value_1", "src_ip_ranges_value_2", ] }, "expr": { "description": "description_value", "expression": "expression_value", "location": "location_value", "title": "title_value", }, "versioned_expr": "versioned_expr_value", }, "preview": True, "priority": 898, } ], "self_link": "self_link_value", } request = request_type(request_init) # Mock the http request call within the method and fake a BadRequest error. with mock.patch.object(Session, "request") as req, pytest.raises( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 response_value.request = Request() req.return_value = response_value client.insert_unary(request) def test_insert_unary_rest_flattened(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.Operation() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value # get arguments that satisfy an http rule for this method sample_request = {"project": "sample1"} # get truthy value for each flattened field mock_args = dict( project="project_value", security_policy_resource=compute.SecurityPolicy( adaptive_protection_config=compute.SecurityPolicyAdaptiveProtectionConfig( layer7_ddos_defense_config=compute.SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfig( enable=True ) ) ), ) mock_args.update(sample_request) client.insert_unary(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( "https://%s/compute/v1/projects/{project}/global/securityPolicies" % client.transport._host, args[1], ) def test_insert_unary_rest_flattened_error(transport: str = "rest"): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.insert_unary( compute.InsertSecurityPolicyRequest(), project="project_value", security_policy_resource=compute.SecurityPolicy( adaptive_protection_config=compute.SecurityPolicyAdaptiveProtectionConfig( layer7_ddos_defense_config=compute.SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfig( enable=True ) ) ), ) def test_insert_unary_rest_error(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @pytest.mark.parametrize("request_type", [compute.ListSecurityPoliciesRequest, dict,]) def test_list_rest(request_type): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding request_init = {"project": "sample1"} request = request_type(request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.SecurityPolicyList( id="id_value", kind="kind_value", next_page_token="next_page_token_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.SecurityPolicyList.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.list(request) # Establish that the response is the type that we expect. assert isinstance(response, pagers.ListPager) assert response.id == "id_value" assert response.kind == "kind_value" assert response.next_page_token == "next_page_token_value" def test_list_rest_required_fields(request_type=compute.ListSecurityPoliciesRequest): transport_class = transports.SecurityPoliciesRestTransport request_init = {} request_init["project"] = "" request = request_type(request_init) jsonified_request = json.loads( request_type.to_json( request, including_default_value_fields=False, use_integers_for_enums=False ) ) # verify fields with default values are dropped unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).list._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["project"] = "project_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).list._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ("max_results", "filter", "order_by", "page_token", "return_partial_success",) ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type(request_init) # Designate an appropriate value for the returned response. return_value = compute.SecurityPolicyList() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. transcode_result = { "uri": "v1/sample_method", "method": "get", "query_params": request_init, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = compute.SecurityPolicyList.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.list(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_list_rest_unset_required_fields(): transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = transport.list._get_unset_required_fields({}) assert set(unset_fields) == ( set(("maxResults", "filter", "orderBy", "pageToken", "returnPartialSuccess",)) & set(("project",)) ) def test_list_rest_bad_request( transport: str = "rest", request_type=compute.ListSecurityPoliciesRequest ): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding request_init = {"project": "sample1"} request = request_type(request_init) # Mock the http request call within the method and fake a BadRequest error. with mock.patch.object(Session, "request") as req, pytest.raises( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 response_value.request = Request() req.return_value = response_value client.list(request) def test_list_rest_flattened(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.SecurityPolicyList() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.SecurityPolicyList.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value # get arguments that satisfy an http rule for this method sample_request = {"project": "sample1"} # get truthy value for each flattened field mock_args = dict(project="project_value",) mock_args.update(sample_request) client.list(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( "https://%s/compute/v1/projects/{project}/global/securityPolicies" % client.transport._host, args[1], ) def test_list_rest_flattened_error(transport: str = "rest"): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.list( compute.ListSecurityPoliciesRequest(), project="project_value", ) def test_list_rest_pager(transport: str = "rest"): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # TODO(kbandes): remove this mock unless there's a good reason for it. # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( compute.SecurityPolicyList( items=[ compute.SecurityPolicy(), compute.SecurityPolicy(), compute.SecurityPolicy(), ], next_page_token="abc", ), compute.SecurityPolicyList(items=[], next_page_token="def",), compute.SecurityPolicyList( items=[compute.SecurityPolicy(),], next_page_token="ghi", ), compute.SecurityPolicyList( items=[compute.SecurityPolicy(), compute.SecurityPolicy(),], ), ) # Two responses for two calls response = response + response # Wrap the values into proper Response objs response = tuple(compute.SecurityPolicyList.to_json(x) for x in response) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): return_val._content = response_val.encode("UTF-8") return_val.status_code = 200 req.side_effect = return_values sample_request = {"project": "sample1"} pager = client.list(request=sample_request) results = list(pager) assert len(results) == 6 assert all(isinstance(i, compute.SecurityPolicy) for i in results) pages = list(client.list(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( "request_type", [compute.ListPreconfiguredExpressionSetsSecurityPoliciesRequest, dict,], ) def test_list_preconfigured_expression_sets_rest(request_type): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding request_init = {"project": "sample1"} request = request_type(request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse.to_json( return_value ) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.list_preconfigured_expression_sets(request) # Establish that the response is the type that we expect. assert isinstance( response, compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse ) def test_list_preconfigured_expression_sets_rest_required_fields( request_type=compute.ListPreconfiguredExpressionSetsSecurityPoliciesRequest, ): transport_class = transports.SecurityPoliciesRestTransport request_init = {} request_init["project"] = "" request = request_type(request_init) jsonified_request = json.loads( request_type.to_json( request, including_default_value_fields=False, use_integers_for_enums=False ) ) # verify fields with default values are dropped unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).list_preconfigured_expression_sets._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["project"] = "project_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).list_preconfigured_expression_sets._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ("max_results", "filter", "order_by", "page_token", "return_partial_success",) ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type(request_init) # Designate an appropriate value for the returned response. return_value = compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. transcode_result = { "uri": "v1/sample_method", "method": "get", "query_params": request_init, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse.to_json( return_value ) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.list_preconfigured_expression_sets(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_list_preconfigured_expression_sets_rest_unset_required_fields(): transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = transport.list_preconfigured_expression_sets._get_unset_required_fields( {} ) assert set(unset_fields) == ( set(("maxResults", "filter", "orderBy", "pageToken", "returnPartialSuccess",)) & set(("project",)) ) def test_list_preconfigured_expression_sets_rest_bad_request( transport: str = "rest", request_type=compute.ListPreconfiguredExpressionSetsSecurityPoliciesRequest, ): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding request_init = {"project": "sample1"} request = request_type(request_init) # Mock the http request call within the method and fake a BadRequest error. with mock.patch.object(Session, "request") as req, pytest.raises( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 response_value.request = Request() req.return_value = response_value client.list_preconfigured_expression_sets(request) def test_list_preconfigured_expression_sets_rest_flattened(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse.to_json( return_value ) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value # get arguments that satisfy an http rule for this method sample_request = {"project": "sample1"} # get truthy value for each flattened field mock_args = dict(project="project_value",) mock_args.update(sample_request) client.list_preconfigured_expression_sets(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( "https://%s/compute/v1/projects/{project}/global/securityPolicies/listPreconfiguredExpressionSets" % client.transport._host, args[1], ) def test_list_preconfigured_expression_sets_rest_flattened_error( transport: str = "rest", ): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.list_preconfigured_expression_sets( compute.ListPreconfiguredExpressionSetsSecurityPoliciesRequest(), project="project_value", ) def test_list_preconfigured_expression_sets_rest_error(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @pytest.mark.parametrize("request_type", [compute.PatchSecurityPolicyRequest, dict,]) def test_patch_unary_rest(request_type): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "security_policy": "sample2"} request_init["security_policy_resource"] = { "adaptive_protection_config": { "layer7_ddos_defense_config": { "enable": True, "rule_visibility": "rule_visibility_value", } }, "advanced_options_config": { "json_parsing": "json_parsing_value", "log_level": "log_level_value", }, "creation_timestamp": "creation_timestamp_value", "description": "description_value", "fingerprint": "fingerprint_value", "id": 205, "kind": "kind_value", "name": "name_value", "rules": [ { "action": "action_value", "description": "description_value", "kind": "kind_value", "match": { "config": { "src_ip_ranges": [ "src_ip_ranges_value_1", "src_ip_ranges_value_2", ] }, "expr": { "description": "description_value", "expression": "expression_value", "location": "location_value", "title": "title_value", }, "versioned_expr": "versioned_expr_value", }, "preview": True, "priority": 898, } ], "self_link": "self_link_value", } request = request_type(request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.Operation( client_operation_id="client_operation_id_value", creation_timestamp="creation_timestamp_value", description="description_value", end_time="end_time_value", http_error_message="http_error_message_value", http_error_status_code=2374, id=205, insert_time="insert_time_value", kind="kind_value", name="name_value", operation_group_id="operation_group_id_value", operation_type="operation_type_value", progress=885, region="region_value", self_link="self_link_value", start_time="start_time_value", status=compute.Operation.Status.DONE, status_message="status_message_value", target_id=947, target_link="target_link_value", user="user_value", zone="zone_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.patch_unary(request) # Establish that the response is the type that we expect. assert isinstance(response, compute.Operation) assert response.client_operation_id == "client_operation_id_value" assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" assert response.end_time == "end_time_value" assert response.http_error_message == "http_error_message_value" assert response.http_error_status_code == 2374 assert response.id == 205 assert response.insert_time == "insert_time_value" assert response.kind == "kind_value" assert response.name == "name_value" assert response.operation_group_id == "operation_group_id_value" assert response.operation_type == "operation_type_value" assert response.progress == 885 assert response.region == "region_value" assert response.self_link == "self_link_value" assert response.start_time == "start_time_value" assert response.status == compute.Operation.Status.DONE assert response.status_message == "status_message_value" assert response.target_id == 947 assert response.target_link == "target_link_value" assert response.user == "user_value" assert response.zone == "zone_value" def test_patch_unary_rest_required_fields( request_type=compute.PatchSecurityPolicyRequest, ): transport_class = transports.SecurityPoliciesRestTransport request_init = {} request_init["project"] = "" request_init["security_policy"] = "" request = request_type(request_init) jsonified_request = json.loads( request_type.to_json( request, including_default_value_fields=False, use_integers_for_enums=False ) ) # verify fields with default values are dropped unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).patch._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["project"] = "project_value" jsonified_request["securityPolicy"] = "security_policy_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).patch._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" assert "securityPolicy" in jsonified_request assert jsonified_request["securityPolicy"] == "security_policy_value" client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type(request_init) # Designate an appropriate value for the returned response. return_value = compute.Operation() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. transcode_result = { "uri": "v1/sample_method", "method": "patch", "query_params": request_init, } transcode_result["body"] = {} transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.patch_unary(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_patch_unary_rest_unset_required_fields(): transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = transport.patch._get_unset_required_fields({}) assert set(unset_fields) == ( set(("requestId",)) & set(("project", "securityPolicy", "securityPolicyResource",)) ) def test_patch_unary_rest_bad_request( transport: str = "rest", request_type=compute.PatchSecurityPolicyRequest ): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "security_policy": "sample2"} request_init["security_policy_resource"] = { "adaptive_protection_config": { "layer7_ddos_defense_config": { "enable": True, "rule_visibility": "rule_visibility_value", } }, "advanced_options_config": { "json_parsing": "json_parsing_value", "log_level": "log_level_value", }, "creation_timestamp": "creation_timestamp_value", "description": "description_value", "fingerprint": "fingerprint_value", "id": 205, "kind": "kind_value", "name": "name_value", "rules": [ { "action": "action_value", "description": "description_value", "kind": "kind_value", "match": { "config": { "src_ip_ranges": [ "src_ip_ranges_value_1", "src_ip_ranges_value_2", ] }, "expr": { "description": "description_value", "expression": "expression_value", "location": "location_value", "title": "title_value", }, "versioned_expr": "versioned_expr_value", }, "preview": True, "priority": 898, } ], "self_link": "self_link_value", } request = request_type(request_init) # Mock the http request call within the method and fake a BadRequest error. with mock.patch.object(Session, "request") as req, pytest.raises( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 response_value.request = Request() req.return_value = response_value client.patch_unary(request) def test_patch_unary_rest_flattened(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.Operation() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value # get arguments that satisfy an http rule for this method sample_request = {"project": "sample1", "security_policy": "sample2"} # get truthy value for each flattened field mock_args = dict( project="project_value", security_policy="security_policy_value", security_policy_resource=compute.SecurityPolicy( adaptive_protection_config=compute.SecurityPolicyAdaptiveProtectionConfig( layer7_ddos_defense_config=compute.SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfig( enable=True ) ) ), ) mock_args.update(sample_request) client.patch_unary(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( "https://%s/compute/v1/projects/{project}/global/securityPolicies/{security_policy}" % client.transport._host, args[1], ) def test_patch_unary_rest_flattened_error(transport: str = "rest"): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.patch_unary( compute.PatchSecurityPolicyRequest(), project="project_value", security_policy="security_policy_value", security_policy_resource=compute.SecurityPolicy( adaptive_protection_config=compute.SecurityPolicyAdaptiveProtectionConfig( layer7_ddos_defense_config=compute.SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfig( enable=True ) ) ), ) def test_patch_unary_rest_error(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @pytest.mark.parametrize( "request_type", [compute.PatchRuleSecurityPolicyRequest, dict,] ) def test_patch_rule_unary_rest(request_type): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "security_policy": "sample2"} request_init["security_policy_rule_resource"] = { "action": "action_value", "description": "description_value", "kind": "kind_value", "match": { "config": { "src_ip_ranges": ["src_ip_ranges_value_1", "src_ip_ranges_value_2"] }, "expr": { "description": "description_value", "expression": "expression_value", "location": "location_value", "title": "title_value", }, "versioned_expr": "versioned_expr_value", }, "preview": True, "priority": 898, } request = request_type(request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.Operation( client_operation_id="client_operation_id_value", creation_timestamp="creation_timestamp_value", description="description_value", end_time="end_time_value", http_error_message="http_error_message_value", http_error_status_code=2374, id=205, insert_time="insert_time_value", kind="kind_value", name="name_value", operation_group_id="operation_group_id_value", operation_type="operation_type_value", progress=885, region="region_value", self_link="self_link_value", start_time="start_time_value", status=compute.Operation.Status.DONE, status_message="status_message_value", target_id=947, target_link="target_link_value", user="user_value", zone="zone_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.patch_rule_unary(request) # Establish that the response is the type that we expect. assert isinstance(response, compute.Operation) assert response.client_operation_id == "client_operation_id_value" assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" assert response.end_time == "end_time_value" assert response.http_error_message == "http_error_message_value" assert response.http_error_status_code == 2374 assert response.id == 205 assert response.insert_time == "insert_time_value" assert response.kind == "kind_value" assert response.name == "name_value" assert response.operation_group_id == "operation_group_id_value" assert response.operation_type == "operation_type_value" assert response.progress == 885 assert response.region == "region_value" assert response.self_link == "self_link_value" assert response.start_time == "start_time_value" assert response.status == compute.Operation.Status.DONE assert response.status_message == "status_message_value" assert response.target_id == 947 assert response.target_link == "target_link_value" assert response.user == "user_value" assert response.zone == "zone_value" def test_patch_rule_unary_rest_required_fields( request_type=compute.PatchRuleSecurityPolicyRequest, ): transport_class = transports.SecurityPoliciesRestTransport request_init = {} request_init["project"] = "" request_init["security_policy"] = "" request = request_type(request_init) jsonified_request = json.loads( request_type.to_json( request, including_default_value_fields=False, use_integers_for_enums=False ) ) # verify fields with default values are dropped unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).patch_rule._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["project"] = "project_value" jsonified_request["securityPolicy"] = "security_policy_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).patch_rule._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set(("priority",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" assert "securityPolicy" in jsonified_request assert jsonified_request["securityPolicy"] == "security_policy_value" client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type(request_init) # Designate an appropriate value for the returned response. return_value = compute.Operation() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. transcode_result = { "uri": "v1/sample_method", "method": "post", "query_params": request_init, } transcode_result["body"] = {} transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.patch_rule_unary(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_patch_rule_unary_rest_unset_required_fields(): transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = transport.patch_rule._get_unset_required_fields({}) assert set(unset_fields) == ( set(("priority",)) & set(("project", "securityPolicy", "securityPolicyRuleResource",)) ) def test_patch_rule_unary_rest_bad_request( transport: str = "rest", request_type=compute.PatchRuleSecurityPolicyRequest ): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "security_policy": "sample2"} request_init["security_policy_rule_resource"] = { "action": "action_value", "description": "description_value", "kind": "kind_value", "match": { "config": { "src_ip_ranges": ["src_ip_ranges_value_1", "src_ip_ranges_value_2"] }, "expr": { "description": "description_value", "expression": "expression_value", "location": "location_value", "title": "title_value", }, "versioned_expr": "versioned_expr_value", }, "preview": True, "priority": 898, } request = request_type(request_init) # Mock the http request call within the method and fake a BadRequest error. with mock.patch.object(Session, "request") as req, pytest.raises( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 response_value.request = Request() req.return_value = response_value client.patch_rule_unary(request) def test_patch_rule_unary_rest_flattened(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.Operation() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value # get arguments that satisfy an http rule for this method sample_request = {"project": "sample1", "security_policy": "sample2"} # get truthy value for each flattened field mock_args = dict( project="project_value", security_policy="security_policy_value", security_policy_rule_resource=compute.SecurityPolicyRule( action="action_value" ), ) mock_args.update(sample_request) client.patch_rule_unary(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( "https://%s/compute/v1/projects/{project}/global/securityPolicies/{security_policy}/patchRule" % client.transport._host, args[1], ) def test_patch_rule_unary_rest_flattened_error(transport: str = "rest"): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.patch_rule_unary( compute.PatchRuleSecurityPolicyRequest(), project="project_value", security_policy="security_policy_value", security_policy_rule_resource=compute.SecurityPolicyRule( action="action_value" ), ) def test_patch_rule_unary_rest_error(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @pytest.mark.parametrize( "request_type", [compute.RemoveRuleSecurityPolicyRequest, dict,] ) def test_remove_rule_unary_rest(request_type): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "security_policy": "sample2"} request = request_type(request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.Operation( client_operation_id="client_operation_id_value", creation_timestamp="creation_timestamp_value", description="description_value", end_time="end_time_value", http_error_message="http_error_message_value", http_error_status_code=2374, id=205, insert_time="insert_time_value", kind="kind_value", name="name_value", operation_group_id="operation_group_id_value", operation_type="operation_type_value", progress=885, region="region_value", self_link="self_link_value", start_time="start_time_value", status=compute.Operation.Status.DONE, status_message="status_message_value", target_id=947, target_link="target_link_value", user="user_value", zone="zone_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.remove_rule_unary(request) # Establish that the response is the type that we expect. assert isinstance(response, compute.Operation) assert response.client_operation_id == "client_operation_id_value" assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" assert response.end_time == "end_time_value" assert response.http_error_message == "http_error_message_value" assert response.http_error_status_code == 2374 assert response.id == 205 assert response.insert_time == "insert_time_value" assert response.kind == "kind_value" assert response.name == "name_value" assert response.operation_group_id == "operation_group_id_value" assert response.operation_type == "operation_type_value" assert response.progress == 885 assert response.region == "region_value" assert response.self_link == "self_link_value" assert response.start_time == "start_time_value" assert response.status == compute.Operation.Status.DONE assert response.status_message == "status_message_value" assert response.target_id == 947 assert response.target_link == "target_link_value" assert response.user == "user_value" assert response.zone == "zone_value" def test_remove_rule_unary_rest_required_fields( request_type=compute.RemoveRuleSecurityPolicyRequest, ): transport_class = transports.SecurityPoliciesRestTransport request_init = {} request_init["project"] = "" request_init["security_policy"] = "" request = request_type(request_init) jsonified_request = json.loads( request_type.to_json( request, including_default_value_fields=False, use_integers_for_enums=False ) ) # verify fields with default values are dropped unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).remove_rule._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["project"] = "project_value" jsonified_request["securityPolicy"] = "security_policy_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).remove_rule._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set(("priority",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" assert "securityPolicy" in jsonified_request assert jsonified_request["securityPolicy"] == "security_policy_value" client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type(request_init) # Designate an appropriate value for the returned response. return_value = compute.Operation() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. transcode_result = { "uri": "v1/sample_method", "method": "post", "query_params": request_init, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.remove_rule_unary(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_remove_rule_unary_rest_unset_required_fields(): transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = transport.remove_rule._get_unset_required_fields({}) assert set(unset_fields) == ( set(("priority",)) & set(("project", "securityPolicy",)) ) def test_remove_rule_unary_rest_bad_request( transport: str = "rest", request_type=compute.RemoveRuleSecurityPolicyRequest ): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "security_policy": "sample2"} request = request_type(request_init) # Mock the http request call within the method and fake a BadRequest error. with mock.patch.object(Session, "request") as req, pytest.raises( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 response_value.request = Request() req.return_value = response_value client.remove_rule_unary(request) def test_remove_rule_unary_rest_flattened(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.Operation() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value # get arguments that satisfy an http rule for this method sample_request = {"project": "sample1", "security_policy": "sample2"} # get truthy value for each flattened field mock_args = dict( project="project_value", security_policy="security_policy_value", ) mock_args.update(sample_request) client.remove_rule_unary(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( "https://%s/compute/v1/projects/{project}/global/securityPolicies/{security_policy}/removeRule" % client.transport._host, args[1], ) def test_remove_rule_unary_rest_flattened_error(transport: str = "rest"): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.remove_rule_unary( compute.RemoveRuleSecurityPolicyRequest(), project="project_value", security_policy="security_policy_value", ) def test_remove_rule_unary_rest_error(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SecurityPoliciesClient( client_options={"credentials_file": "credentials.json"}, transport=transport, ) # It is an error to provide an api_key and a transport instance. transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials(), ) options = client_options.ClientOptions() options.api_key = "api_key" with pytest.raises(ValueError): client = SecurityPoliciesClient(client_options=options, transport=transport,) # It is an error to provide an api_key and a credential. options = mock.Mock() options.api_key = "api_key" with pytest.raises(ValueError): client = SecurityPoliciesClient( client_options=options, credentials=ga_credentials.AnonymousCredentials() ) # It is an error to provide scopes and a transport instance. transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SecurityPoliciesClient( client_options={"scopes": ["1", "2"]}, transport=transport, ) def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials(), ) client = SecurityPoliciesClient(transport=transport) assert client.transport is transport @pytest.mark.parametrize("transport_class", [transports.SecurityPoliciesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. with mock.patch.object(google.auth, "default") as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_security_policies_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.SecurityPoliciesTransport( credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) def test_security_policies_base_transport(): # Instantiate the base transport. with mock.patch( "google.cloud.compute_v1.services.security_policies.transports.SecurityPoliciesTransport.__init__" ) as Transport: Transport.return_value = None transport = transports.SecurityPoliciesTransport( credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly # raise NotImplementedError. methods = ( "add_rule", "delete", "get", "get_rule", "insert", "list", "list_preconfigured_expression_sets", "patch", "patch_rule", "remove_rule", ) for method in methods: with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) with pytest.raises(NotImplementedError): transport.close() def test_security_policies_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.security_policies.transports.SecurityPoliciesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SecurityPoliciesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) load_creds.assert_called_once_with( "credentials.json", scopes=None, default_scopes=( "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/cloud-platform", ), quota_project_id="octopus", ) def test_security_policies_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.security_policies.transports.SecurityPoliciesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SecurityPoliciesTransport() adc.assert_called_once() def test_security_policies_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) SecurityPoliciesClient() adc.assert_called_once_with( scopes=None, default_scopes=( "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/cloud-platform", ), quota_project_id=None, ) def test_security_policies_http_transport_client_cert_source_for_mtls(): cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: transports.SecurityPoliciesRestTransport( credentials=cred, client_cert_source_for_mtls=client_cert_source_callback ) mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) def test_security_policies_host_no_port(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), ) assert client.transport._host == "compute.googleapis.com:443" def test_security_policies_host_with_port(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), ) assert client.transport._host == "compute.googleapis.com:8000" def test_common_billing_account_path(): billing_account = "squid" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) actual = SecurityPoliciesClient.common_billing_account_path(billing_account) assert expected == actual def test_parse_common_billing_account_path(): expected = { "billing_account": "clam", } path = SecurityPoliciesClient.common_billing_account_path(**expected) # Check that the path construction is reversible. actual = SecurityPoliciesClient.parse_common_billing_account_path(path) assert expected == actual def test_common_folder_path(): folder = "whelk" expected = "folders/{folder}".format(folder=folder,) actual = SecurityPoliciesClient.common_folder_path(folder) assert expected == actual def test_parse_common_folder_path(): expected = { "folder": "octopus", } path = SecurityPoliciesClient.common_folder_path(**expected) # Check that the path construction is reversible. actual = SecurityPoliciesClient.parse_common_folder_path(path) assert expected == actual def test_common_organization_path(): organization = "oyster" expected = "organizations/{organization}".format(organization=organization,) actual = SecurityPoliciesClient.common_organization_path(organization) assert expected == actual def test_parse_common_organization_path(): expected = { "organization": "nudibranch", } path = SecurityPoliciesClient.common_organization_path(**expected) # Check that the path construction is reversible. actual = SecurityPoliciesClient.parse_common_organization_path(path) assert expected == actual def test_common_project_path(): project = "cuttlefish" expected = "projects/{project}".format(project=project,) actual = SecurityPoliciesClient.common_project_path(project) assert expected == actual def test_parse_common_project_path(): expected = { "project": "mussel", } path = SecurityPoliciesClient.common_project_path(**expected) # Check that the path construction is reversible. actual = SecurityPoliciesClient.parse_common_project_path(path) assert expected == actual def test_common_location_path(): project = "winkle" location = "nautilus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) actual = SecurityPoliciesClient.common_location_path(project, location) assert expected == actual def test_parse_common_location_path(): expected = { "project": "scallop", "location": "abalone", } path = SecurityPoliciesClient.common_location_path(**expected) # Check that the path construction is reversible. actual = SecurityPoliciesClient.parse_common_location_path(path) assert expected == actual def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() with mock.patch.object( transports.SecurityPoliciesTransport, "_prep_wrapped_messages" ) as prep: client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) with mock.patch.object( transports.SecurityPoliciesTransport, "_prep_wrapped_messages" ) as prep: transport_class = SecurityPoliciesClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) def test_transport_close(): transports = { "rest": "_session", } for transport, close_name in transports.items(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport ) with mock.patch.object( type(getattr(client.transport, close_name)), "close" ) as close: with client: close.assert_not_called() close.assert_called_once() def test_client_ctx(): transports = [ "rest", ] for transport in transports: client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport ) # Test client calls underlying transport. with mock.patch.object(type(client.transport), "close") as close: close.assert_not_called() with client: pass close.assert_called() @pytest.mark.parametrize( "client_class,transport_class", [(SecurityPoliciesClient, transports.SecurityPoliciesRestTransport),], ) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True ) as get_api_key_credentials: mock_cred = mock.Mock() get_api_key_credentials.return_value = mock_cred options = client_options.ClientOptions() options.api_key = "api_key" with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options) patched.assert_called_once_with( credentials=mock_cred, credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, )
39.004049
120
0.677363
import os import mock import grpc from grpc.experimental import aio import json import math import pytest from proto.marshal.rules.dates import DurationRule, TimestampRule from requests import Response from requests import Request, PreparedRequest from requests.sessions import Session from google.api_core import client_options from google.api_core import exceptions as core_exceptions from google.api_core import gapic_v1 from google.api_core import grpc_helpers from google.api_core import grpc_helpers_async from google.api_core import path_template from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError from google.cloud.compute_v1.services.security_policies import SecurityPoliciesClient from google.cloud.compute_v1.services.security_policies import pagers from google.cloud.compute_v1.services.security_policies import transports from google.cloud.compute_v1.types import compute from google.oauth2 import service_account import google.auth def client_cert_source_callback(): return b"cert bytes", b"key bytes" def modify_default_endpoint(client): return ( "foo.googleapis.com" if ("localhost" in client.DEFAULT_ENDPOINT) else client.DEFAULT_ENDPOINT ) def test__get_default_mtls_endpoint(): api_endpoint = "example.googleapis.com" api_mtls_endpoint = "example.mtls.googleapis.com" sandbox_endpoint = "example.sandbox.googleapis.com" sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" non_googleapi = "api.example.com" assert SecurityPoliciesClient._get_default_mtls_endpoint(None) is None assert ( SecurityPoliciesClient._get_default_mtls_endpoint(api_endpoint) == api_mtls_endpoint ) assert ( SecurityPoliciesClient._get_default_mtls_endpoint(api_mtls_endpoint) == api_mtls_endpoint ) assert ( SecurityPoliciesClient._get_default_mtls_endpoint(sandbox_endpoint) == sandbox_mtls_endpoint ) assert ( SecurityPoliciesClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) == sandbox_mtls_endpoint ) assert ( SecurityPoliciesClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi ) @pytest.mark.parametrize("client_class", [SecurityPoliciesClient,]) def test_security_policies_client_from_service_account_info(client_class): creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_info" ) as factory: factory.return_value = creds info = {"valid": True} client = client_class.from_service_account_info(info) assert client.transport._credentials == creds assert isinstance(client, client_class) assert client.transport._host == "compute.googleapis.com:443" @pytest.mark.parametrize( "transport_class,transport_name", [(transports.SecurityPoliciesRestTransport, "rest"),], ) def test_security_policies_client_service_account_always_use_jwt( transport_class, transport_name ): with mock.patch.object( service_account.Credentials, "with_always_use_jwt_access", create=True ) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=True) use_jwt.assert_called_once_with(True) with mock.patch.object( service_account.Credentials, "with_always_use_jwt_access", create=True ) as use_jwt: creds = service_account.Credentials(None, None, None) transport = transport_class(credentials=creds, always_use_jwt_access=False) use_jwt.assert_not_called() @pytest.mark.parametrize("client_class", [SecurityPoliciesClient,]) def test_security_policies_client_from_service_account_file(client_class): creds = ga_credentials.AnonymousCredentials() with mock.patch.object( service_account.Credentials, "from_service_account_file" ) as factory: factory.return_value = creds client = client_class.from_service_account_file("dummy/file/path.json") assert client.transport._credentials == creds assert isinstance(client, client_class) client = client_class.from_service_account_json("dummy/file/path.json") assert client.transport._credentials == creds assert isinstance(client, client_class) assert client.transport._host == "compute.googleapis.com:443" def test_security_policies_client_get_transport_class(): transport = SecurityPoliciesClient.get_transport_class() available_transports = [ transports.SecurityPoliciesRestTransport, ] assert transport in available_transports transport = SecurityPoliciesClient.get_transport_class("rest") assert transport == transports.SecurityPoliciesRestTransport @pytest.mark.parametrize( "client_class,transport_class,transport_name", [(SecurityPoliciesClient, transports.SecurityPoliciesRestTransport, "rest"),], ) @mock.patch.object( SecurityPoliciesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityPoliciesClient), ) def test_security_policies_client_client_options( client_class, transport_class, transport_name ): with mock.patch.object(SecurityPoliciesClient, "get_transport_class") as gtc: transport = transport_class(credentials=ga_credentials.AnonymousCredentials()) client = client_class(transport=transport) gtc.assert_not_called() # Check that if channel is provided via str we will create a new one. with mock.patch.object(SecurityPoliciesClient, "get_transport_class") as gtc: client = client_class(transport=transport_name) gtc.assert_called() # Check the case api_endpoint is provided. options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name, client_options=options) patched.assert_called_once_with( credentials=None, credentials_file=None, host="squid.clam.whelk", scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is # "always". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, host=client.DEFAULT_MTLS_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has # unsupported value. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): with pytest.raises(MutualTLSChannelError): client = client_class(transport=transport_name) # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} ): with pytest.raises(ValueError): client = client_class(transport=transport_name) # Check the case quota_project_id is provided options = client_options.ClientOptions(quota_project_id="octopus") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id="octopus", client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) @pytest.mark.parametrize( "client_class,transport_class,transport_name,use_client_cert_env", [ ( SecurityPoliciesClient, transports.SecurityPoliciesRestTransport, "rest", "true", ), ( SecurityPoliciesClient, transports.SecurityPoliciesRestTransport, "rest", "false", ), ], ) @mock.patch.object( SecurityPoliciesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityPoliciesClient), ) @mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) def test_security_policies_client_mtls_env_auto( client_class, transport_class, transport_name, use_client_cert_env ): # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. # Check the case client_cert_source is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} ): options = client_options.ClientOptions( client_cert_source=client_cert_source_callback ) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) if use_client_cert_env == "false": expected_client_cert_source = None expected_host = client.DEFAULT_ENDPOINT else: expected_client_cert_source = client_cert_source_callback expected_host = client.DEFAULT_MTLS_ENDPOINT patched.assert_called_once_with( credentials=None, credentials_file=None, host=expected_host, scopes=None, client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) # Check the case ADC client cert is provided. Whether client cert is used depends on # GOOGLE_API_USE_CLIENT_CERTIFICATE value. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} ): with mock.patch.object(transport_class, "__init__") as patched: with mock.patch( "google.auth.transport.mtls.has_default_client_cert_source", return_value=True, ): with mock.patch( "google.auth.transport.mtls.default_client_cert_source", return_value=client_cert_source_callback, ): if use_client_cert_env == "false": expected_host = client.DEFAULT_ENDPOINT expected_client_cert_source = None else: expected_host = client.DEFAULT_MTLS_ENDPOINT expected_client_cert_source = client_cert_source_callback patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, host=expected_host, scopes=None, client_cert_source_for_mtls=expected_client_cert_source, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) # Check the case client_cert_source and ADC client cert are not provided. with mock.patch.dict( os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} ): with mock.patch.object(transport_class, "__init__") as patched: with mock.patch( "google.auth.transport.mtls.has_default_client_cert_source", return_value=False, ): patched.return_value = None client = client_class(transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) @pytest.mark.parametrize("client_class", [SecurityPoliciesClient]) @mock.patch.object( SecurityPoliciesClient, "DEFAULT_ENDPOINT", modify_default_endpoint(SecurityPoliciesClient), ) def test_security_policies_client_get_mtls_endpoint_and_cert_source(client_class): mock_client_cert_source = mock.Mock() # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "true". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): mock_api_endpoint = "foo" options = client_options.ClientOptions( client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint ) api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( options ) assert api_endpoint == mock_api_endpoint assert cert_source == mock_client_cert_source # Test the case GOOGLE_API_USE_CLIENT_CERTIFICATE is "false". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "false"}): mock_client_cert_source = mock.Mock() mock_api_endpoint = "foo" options = client_options.ClientOptions( client_cert_source=mock_client_cert_source, api_endpoint=mock_api_endpoint ) api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source( options ) assert api_endpoint == mock_api_endpoint assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "never". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "always". with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source is None # Test the case GOOGLE_API_USE_MTLS_ENDPOINT is "auto" and default cert doesn't exist. with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): with mock.patch( "google.auth.transport.mtls.has_default_client_cert_source", return_value=False, ): api_endpoint, cert_source = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_ENDPOINT assert cert_source is None with mock.patch.dict(os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "true"}): with mock.patch( "google.auth.transport.mtls.has_default_client_cert_source", return_value=True, ): with mock.patch( "google.auth.transport.mtls.default_client_cert_source", return_value=mock_client_cert_source, ): ( api_endpoint, cert_source, ) = client_class.get_mtls_endpoint_and_cert_source() assert api_endpoint == client_class.DEFAULT_MTLS_ENDPOINT assert cert_source == mock_client_cert_source @pytest.mark.parametrize( "client_class,transport_class,transport_name", [(SecurityPoliciesClient, transports.SecurityPoliciesRestTransport, "rest"),], ) def test_security_policies_client_client_options_scopes( client_class, transport_class, transport_name ): options = client_options.ClientOptions(scopes=["1", "2"],) with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=["1", "2"], client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) @pytest.mark.parametrize( "client_class,transport_class,transport_name", [(SecurityPoliciesClient, transports.SecurityPoliciesRestTransport, "rest"),], ) def test_security_policies_client_client_options_credentials_file( client_class, transport_class, transport_name ): options = client_options.ClientOptions(credentials_file="credentials.json") with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options, transport=transport_name) patched.assert_called_once_with( credentials=None, credentials_file="credentials.json", host=client.DEFAULT_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, ) @pytest.mark.parametrize("request_type", [compute.AddRuleSecurityPolicyRequest, dict,]) def test_add_rule_unary_rest(request_type): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request_init = {"project": "sample1", "security_policy": "sample2"} request_init["security_policy_rule_resource"] = { "action": "action_value", "description": "description_value", "kind": "kind_value", "match": { "config": { "src_ip_ranges": ["src_ip_ranges_value_1", "src_ip_ranges_value_2"] }, "expr": { "description": "description_value", "expression": "expression_value", "location": "location_value", "title": "title_value", }, "versioned_expr": "versioned_expr_value", }, "preview": True, "priority": 898, } request = request_type(request_init) with mock.patch.object(type(client.transport._session), "request") as req: return_value = compute.Operation( client_operation_id="client_operation_id_value", creation_timestamp="creation_timestamp_value", description="description_value", end_time="end_time_value", http_error_message="http_error_message_value", http_error_status_code=2374, id=205, insert_time="insert_time_value", kind="kind_value", name="name_value", operation_group_id="operation_group_id_value", operation_type="operation_type_value", progress=885, region="region_value", self_link="self_link_value", start_time="start_time_value", status=compute.Operation.Status.DONE, status_message="status_message_value", target_id=947, target_link="target_link_value", user="user_value", zone="zone_value", ) response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.add_rule_unary(request) assert isinstance(response, compute.Operation) assert response.client_operation_id == "client_operation_id_value" assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" assert response.end_time == "end_time_value" assert response.http_error_message == "http_error_message_value" assert response.http_error_status_code == 2374 assert response.id == 205 assert response.insert_time == "insert_time_value" assert response.kind == "kind_value" assert response.name == "name_value" assert response.operation_group_id == "operation_group_id_value" assert response.operation_type == "operation_type_value" assert response.progress == 885 assert response.region == "region_value" assert response.self_link == "self_link_value" assert response.start_time == "start_time_value" assert response.status == compute.Operation.Status.DONE assert response.status_message == "status_message_value" assert response.target_id == 947 assert response.target_link == "target_link_value" assert response.user == "user_value" assert response.zone == "zone_value" def test_add_rule_unary_rest_required_fields( request_type=compute.AddRuleSecurityPolicyRequest, ): transport_class = transports.SecurityPoliciesRestTransport request_init = {} request_init["project"] = "" request_init["security_policy"] = "" request = request_type(request_init) jsonified_request = json.loads( request_type.to_json( request, including_default_value_fields=False, use_integers_for_enums=False ) ) unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).add_rule._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) jsonified_request["project"] = "project_value" jsonified_request["securityPolicy"] = "security_policy_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).add_rule._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" assert "securityPolicy" in jsonified_request assert jsonified_request["securityPolicy"] == "security_policy_value" client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type(request_init) return_value = compute.Operation() with mock.patch.object(Session, "request") as req: with mock.patch.object(path_template, "transcode") as transcode: transcode_result = { "uri": "v1/sample_method", "method": "post", "query_params": request_init, } transcode_result["body"] = {} transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.add_rule_unary(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_add_rule_unary_rest_unset_required_fields(): transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = transport.add_rule._get_unset_required_fields({}) assert set(unset_fields) == ( set(()) & set(("project", "securityPolicy", "securityPolicyRuleResource",)) ) def test_add_rule_unary_rest_bad_request( transport: str = "rest", request_type=compute.AddRuleSecurityPolicyRequest ): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) request_init = {"project": "sample1", "security_policy": "sample2"} request_init["security_policy_rule_resource"] = { "action": "action_value", "description": "description_value", "kind": "kind_value", "match": { "config": { "src_ip_ranges": ["src_ip_ranges_value_1", "src_ip_ranges_value_2"] }, "expr": { "description": "description_value", "expression": "expression_value", "location": "location_value", "title": "title_value", }, "versioned_expr": "versioned_expr_value", }, "preview": True, "priority": 898, } request = request_type(request_init) with mock.patch.object(Session, "request") as req, pytest.raises( core_exceptions.BadRequest ): response_value = Response() response_value.status_code = 400 response_value.request = Request() req.return_value = response_value client.add_rule_unary(request) def test_add_rule_unary_rest_flattened(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) with mock.patch.object(type(client.transport._session), "request") as req: return_value = compute.Operation() response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value sample_request = {"project": "sample1", "security_policy": "sample2"} mock_args = dict( project="project_value", security_policy="security_policy_value", security_policy_rule_resource=compute.SecurityPolicyRule( action="action_value" ), ) mock_args.update(sample_request) client.add_rule_unary(**mock_args) assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( "https://%s/compute/v1/projects/{project}/global/securityPolicies/{security_policy}/addRule" % client.transport._host, args[1], ) def test_add_rule_unary_rest_flattened_error(transport: str = "rest"): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) with pytest.raises(ValueError): client.add_rule_unary( compute.AddRuleSecurityPolicyRequest(), project="project_value", security_policy="security_policy_value", security_policy_rule_resource=compute.SecurityPolicyRule( action="action_value" ), ) def test_add_rule_unary_rest_error(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @pytest.mark.parametrize("request_type", [compute.DeleteSecurityPolicyRequest, dict,]) def test_delete_unary_rest(request_type): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request_init = {"project": "sample1", "security_policy": "sample2"} request = request_type(request_init) with mock.patch.object(type(client.transport._session), "request") as req: return_value = compute.Operation( client_operation_id="client_operation_id_value", creation_timestamp="creation_timestamp_value", description="description_value", end_time="end_time_value", http_error_message="http_error_message_value", http_error_status_code=2374, id=205, insert_time="insert_time_value", kind="kind_value", name="name_value", operation_group_id="operation_group_id_value", operation_type="operation_type_value", progress=885, region="region_value", self_link="self_link_value", start_time="start_time_value", status=compute.Operation.Status.DONE, status_message="status_message_value", target_id=947, target_link="target_link_value", user="user_value", zone="zone_value", ) response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.delete_unary(request) assert isinstance(response, compute.Operation) assert response.client_operation_id == "client_operation_id_value" assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" assert response.end_time == "end_time_value" assert response.http_error_message == "http_error_message_value" assert response.http_error_status_code == 2374 assert response.id == 205 assert response.insert_time == "insert_time_value" assert response.kind == "kind_value" assert response.name == "name_value" assert response.operation_group_id == "operation_group_id_value" assert response.operation_type == "operation_type_value" assert response.progress == 885 assert response.region == "region_value" assert response.self_link == "self_link_value" assert response.start_time == "start_time_value" assert response.status == compute.Operation.Status.DONE assert response.status_message == "status_message_value" assert response.target_id == 947 assert response.target_link == "target_link_value" assert response.user == "user_value" assert response.zone == "zone_value" def test_delete_unary_rest_required_fields( request_type=compute.DeleteSecurityPolicyRequest, ): transport_class = transports.SecurityPoliciesRestTransport request_init = {} request_init["project"] = "" request_init["security_policy"] = "" request = request_type(request_init) jsonified_request = json.loads( request_type.to_json( request, including_default_value_fields=False, use_integers_for_enums=False ) ) unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).delete._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) jsonified_request["project"] = "project_value" jsonified_request["securityPolicy"] = "security_policy_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).delete._get_unset_required_fields(jsonified_request) assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" assert "securityPolicy" in jsonified_request assert jsonified_request["securityPolicy"] == "security_policy_value" client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type(request_init) return_value = compute.Operation() with mock.patch.object(Session, "request") as req: with mock.patch.object(path_template, "transcode") as transcode: transcode_result = { "uri": "v1/sample_method", "method": "delete", "query_params": request_init, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.delete_unary(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_delete_unary_rest_unset_required_fields(): transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = transport.delete._get_unset_required_fields({}) assert set(unset_fields) == ( set(("requestId",)) & set(("project", "securityPolicy",)) ) def test_delete_unary_rest_bad_request( transport: str = "rest", request_type=compute.DeleteSecurityPolicyRequest ): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) request_init = {"project": "sample1", "security_policy": "sample2"} request = request_type(request_init) with mock.patch.object(Session, "request") as req, pytest.raises( core_exceptions.BadRequest ): response_value = Response() response_value.status_code = 400 response_value.request = Request() req.return_value = response_value client.delete_unary(request) def test_delete_unary_rest_flattened(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) with mock.patch.object(type(client.transport._session), "request") as req: return_value = compute.Operation() response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value sample_request = {"project": "sample1", "security_policy": "sample2"} mock_args = dict( project="project_value", security_policy="security_policy_value", ) mock_args.update(sample_request) client.delete_unary(**mock_args) assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( "https://%s/compute/v1/projects/{project}/global/securityPolicies/{security_policy}" % client.transport._host, args[1], ) def test_delete_unary_rest_flattened_error(transport: str = "rest"): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) with pytest.raises(ValueError): client.delete_unary( compute.DeleteSecurityPolicyRequest(), project="project_value", security_policy="security_policy_value", ) def test_delete_unary_rest_error(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @pytest.mark.parametrize("request_type", [compute.GetSecurityPolicyRequest, dict,]) def test_get_rest(request_type): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request_init = {"project": "sample1", "security_policy": "sample2"} request = request_type(request_init) with mock.patch.object(type(client.transport._session), "request") as req: return_value = compute.SecurityPolicy( creation_timestamp="creation_timestamp_value", description="description_value", fingerprint="fingerprint_value", id=205, kind="kind_value", name="name_value", self_link="self_link_value", ) response_value = Response() response_value.status_code = 200 json_return_value = compute.SecurityPolicy.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.get(request) assert isinstance(response, compute.SecurityPolicy) assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" assert response.fingerprint == "fingerprint_value" assert response.id == 205 assert response.kind == "kind_value" assert response.name == "name_value" assert response.self_link == "self_link_value" def test_get_rest_required_fields(request_type=compute.GetSecurityPolicyRequest): transport_class = transports.SecurityPoliciesRestTransport request_init = {} request_init["project"] = "" request_init["security_policy"] = "" request = request_type(request_init) jsonified_request = json.loads( request_type.to_json( request, including_default_value_fields=False, use_integers_for_enums=False ) ) unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).get._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) jsonified_request["project"] = "project_value" jsonified_request["securityPolicy"] = "security_policy_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).get._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" assert "securityPolicy" in jsonified_request assert jsonified_request["securityPolicy"] == "security_policy_value" client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type(request_init) return_value = compute.SecurityPolicy() with mock.patch.object(Session, "request") as req: with mock.patch.object(path_template, "transcode") as transcode: transcode_result = { "uri": "v1/sample_method", "method": "get", "query_params": request_init, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = compute.SecurityPolicy.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.get(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_rest_unset_required_fields(): transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = transport.get._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("project", "securityPolicy",))) def test_get_rest_bad_request( transport: str = "rest", request_type=compute.GetSecurityPolicyRequest ): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) request_init = {"project": "sample1", "security_policy": "sample2"} request = request_type(request_init) with mock.patch.object(Session, "request") as req, pytest.raises( core_exceptions.BadRequest ): response_value = Response() response_value.status_code = 400 response_value.request = Request() req.return_value = response_value client.get(request) def test_get_rest_flattened(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) with mock.patch.object(type(client.transport._session), "request") as req: return_value = compute.SecurityPolicy() response_value = Response() response_value.status_code = 200 json_return_value = compute.SecurityPolicy.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value sample_request = {"project": "sample1", "security_policy": "sample2"} mock_args = dict( project="project_value", security_policy="security_policy_value", ) mock_args.update(sample_request) client.get(**mock_args) assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( "https://%s/compute/v1/projects/{project}/global/securityPolicies/{security_policy}" % client.transport._host, args[1], ) def test_get_rest_flattened_error(transport: str = "rest"): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) with pytest.raises(ValueError): client.get( compute.GetSecurityPolicyRequest(), project="project_value", security_policy="security_policy_value", ) def test_get_rest_error(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @pytest.mark.parametrize("request_type", [compute.GetRuleSecurityPolicyRequest, dict,]) def test_get_rule_rest(request_type): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request_init = {"project": "sample1", "security_policy": "sample2"} request = request_type(request_init) with mock.patch.object(type(client.transport._session), "request") as req: return_value = compute.SecurityPolicyRule( action="action_value", description="description_value", kind="kind_value", preview=True, priority=898, ) response_value = Response() response_value.status_code = 200 json_return_value = compute.SecurityPolicyRule.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.get_rule(request) assert isinstance(response, compute.SecurityPolicyRule) assert response.action == "action_value" assert response.description == "description_value" assert response.kind == "kind_value" assert response.preview is True assert response.priority == 898 def test_get_rule_rest_required_fields( request_type=compute.GetRuleSecurityPolicyRequest, ): transport_class = transports.SecurityPoliciesRestTransport request_init = {} request_init["project"] = "" request_init["security_policy"] = "" request = request_type(request_init) jsonified_request = json.loads( request_type.to_json( request, including_default_value_fields=False, use_integers_for_enums=False ) ) unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).get_rule._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) jsonified_request["project"] = "project_value" jsonified_request["securityPolicy"] = "security_policy_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).get_rule._get_unset_required_fields(jsonified_request) assert not set(unset_fields) - set(("priority",)) jsonified_request.update(unset_fields) assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" assert "securityPolicy" in jsonified_request assert jsonified_request["securityPolicy"] == "security_policy_value" client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type(request_init) return_value = compute.SecurityPolicyRule() with mock.patch.object(Session, "request") as req: with mock.patch.object(path_template, "transcode") as transcode: transcode_result = { "uri": "v1/sample_method", "method": "get", "query_params": request_init, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = compute.SecurityPolicyRule.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.get_rule(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_get_rule_rest_unset_required_fields(): transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = transport.get_rule._get_unset_required_fields({}) assert set(unset_fields) == ( set(("priority",)) & set(("project", "securityPolicy",)) ) def test_get_rule_rest_bad_request( transport: str = "rest", request_type=compute.GetRuleSecurityPolicyRequest ): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) request_init = {"project": "sample1", "security_policy": "sample2"} request = request_type(request_init) with mock.patch.object(Session, "request") as req, pytest.raises( core_exceptions.BadRequest ): response_value = Response() response_value.status_code = 400 response_value.request = Request() req.return_value = response_value client.get_rule(request) def test_get_rule_rest_flattened(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) with mock.patch.object(type(client.transport._session), "request") as req: return_value = compute.SecurityPolicyRule() response_value = Response() response_value.status_code = 200 json_return_value = compute.SecurityPolicyRule.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value sample_request = {"project": "sample1", "security_policy": "sample2"} mock_args = dict( project="project_value", security_policy="security_policy_value", ) mock_args.update(sample_request) client.get_rule(**mock_args) assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( "https://%s/compute/v1/projects/{project}/global/securityPolicies/{security_policy}/getRule" % client.transport._host, args[1], ) def test_get_rule_rest_flattened_error(transport: str = "rest"): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) with pytest.raises(ValueError): client.get_rule( compute.GetRuleSecurityPolicyRequest(), project="project_value", security_policy="security_policy_value", ) def test_get_rule_rest_error(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @pytest.mark.parametrize("request_type", [compute.InsertSecurityPolicyRequest, dict,]) def test_insert_unary_rest(request_type): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request_init = {"project": "sample1"} request_init["security_policy_resource"] = { "adaptive_protection_config": { "layer7_ddos_defense_config": { "enable": True, "rule_visibility": "rule_visibility_value", } }, "advanced_options_config": { "json_parsing": "json_parsing_value", "log_level": "log_level_value", }, "creation_timestamp": "creation_timestamp_value", "description": "description_value", "fingerprint": "fingerprint_value", "id": 205, "kind": "kind_value", "name": "name_value", "rules": [ { "action": "action_value", "description": "description_value", "kind": "kind_value", "match": { "config": { "src_ip_ranges": [ "src_ip_ranges_value_1", "src_ip_ranges_value_2", ] }, "expr": { "description": "description_value", "expression": "expression_value", "location": "location_value", "title": "title_value", }, "versioned_expr": "versioned_expr_value", }, "preview": True, "priority": 898, } ], "self_link": "self_link_value", } request = request_type(request_init) with mock.patch.object(type(client.transport._session), "request") as req: return_value = compute.Operation( client_operation_id="client_operation_id_value", creation_timestamp="creation_timestamp_value", description="description_value", end_time="end_time_value", http_error_message="http_error_message_value", http_error_status_code=2374, id=205, insert_time="insert_time_value", kind="kind_value", name="name_value", operation_group_id="operation_group_id_value", operation_type="operation_type_value", progress=885, region="region_value", self_link="self_link_value", start_time="start_time_value", status=compute.Operation.Status.DONE, status_message="status_message_value", target_id=947, target_link="target_link_value", user="user_value", zone="zone_value", ) response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.insert_unary(request) assert isinstance(response, compute.Operation) assert response.client_operation_id == "client_operation_id_value" assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" assert response.end_time == "end_time_value" assert response.http_error_message == "http_error_message_value" assert response.http_error_status_code == 2374 assert response.id == 205 assert response.insert_time == "insert_time_value" assert response.kind == "kind_value" assert response.name == "name_value" assert response.operation_group_id == "operation_group_id_value" assert response.operation_type == "operation_type_value" assert response.progress == 885 assert response.region == "region_value" assert response.self_link == "self_link_value" assert response.start_time == "start_time_value" assert response.status == compute.Operation.Status.DONE assert response.status_message == "status_message_value" assert response.target_id == 947 assert response.target_link == "target_link_value" assert response.user == "user_value" assert response.zone == "zone_value" def test_insert_unary_rest_required_fields( request_type=compute.InsertSecurityPolicyRequest, ): transport_class = transports.SecurityPoliciesRestTransport request_init = {} request_init["project"] = "" request = request_type(request_init) jsonified_request = json.loads( request_type.to_json( request, including_default_value_fields=False, use_integers_for_enums=False ) ) unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).insert._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) jsonified_request["project"] = "project_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).insert._get_unset_required_fields(jsonified_request) assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type(request_init) return_value = compute.Operation() with mock.patch.object(Session, "request") as req: with mock.patch.object(path_template, "transcode") as transcode: transcode_result = { "uri": "v1/sample_method", "method": "post", "query_params": request_init, } transcode_result["body"] = {} transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.insert_unary(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_insert_unary_rest_unset_required_fields(): transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = transport.insert._get_unset_required_fields({}) assert set(unset_fields) == ( set(("requestId",)) & set(("project", "securityPolicyResource",)) ) def test_insert_unary_rest_bad_request( transport: str = "rest", request_type=compute.InsertSecurityPolicyRequest ): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) request_init = {"project": "sample1"} request_init["security_policy_resource"] = { "adaptive_protection_config": { "layer7_ddos_defense_config": { "enable": True, "rule_visibility": "rule_visibility_value", } }, "advanced_options_config": { "json_parsing": "json_parsing_value", "log_level": "log_level_value", }, "creation_timestamp": "creation_timestamp_value", "description": "description_value", "fingerprint": "fingerprint_value", "id": 205, "kind": "kind_value", "name": "name_value", "rules": [ { "action": "action_value", "description": "description_value", "kind": "kind_value", "match": { "config": { "src_ip_ranges": [ "src_ip_ranges_value_1", "src_ip_ranges_value_2", ] }, "expr": { "description": "description_value", "expression": "expression_value", "location": "location_value", "title": "title_value", }, "versioned_expr": "versioned_expr_value", }, "preview": True, "priority": 898, } ], "self_link": "self_link_value", } request = request_type(request_init) with mock.patch.object(Session, "request") as req, pytest.raises( core_exceptions.BadRequest ): response_value = Response() response_value.status_code = 400 response_value.request = Request() req.return_value = response_value client.insert_unary(request) def test_insert_unary_rest_flattened(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) with mock.patch.object(type(client.transport._session), "request") as req: return_value = compute.Operation() response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value sample_request = {"project": "sample1"} mock_args = dict( project="project_value", security_policy_resource=compute.SecurityPolicy( adaptive_protection_config=compute.SecurityPolicyAdaptiveProtectionConfig( layer7_ddos_defense_config=compute.SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfig( enable=True ) ) ), ) mock_args.update(sample_request) client.insert_unary(**mock_args) assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( "https://%s/compute/v1/projects/{project}/global/securityPolicies" % client.transport._host, args[1], ) def test_insert_unary_rest_flattened_error(transport: str = "rest"): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) with pytest.raises(ValueError): client.insert_unary( compute.InsertSecurityPolicyRequest(), project="project_value", security_policy_resource=compute.SecurityPolicy( adaptive_protection_config=compute.SecurityPolicyAdaptiveProtectionConfig( layer7_ddos_defense_config=compute.SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfig( enable=True ) ) ), ) def test_insert_unary_rest_error(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @pytest.mark.parametrize("request_type", [compute.ListSecurityPoliciesRequest, dict,]) def test_list_rest(request_type): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request_init = {"project": "sample1"} request = request_type(request_init) with mock.patch.object(type(client.transport._session), "request") as req: return_value = compute.SecurityPolicyList( id="id_value", kind="kind_value", next_page_token="next_page_token_value", ) response_value = Response() response_value.status_code = 200 json_return_value = compute.SecurityPolicyList.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.list(request) assert isinstance(response, pagers.ListPager) assert response.id == "id_value" assert response.kind == "kind_value" assert response.next_page_token == "next_page_token_value" def test_list_rest_required_fields(request_type=compute.ListSecurityPoliciesRequest): transport_class = transports.SecurityPoliciesRestTransport request_init = {} request_init["project"] = "" request = request_type(request_init) jsonified_request = json.loads( request_type.to_json( request, including_default_value_fields=False, use_integers_for_enums=False ) ) unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).list._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) jsonified_request["project"] = "project_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).list._get_unset_required_fields(jsonified_request) assert not set(unset_fields) - set( ("max_results", "filter", "order_by", "page_token", "return_partial_success",) ) jsonified_request.update(unset_fields) assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type(request_init) return_value = compute.SecurityPolicyList() with mock.patch.object(Session, "request") as req: with mock.patch.object(path_template, "transcode") as transcode: transcode_result = { "uri": "v1/sample_method", "method": "get", "query_params": request_init, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = compute.SecurityPolicyList.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.list(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_list_rest_unset_required_fields(): transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = transport.list._get_unset_required_fields({}) assert set(unset_fields) == ( set(("maxResults", "filter", "orderBy", "pageToken", "returnPartialSuccess",)) & set(("project",)) ) def test_list_rest_bad_request( transport: str = "rest", request_type=compute.ListSecurityPoliciesRequest ): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) request_init = {"project": "sample1"} request = request_type(request_init) with mock.patch.object(Session, "request") as req, pytest.raises( core_exceptions.BadRequest ): response_value = Response() response_value.status_code = 400 response_value.request = Request() req.return_value = response_value client.list(request) def test_list_rest_flattened(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) with mock.patch.object(type(client.transport._session), "request") as req: return_value = compute.SecurityPolicyList() response_value = Response() response_value.status_code = 200 json_return_value = compute.SecurityPolicyList.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value sample_request = {"project": "sample1"} mock_args = dict(project="project_value",) mock_args.update(sample_request) client.list(**mock_args) assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( "https://%s/compute/v1/projects/{project}/global/securityPolicies" % client.transport._host, args[1], ) def test_list_rest_flattened_error(transport: str = "rest"): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) with pytest.raises(ValueError): client.list( compute.ListSecurityPoliciesRequest(), project="project_value", ) def test_list_rest_pager(transport: str = "rest"): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) with mock.patch.object(Session, "request") as req: # with mock.patch.object(path_template, 'transcode') as transcode: # Set the response as a series of pages response = ( compute.SecurityPolicyList( items=[ compute.SecurityPolicy(), compute.SecurityPolicy(), compute.SecurityPolicy(), ], next_page_token="abc", ), compute.SecurityPolicyList(items=[], next_page_token="def",), compute.SecurityPolicyList( items=[compute.SecurityPolicy(),], next_page_token="ghi", ), compute.SecurityPolicyList( items=[compute.SecurityPolicy(), compute.SecurityPolicy(),], ), ) # Two responses for two calls response = response + response # Wrap the values into proper Response objs response = tuple(compute.SecurityPolicyList.to_json(x) for x in response) return_values = tuple(Response() for i in response) for return_val, response_val in zip(return_values, response): return_val._content = response_val.encode("UTF-8") return_val.status_code = 200 req.side_effect = return_values sample_request = {"project": "sample1"} pager = client.list(request=sample_request) results = list(pager) assert len(results) == 6 assert all(isinstance(i, compute.SecurityPolicy) for i in results) pages = list(client.list(request=sample_request).pages) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( "request_type", [compute.ListPreconfiguredExpressionSetsSecurityPoliciesRequest, dict,], ) def test_list_preconfigured_expression_sets_rest(request_type): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding request_init = {"project": "sample1"} request = request_type(request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse.to_json( return_value ) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.list_preconfigured_expression_sets(request) # Establish that the response is the type that we expect. assert isinstance( response, compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse ) def test_list_preconfigured_expression_sets_rest_required_fields( request_type=compute.ListPreconfiguredExpressionSetsSecurityPoliciesRequest, ): transport_class = transports.SecurityPoliciesRestTransport request_init = {} request_init["project"] = "" request = request_type(request_init) jsonified_request = json.loads( request_type.to_json( request, including_default_value_fields=False, use_integers_for_enums=False ) ) # verify fields with default values are dropped unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).list_preconfigured_expression_sets._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["project"] = "project_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).list_preconfigured_expression_sets._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ("max_results", "filter", "order_by", "page_token", "return_partial_success",) ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type(request_init) # Designate an appropriate value for the returned response. return_value = compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. transcode_result = { "uri": "v1/sample_method", "method": "get", "query_params": request_init, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse.to_json( return_value ) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.list_preconfigured_expression_sets(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_list_preconfigured_expression_sets_rest_unset_required_fields(): transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = transport.list_preconfigured_expression_sets._get_unset_required_fields( {} ) assert set(unset_fields) == ( set(("maxResults", "filter", "orderBy", "pageToken", "returnPartialSuccess",)) & set(("project",)) ) def test_list_preconfigured_expression_sets_rest_bad_request( transport: str = "rest", request_type=compute.ListPreconfiguredExpressionSetsSecurityPoliciesRequest, ): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding request_init = {"project": "sample1"} request = request_type(request_init) # Mock the http request call within the method and fake a BadRequest error. with mock.patch.object(Session, "request") as req, pytest.raises( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 response_value.request = Request() req.return_value = response_value client.list_preconfigured_expression_sets(request) def test_list_preconfigured_expression_sets_rest_flattened(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.SecurityPoliciesListPreconfiguredExpressionSetsResponse.to_json( return_value ) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value # get arguments that satisfy an http rule for this method sample_request = {"project": "sample1"} # get truthy value for each flattened field mock_args = dict(project="project_value",) mock_args.update(sample_request) client.list_preconfigured_expression_sets(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( "https://%s/compute/v1/projects/{project}/global/securityPolicies/listPreconfiguredExpressionSets" % client.transport._host, args[1], ) def test_list_preconfigured_expression_sets_rest_flattened_error( transport: str = "rest", ): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.list_preconfigured_expression_sets( compute.ListPreconfiguredExpressionSetsSecurityPoliciesRequest(), project="project_value", ) def test_list_preconfigured_expression_sets_rest_error(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @pytest.mark.parametrize("request_type", [compute.PatchSecurityPolicyRequest, dict,]) def test_patch_unary_rest(request_type): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "security_policy": "sample2"} request_init["security_policy_resource"] = { "adaptive_protection_config": { "layer7_ddos_defense_config": { "enable": True, "rule_visibility": "rule_visibility_value", } }, "advanced_options_config": { "json_parsing": "json_parsing_value", "log_level": "log_level_value", }, "creation_timestamp": "creation_timestamp_value", "description": "description_value", "fingerprint": "fingerprint_value", "id": 205, "kind": "kind_value", "name": "name_value", "rules": [ { "action": "action_value", "description": "description_value", "kind": "kind_value", "match": { "config": { "src_ip_ranges": [ "src_ip_ranges_value_1", "src_ip_ranges_value_2", ] }, "expr": { "description": "description_value", "expression": "expression_value", "location": "location_value", "title": "title_value", }, "versioned_expr": "versioned_expr_value", }, "preview": True, "priority": 898, } ], "self_link": "self_link_value", } request = request_type(request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.Operation( client_operation_id="client_operation_id_value", creation_timestamp="creation_timestamp_value", description="description_value", end_time="end_time_value", http_error_message="http_error_message_value", http_error_status_code=2374, id=205, insert_time="insert_time_value", kind="kind_value", name="name_value", operation_group_id="operation_group_id_value", operation_type="operation_type_value", progress=885, region="region_value", self_link="self_link_value", start_time="start_time_value", status=compute.Operation.Status.DONE, status_message="status_message_value", target_id=947, target_link="target_link_value", user="user_value", zone="zone_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.patch_unary(request) # Establish that the response is the type that we expect. assert isinstance(response, compute.Operation) assert response.client_operation_id == "client_operation_id_value" assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" assert response.end_time == "end_time_value" assert response.http_error_message == "http_error_message_value" assert response.http_error_status_code == 2374 assert response.id == 205 assert response.insert_time == "insert_time_value" assert response.kind == "kind_value" assert response.name == "name_value" assert response.operation_group_id == "operation_group_id_value" assert response.operation_type == "operation_type_value" assert response.progress == 885 assert response.region == "region_value" assert response.self_link == "self_link_value" assert response.start_time == "start_time_value" assert response.status == compute.Operation.Status.DONE assert response.status_message == "status_message_value" assert response.target_id == 947 assert response.target_link == "target_link_value" assert response.user == "user_value" assert response.zone == "zone_value" def test_patch_unary_rest_required_fields( request_type=compute.PatchSecurityPolicyRequest, ): transport_class = transports.SecurityPoliciesRestTransport request_init = {} request_init["project"] = "" request_init["security_policy"] = "" request = request_type(request_init) jsonified_request = json.loads( request_type.to_json( request, including_default_value_fields=False, use_integers_for_enums=False ) ) # verify fields with default values are dropped unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).patch._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["project"] = "project_value" jsonified_request["securityPolicy"] = "security_policy_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).patch._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" assert "securityPolicy" in jsonified_request assert jsonified_request["securityPolicy"] == "security_policy_value" client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type(request_init) # Designate an appropriate value for the returned response. return_value = compute.Operation() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. transcode_result = { "uri": "v1/sample_method", "method": "patch", "query_params": request_init, } transcode_result["body"] = {} transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.patch_unary(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_patch_unary_rest_unset_required_fields(): transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = transport.patch._get_unset_required_fields({}) assert set(unset_fields) == ( set(("requestId",)) & set(("project", "securityPolicy", "securityPolicyResource",)) ) def test_patch_unary_rest_bad_request( transport: str = "rest", request_type=compute.PatchSecurityPolicyRequest ): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "security_policy": "sample2"} request_init["security_policy_resource"] = { "adaptive_protection_config": { "layer7_ddos_defense_config": { "enable": True, "rule_visibility": "rule_visibility_value", } }, "advanced_options_config": { "json_parsing": "json_parsing_value", "log_level": "log_level_value", }, "creation_timestamp": "creation_timestamp_value", "description": "description_value", "fingerprint": "fingerprint_value", "id": 205, "kind": "kind_value", "name": "name_value", "rules": [ { "action": "action_value", "description": "description_value", "kind": "kind_value", "match": { "config": { "src_ip_ranges": [ "src_ip_ranges_value_1", "src_ip_ranges_value_2", ] }, "expr": { "description": "description_value", "expression": "expression_value", "location": "location_value", "title": "title_value", }, "versioned_expr": "versioned_expr_value", }, "preview": True, "priority": 898, } ], "self_link": "self_link_value", } request = request_type(request_init) # Mock the http request call within the method and fake a BadRequest error. with mock.patch.object(Session, "request") as req, pytest.raises( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 response_value.request = Request() req.return_value = response_value client.patch_unary(request) def test_patch_unary_rest_flattened(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.Operation() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value # get arguments that satisfy an http rule for this method sample_request = {"project": "sample1", "security_policy": "sample2"} # get truthy value for each flattened field mock_args = dict( project="project_value", security_policy="security_policy_value", security_policy_resource=compute.SecurityPolicy( adaptive_protection_config=compute.SecurityPolicyAdaptiveProtectionConfig( layer7_ddos_defense_config=compute.SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfig( enable=True ) ) ), ) mock_args.update(sample_request) client.patch_unary(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( "https://%s/compute/v1/projects/{project}/global/securityPolicies/{security_policy}" % client.transport._host, args[1], ) def test_patch_unary_rest_flattened_error(transport: str = "rest"): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.patch_unary( compute.PatchSecurityPolicyRequest(), project="project_value", security_policy="security_policy_value", security_policy_resource=compute.SecurityPolicy( adaptive_protection_config=compute.SecurityPolicyAdaptiveProtectionConfig( layer7_ddos_defense_config=compute.SecurityPolicyAdaptiveProtectionConfigLayer7DdosDefenseConfig( enable=True ) ) ), ) def test_patch_unary_rest_error(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @pytest.mark.parametrize( "request_type", [compute.PatchRuleSecurityPolicyRequest, dict,] ) def test_patch_rule_unary_rest(request_type): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "security_policy": "sample2"} request_init["security_policy_rule_resource"] = { "action": "action_value", "description": "description_value", "kind": "kind_value", "match": { "config": { "src_ip_ranges": ["src_ip_ranges_value_1", "src_ip_ranges_value_2"] }, "expr": { "description": "description_value", "expression": "expression_value", "location": "location_value", "title": "title_value", }, "versioned_expr": "versioned_expr_value", }, "preview": True, "priority": 898, } request = request_type(request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.Operation( client_operation_id="client_operation_id_value", creation_timestamp="creation_timestamp_value", description="description_value", end_time="end_time_value", http_error_message="http_error_message_value", http_error_status_code=2374, id=205, insert_time="insert_time_value", kind="kind_value", name="name_value", operation_group_id="operation_group_id_value", operation_type="operation_type_value", progress=885, region="region_value", self_link="self_link_value", start_time="start_time_value", status=compute.Operation.Status.DONE, status_message="status_message_value", target_id=947, target_link="target_link_value", user="user_value", zone="zone_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.patch_rule_unary(request) # Establish that the response is the type that we expect. assert isinstance(response, compute.Operation) assert response.client_operation_id == "client_operation_id_value" assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" assert response.end_time == "end_time_value" assert response.http_error_message == "http_error_message_value" assert response.http_error_status_code == 2374 assert response.id == 205 assert response.insert_time == "insert_time_value" assert response.kind == "kind_value" assert response.name == "name_value" assert response.operation_group_id == "operation_group_id_value" assert response.operation_type == "operation_type_value" assert response.progress == 885 assert response.region == "region_value" assert response.self_link == "self_link_value" assert response.start_time == "start_time_value" assert response.status == compute.Operation.Status.DONE assert response.status_message == "status_message_value" assert response.target_id == 947 assert response.target_link == "target_link_value" assert response.user == "user_value" assert response.zone == "zone_value" def test_patch_rule_unary_rest_required_fields( request_type=compute.PatchRuleSecurityPolicyRequest, ): transport_class = transports.SecurityPoliciesRestTransport request_init = {} request_init["project"] = "" request_init["security_policy"] = "" request = request_type(request_init) jsonified_request = json.loads( request_type.to_json( request, including_default_value_fields=False, use_integers_for_enums=False ) ) # verify fields with default values are dropped unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).patch_rule._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["project"] = "project_value" jsonified_request["securityPolicy"] = "security_policy_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).patch_rule._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set(("priority",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" assert "securityPolicy" in jsonified_request assert jsonified_request["securityPolicy"] == "security_policy_value" client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type(request_init) # Designate an appropriate value for the returned response. return_value = compute.Operation() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. transcode_result = { "uri": "v1/sample_method", "method": "post", "query_params": request_init, } transcode_result["body"] = {} transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.patch_rule_unary(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_patch_rule_unary_rest_unset_required_fields(): transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = transport.patch_rule._get_unset_required_fields({}) assert set(unset_fields) == ( set(("priority",)) & set(("project", "securityPolicy", "securityPolicyRuleResource",)) ) def test_patch_rule_unary_rest_bad_request( transport: str = "rest", request_type=compute.PatchRuleSecurityPolicyRequest ): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "security_policy": "sample2"} request_init["security_policy_rule_resource"] = { "action": "action_value", "description": "description_value", "kind": "kind_value", "match": { "config": { "src_ip_ranges": ["src_ip_ranges_value_1", "src_ip_ranges_value_2"] }, "expr": { "description": "description_value", "expression": "expression_value", "location": "location_value", "title": "title_value", }, "versioned_expr": "versioned_expr_value", }, "preview": True, "priority": 898, } request = request_type(request_init) # Mock the http request call within the method and fake a BadRequest error. with mock.patch.object(Session, "request") as req, pytest.raises( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 response_value.request = Request() req.return_value = response_value client.patch_rule_unary(request) def test_patch_rule_unary_rest_flattened(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.Operation() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value # get arguments that satisfy an http rule for this method sample_request = {"project": "sample1", "security_policy": "sample2"} # get truthy value for each flattened field mock_args = dict( project="project_value", security_policy="security_policy_value", security_policy_rule_resource=compute.SecurityPolicyRule( action="action_value" ), ) mock_args.update(sample_request) client.patch_rule_unary(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( "https://%s/compute/v1/projects/{project}/global/securityPolicies/{security_policy}/patchRule" % client.transport._host, args[1], ) def test_patch_rule_unary_rest_flattened_error(transport: str = "rest"): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.patch_rule_unary( compute.PatchRuleSecurityPolicyRequest(), project="project_value", security_policy="security_policy_value", security_policy_rule_resource=compute.SecurityPolicyRule( action="action_value" ), ) def test_patch_rule_unary_rest_error(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @pytest.mark.parametrize( "request_type", [compute.RemoveRuleSecurityPolicyRequest, dict,] ) def test_remove_rule_unary_rest(request_type): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "security_policy": "sample2"} request = request_type(request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.Operation( client_operation_id="client_operation_id_value", creation_timestamp="creation_timestamp_value", description="description_value", end_time="end_time_value", http_error_message="http_error_message_value", http_error_status_code=2374, id=205, insert_time="insert_time_value", kind="kind_value", name="name_value", operation_group_id="operation_group_id_value", operation_type="operation_type_value", progress=885, region="region_value", self_link="self_link_value", start_time="start_time_value", status=compute.Operation.Status.DONE, status_message="status_message_value", target_id=947, target_link="target_link_value", user="user_value", zone="zone_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.remove_rule_unary(request) # Establish that the response is the type that we expect. assert isinstance(response, compute.Operation) assert response.client_operation_id == "client_operation_id_value" assert response.creation_timestamp == "creation_timestamp_value" assert response.description == "description_value" assert response.end_time == "end_time_value" assert response.http_error_message == "http_error_message_value" assert response.http_error_status_code == 2374 assert response.id == 205 assert response.insert_time == "insert_time_value" assert response.kind == "kind_value" assert response.name == "name_value" assert response.operation_group_id == "operation_group_id_value" assert response.operation_type == "operation_type_value" assert response.progress == 885 assert response.region == "region_value" assert response.self_link == "self_link_value" assert response.start_time == "start_time_value" assert response.status == compute.Operation.Status.DONE assert response.status_message == "status_message_value" assert response.target_id == 947 assert response.target_link == "target_link_value" assert response.user == "user_value" assert response.zone == "zone_value" def test_remove_rule_unary_rest_required_fields( request_type=compute.RemoveRuleSecurityPolicyRequest, ): transport_class = transports.SecurityPoliciesRestTransport request_init = {} request_init["project"] = "" request_init["security_policy"] = "" request = request_type(request_init) jsonified_request = json.loads( request_type.to_json( request, including_default_value_fields=False, use_integers_for_enums=False ) ) # verify fields with default values are dropped unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).remove_rule._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["project"] = "project_value" jsonified_request["securityPolicy"] = "security_policy_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() ).remove_rule._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set(("priority",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "project" in jsonified_request assert jsonified_request["project"] == "project_value" assert "securityPolicy" in jsonified_request assert jsonified_request["securityPolicy"] == "security_policy_value" client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) request = request_type(request_init) # Designate an appropriate value for the returned response. return_value = compute.Operation() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. with mock.patch.object(path_template, "transcode") as transcode: # A uri without fields and an empty body will force all the # request fields to show up in the query_params. transcode_result = { "uri": "v1/sample_method", "method": "post", "query_params": request_init, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value response = client.remove_rule_unary(request) expected_params = [] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params def test_remove_rule_unary_rest_unset_required_fields(): transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials ) unset_fields = transport.remove_rule._get_unset_required_fields({}) assert set(unset_fields) == ( set(("priority",)) & set(("project", "securityPolicy",)) ) def test_remove_rule_unary_rest_bad_request( transport: str = "rest", request_type=compute.RemoveRuleSecurityPolicyRequest ): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # send a request that will satisfy transcoding request_init = {"project": "sample1", "security_policy": "sample2"} request = request_type(request_init) # Mock the http request call within the method and fake a BadRequest error. with mock.patch.object(Session, "request") as req, pytest.raises( core_exceptions.BadRequest ): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 400 response_value.request = Request() req.return_value = response_value client.remove_rule_unary(request) def test_remove_rule_unary_rest_flattened(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. return_value = compute.Operation() # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 json_return_value = compute.Operation.to_json(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value # get arguments that satisfy an http rule for this method sample_request = {"project": "sample1", "security_policy": "sample2"} # get truthy value for each flattened field mock_args = dict( project="project_value", security_policy="security_policy_value", ) mock_args.update(sample_request) client.remove_rule_unary(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( "https://%s/compute/v1/projects/{project}/global/securityPolicies/{security_policy}/removeRule" % client.transport._host, args[1], ) def test_remove_rule_unary_rest_flattened_error(transport: str = "rest"): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): client.remove_rule_unary( compute.RemoveRuleSecurityPolicyRequest(), project="project_value", security_policy="security_policy_value", ) def test_remove_rule_unary_rest_error(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) def test_credentials_transport_error(): # It is an error to provide credentials and a transport instance. transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) # It is an error to provide a credentials file and a transport instance. transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SecurityPoliciesClient( client_options={"credentials_file": "credentials.json"}, transport=transport, ) # It is an error to provide an api_key and a transport instance. transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials(), ) options = client_options.ClientOptions() options.api_key = "api_key" with pytest.raises(ValueError): client = SecurityPoliciesClient(client_options=options, transport=transport,) # It is an error to provide an api_key and a credential. options = mock.Mock() options.api_key = "api_key" with pytest.raises(ValueError): client = SecurityPoliciesClient( client_options=options, credentials=ga_credentials.AnonymousCredentials() ) # It is an error to provide scopes and a transport instance. transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials(), ) with pytest.raises(ValueError): client = SecurityPoliciesClient( client_options={"scopes": ["1", "2"]}, transport=transport, ) def test_transport_instance(): # A client may be instantiated with a custom transport instance. transport = transports.SecurityPoliciesRestTransport( credentials=ga_credentials.AnonymousCredentials(), ) client = SecurityPoliciesClient(transport=transport) assert client.transport is transport @pytest.mark.parametrize("transport_class", [transports.SecurityPoliciesRestTransport,]) def test_transport_adc(transport_class): # Test default credentials are used if not provided. with mock.patch.object(google.auth, "default") as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport_class() adc.assert_called_once() def test_security_policies_base_transport_error(): # Passing both a credentials object and credentials_file should raise an error with pytest.raises(core_exceptions.DuplicateCredentialArgs): transport = transports.SecurityPoliciesTransport( credentials=ga_credentials.AnonymousCredentials(), credentials_file="credentials.json", ) def test_security_policies_base_transport(): # Instantiate the base transport. with mock.patch( "google.cloud.compute_v1.services.security_policies.transports.SecurityPoliciesTransport.__init__" ) as Transport: Transport.return_value = None transport = transports.SecurityPoliciesTransport( credentials=ga_credentials.AnonymousCredentials(), ) # Every method on the transport should just blindly # raise NotImplementedError. methods = ( "add_rule", "delete", "get", "get_rule", "insert", "list", "list_preconfigured_expression_sets", "patch", "patch_rule", "remove_rule", ) for method in methods: with pytest.raises(NotImplementedError): getattr(transport, method)(request=object()) with pytest.raises(NotImplementedError): transport.close() def test_security_policies_base_transport_with_credentials_file(): # Instantiate the base transport with a credentials file with mock.patch.object( google.auth, "load_credentials_from_file", autospec=True ) as load_creds, mock.patch( "google.cloud.compute_v1.services.security_policies.transports.SecurityPoliciesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SecurityPoliciesTransport( credentials_file="credentials.json", quota_project_id="octopus", ) load_creds.assert_called_once_with( "credentials.json", scopes=None, default_scopes=( "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/cloud-platform", ), quota_project_id="octopus", ) def test_security_policies_base_transport_with_adc(): # Test the default credentials are used if credentials and credentials_file are None. with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( "google.cloud.compute_v1.services.security_policies.transports.SecurityPoliciesTransport._prep_wrapped_messages" ) as Transport: Transport.return_value = None adc.return_value = (ga_credentials.AnonymousCredentials(), None) transport = transports.SecurityPoliciesTransport() adc.assert_called_once() def test_security_policies_auth_adc(): # If no credentials are provided, we should use ADC credentials. with mock.patch.object(google.auth, "default", autospec=True) as adc: adc.return_value = (ga_credentials.AnonymousCredentials(), None) SecurityPoliciesClient() adc.assert_called_once_with( scopes=None, default_scopes=( "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/cloud-platform", ), quota_project_id=None, ) def test_security_policies_http_transport_client_cert_source_for_mtls(): cred = ga_credentials.AnonymousCredentials() with mock.patch( "google.auth.transport.requests.AuthorizedSession.configure_mtls_channel" ) as mock_configure_mtls_channel: transports.SecurityPoliciesRestTransport( credentials=cred, client_cert_source_for_mtls=client_cert_source_callback ) mock_configure_mtls_channel.assert_called_once_with(client_cert_source_callback) def test_security_policies_host_no_port(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com" ), ) assert client.transport._host == "compute.googleapis.com:443" def test_security_policies_host_with_port(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), client_options=client_options.ClientOptions( api_endpoint="compute.googleapis.com:8000" ), ) assert client.transport._host == "compute.googleapis.com:8000" def test_common_billing_account_path(): billing_account = "squid" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) actual = SecurityPoliciesClient.common_billing_account_path(billing_account) assert expected == actual def test_parse_common_billing_account_path(): expected = { "billing_account": "clam", } path = SecurityPoliciesClient.common_billing_account_path(**expected) # Check that the path construction is reversible. actual = SecurityPoliciesClient.parse_common_billing_account_path(path) assert expected == actual def test_common_folder_path(): folder = "whelk" expected = "folders/{folder}".format(folder=folder,) actual = SecurityPoliciesClient.common_folder_path(folder) assert expected == actual def test_parse_common_folder_path(): expected = { "folder": "octopus", } path = SecurityPoliciesClient.common_folder_path(**expected) # Check that the path construction is reversible. actual = SecurityPoliciesClient.parse_common_folder_path(path) assert expected == actual def test_common_organization_path(): organization = "oyster" expected = "organizations/{organization}".format(organization=organization,) actual = SecurityPoliciesClient.common_organization_path(organization) assert expected == actual def test_parse_common_organization_path(): expected = { "organization": "nudibranch", } path = SecurityPoliciesClient.common_organization_path(**expected) # Check that the path construction is reversible. actual = SecurityPoliciesClient.parse_common_organization_path(path) assert expected == actual def test_common_project_path(): project = "cuttlefish" expected = "projects/{project}".format(project=project,) actual = SecurityPoliciesClient.common_project_path(project) assert expected == actual def test_parse_common_project_path(): expected = { "project": "mussel", } path = SecurityPoliciesClient.common_project_path(**expected) # Check that the path construction is reversible. actual = SecurityPoliciesClient.parse_common_project_path(path) assert expected == actual def test_common_location_path(): project = "winkle" location = "nautilus" expected = "projects/{project}/locations/{location}".format( project=project, location=location, ) actual = SecurityPoliciesClient.common_location_path(project, location) assert expected == actual def test_parse_common_location_path(): expected = { "project": "scallop", "location": "abalone", } path = SecurityPoliciesClient.common_location_path(**expected) # Check that the path construction is reversible. actual = SecurityPoliciesClient.parse_common_location_path(path) assert expected == actual def test_client_with_default_client_info(): client_info = gapic_v1.client_info.ClientInfo() with mock.patch.object( transports.SecurityPoliciesTransport, "_prep_wrapped_messages" ) as prep: client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) with mock.patch.object( transports.SecurityPoliciesTransport, "_prep_wrapped_messages" ) as prep: transport_class = SecurityPoliciesClient.get_transport_class() transport = transport_class( credentials=ga_credentials.AnonymousCredentials(), client_info=client_info, ) prep.assert_called_once_with(client_info) def test_transport_close(): transports = { "rest": "_session", } for transport, close_name in transports.items(): client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport ) with mock.patch.object( type(getattr(client.transport, close_name)), "close" ) as close: with client: close.assert_not_called() close.assert_called_once() def test_client_ctx(): transports = [ "rest", ] for transport in transports: client = SecurityPoliciesClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport ) # Test client calls underlying transport. with mock.patch.object(type(client.transport), "close") as close: close.assert_not_called() with client: pass close.assert_called() @pytest.mark.parametrize( "client_class,transport_class", [(SecurityPoliciesClient, transports.SecurityPoliciesRestTransport),], ) def test_api_key_credentials(client_class, transport_class): with mock.patch.object( google.auth._default, "get_api_key_credentials", create=True ) as get_api_key_credentials: mock_cred = mock.Mock() get_api_key_credentials.return_value = mock_cred options = client_options.ClientOptions() options.api_key = "api_key" with mock.patch.object(transport_class, "__init__") as patched: patched.return_value = None client = client_class(client_options=options) patched.assert_called_once_with( credentials=mock_cred, credentials_file=None, host=client.DEFAULT_ENDPOINT, scopes=None, client_cert_source_for_mtls=None, quota_project_id=None, client_info=transports.base.DEFAULT_CLIENT_INFO, always_use_jwt_access=True, )
true
true
f7f9fb592196e930a5afd3cbd2c3ff3c38289e5b
1,939
py
Python
CNG111-IntroductionToComputerEngineeringConcepts/2-SecretCodeComprehension/breaker.py
furkantokac/Lectures
a4dd6615691ce8d9d2bfec6910f6af108b741d7f
[ "MIT" ]
null
null
null
CNG111-IntroductionToComputerEngineeringConcepts/2-SecretCodeComprehension/breaker.py
furkantokac/Lectures
a4dd6615691ce8d9d2bfec6910f6af108b741d7f
[ "MIT" ]
null
null
null
CNG111-IntroductionToComputerEngineeringConcepts/2-SecretCodeComprehension/breaker.py
furkantokac/Lectures
a4dd6615691ce8d9d2bfec6910f6af108b741d7f
[ "MIT" ]
2
2019-12-05T16:37:53.000Z
2020-04-26T12:16:18.000Z
from random import randint def comparer(pw, gs): matches = 0 members = 0 pw = str(pw) gs = str(gs) for i in xrange(4): if pw[i] == gs[i]: matches+=1 elif gs[i] in pw: members+=1 return matches, members def fullCandidates(): cand=0 sayi = 0 candidates.append("") for i in xrange(1,10): cand = str(i); for j in xrange(0,10): if str(j) in cand: continue cand = cand[0:1] + str(j); for k in xrange(0,10): if str(k) in cand: continue cand = cand[0:2] + str(k); for l in xrange(0,10): if str(l) in cand: continue candidates[sayi] = cand+str(l) sayi+=1 candidates.append("") candidates.pop(len(candidates)-1) def removing(macs, mems, gus): newList = [] for i in xrange(0, len(candidates)): macsTemp, memsTemp = comparer(candidates[i],gus) if macs == str(macsTemp) and mems == str(memsTemp): newList.append(candidates[i]) return newList candidates=[] fullCandidates() guess=0 turn = 0 report = "" while turn < 8: guess = candidates[ randint(0,len(candidates)-1) ] print "The Guess is", guess report = raw_input("Enter Report> ") macs = str(report[0]) mems = str(report[2]) if not macs == "4" and len(candidates) > 1: candidates = removing(macs, mems, guess) print "Remaining possibilities:", len(candidates) print "Turn Guess Matches Members" print "{}. {} {} {}".format(turn+1, guess, macs, mems) if len(candidates) <= 1: turn = 10 else: turn = 10 #Use turn like key. This will end the loop end turn will be 11 turn+=1 if len(candidates) == 0 : print "You did something wrong :(" elif turn == 11 : print "I win ! (Your number :", candidates[0],")" else : print "I lose :("
26.202703
78
0.549768
from random import randint def comparer(pw, gs): matches = 0 members = 0 pw = str(pw) gs = str(gs) for i in xrange(4): if pw[i] == gs[i]: matches+=1 elif gs[i] in pw: members+=1 return matches, members def fullCandidates(): cand=0 sayi = 0 candidates.append("") for i in xrange(1,10): cand = str(i); for j in xrange(0,10): if str(j) in cand: continue cand = cand[0:1] + str(j); for k in xrange(0,10): if str(k) in cand: continue cand = cand[0:2] + str(k); for l in xrange(0,10): if str(l) in cand: continue candidates[sayi] = cand+str(l) sayi+=1 candidates.append("") candidates.pop(len(candidates)-1) def removing(macs, mems, gus): newList = [] for i in xrange(0, len(candidates)): macsTemp, memsTemp = comparer(candidates[i],gus) if macs == str(macsTemp) and mems == str(memsTemp): newList.append(candidates[i]) return newList candidates=[] fullCandidates() guess=0 turn = 0 report = "" while turn < 8: guess = candidates[ randint(0,len(candidates)-1) ] print "The Guess is", guess report = raw_input("Enter Report> ") macs = str(report[0]) mems = str(report[2]) if not macs == "4" and len(candidates) > 1: candidates = removing(macs, mems, guess) print "Remaining possibilities:", len(candidates) print "Turn Guess Matches Members" print "{}. {} {} {}".format(turn+1, guess, macs, mems) if len(candidates) <= 1: turn = 10 else: turn = 10 turn+=1 if len(candidates) == 0 : print "You did something wrong :(" elif turn == 11 : print "I win ! (Your number :", candidates[0],")" else : print "I lose :("
false
true
f7f9fb8e285474fad4112acdf4985f0dddf32585
536
py
Python
Lab 3/Lab3_19201086.py
farhad324/CSE420
782cb7a4133a54132956c931a64778c353a1ab9c
[ "MIT" ]
null
null
null
Lab 3/Lab3_19201086.py
farhad324/CSE420
782cb7a4133a54132956c931a64778c353a1ab9c
[ "MIT" ]
null
null
null
Lab 3/Lab3_19201086.py
farhad324/CSE420
782cb7a4133a54132956c931a64778c353a1ab9c
[ "MIT" ]
null
null
null
import re inp_count = int(input()) regex_list = [] for i in range(inp_count): regex_list.append(input()) count2 = int(input()) str_list = [] for i in range(count2): str_list.append(input()) for i in range(len(str_list)): for j in range(len(regex_list)): state = re.match(regex_list[j], str_list[i]) if state is not None: print('YES', str(j + 1)) break elif j == len(regex_list) - 1 and state is None: print('NO, 0') break
21.44
57
0.544776
import re inp_count = int(input()) regex_list = [] for i in range(inp_count): regex_list.append(input()) count2 = int(input()) str_list = [] for i in range(count2): str_list.append(input()) for i in range(len(str_list)): for j in range(len(regex_list)): state = re.match(regex_list[j], str_list[i]) if state is not None: print('YES', str(j + 1)) break elif j == len(regex_list) - 1 and state is None: print('NO, 0') break
true
true
f7f9fbc19fd9742de76bd5a4b6e72506a12a4d2d
3,685
py
Python
tensorflow_federated/python/core/impl/executors/eager_tf_executor_multi_gpu_test.py
amrzv/federated
d8ac0d5f8d52541860fba881e87ccdd44c5d5b9b
[ "Apache-2.0" ]
1
2020-12-28T19:20:04.000Z
2020-12-28T19:20:04.000Z
tensorflow_federated/python/core/impl/executors/eager_tf_executor_multi_gpu_test.py
amrzv/federated
d8ac0d5f8d52541860fba881e87ccdd44c5d5b9b
[ "Apache-2.0" ]
null
null
null
tensorflow_federated/python/core/impl/executors/eager_tf_executor_multi_gpu_test.py
amrzv/federated
d8ac0d5f8d52541860fba881e87ccdd44c5d5b9b
[ "Apache-2.0" ]
null
null
null
# Copyright 2019, The TensorFlow Federated Authors. # # 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 numpy as np import tensorflow as tf from tensorflow_federated.python.common_libs import test_utils from tensorflow_federated.python.core.api import computations from tensorflow_federated.python.core.impl import computation_impl from tensorflow_federated.python.core.impl.executors import eager_tf_executor class MultiGPUTest(tf.test.TestCase): def setUp(self): super().setUp() test_utils.create_logical_multi_gpus() def test_check_dataset_reduce_in_multi_gpu_no_reduce_no_raise(self): with tf.Graph().as_default() as graph: tf.data.Dataset.range(10).map(lambda x: x + 1) eager_tf_executor._check_dataset_reduce_in_multi_gpu(graph.as_graph_def()) def test_check_dataset_reduce_in_multi_gpu(self): with tf.Graph().as_default() as graph: tf.data.Dataset.range(10).reduce(np.int64(0), lambda p, q: p + q) with self.assertRaisesRegex( ValueError, 'Detected dataset reduce op in multi-GPU TFF simulation.*'): eager_tf_executor._check_dataset_reduce_in_multi_gpu(graph.as_graph_def()) def test_check_dataset_reduce_in_multi_gpu_tf_device_no_raise(self): logical_gpus = tf.config.list_logical_devices('GPU') with tf.Graph().as_default() as graph: with tf.device(logical_gpus[0].name): tf.data.Dataset.range(10).reduce(np.int64(0), lambda p, q: p + q) eager_tf_executor._check_dataset_reduce_in_multi_gpu(graph.as_graph_def()) def test_get_no_arg_wrapped_function_check_dataset_reduce_in_multi_gpu(self): @computations.tf_computation def comp(): return tf.data.Dataset.range(10).reduce(np.int64(0), lambda p, q: p + q) with self.assertRaisesRegex( ValueError, 'Detected dataset reduce op in multi-GPU TFF simulation.*'): eager_tf_executor._get_wrapped_function_from_comp( computation_impl.ComputationImpl.get_proto(comp), must_pin_function_to_cpu=False, param_type=None, device=None) def test_get_no_arg_wrapped_function_multi_gpu_no_reduce(self): @computations.tf_computation @tf.function def comp(): value = tf.constant(0, dtype=tf.int64) for d in iter(tf.data.Dataset.range(10)): value += d return value wrapped_fn = eager_tf_executor._get_wrapped_function_from_comp( computation_impl.ComputationImpl.get_proto(comp), must_pin_function_to_cpu=False, param_type=None, device=None) self.assertEqual(wrapped_fn(), np.int64(45)) def test_get_no_arg_wrapped_function_multi_gpu_tf_device(self): logical_gpus = tf.config.list_logical_devices('GPU') @computations.tf_computation def comp(): with tf.device(logical_gpus[0].name): return tf.data.Dataset.range(10).reduce(np.int64(0), lambda p, q: p + q) wrapped_fn = eager_tf_executor._get_wrapped_function_from_comp( computation_impl.ComputationImpl.get_proto(comp), must_pin_function_to_cpu=False, param_type=None, device=None) self.assertEqual(wrapped_fn(), np.int64(45)) if __name__ == '__main__': tf.test.main()
37.222222
80
0.742469
import numpy as np import tensorflow as tf from tensorflow_federated.python.common_libs import test_utils from tensorflow_federated.python.core.api import computations from tensorflow_federated.python.core.impl import computation_impl from tensorflow_federated.python.core.impl.executors import eager_tf_executor class MultiGPUTest(tf.test.TestCase): def setUp(self): super().setUp() test_utils.create_logical_multi_gpus() def test_check_dataset_reduce_in_multi_gpu_no_reduce_no_raise(self): with tf.Graph().as_default() as graph: tf.data.Dataset.range(10).map(lambda x: x + 1) eager_tf_executor._check_dataset_reduce_in_multi_gpu(graph.as_graph_def()) def test_check_dataset_reduce_in_multi_gpu(self): with tf.Graph().as_default() as graph: tf.data.Dataset.range(10).reduce(np.int64(0), lambda p, q: p + q) with self.assertRaisesRegex( ValueError, 'Detected dataset reduce op in multi-GPU TFF simulation.*'): eager_tf_executor._check_dataset_reduce_in_multi_gpu(graph.as_graph_def()) def test_check_dataset_reduce_in_multi_gpu_tf_device_no_raise(self): logical_gpus = tf.config.list_logical_devices('GPU') with tf.Graph().as_default() as graph: with tf.device(logical_gpus[0].name): tf.data.Dataset.range(10).reduce(np.int64(0), lambda p, q: p + q) eager_tf_executor._check_dataset_reduce_in_multi_gpu(graph.as_graph_def()) def test_get_no_arg_wrapped_function_check_dataset_reduce_in_multi_gpu(self): @computations.tf_computation def comp(): return tf.data.Dataset.range(10).reduce(np.int64(0), lambda p, q: p + q) with self.assertRaisesRegex( ValueError, 'Detected dataset reduce op in multi-GPU TFF simulation.*'): eager_tf_executor._get_wrapped_function_from_comp( computation_impl.ComputationImpl.get_proto(comp), must_pin_function_to_cpu=False, param_type=None, device=None) def test_get_no_arg_wrapped_function_multi_gpu_no_reduce(self): @computations.tf_computation @tf.function def comp(): value = tf.constant(0, dtype=tf.int64) for d in iter(tf.data.Dataset.range(10)): value += d return value wrapped_fn = eager_tf_executor._get_wrapped_function_from_comp( computation_impl.ComputationImpl.get_proto(comp), must_pin_function_to_cpu=False, param_type=None, device=None) self.assertEqual(wrapped_fn(), np.int64(45)) def test_get_no_arg_wrapped_function_multi_gpu_tf_device(self): logical_gpus = tf.config.list_logical_devices('GPU') @computations.tf_computation def comp(): with tf.device(logical_gpus[0].name): return tf.data.Dataset.range(10).reduce(np.int64(0), lambda p, q: p + q) wrapped_fn = eager_tf_executor._get_wrapped_function_from_comp( computation_impl.ComputationImpl.get_proto(comp), must_pin_function_to_cpu=False, param_type=None, device=None) self.assertEqual(wrapped_fn(), np.int64(45)) if __name__ == '__main__': tf.test.main()
true
true
f7f9fbebc9a59d5d2c57e9d4a9182eb3f61c9572
4,888
py
Python
pyhighlighterclient/research_plan_metric.py
wgoldm/pyhighlighterclient
533da226af7f1103f96edeec8c47fe3f8e067bf1
[ "MIT" ]
null
null
null
pyhighlighterclient/research_plan_metric.py
wgoldm/pyhighlighterclient
533da226af7f1103f96edeec8c47fe3f8e067bf1
[ "MIT" ]
null
null
null
pyhighlighterclient/research_plan_metric.py
wgoldm/pyhighlighterclient
533da226af7f1103f96edeec8c47fe3f8e067bf1
[ "MIT" ]
null
null
null
# coding=utf-8 __author__ = 'Mykhailo' import os from pathlib import Path from dotenv import load_dotenv from sgqlc.endpoint.http import HTTPEndpoint as HTTPEndpoint import logging from .schema.silverpond_schema import silverpond_schema from sgqlc.operation import Operation from .fieldset_functions import * class ResearchPlanMetric(object): """ all functions of ResearchPlanMetric schema """ logger = logging.getLogger('silverpond') def __init__(self, apitoken=None, apiurl=None): env_path = Path('.') / '.env' load_dotenv(dotenv_path=env_path) if apitoken is None: self.GRAPHQL_API_TOKEN = os.getenv("GRAPHQL_API_TOKEN") else: self.GRAPHQL_API_TOKEN = apitoken if apiurl is None: self.GRAPHQL_API_ENDPOINT = os.getenv("GRAPHQL_API_ENDPOINT") else: self.GRAPHQL_API_ENDPOINT = apiurl if self.GRAPHQL_API_TOKEN is None: raise Exception('API TOKEN is not validate.') if self.GRAPHQL_API_ENDPOINT is None: raise Exception('API URL is not validate.') self.headers = {'Authorization': 'Token ' + self.GRAPHQL_API_TOKEN, 'Content-Type': 'application/json'} pass def create_research_plan_metric(self, research_plan_id, code, name, description, iou, weighted, object_class_id): """ create the researchPlanMetric. but research_plan_id and code, name are required. :param research_plan_id: :param code: :param name: :param description: :param iou: :param weighted: :param object_class_id: """ if (research_plan_id is None or research_plan_id == '' or research_plan_id == 0) or \ (code is None or code == '') or \ (name is None or name == ''): raise Exception('research_plan_id and code, name are required.') op = Operation(silverpond_schema.Mutation) parent = op.create_research_plan_metric(research_plan_id=research_plan_id, code=code, name=name, description=description, iou=iou, weighted=weighted, object_class_id=object_class_id ) # Field Set parent.errors() researchplanmetric = parent.research_plan_metric() fieldset_research_plan_metrics(researchplanmetric) ql_endpoint = HTTPEndpoint(self.GRAPHQL_API_ENDPOINT, self.headers) data = ql_endpoint(op) obj = op + data if len(obj.create_research_plan_metric.errors) > 0: raise Exception(obj.create_research_plan_metric.errors[0]) return obj.create_research_plan_metric.research_plan_metric def update_research_plan_metric(self, id, research_plan_id, code, name, description, iou, weighted, object_class_id): """ update the experiment. but id, research_plan_id, code, name are required. :param id: :param research_plan_id: :param code: :param name: :param description: :param iou: :param weighted: :param object_class_id: """ if (id is None or id == '' or id == 0) or \ (research_plan_id is None or research_plan_id == '' or research_plan_id == 0) or \ (code is None or code == '') or \ (name is None or name == ''): raise Exception('id and research_plan_id, code, name are required.') op = Operation(silverpond_schema.Mutation) parent = op.update_research_plan_metric(id=id, research_plan_id=research_plan_id, code=code, name=name, description=description, iou=iou, weighted=weighted, object_class_id=object_class_id ) # Field Set parent.errors() researchplanmetric = parent.research_plan_metric() fieldset_research_plan_metrics(researchplanmetric) ql_endpoint = HTTPEndpoint(self.GRAPHQL_API_ENDPOINT, self.headers) data = ql_endpoint(op) obj = op + data if len(obj.update_research_plan_metric.errors) > 0: raise Exception(obj.update_research_plan_metric.errors[0]) return obj.update_research_plan_metric.research_plan_metric
40.065574
121
0.565262
__author__ = 'Mykhailo' import os from pathlib import Path from dotenv import load_dotenv from sgqlc.endpoint.http import HTTPEndpoint as HTTPEndpoint import logging from .schema.silverpond_schema import silverpond_schema from sgqlc.operation import Operation from .fieldset_functions import * class ResearchPlanMetric(object): logger = logging.getLogger('silverpond') def __init__(self, apitoken=None, apiurl=None): env_path = Path('.') / '.env' load_dotenv(dotenv_path=env_path) if apitoken is None: self.GRAPHQL_API_TOKEN = os.getenv("GRAPHQL_API_TOKEN") else: self.GRAPHQL_API_TOKEN = apitoken if apiurl is None: self.GRAPHQL_API_ENDPOINT = os.getenv("GRAPHQL_API_ENDPOINT") else: self.GRAPHQL_API_ENDPOINT = apiurl if self.GRAPHQL_API_TOKEN is None: raise Exception('API TOKEN is not validate.') if self.GRAPHQL_API_ENDPOINT is None: raise Exception('API URL is not validate.') self.headers = {'Authorization': 'Token ' + self.GRAPHQL_API_TOKEN, 'Content-Type': 'application/json'} pass def create_research_plan_metric(self, research_plan_id, code, name, description, iou, weighted, object_class_id): if (research_plan_id is None or research_plan_id == '' or research_plan_id == 0) or \ (code is None or code == '') or \ (name is None or name == ''): raise Exception('research_plan_id and code, name are required.') op = Operation(silverpond_schema.Mutation) parent = op.create_research_plan_metric(research_plan_id=research_plan_id, code=code, name=name, description=description, iou=iou, weighted=weighted, object_class_id=object_class_id ) parent.errors() researchplanmetric = parent.research_plan_metric() fieldset_research_plan_metrics(researchplanmetric) ql_endpoint = HTTPEndpoint(self.GRAPHQL_API_ENDPOINT, self.headers) data = ql_endpoint(op) obj = op + data if len(obj.create_research_plan_metric.errors) > 0: raise Exception(obj.create_research_plan_metric.errors[0]) return obj.create_research_plan_metric.research_plan_metric def update_research_plan_metric(self, id, research_plan_id, code, name, description, iou, weighted, object_class_id): if (id is None or id == '' or id == 0) or \ (research_plan_id is None or research_plan_id == '' or research_plan_id == 0) or \ (code is None or code == '') or \ (name is None or name == ''): raise Exception('id and research_plan_id, code, name are required.') op = Operation(silverpond_schema.Mutation) parent = op.update_research_plan_metric(id=id, research_plan_id=research_plan_id, code=code, name=name, description=description, iou=iou, weighted=weighted, object_class_id=object_class_id ) parent.errors() researchplanmetric = parent.research_plan_metric() fieldset_research_plan_metrics(researchplanmetric) ql_endpoint = HTTPEndpoint(self.GRAPHQL_API_ENDPOINT, self.headers) data = ql_endpoint(op) obj = op + data if len(obj.update_research_plan_metric.errors) > 0: raise Exception(obj.update_research_plan_metric.errors[0]) return obj.update_research_plan_metric.research_plan_metric
true
true
f7f9fc697b9a0715618f38f50199d910f5df537b
908
py
Python
curious_agent/util/custom_json_encoder.py
kingspp/curious_agent
01b3c6568f263d60cb8a7e9c3b048d93b64443d4
[ "MIT" ]
1
2020-12-20T15:24:31.000Z
2020-12-20T15:24:31.000Z
curious_agent/util/custom_json_encoder.py
kingspp/curious_agent
01b3c6568f263d60cb8a7e9c3b048d93b64443d4
[ "MIT" ]
8
2019-11-10T16:53:26.000Z
2019-11-23T03:26:34.000Z
curious_agent/util/custom_json_encoder.py
kingspp/curious_agent
01b3c6568f263d60cb8a7e9c3b048d93b64443d4
[ "MIT" ]
null
null
null
import json import numpy as np from torch import nn class CustomJsonEncoder(json.JSONEncoder): """ Special json encoder for numpy types """ def default(self, obj): if isinstance(obj, (np.int_, np.intc, np.intp, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64)): return int(obj) elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)): return float(obj) elif isinstance(obj, (np.ndarray,)): return obj.tolist() elif isinstance(obj, set): return list(obj) elif isinstance(obj, nn.Module): return obj.__str__() else: try: return obj.default() except Exception: return f'Object not serializable - {obj}'
32.428571
67
0.528634
import json import numpy as np from torch import nn class CustomJsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, (np.int_, np.intc, np.intp, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64)): return int(obj) elif isinstance(obj, (np.float_, np.float16, np.float32, np.float64)): return float(obj) elif isinstance(obj, (np.ndarray,)): return obj.tolist() elif isinstance(obj, set): return list(obj) elif isinstance(obj, nn.Module): return obj.__str__() else: try: return obj.default() except Exception: return f'Object not serializable - {obj}'
true
true
f7f9fc87e135b4785df9ba0665c0efcec7ca2eb4
263
py
Python
livesettings/urls.py
predatell/django-livesettings
ea2cc09adf50cbac01c671841e8cb3d7e5c292e8
[ "BSD-3-Clause" ]
null
null
null
livesettings/urls.py
predatell/django-livesettings
ea2cc09adf50cbac01c671841e8cb3d7e5c292e8
[ "BSD-3-Clause" ]
null
null
null
livesettings/urls.py
predatell/django-livesettings
ea2cc09adf50cbac01c671841e8cb3d7e5c292e8
[ "BSD-3-Clause" ]
2
2018-12-04T10:47:35.000Z
2019-03-06T17:28:27.000Z
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.site_settings, {}, 'satchmo_site_settings'), url(r'^export/$', views.export_as_python, {}, 'settings_export'), url(r'^(?P<group>[^/]+)/$', views.group_settings), ]
29.222222
69
0.65019
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.site_settings, {}, 'satchmo_site_settings'), url(r'^export/$', views.export_as_python, {}, 'settings_export'), url(r'^(?P<group>[^/]+)/$', views.group_settings), ]
true
true
f7f9fd58985adb8a08c6fb3613b2ae424b4c2df6
452,894
py
Python
run_unittests.py
gh-fork-dump/meson
10c8bd0e6742b297ea5f78bf19711c451f8f0165
[ "Apache-2.0" ]
null
null
null
run_unittests.py
gh-fork-dump/meson
10c8bd0e6742b297ea5f78bf19711c451f8f0165
[ "Apache-2.0" ]
null
null
null
run_unittests.py
gh-fork-dump/meson
10c8bd0e6742b297ea5f78bf19711c451f8f0165
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 # Copyright 2016-2017 The Meson development team # 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 time import stat import subprocess import re import json import tempfile import textwrap import os import shutil import sys import unittest import platform import pickle import functools import io import operator import threading import zipfile, tarfile import hashlib from itertools import chain from unittest import mock from configparser import ConfigParser from contextlib import contextmanager from glob import glob from pathlib import (PurePath, Path) from distutils.dir_util import copy_tree import typing as T import mesonbuild.mlog import mesonbuild.depfile import mesonbuild.dependencies.base import mesonbuild.compilers import mesonbuild.envconfig import mesonbuild.environment import mesonbuild.mesonlib import mesonbuild.coredata import mesonbuild.modules.gnome from mesonbuild.interpreter import Interpreter, ObjectHolder from mesonbuild.interpreterbase import typed_pos_args, InvalidArguments from mesonbuild.ast import AstInterpreter from mesonbuild.mesonlib import ( BuildDirLock, LibType, MachineChoice, PerMachine, Version, is_windows, is_osx, is_cygwin, is_dragonflybsd, is_openbsd, is_haiku, is_sunos, windows_proof_rmtree, python_command, version_compare, split_args, quote_arg, relpath, is_linux, git ) from mesonbuild.environment import detect_ninja from mesonbuild.mesonlib import MesonException, EnvironmentException, OptionKey from mesonbuild.dependencies import PkgConfigDependency, ExternalProgram import mesonbuild.dependencies.base from mesonbuild.build import Target, ConfigurationData import mesonbuild.modules.pkgconfig from mesonbuild.scripts import destdir_join from mesonbuild.mtest import TAPParser, TestResult from mesonbuild.wrap.wrap import PackageDefinition, WrapException from run_tests import ( Backend, FakeBuild, FakeCompilerOptions, ensure_backend_detects_changes, exe_suffix, get_backend_commands, get_builddir_target_args, get_fake_env, get_fake_options, get_meson_script, run_configure_inprocess, run_mtest_inprocess ) if T.TYPE_CHECKING: from mesonbuild.compilers import Compiler URLOPEN_TIMEOUT = 5 @contextmanager def chdir(path: str): curdir = os.getcwd() os.chdir(path) try: yield finally: os.chdir(curdir) def get_dynamic_section_entry(fname: str, entry: str) -> T.Optional[str]: if is_cygwin() or is_osx(): raise unittest.SkipTest('Test only applicable to ELF platforms') try: raw_out = subprocess.check_output(['readelf', '-d', fname], universal_newlines=True) except FileNotFoundError: # FIXME: Try using depfixer.py:Elf() as a fallback raise unittest.SkipTest('readelf not found') pattern = re.compile(entry + r': \[(.*?)\]') for line in raw_out.split('\n'): m = pattern.search(line) if m is not None: return str(m.group(1)) return None # The file did not contain the specified entry. def get_soname(fname: str) -> T.Optional[str]: return get_dynamic_section_entry(fname, 'soname') def get_rpath(fname: str) -> T.Optional[str]: raw = get_dynamic_section_entry(fname, r'(?:rpath|runpath)') # Get both '' and None here if not raw: return None # nix/nixos adds a bunch of stuff to the rpath out of necessity that we # don't check for, so clear those final = ':'.join([e for e in raw.split(':') if not e.startswith('/nix')]) return final def is_tarball(): if not os.path.isdir('docs'): return True return False def is_ci(): if 'CI' in os.environ: return True return False def _git_init(project_dir): # If a user has git configuration init.defaultBranch set we want to override that with tempfile.TemporaryDirectory() as d: out = git(['--version'], str(d))[1] if version_compare(mesonbuild.environment.search_version(out), '>= 2.28'): extra_cmd = ['--initial-branch', 'master'] else: extra_cmd = [] subprocess.check_call(['git', 'init'] + extra_cmd, cwd=project_dir, stdout=subprocess.DEVNULL) subprocess.check_call(['git', 'config', 'user.name', 'Author Person'], cwd=project_dir) subprocess.check_call(['git', 'config', 'user.email', 'teh_coderz@example.com'], cwd=project_dir) _git_add_all(project_dir) def _git_add_all(project_dir): subprocess.check_call('git add *', cwd=project_dir, shell=True, stdout=subprocess.DEVNULL) subprocess.check_call(['git', 'commit', '-a', '-m', 'I am a project'], cwd=project_dir, stdout=subprocess.DEVNULL) @functools.lru_cache() def is_real_gnu_compiler(path): ''' Check if the gcc we have is a real gcc and not a macOS wrapper around clang ''' if not path: return False out = subprocess.check_output([path, '--version'], universal_newlines=True, stderr=subprocess.STDOUT) return 'Free Software Foundation' in out def skipIfNoExecutable(exename): ''' Skip this test if the given executable is not found. ''' def wrapper(func): @functools.wraps(func) def wrapped(*args, **kwargs): if shutil.which(exename) is None: raise unittest.SkipTest(exename + ' not found') return func(*args, **kwargs) return wrapped return wrapper def skipIfNoPkgconfig(f): ''' Skip this test if no pkg-config is found, unless we're on CI. This allows users to run our test suite without having pkg-config installed on, f.ex., macOS, while ensuring that our CI does not silently skip the test because of misconfiguration. Note: Yes, we provide pkg-config even while running Windows CI ''' @functools.wraps(f) def wrapped(*args, **kwargs): if not is_ci() and shutil.which('pkg-config') is None: raise unittest.SkipTest('pkg-config not found') return f(*args, **kwargs) return wrapped def skipIfNoPkgconfigDep(depname): ''' Skip this test if the given pkg-config dep is not found, unless we're on CI. ''' def wrapper(func): @functools.wraps(func) def wrapped(*args, **kwargs): if not is_ci() and shutil.which('pkg-config') is None: raise unittest.SkipTest('pkg-config not found') if not is_ci() and subprocess.call(['pkg-config', '--exists', depname]) != 0: raise unittest.SkipTest('pkg-config dependency {} not found.'.format(depname)) return func(*args, **kwargs) return wrapped return wrapper def skip_if_no_cmake(f): ''' Skip this test if no cmake is found, unless we're on CI. This allows users to run our test suite without having cmake installed on, f.ex., macOS, while ensuring that our CI does not silently skip the test because of misconfiguration. ''' @functools.wraps(f) def wrapped(*args, **kwargs): if not is_ci() and shutil.which('cmake') is None: raise unittest.SkipTest('cmake not found') return f(*args, **kwargs) return wrapped def skip_if_not_language(lang): def wrapper(func): @functools.wraps(func) def wrapped(*args, **kwargs): try: env = get_fake_env() f = getattr(env, 'detect_{}_compiler'.format(lang)) f(MachineChoice.HOST) except EnvironmentException: raise unittest.SkipTest('No {} compiler found.'.format(lang)) return func(*args, **kwargs) return wrapped return wrapper def skip_if_env_set(key): ''' Skip a test if a particular env is set, except when running under CI ''' def wrapper(func): @functools.wraps(func) def wrapped(*args, **kwargs): old = None if key in os.environ: if not is_ci(): raise unittest.SkipTest('Env var {!r} set, skipping'.format(key)) old = os.environ.pop(key) try: return func(*args, **kwargs) finally: if old is not None: os.environ[key] = old return wrapped return wrapper def skip_if_not_base_option(feature): """Skip tests if The compiler does not support a given base option. for example, ICC doesn't currently support b_sanitize. """ def actual(f): @functools.wraps(f) def wrapped(*args, **kwargs): env = get_fake_env() cc = env.detect_c_compiler(MachineChoice.HOST) key = OptionKey(feature) if key not in cc.base_options: raise unittest.SkipTest( '{} not available with {}'.format(feature, cc.id)) return f(*args, **kwargs) return wrapped return actual @contextmanager def temp_filename(): '''A context manager which provides a filename to an empty temporary file. On exit the file will be deleted. ''' fd, filename = tempfile.mkstemp() os.close(fd) try: yield filename finally: try: os.remove(filename) except OSError: pass @contextmanager def no_pkgconfig(): ''' A context manager that overrides shutil.which and ExternalProgram to force them to return None for pkg-config to simulate it not existing. ''' old_which = shutil.which old_search = ExternalProgram._search def new_search(self, name, search_dir): if name == 'pkg-config': return [None] return old_search(self, name, search_dir) def new_which(cmd, *kwargs): if cmd == 'pkg-config': return None return old_which(cmd, *kwargs) shutil.which = new_which ExternalProgram._search = new_search try: yield finally: shutil.which = old_which ExternalProgram._search = old_search class InternalTests(unittest.TestCase): def test_version_number(self): searchfunc = mesonbuild.environment.search_version self.assertEqual(searchfunc('foobar 1.2.3'), '1.2.3') self.assertEqual(searchfunc('1.2.3'), '1.2.3') self.assertEqual(searchfunc('foobar 2016.10.28 1.2.3'), '1.2.3') self.assertEqual(searchfunc('2016.10.28 1.2.3'), '1.2.3') self.assertEqual(searchfunc('foobar 2016.10.128'), '2016.10.128') self.assertEqual(searchfunc('2016.10.128'), '2016.10.128') self.assertEqual(searchfunc('2016.10'), '2016.10') self.assertEqual(searchfunc('2016.10 1.2.3'), '1.2.3') self.assertEqual(searchfunc('oops v1.2.3'), '1.2.3') self.assertEqual(searchfunc('2016.oops 1.2.3'), '1.2.3') self.assertEqual(searchfunc('2016.x'), 'unknown version') def test_mode_symbolic_to_bits(self): modefunc = mesonbuild.mesonlib.FileMode.perms_s_to_bits self.assertEqual(modefunc('---------'), 0) self.assertEqual(modefunc('r--------'), stat.S_IRUSR) self.assertEqual(modefunc('---r-----'), stat.S_IRGRP) self.assertEqual(modefunc('------r--'), stat.S_IROTH) self.assertEqual(modefunc('-w-------'), stat.S_IWUSR) self.assertEqual(modefunc('----w----'), stat.S_IWGRP) self.assertEqual(modefunc('-------w-'), stat.S_IWOTH) self.assertEqual(modefunc('--x------'), stat.S_IXUSR) self.assertEqual(modefunc('-----x---'), stat.S_IXGRP) self.assertEqual(modefunc('--------x'), stat.S_IXOTH) self.assertEqual(modefunc('--S------'), stat.S_ISUID) self.assertEqual(modefunc('-----S---'), stat.S_ISGID) self.assertEqual(modefunc('--------T'), stat.S_ISVTX) self.assertEqual(modefunc('--s------'), stat.S_ISUID | stat.S_IXUSR) self.assertEqual(modefunc('-----s---'), stat.S_ISGID | stat.S_IXGRP) self.assertEqual(modefunc('--------t'), stat.S_ISVTX | stat.S_IXOTH) self.assertEqual(modefunc('rwx------'), stat.S_IRWXU) self.assertEqual(modefunc('---rwx---'), stat.S_IRWXG) self.assertEqual(modefunc('------rwx'), stat.S_IRWXO) # We could keep listing combinations exhaustively but that seems # tedious and pointless. Just test a few more. self.assertEqual(modefunc('rwxr-xr-x'), stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH) self.assertEqual(modefunc('rw-r--r--'), stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH) self.assertEqual(modefunc('rwsr-x---'), stat.S_IRWXU | stat.S_ISUID | stat.S_IRGRP | stat.S_IXGRP) def test_compiler_args_class_none_flush(self): cc = mesonbuild.compilers.ClangCCompiler([], 'fake', MachineChoice.HOST, False, mock.Mock()) a = cc.compiler_args(['-I.']) #first we are checking if the tree construction deduplicates the correct -I argument a += ['-I..'] a += ['-I./tests/'] a += ['-I./tests2/'] #think this here as assertion, we cannot apply it, otherwise the CompilerArgs would already flush the changes: # assertEqual(a, ['-I.', '-I./tests2/', '-I./tests/', '-I..', '-I.']) a += ['-I.'] a += ['-I.', '-I./tests/'] self.assertEqual(a, ['-I.', '-I./tests/', '-I./tests2/', '-I..']) #then we are checking that when CompilerArgs already have a build container list, that the deduplication is taking the correct one a += ['-I.', '-I./tests2/'] self.assertEqual(a, ['-I.', '-I./tests2/', '-I./tests/', '-I..']) def test_compiler_args_class_d(self): d = mesonbuild.compilers.DmdDCompiler([], 'fake', MachineChoice.HOST, 'info', 'arch') # check include order is kept when deduplicating a = d.compiler_args(['-Ifirst', '-Isecond', '-Ithird']) a += ['-Ifirst'] self.assertEqual(a, ['-Ifirst', '-Isecond', '-Ithird']) def test_compiler_args_class_clike(self): cc = mesonbuild.compilers.ClangCCompiler([], 'fake', MachineChoice.HOST, False, mock.Mock()) # Test that empty initialization works a = cc.compiler_args() self.assertEqual(a, []) # Test that list initialization works a = cc.compiler_args(['-I.', '-I..']) self.assertEqual(a, ['-I.', '-I..']) # Test that there is no de-dup on initialization self.assertEqual(cc.compiler_args(['-I.', '-I.']), ['-I.', '-I.']) ## Test that appending works a.append('-I..') self.assertEqual(a, ['-I..', '-I.']) a.append('-O3') self.assertEqual(a, ['-I..', '-I.', '-O3']) ## Test that in-place addition works a += ['-O2', '-O2'] self.assertEqual(a, ['-I..', '-I.', '-O3', '-O2', '-O2']) # Test that removal works a.remove('-O2') self.assertEqual(a, ['-I..', '-I.', '-O3', '-O2']) # Test that de-dup happens on addition a += ['-Ifoo', '-Ifoo'] self.assertEqual(a, ['-Ifoo', '-I..', '-I.', '-O3', '-O2']) # .extend() is just +=, so we don't test it ## Test that addition works # Test that adding a list with just one old arg works and yields the same array a = a + ['-Ifoo'] self.assertEqual(a, ['-Ifoo', '-I..', '-I.', '-O3', '-O2']) # Test that adding a list with one arg new and one old works a = a + ['-Ifoo', '-Ibaz'] self.assertEqual(a, ['-Ifoo', '-Ibaz', '-I..', '-I.', '-O3', '-O2']) # Test that adding args that must be prepended and appended works a = a + ['-Ibar', '-Wall'] self.assertEqual(a, ['-Ibar', '-Ifoo', '-Ibaz', '-I..', '-I.', '-O3', '-O2', '-Wall']) ## Test that reflected addition works # Test that adding to a list with just one old arg works and yields the same array a = ['-Ifoo'] + a self.assertEqual(a, ['-Ibar', '-Ifoo', '-Ibaz', '-I..', '-I.', '-O3', '-O2', '-Wall']) # Test that adding to a list with just one new arg that is not pre-pended works a = ['-Werror'] + a self.assertEqual(a, ['-Ibar', '-Ifoo', '-Ibaz', '-I..', '-I.', '-Werror', '-O3', '-O2', '-Wall']) # Test that adding to a list with two new args preserves the order a = ['-Ldir', '-Lbah'] + a self.assertEqual(a, ['-Ibar', '-Ifoo', '-Ibaz', '-I..', '-I.', '-Ldir', '-Lbah', '-Werror', '-O3', '-O2', '-Wall']) # Test that adding to a list with old args does nothing a = ['-Ibar', '-Ibaz', '-Ifoo'] + a self.assertEqual(a, ['-Ibar', '-Ifoo', '-Ibaz', '-I..', '-I.', '-Ldir', '-Lbah', '-Werror', '-O3', '-O2', '-Wall']) ## Test that adding libraries works l = cc.compiler_args(['-Lfoodir', '-lfoo']) self.assertEqual(l, ['-Lfoodir', '-lfoo']) # Adding a library and a libpath appends both correctly l += ['-Lbardir', '-lbar'] self.assertEqual(l, ['-Lbardir', '-Lfoodir', '-lfoo', '-lbar']) # Adding the same library again does nothing l += ['-lbar'] self.assertEqual(l, ['-Lbardir', '-Lfoodir', '-lfoo', '-lbar']) ## Test that 'direct' append and extend works l = cc.compiler_args(['-Lfoodir', '-lfoo']) self.assertEqual(l, ['-Lfoodir', '-lfoo']) # Direct-adding a library and a libpath appends both correctly l.extend_direct(['-Lbardir', '-lbar']) self.assertEqual(l, ['-Lfoodir', '-lfoo', '-Lbardir', '-lbar']) # Direct-adding the same library again still adds it l.append_direct('-lbar') self.assertEqual(l, ['-Lfoodir', '-lfoo', '-Lbardir', '-lbar', '-lbar']) # Direct-adding with absolute path deduplicates l.append_direct('/libbaz.a') self.assertEqual(l, ['-Lfoodir', '-lfoo', '-Lbardir', '-lbar', '-lbar', '/libbaz.a']) # Adding libbaz again does nothing l.append_direct('/libbaz.a') self.assertEqual(l, ['-Lfoodir', '-lfoo', '-Lbardir', '-lbar', '-lbar', '/libbaz.a']) def test_compiler_args_class_gnuld(self): ## Test --start/end-group linker = mesonbuild.linkers.GnuBFDDynamicLinker([], MachineChoice.HOST, '-Wl,', []) gcc = mesonbuild.compilers.GnuCCompiler([], 'fake', False, MachineChoice.HOST, mock.Mock(), linker=linker) ## Ensure that the fake compiler is never called by overriding the relevant function gcc.get_default_include_dirs = lambda: ['/usr/include', '/usr/share/include', '/usr/local/include'] ## Test that 'direct' append and extend works l = gcc.compiler_args(['-Lfoodir', '-lfoo']) self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-Wl,--start-group', '-lfoo', '-Wl,--end-group']) # Direct-adding a library and a libpath appends both correctly l.extend_direct(['-Lbardir', '-lbar']) self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-Wl,--start-group', '-lfoo', '-Lbardir', '-lbar', '-Wl,--end-group']) # Direct-adding the same library again still adds it l.append_direct('-lbar') self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-Wl,--start-group', '-lfoo', '-Lbardir', '-lbar', '-lbar', '-Wl,--end-group']) # Direct-adding with absolute path deduplicates l.append_direct('/libbaz.a') self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-Wl,--start-group', '-lfoo', '-Lbardir', '-lbar', '-lbar', '/libbaz.a', '-Wl,--end-group']) # Adding libbaz again does nothing l.append_direct('/libbaz.a') self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-Wl,--start-group', '-lfoo', '-Lbardir', '-lbar', '-lbar', '/libbaz.a', '-Wl,--end-group']) # Adding a non-library argument doesn't include it in the group l += ['-Lfoo', '-Wl,--export-dynamic'] self.assertEqual(l.to_native(copy=True), ['-Lfoo', '-Lfoodir', '-Wl,--start-group', '-lfoo', '-Lbardir', '-lbar', '-lbar', '/libbaz.a', '-Wl,--end-group', '-Wl,--export-dynamic']) # -Wl,-lfoo is detected as a library and gets added to the group l.append('-Wl,-ldl') self.assertEqual(l.to_native(copy=True), ['-Lfoo', '-Lfoodir', '-Wl,--start-group', '-lfoo', '-Lbardir', '-lbar', '-lbar', '/libbaz.a', '-Wl,--export-dynamic', '-Wl,-ldl', '-Wl,--end-group']) def test_compiler_args_remove_system(self): ## Test --start/end-group linker = mesonbuild.linkers.GnuBFDDynamicLinker([], MachineChoice.HOST, '-Wl,', []) gcc = mesonbuild.compilers.GnuCCompiler([], 'fake', False, MachineChoice.HOST, mock.Mock(), linker=linker) ## Ensure that the fake compiler is never called by overriding the relevant function gcc.get_default_include_dirs = lambda: ['/usr/include', '/usr/share/include', '/usr/local/include'] ## Test that 'direct' append and extend works l = gcc.compiler_args(['-Lfoodir', '-lfoo']) self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-Wl,--start-group', '-lfoo', '-Wl,--end-group']) ## Test that to_native removes all system includes l += ['-isystem/usr/include', '-isystem=/usr/share/include', '-DSOMETHING_IMPORTANT=1', '-isystem', '/usr/local/include'] self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-Wl,--start-group', '-lfoo', '-Wl,--end-group', '-DSOMETHING_IMPORTANT=1']) def test_string_templates_substitution(self): dictfunc = mesonbuild.mesonlib.get_filenames_templates_dict substfunc = mesonbuild.mesonlib.substitute_values ME = mesonbuild.mesonlib.MesonException # Identity self.assertEqual(dictfunc([], []), {}) # One input, no outputs inputs = ['bar/foo.c.in'] outputs = [] ret = dictfunc(inputs, outputs) d = {'@INPUT@': inputs, '@INPUT0@': inputs[0], '@PLAINNAME@': 'foo.c.in', '@BASENAME@': 'foo.c'} # Check dictionary self.assertEqual(ret, d) # Check substitutions cmd = ['some', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), cmd) cmd = ['@INPUT@.out', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), [inputs[0] + '.out'] + cmd[1:]) cmd = ['@INPUT0@.out', '@PLAINNAME@.ok', 'strings'] self.assertEqual(substfunc(cmd, d), [inputs[0] + '.out'] + [d['@PLAINNAME@'] + '.ok'] + cmd[2:]) cmd = ['@INPUT@', '@BASENAME@.hah', 'strings'] self.assertEqual(substfunc(cmd, d), inputs + [d['@BASENAME@'] + '.hah'] + cmd[2:]) cmd = ['@OUTPUT@'] self.assertRaises(ME, substfunc, cmd, d) # One input, one output inputs = ['bar/foo.c.in'] outputs = ['out.c'] ret = dictfunc(inputs, outputs) d = {'@INPUT@': inputs, '@INPUT0@': inputs[0], '@PLAINNAME@': 'foo.c.in', '@BASENAME@': 'foo.c', '@OUTPUT@': outputs, '@OUTPUT0@': outputs[0], '@OUTDIR@': '.'} # Check dictionary self.assertEqual(ret, d) # Check substitutions cmd = ['some', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), cmd) cmd = ['@INPUT@.out', '@OUTPUT@', 'strings'] self.assertEqual(substfunc(cmd, d), [inputs[0] + '.out'] + outputs + cmd[2:]) cmd = ['@INPUT0@.out', '@PLAINNAME@.ok', '@OUTPUT0@'] self.assertEqual(substfunc(cmd, d), [inputs[0] + '.out', d['@PLAINNAME@'] + '.ok'] + outputs) cmd = ['@INPUT@', '@BASENAME@.hah', 'strings'] self.assertEqual(substfunc(cmd, d), inputs + [d['@BASENAME@'] + '.hah'] + cmd[2:]) # One input, one output with a subdir outputs = ['dir/out.c'] ret = dictfunc(inputs, outputs) d = {'@INPUT@': inputs, '@INPUT0@': inputs[0], '@PLAINNAME@': 'foo.c.in', '@BASENAME@': 'foo.c', '@OUTPUT@': outputs, '@OUTPUT0@': outputs[0], '@OUTDIR@': 'dir'} # Check dictionary self.assertEqual(ret, d) # Two inputs, no outputs inputs = ['bar/foo.c.in', 'baz/foo.c.in'] outputs = [] ret = dictfunc(inputs, outputs) d = {'@INPUT@': inputs, '@INPUT0@': inputs[0], '@INPUT1@': inputs[1]} # Check dictionary self.assertEqual(ret, d) # Check substitutions cmd = ['some', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), cmd) cmd = ['@INPUT@', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), inputs + cmd[1:]) cmd = ['@INPUT0@.out', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), [inputs[0] + '.out'] + cmd[1:]) cmd = ['@INPUT0@.out', '@INPUT1@.ok', 'strings'] self.assertEqual(substfunc(cmd, d), [inputs[0] + '.out', inputs[1] + '.ok'] + cmd[2:]) cmd = ['@INPUT0@', '@INPUT1@', 'strings'] self.assertEqual(substfunc(cmd, d), inputs + cmd[2:]) # Many inputs, can't use @INPUT@ like this cmd = ['@INPUT@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) # Not enough inputs cmd = ['@INPUT2@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) # Too many inputs cmd = ['@PLAINNAME@'] self.assertRaises(ME, substfunc, cmd, d) cmd = ['@BASENAME@'] self.assertRaises(ME, substfunc, cmd, d) # No outputs cmd = ['@OUTPUT@'] self.assertRaises(ME, substfunc, cmd, d) cmd = ['@OUTPUT0@'] self.assertRaises(ME, substfunc, cmd, d) cmd = ['@OUTDIR@'] self.assertRaises(ME, substfunc, cmd, d) # Two inputs, one output outputs = ['dir/out.c'] ret = dictfunc(inputs, outputs) d = {'@INPUT@': inputs, '@INPUT0@': inputs[0], '@INPUT1@': inputs[1], '@OUTPUT@': outputs, '@OUTPUT0@': outputs[0], '@OUTDIR@': 'dir'} # Check dictionary self.assertEqual(ret, d) # Check substitutions cmd = ['some', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), cmd) cmd = ['@OUTPUT@', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), outputs + cmd[1:]) cmd = ['@OUTPUT@.out', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), [outputs[0] + '.out'] + cmd[1:]) cmd = ['@OUTPUT0@.out', '@INPUT1@.ok', 'strings'] self.assertEqual(substfunc(cmd, d), [outputs[0] + '.out', inputs[1] + '.ok'] + cmd[2:]) # Many inputs, can't use @INPUT@ like this cmd = ['@INPUT@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) # Not enough inputs cmd = ['@INPUT2@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) # Not enough outputs cmd = ['@OUTPUT2@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) # Two inputs, two outputs outputs = ['dir/out.c', 'dir/out2.c'] ret = dictfunc(inputs, outputs) d = {'@INPUT@': inputs, '@INPUT0@': inputs[0], '@INPUT1@': inputs[1], '@OUTPUT@': outputs, '@OUTPUT0@': outputs[0], '@OUTPUT1@': outputs[1], '@OUTDIR@': 'dir'} # Check dictionary self.assertEqual(ret, d) # Check substitutions cmd = ['some', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), cmd) cmd = ['@OUTPUT@', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), outputs + cmd[1:]) cmd = ['@OUTPUT0@', '@OUTPUT1@', 'strings'] self.assertEqual(substfunc(cmd, d), outputs + cmd[2:]) cmd = ['@OUTPUT0@.out', '@INPUT1@.ok', '@OUTDIR@'] self.assertEqual(substfunc(cmd, d), [outputs[0] + '.out', inputs[1] + '.ok', 'dir']) # Many inputs, can't use @INPUT@ like this cmd = ['@INPUT@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) # Not enough inputs cmd = ['@INPUT2@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) # Not enough outputs cmd = ['@OUTPUT2@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) # Many outputs, can't use @OUTPUT@ like this cmd = ['@OUTPUT@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) def test_needs_exe_wrapper_override(self): config = ConfigParser() config['binaries'] = { 'c': '\'/usr/bin/gcc\'', } config['host_machine'] = { 'system': '\'linux\'', 'cpu_family': '\'arm\'', 'cpu': '\'armv7\'', 'endian': '\'little\'', } # Can not be used as context manager because we need to # open it a second time and this is not possible on # Windows. configfile = tempfile.NamedTemporaryFile(mode='w+', delete=False) configfilename = configfile.name config.write(configfile) configfile.flush() configfile.close() opts = get_fake_options() opts.cross_file = (configfilename,) env = get_fake_env(opts=opts) detected_value = env.need_exe_wrapper() os.unlink(configfilename) desired_value = not detected_value config['properties'] = { 'needs_exe_wrapper': 'true' if desired_value else 'false' } configfile = tempfile.NamedTemporaryFile(mode='w+', delete=False) configfilename = configfile.name config.write(configfile) configfile.close() opts = get_fake_options() opts.cross_file = (configfilename,) env = get_fake_env(opts=opts) forced_value = env.need_exe_wrapper() os.unlink(configfilename) self.assertEqual(forced_value, desired_value) def test_listify(self): listify = mesonbuild.mesonlib.listify # Test sanity self.assertEqual([1], listify(1)) self.assertEqual([], listify([])) self.assertEqual([1], listify([1])) # Test flattening self.assertEqual([1, 2, 3], listify([1, [2, 3]])) self.assertEqual([1, 2, 3], listify([1, [2, [3]]])) self.assertEqual([1, [2, [3]]], listify([1, [2, [3]]], flatten=False)) # Test flattening and unholdering holder1 = ObjectHolder(1) self.assertEqual([holder1], listify(holder1)) self.assertEqual([holder1], listify([holder1])) self.assertEqual([holder1, 2], listify([holder1, 2])) self.assertEqual([holder1, 2, 3], listify([holder1, 2, [3]])) def test_unholder(self): unholder = mesonbuild.mesonlib.unholder holder1 = ObjectHolder(1) holder3 = ObjectHolder(3) holders = [holder1, holder3] self.assertEqual(1, unholder(holder1)) self.assertEqual([1], unholder([holder1])) self.assertEqual([1, 3], unholder(holders)) def test_extract_as_list(self): extract = mesonbuild.mesonlib.extract_as_list # Test sanity kwargs = {'sources': [1, 2, 3]} self.assertEqual([1, 2, 3], extract(kwargs, 'sources')) self.assertEqual(kwargs, {'sources': [1, 2, 3]}) self.assertEqual([1, 2, 3], extract(kwargs, 'sources', pop=True)) self.assertEqual(kwargs, {}) # Test unholding holder3 = ObjectHolder(3) kwargs = {'sources': [1, 2, holder3]} self.assertEqual(kwargs, {'sources': [1, 2, holder3]}) # flatten nested lists kwargs = {'sources': [1, [2, [3]]]} self.assertEqual([1, 2, 3], extract(kwargs, 'sources')) def test_pkgconfig_module(self): dummystate = mock.Mock() dummystate.subproject = 'dummy' _mock = mock.Mock(spec=mesonbuild.dependencies.ExternalDependency) _mock.pcdep = mock.Mock() _mock.pcdep.name = "some_name" _mock.version_reqs = [] _mock = mock.Mock(held_object=_mock) # pkgconfig dependency as lib deps = mesonbuild.modules.pkgconfig.DependenciesHelper(dummystate, "thislib") deps.add_pub_libs([_mock]) self.assertEqual(deps.format_reqs(deps.pub_reqs), "some_name") # pkgconfig dependency as requires deps = mesonbuild.modules.pkgconfig.DependenciesHelper(dummystate, "thislib") deps.add_pub_reqs([_mock]) self.assertEqual(deps.format_reqs(deps.pub_reqs), "some_name") def _test_all_naming(self, cc, env, patterns, platform): shr = patterns[platform]['shared'] stc = patterns[platform]['static'] shrstc = shr + tuple([x for x in stc if x not in shr]) stcshr = stc + tuple([x for x in shr if x not in stc]) p = cc.get_library_naming(env, LibType.SHARED) self.assertEqual(p, shr) p = cc.get_library_naming(env, LibType.STATIC) self.assertEqual(p, stc) p = cc.get_library_naming(env, LibType.PREFER_STATIC) self.assertEqual(p, stcshr) p = cc.get_library_naming(env, LibType.PREFER_SHARED) self.assertEqual(p, shrstc) # Test find library by mocking up openbsd if platform != 'openbsd': return with tempfile.TemporaryDirectory() as tmpdir: with open(os.path.join(tmpdir, 'libfoo.so.6.0'), 'w') as f: f.write('') with open(os.path.join(tmpdir, 'libfoo.so.5.0'), 'w') as f: f.write('') with open(os.path.join(tmpdir, 'libfoo.so.54.0'), 'w') as f: f.write('') with open(os.path.join(tmpdir, 'libfoo.so.66a.0b'), 'w') as f: f.write('') with open(os.path.join(tmpdir, 'libfoo.so.70.0.so.1'), 'w') as f: f.write('') found = cc._find_library_real('foo', env, [tmpdir], '', LibType.PREFER_SHARED) self.assertEqual(os.path.basename(found[0]), 'libfoo.so.54.0') def test_find_library_patterns(self): ''' Unit test for the library search patterns used by find_library() ''' unix_static = ('lib{}.a', '{}.a') msvc_static = ('lib{}.a', 'lib{}.lib', '{}.a', '{}.lib') # This is the priority list of pattern matching for library searching patterns = {'openbsd': {'shared': ('lib{}.so', '{}.so', 'lib{}.so.[0-9]*.[0-9]*', '{}.so.[0-9]*.[0-9]*'), 'static': unix_static}, 'linux': {'shared': ('lib{}.so', '{}.so'), 'static': unix_static}, 'darwin': {'shared': ('lib{}.dylib', 'lib{}.so', '{}.dylib', '{}.so'), 'static': unix_static}, 'cygwin': {'shared': ('cyg{}.dll', 'cyg{}.dll.a', 'lib{}.dll', 'lib{}.dll.a', '{}.dll', '{}.dll.a'), 'static': ('cyg{}.a',) + unix_static}, 'windows-msvc': {'shared': ('lib{}.lib', '{}.lib'), 'static': msvc_static}, 'windows-mingw': {'shared': ('lib{}.dll.a', 'lib{}.lib', 'lib{}.dll', '{}.dll.a', '{}.lib', '{}.dll'), 'static': msvc_static}} env = get_fake_env() cc = env.detect_c_compiler(MachineChoice.HOST) if is_osx(): self._test_all_naming(cc, env, patterns, 'darwin') elif is_cygwin(): self._test_all_naming(cc, env, patterns, 'cygwin') elif is_windows(): if cc.get_argument_syntax() == 'msvc': self._test_all_naming(cc, env, patterns, 'windows-msvc') else: self._test_all_naming(cc, env, patterns, 'windows-mingw') elif is_openbsd(): self._test_all_naming(cc, env, patterns, 'openbsd') else: self._test_all_naming(cc, env, patterns, 'linux') env.machines.host.system = 'openbsd' self._test_all_naming(cc, env, patterns, 'openbsd') env.machines.host.system = 'darwin' self._test_all_naming(cc, env, patterns, 'darwin') env.machines.host.system = 'cygwin' self._test_all_naming(cc, env, patterns, 'cygwin') env.machines.host.system = 'windows' self._test_all_naming(cc, env, patterns, 'windows-mingw') @skipIfNoPkgconfig def test_pkgconfig_parse_libs(self): ''' Unit test for parsing of pkg-config output to search for libraries https://github.com/mesonbuild/meson/issues/3951 ''' def create_static_lib(name): if not is_osx(): name.open('w').close() return src = name.with_suffix('.c') out = name.with_suffix('.o') with src.open('w') as f: f.write('int meson_foobar (void) { return 0; }') subprocess.check_call(['clang', '-c', str(src), '-o', str(out)]) subprocess.check_call(['ar', 'csr', str(name), str(out)]) with tempfile.TemporaryDirectory() as tmpdir: pkgbin = ExternalProgram('pkg-config', command=['pkg-config'], silent=True) env = get_fake_env() compiler = env.detect_c_compiler(MachineChoice.HOST) env.coredata.compilers.host = {'c': compiler} env.coredata.options[OptionKey('link_args', lang='c')] = FakeCompilerOptions() p1 = Path(tmpdir) / '1' p2 = Path(tmpdir) / '2' p1.mkdir() p2.mkdir() # libfoo.a is in one prefix create_static_lib(p1 / 'libfoo.a') # libbar.a is in both prefixes create_static_lib(p1 / 'libbar.a') create_static_lib(p2 / 'libbar.a') # Ensure that we never statically link to these create_static_lib(p1 / 'libpthread.a') create_static_lib(p1 / 'libm.a') create_static_lib(p1 / 'libc.a') create_static_lib(p1 / 'libdl.a') create_static_lib(p1 / 'librt.a') def fake_call_pkgbin(self, args, env=None): if '--libs' not in args: return 0, '', '' if args[-1] == 'foo': return 0, '-L{} -lfoo -L{} -lbar'.format(p2.as_posix(), p1.as_posix()), '' if args[-1] == 'bar': return 0, '-L{} -lbar'.format(p2.as_posix()), '' if args[-1] == 'internal': return 0, '-L{} -lpthread -lm -lc -lrt -ldl'.format(p1.as_posix()), '' old_call = PkgConfigDependency._call_pkgbin old_check = PkgConfigDependency.check_pkgconfig PkgConfigDependency._call_pkgbin = fake_call_pkgbin PkgConfigDependency.check_pkgconfig = lambda x, _: pkgbin # Test begins try: kwargs = {'required': True, 'silent': True} foo_dep = PkgConfigDependency('foo', env, kwargs) self.assertEqual(foo_dep.get_link_args(), [(p1 / 'libfoo.a').as_posix(), (p2 / 'libbar.a').as_posix()]) bar_dep = PkgConfigDependency('bar', env, kwargs) self.assertEqual(bar_dep.get_link_args(), [(p2 / 'libbar.a').as_posix()]) internal_dep = PkgConfigDependency('internal', env, kwargs) if compiler.get_argument_syntax() == 'msvc': self.assertEqual(internal_dep.get_link_args(), []) else: link_args = internal_dep.get_link_args() for link_arg in link_args: for lib in ('pthread', 'm', 'c', 'dl', 'rt'): self.assertNotIn('lib{}.a'.format(lib), link_arg, msg=link_args) finally: # Test ends PkgConfigDependency._call_pkgbin = old_call PkgConfigDependency.check_pkgconfig = old_check # Reset dependency class to ensure that in-process configure doesn't mess up PkgConfigDependency.pkgbin_cache = {} PkgConfigDependency.class_pkgbin = PerMachine(None, None) def test_version_compare(self): comparefunc = mesonbuild.mesonlib.version_compare_many for (a, b, result) in [ ('0.99.beta19', '>= 0.99.beta14', True), ]: self.assertEqual(comparefunc(a, b)[0], result) for (a, b, op) in [ # examples from https://fedoraproject.org/wiki/Archive:Tools/RPM/VersionComparison ("1.0010", "1.9", operator.gt), ("1.05", "1.5", operator.eq), ("1.0", "1", operator.gt), ("2.50", "2.5", operator.gt), ("fc4", "fc.4", operator.eq), ("FC5", "fc4", operator.lt), ("2a", "2.0", operator.lt), ("1.0", "1.fc4", operator.gt), ("3.0.0_fc", "3.0.0.fc", operator.eq), # from RPM tests ("1.0", "1.0", operator.eq), ("1.0", "2.0", operator.lt), ("2.0", "1.0", operator.gt), ("2.0.1", "2.0.1", operator.eq), ("2.0", "2.0.1", operator.lt), ("2.0.1", "2.0", operator.gt), ("2.0.1a", "2.0.1a", operator.eq), ("2.0.1a", "2.0.1", operator.gt), ("2.0.1", "2.0.1a", operator.lt), ("5.5p1", "5.5p1", operator.eq), ("5.5p1", "5.5p2", operator.lt), ("5.5p2", "5.5p1", operator.gt), ("5.5p10", "5.5p10", operator.eq), ("5.5p1", "5.5p10", operator.lt), ("5.5p10", "5.5p1", operator.gt), ("10xyz", "10.1xyz", operator.lt), ("10.1xyz", "10xyz", operator.gt), ("xyz10", "xyz10", operator.eq), ("xyz10", "xyz10.1", operator.lt), ("xyz10.1", "xyz10", operator.gt), ("xyz.4", "xyz.4", operator.eq), ("xyz.4", "8", operator.lt), ("8", "xyz.4", operator.gt), ("xyz.4", "2", operator.lt), ("2", "xyz.4", operator.gt), ("5.5p2", "5.6p1", operator.lt), ("5.6p1", "5.5p2", operator.gt), ("5.6p1", "6.5p1", operator.lt), ("6.5p1", "5.6p1", operator.gt), ("6.0.rc1", "6.0", operator.gt), ("6.0", "6.0.rc1", operator.lt), ("10b2", "10a1", operator.gt), ("10a2", "10b2", operator.lt), ("1.0aa", "1.0aa", operator.eq), ("1.0a", "1.0aa", operator.lt), ("1.0aa", "1.0a", operator.gt), ("10.0001", "10.0001", operator.eq), ("10.0001", "10.1", operator.eq), ("10.1", "10.0001", operator.eq), ("10.0001", "10.0039", operator.lt), ("10.0039", "10.0001", operator.gt), ("4.999.9", "5.0", operator.lt), ("5.0", "4.999.9", operator.gt), ("20101121", "20101121", operator.eq), ("20101121", "20101122", operator.lt), ("20101122", "20101121", operator.gt), ("2_0", "2_0", operator.eq), ("2.0", "2_0", operator.eq), ("2_0", "2.0", operator.eq), ("a", "a", operator.eq), ("a+", "a+", operator.eq), ("a+", "a_", operator.eq), ("a_", "a+", operator.eq), ("+a", "+a", operator.eq), ("+a", "_a", operator.eq), ("_a", "+a", operator.eq), ("+_", "+_", operator.eq), ("_+", "+_", operator.eq), ("_+", "_+", operator.eq), ("+", "_", operator.eq), ("_", "+", operator.eq), # other tests ('0.99.beta19', '0.99.beta14', operator.gt), ("1.0.0", "2.0.0", operator.lt), (".0.0", "2.0.0", operator.lt), ("alpha", "beta", operator.lt), ("1.0", "1.0.0", operator.lt), ("2.456", "2.1000", operator.lt), ("2.1000", "3.111", operator.lt), ("2.001", "2.1", operator.eq), ("2.34", "2.34", operator.eq), ("6.1.2", "6.3.8", operator.lt), ("1.7.3.0", "2.0.0", operator.lt), ("2.24.51", "2.25", operator.lt), ("2.1.5+20120813+gitdcbe778", "2.1.5", operator.gt), ("3.4.1", "3.4b1", operator.gt), ("041206", "200090325", operator.lt), ("0.6.2+git20130413", "0.6.2", operator.gt), ("2.6.0+bzr6602", "2.6.0", operator.gt), ("2.6.0", "2.6b2", operator.gt), ("2.6.0+bzr6602", "2.6b2x", operator.gt), ("0.6.7+20150214+git3a710f9", "0.6.7", operator.gt), ("15.8b", "15.8.0.1", operator.lt), ("1.2rc1", "1.2.0", operator.lt), ]: ver_a = Version(a) ver_b = Version(b) if op is operator.eq: for o, name in [(op, 'eq'), (operator.ge, 'ge'), (operator.le, 'le')]: self.assertTrue(o(ver_a, ver_b), '{} {} {}'.format(ver_a, name, ver_b)) if op is operator.lt: for o, name in [(op, 'lt'), (operator.le, 'le'), (operator.ne, 'ne')]: self.assertTrue(o(ver_a, ver_b), '{} {} {}'.format(ver_a, name, ver_b)) for o, name in [(operator.gt, 'gt'), (operator.ge, 'ge'), (operator.eq, 'eq')]: self.assertFalse(o(ver_a, ver_b), '{} {} {}'.format(ver_a, name, ver_b)) if op is operator.gt: for o, name in [(op, 'gt'), (operator.ge, 'ge'), (operator.ne, 'ne')]: self.assertTrue(o(ver_a, ver_b), '{} {} {}'.format(ver_a, name, ver_b)) for o, name in [(operator.lt, 'lt'), (operator.le, 'le'), (operator.eq, 'eq')]: self.assertFalse(o(ver_a, ver_b), '{} {} {}'.format(ver_a, name, ver_b)) def test_msvc_toolset_version(self): ''' Ensure that the toolset version returns the correct value for this MSVC ''' env = get_fake_env() cc = env.detect_c_compiler(MachineChoice.HOST) if cc.get_argument_syntax() != 'msvc': raise unittest.SkipTest('Test only applies to MSVC-like compilers') toolset_ver = cc.get_toolset_version() self.assertIsNotNone(toolset_ver) # Visual Studio 2015 and older versions do not define VCToolsVersion # TODO: ICL doesn't set this in the VSC2015 profile either if cc.id == 'msvc' and int(''.join(cc.version.split('.')[0:2])) < 1910: return if 'VCToolsVersion' in os.environ: vctools_ver = os.environ['VCToolsVersion'] else: self.assertIn('VCINSTALLDIR', os.environ) # See https://devblogs.microsoft.com/cppblog/finding-the-visual-c-compiler-tools-in-visual-studio-2017/ vctools_ver = (Path(os.environ['VCINSTALLDIR']) / 'Auxiliary' / 'Build' / 'Microsoft.VCToolsVersion.default.txt').read_text() self.assertTrue(vctools_ver.startswith(toolset_ver), msg='{!r} does not start with {!r}'.format(vctools_ver, toolset_ver)) def test_split_args(self): split_args = mesonbuild.mesonlib.split_args join_args = mesonbuild.mesonlib.join_args if is_windows(): test_data = [ # examples from https://docs.microsoft.com/en-us/cpp/c-language/parsing-c-command-line-arguments (r'"a b c" d e', ['a b c', 'd', 'e'], True), (r'"ab\"c" "\\" d', ['ab"c', '\\', 'd'], False), (r'a\\\b d"e f"g h', [r'a\\\b', 'de fg', 'h'], False), (r'a\\\"b c d', [r'a\"b', 'c', 'd'], False), (r'a\\\\"b c" d e', [r'a\\b c', 'd', 'e'], False), # other basics (r'""', [''], True), (r'a b c d "" e', ['a', 'b', 'c', 'd', '', 'e'], True), (r"'a b c' d e", ["'a", 'b', "c'", 'd', 'e'], True), (r"'a&b&c' d e", ["'a&b&c'", 'd', 'e'], True), (r"a & b & c d e", ['a', '&', 'b', '&', 'c', 'd', 'e'], True), (r"'a & b & c d e'", ["'a", '&', 'b', '&', 'c', 'd', "e'"], True), ('a b\nc\rd \n\re', ['a', 'b', 'c', 'd', 'e'], False), # more illustrative tests (r'cl test.cpp /O1 /Fe:test.exe', ['cl', 'test.cpp', '/O1', '/Fe:test.exe'], True), (r'cl "test.cpp /O1 /Fe:test.exe"', ['cl', 'test.cpp /O1 /Fe:test.exe'], True), (r'cl /DNAME=\"Bob\" test.cpp', ['cl', '/DNAME="Bob"', 'test.cpp'], False), (r'cl "/DNAME=\"Bob\"" test.cpp', ['cl', '/DNAME="Bob"', 'test.cpp'], True), (r'cl /DNAME=\"Bob, Alice\" test.cpp', ['cl', '/DNAME="Bob,', 'Alice"', 'test.cpp'], False), (r'cl "/DNAME=\"Bob, Alice\"" test.cpp', ['cl', '/DNAME="Bob, Alice"', 'test.cpp'], True), (r'cl C:\path\with\backslashes.cpp', ['cl', r'C:\path\with\backslashes.cpp'], True), (r'cl C:\\path\\with\\double\\backslashes.cpp', ['cl', r'C:\\path\\with\\double\\backslashes.cpp'], True), (r'cl "C:\\path\\with\\double\\backslashes.cpp"', ['cl', r'C:\\path\\with\\double\\backslashes.cpp'], False), (r'cl C:\path with spaces\test.cpp', ['cl', r'C:\path', 'with', r'spaces\test.cpp'], False), (r'cl "C:\path with spaces\test.cpp"', ['cl', r'C:\path with spaces\test.cpp'], True), (r'cl /DPATH="C:\path\with\backslashes test.cpp', ['cl', r'/DPATH=C:\path\with\backslashes test.cpp'], False), (r'cl /DPATH=\"C:\\ends\\with\\backslashes\\\" test.cpp', ['cl', r'/DPATH="C:\\ends\\with\\backslashes\"', 'test.cpp'], False), (r'cl /DPATH="C:\\ends\\with\\backslashes\\" test.cpp', ['cl', '/DPATH=C:\\\\ends\\\\with\\\\backslashes\\', 'test.cpp'], False), (r'cl "/DNAME=\"C:\\ends\\with\\backslashes\\\"" test.cpp', ['cl', r'/DNAME="C:\\ends\\with\\backslashes\"', 'test.cpp'], True), (r'cl "/DNAME=\"C:\\ends\\with\\backslashes\\\\"" test.cpp', ['cl', r'/DNAME="C:\\ends\\with\\backslashes\\ test.cpp'], False), (r'cl "/DNAME=\"C:\\ends\\with\\backslashes\\\\\"" test.cpp', ['cl', r'/DNAME="C:\\ends\\with\\backslashes\\"', 'test.cpp'], True), ] else: test_data = [ (r"'a b c' d e", ['a b c', 'd', 'e'], True), (r"a/b/c d e", ['a/b/c', 'd', 'e'], True), (r"a\b\c d e", [r'abc', 'd', 'e'], False), (r"a\\b\\c d e", [r'a\b\c', 'd', 'e'], False), (r'"a b c" d e', ['a b c', 'd', 'e'], False), (r'"a\\b\\c\\" d e', ['a\\b\\c\\', 'd', 'e'], False), (r"'a\b\c\' d e", ['a\\b\\c\\', 'd', 'e'], True), (r"'a&b&c' d e", ['a&b&c', 'd', 'e'], True), (r"a & b & c d e", ['a', '&', 'b', '&', 'c', 'd', 'e'], False), (r"'a & b & c d e'", ['a & b & c d e'], True), (r"abd'e f'g h", [r'abde fg', 'h'], False), ('a b\nc\rd \n\re', ['a', 'b', 'c', 'd', 'e'], False), ('g++ -DNAME="Bob" test.cpp', ['g++', '-DNAME=Bob', 'test.cpp'], False), ("g++ '-DNAME=\"Bob\"' test.cpp", ['g++', '-DNAME="Bob"', 'test.cpp'], True), ('g++ -DNAME="Bob, Alice" test.cpp', ['g++', '-DNAME=Bob, Alice', 'test.cpp'], False), ("g++ '-DNAME=\"Bob, Alice\"' test.cpp", ['g++', '-DNAME="Bob, Alice"', 'test.cpp'], True), ] for (cmd, expected, roundtrip) in test_data: self.assertEqual(split_args(cmd), expected) if roundtrip: self.assertEqual(join_args(expected), cmd) def test_quote_arg(self): split_args = mesonbuild.mesonlib.split_args quote_arg = mesonbuild.mesonlib.quote_arg if is_windows(): test_data = [ ('', '""'), ('arg1', 'arg1'), ('/option1', '/option1'), ('/Ovalue', '/Ovalue'), ('/OBob&Alice', '/OBob&Alice'), ('/Ovalue with spaces', r'"/Ovalue with spaces"'), (r'/O"value with spaces"', r'"/O\"value with spaces\""'), (r'/OC:\path with spaces\test.exe', r'"/OC:\path with spaces\test.exe"'), ('/LIBPATH:C:\\path with spaces\\ends\\with\\backslashes\\', r'"/LIBPATH:C:\path with spaces\ends\with\backslashes\\"'), ('/LIBPATH:"C:\\path with spaces\\ends\\with\\backslashes\\\\"', r'"/LIBPATH:\"C:\path with spaces\ends\with\backslashes\\\\\""'), (r'/DMSG="Alice said: \"Let\'s go\""', r'"/DMSG=\"Alice said: \\\"Let\'s go\\\"\""'), ] else: test_data = [ ('arg1', 'arg1'), ('--option1', '--option1'), ('-O=value', '-O=value'), ('-O=Bob&Alice', "'-O=Bob&Alice'"), ('-O=value with spaces', "'-O=value with spaces'"), ('-O="value with spaces"', '\'-O=\"value with spaces\"\''), ('-O=/path with spaces/test', '\'-O=/path with spaces/test\''), ('-DMSG="Alice said: \\"Let\'s go\\""', "'-DMSG=\"Alice said: \\\"Let'\"'\"'s go\\\"\"'"), ] for (arg, expected) in test_data: self.assertEqual(quote_arg(arg), expected) self.assertEqual(split_args(expected)[0], arg) def test_depfile(self): for (f, target, expdeps) in [ # empty, unknown target ([''], 'unknown', set()), # simple target & deps (['meson/foo.o : foo.c foo.h'], 'meson/foo.o', set({'foo.c', 'foo.h'})), (['meson/foo.o: foo.c foo.h'], 'foo.c', set()), # get all deps (['meson/foo.o: foo.c foo.h', 'foo.c: gen.py'], 'meson/foo.o', set({'foo.c', 'foo.h', 'gen.py'})), (['meson/foo.o: foo.c foo.h', 'foo.c: gen.py'], 'foo.c', set({'gen.py'})), # linue continuation, multiple targets (['foo.o \\', 'foo.h: bar'], 'foo.h', set({'bar'})), (['foo.o \\', 'foo.h: bar'], 'foo.o', set({'bar'})), # \\ handling (['foo: Program\\ F\\iles\\\\X'], 'foo', set({'Program Files\\X'})), # $ handling (['f$o.o: c/b'], 'f$o.o', set({'c/b'})), (['f$$o.o: c/b'], 'f$o.o', set({'c/b'})), # cycles (['a: b', 'b: a'], 'a', set({'a', 'b'})), (['a: b', 'b: a'], 'b', set({'a', 'b'})), ]: d = mesonbuild.depfile.DepFile(f) deps = d.get_all_dependencies(target) self.assertEqual(sorted(deps), sorted(expdeps)) def test_log_once(self): f = io.StringIO() with mock.patch('mesonbuild.mlog.log_file', f), \ mock.patch('mesonbuild.mlog._logged_once', set()): mesonbuild.mlog.log_once('foo') mesonbuild.mlog.log_once('foo') actual = f.getvalue().strip() self.assertEqual(actual, 'foo', actual) def test_log_once_ansi(self): f = io.StringIO() with mock.patch('mesonbuild.mlog.log_file', f), \ mock.patch('mesonbuild.mlog._logged_once', set()): mesonbuild.mlog.log_once(mesonbuild.mlog.bold('foo')) mesonbuild.mlog.log_once(mesonbuild.mlog.bold('foo')) actual = f.getvalue().strip() self.assertEqual(actual.count('foo'), 1, actual) mesonbuild.mlog.log_once('foo') actual = f.getvalue().strip() self.assertEqual(actual.count('foo'), 1, actual) f.truncate() mesonbuild.mlog.warning('bar', once=True) mesonbuild.mlog.warning('bar', once=True) actual = f.getvalue().strip() self.assertEqual(actual.count('bar'), 1, actual) def test_sort_libpaths(self): sort_libpaths = mesonbuild.dependencies.base.sort_libpaths self.assertEqual(sort_libpaths( ['/home/mesonuser/.local/lib', '/usr/local/lib', '/usr/lib'], ['/home/mesonuser/.local/lib/pkgconfig', '/usr/local/lib/pkgconfig']), ['/home/mesonuser/.local/lib', '/usr/local/lib', '/usr/lib']) self.assertEqual(sort_libpaths( ['/usr/local/lib', '/home/mesonuser/.local/lib', '/usr/lib'], ['/home/mesonuser/.local/lib/pkgconfig', '/usr/local/lib/pkgconfig']), ['/home/mesonuser/.local/lib', '/usr/local/lib', '/usr/lib']) self.assertEqual(sort_libpaths( ['/usr/lib', '/usr/local/lib', '/home/mesonuser/.local/lib'], ['/home/mesonuser/.local/lib/pkgconfig', '/usr/local/lib/pkgconfig']), ['/home/mesonuser/.local/lib', '/usr/local/lib', '/usr/lib']) self.assertEqual(sort_libpaths( ['/usr/lib', '/usr/local/lib', '/home/mesonuser/.local/lib'], ['/home/mesonuser/.local/lib/pkgconfig', '/usr/local/libdata/pkgconfig']), ['/home/mesonuser/.local/lib', '/usr/local/lib', '/usr/lib']) def test_dependency_factory_order(self): b = mesonbuild.dependencies.base with tempfile.TemporaryDirectory() as tmpdir: with chdir(tmpdir): env = get_fake_env() env.scratch_dir = tmpdir f = b.DependencyFactory( 'test_dep', methods=[b.DependencyMethods.PKGCONFIG, b.DependencyMethods.CMAKE] ) actual = [m() for m in f(env, MachineChoice.HOST, {'required': False})] self.assertListEqual([m.type_name for m in actual], ['pkgconfig', 'cmake']) f = b.DependencyFactory( 'test_dep', methods=[b.DependencyMethods.CMAKE, b.DependencyMethods.PKGCONFIG] ) actual = [m() for m in f(env, MachineChoice.HOST, {'required': False})] self.assertListEqual([m.type_name for m in actual], ['cmake', 'pkgconfig']) def test_validate_json(self) -> None: """Validate the json schema for the test cases.""" try: from jsonschema import validate, ValidationError except ImportError: if is_ci(): raise raise unittest.SkipTest('Python jsonschema module not found.') with Path('data/test.schema.json').open() as f: schema = json.load(f) errors = [] # type: T.Tuple[str, Exception] for p in Path('test cases').glob('**/test.json'): with p.open() as f: try: validate(json.load(f), schema=schema) except ValidationError as e: errors.append((p.resolve(), e)) for f, e in errors: print('Failed to validate: "{}"'.format(f)) print(str(e)) self.assertFalse(errors) def test_typed_pos_args_types(self) -> None: @typed_pos_args('foo', str, int, bool) def _(obj, node, args: T.Tuple[str, int, bool], kwargs) -> None: self.assertIsInstance(args, tuple) self.assertIsInstance(args[0], str) self.assertIsInstance(args[1], int) self.assertIsInstance(args[2], bool) _(None, mock.Mock(), ['string', 1, False], None) def test_typed_pos_args_types_invalid(self) -> None: @typed_pos_args('foo', str, int, bool) def _(obj, node, args: T.Tuple[str, int, bool], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string', 1.0, False], None) self.assertEqual(str(cm.exception), 'foo argument 2 was of type "float" but should have been "int"') def test_typed_pos_args_types_wrong_number(self) -> None: @typed_pos_args('foo', str, int, bool) def _(obj, node, args: T.Tuple[str, int, bool], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string', 1], None) self.assertEqual(str(cm.exception), 'foo takes exactly 3 arguments, but got 2.') with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string', 1, True, True], None) self.assertEqual(str(cm.exception), 'foo takes exactly 3 arguments, but got 4.') def test_typed_pos_args_varargs(self) -> None: @typed_pos_args('foo', str, varargs=str) def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None: self.assertIsInstance(args, tuple) self.assertIsInstance(args[0], str) self.assertIsInstance(args[1], list) self.assertIsInstance(args[1][0], str) self.assertIsInstance(args[1][1], str) _(None, mock.Mock(), ['string', 'var', 'args'], None) def test_typed_pos_args_varargs_not_given(self) -> None: @typed_pos_args('foo', str, varargs=str) def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None: self.assertIsInstance(args, tuple) self.assertIsInstance(args[0], str) self.assertIsInstance(args[1], list) self.assertEqual(args[1], []) _(None, mock.Mock(), ['string'], None) def test_typed_pos_args_varargs_invalid(self) -> None: @typed_pos_args('foo', str, varargs=str) def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string', 'var', 'args', 0], None) self.assertEqual(str(cm.exception), 'foo argument 4 was of type "int" but should have been "str"') def test_typed_pos_args_varargs_invalid_mulitple_types(self) -> None: @typed_pos_args('foo', str, varargs=(str, list)) def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string', 'var', 'args', 0], None) self.assertEqual(str(cm.exception), 'foo argument 4 was of type "int" but should have been one of: "str", "list"') def test_typed_pos_args_max_varargs(self) -> None: @typed_pos_args('foo', str, varargs=str, max_varargs=5) def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None: self.assertIsInstance(args, tuple) self.assertIsInstance(args[0], str) self.assertIsInstance(args[1], list) self.assertIsInstance(args[1][0], str) self.assertIsInstance(args[1][1], str) _(None, mock.Mock(), ['string', 'var', 'args'], None) def test_typed_pos_args_max_varargs_exceeded(self) -> None: @typed_pos_args('foo', str, varargs=str, max_varargs=1) def _(obj, node, args: T.Tuple[str, T.Tuple[str, ...]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string', 'var', 'args'], None) self.assertEqual(str(cm.exception), 'foo takes between 1 and 2 arguments, but got 3.') def test_typed_pos_args_min_varargs(self) -> None: @typed_pos_args('foo', varargs=str, max_varargs=2, min_varargs=1) def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None: self.assertIsInstance(args, tuple) self.assertIsInstance(args[0], list) self.assertIsInstance(args[0][0], str) self.assertIsInstance(args[0][1], str) _(None, mock.Mock(), ['string', 'var'], None) def test_typed_pos_args_min_varargs_not_met(self) -> None: @typed_pos_args('foo', str, varargs=str, min_varargs=1) def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string'], None) self.assertEqual(str(cm.exception), 'foo takes at least 2 arguments, but got 1.') def test_typed_pos_args_min_and_max_varargs_exceeded(self) -> None: @typed_pos_args('foo', str, varargs=str, min_varargs=1, max_varargs=2) def _(obj, node, args: T.Tuple[str, T.Tuple[str, ...]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string', 'var', 'args', 'bar'], None) self.assertEqual(str(cm.exception), 'foo takes between 2 and 3 arguments, but got 4.') def test_typed_pos_args_min_and_max_varargs_not_met(self) -> None: @typed_pos_args('foo', str, varargs=str, min_varargs=1, max_varargs=2) def _(obj, node, args: T.Tuple[str, T.Tuple[str, ...]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string'], None) self.assertEqual(str(cm.exception), 'foo takes between 2 and 3 arguments, but got 1.') def test_typed_pos_args_variadic_and_optional(self) -> None: @typed_pos_args('foo', str, optargs=[str], varargs=str, min_varargs=0) def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(AssertionError) as cm: _(None, mock.Mock(), ['string'], None) self.assertEqual( str(cm.exception), 'varargs and optargs not supported together as this would be ambiguous') def test_typed_pos_args_min_optargs_not_met(self) -> None: @typed_pos_args('foo', str, str, optargs=[str]) def _(obj, node, args: T.Tuple[str, T.Optional[str]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string'], None) self.assertEqual(str(cm.exception), 'foo takes at least 2 arguments, but got 1.') def test_typed_pos_args_min_optargs_max_exceeded(self) -> None: @typed_pos_args('foo', str, optargs=[str]) def _(obj, node, args: T.Tuple[str, T.Optional[str]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string', '1', '2'], None) self.assertEqual(str(cm.exception), 'foo takes at most 2 arguments, but got 3.') def test_typed_pos_args_optargs_not_given(self) -> None: @typed_pos_args('foo', str, optargs=[str]) def _(obj, node, args: T.Tuple[str, T.Optional[str]], kwargs) -> None: self.assertEqual(len(args), 2) self.assertIsInstance(args[0], str) self.assertEqual(args[0], 'string') self.assertIsNone(args[1]) _(None, mock.Mock(), ['string'], None) def test_typed_pos_args_optargs_some_given(self) -> None: @typed_pos_args('foo', str, optargs=[str, int]) def _(obj, node, args: T.Tuple[str, T.Optional[str], T.Optional[int]], kwargs) -> None: self.assertEqual(len(args), 3) self.assertIsInstance(args[0], str) self.assertEqual(args[0], 'string') self.assertIsInstance(args[1], str) self.assertEqual(args[1], '1') self.assertIsNone(args[2]) _(None, mock.Mock(), ['string', '1'], None) def test_typed_pos_args_optargs_all_given(self) -> None: @typed_pos_args('foo', str, optargs=[str]) def _(obj, node, args: T.Tuple[str, T.Optional[str]], kwargs) -> None: self.assertEqual(len(args), 2) self.assertIsInstance(args[0], str) self.assertEqual(args[0], 'string') self.assertIsInstance(args[1], str) _(None, mock.Mock(), ['string', '1'], None) @unittest.skipIf(is_tarball(), 'Skipping because this is a tarball release') class DataTests(unittest.TestCase): def test_snippets(self): hashcounter = re.compile('^ *(#)+') snippet_dir = Path('docs/markdown/snippets') self.assertTrue(snippet_dir.is_dir()) for f in snippet_dir.glob('*'): self.assertTrue(f.is_file()) if f.parts[-1].endswith('~'): continue if f.suffix == '.md': in_code_block = False with f.open() as snippet: for line in snippet: if line.startswith(' '): continue if line.startswith('```'): in_code_block = not in_code_block if in_code_block: continue m = re.match(hashcounter, line) if m: self.assertEqual(len(m.group(0)), 2, 'All headings in snippets must have two hash symbols: ' + f.name) self.assertFalse(in_code_block, 'Unclosed code block.') else: if f.name != 'add_release_note_snippets_here': self.assertTrue(False, 'A file without .md suffix in snippets dir: ' + f.name) def test_compiler_options_documented(self): ''' Test that C and C++ compiler options and base options are documented in Builtin-Options.md. Only tests the default compiler for the current platform on the CI. ''' md = None with open('docs/markdown/Builtin-options.md', encoding='utf-8') as f: md = f.read() self.assertIsNotNone(md) env = get_fake_env() # FIXME: Support other compilers cc = env.detect_c_compiler(MachineChoice.HOST) cpp = env.detect_cpp_compiler(MachineChoice.HOST) for comp in (cc, cpp): for opt in comp.get_options(): self.assertIn(str(opt), md) for opt in comp.base_options: self.assertIn(str(opt), md) self.assertNotIn('b_unknown', md) @staticmethod def _get_section_content(name, sections, md): for section in sections: if section and section.group(1) == name: try: next_section = next(sections) end = next_section.start() except StopIteration: end = len(md) # Extract the content for this section return md[section.end():end] raise RuntimeError('Could not find "{}" heading'.format(name)) def test_builtin_options_documented(self): ''' Test that universal options and base options are documented in Builtin-Options.md. ''' from itertools import tee md = None with open('docs/markdown/Builtin-options.md', encoding='utf-8') as f: md = f.read() self.assertIsNotNone(md) found_entries = set() sections = re.finditer(r"^## (.+)$", md, re.MULTILINE) # Extract the content for this section content = self._get_section_content("Universal options", sections, md) subsections = tee(re.finditer(r"^### (.+)$", content, re.MULTILINE)) subcontent1 = self._get_section_content("Directories", subsections[0], content) subcontent2 = self._get_section_content("Core options", subsections[1], content) for subcontent in (subcontent1, subcontent2): # Find the option names options = set() # Match either a table row or a table heading separator: | ------ | rows = re.finditer(r"^\|(?: (\w+) .* | *-+ *)\|", subcontent, re.MULTILINE) # Skip the header of the first table next(rows) # Skip the heading separator of the first table next(rows) for m in rows: value = m.group(1) # End when the `buildtype` table starts if value is None: break options.add(value) self.assertEqual(len(found_entries & options), 0) found_entries |= options self.assertEqual(found_entries, set([ *[str(k) for k in mesonbuild.coredata.BUILTIN_OPTIONS], *[str(k) for k in mesonbuild.coredata.BUILTIN_OPTIONS_PER_MACHINE], ])) # Check that `buildtype` table inside `Core options` matches how # setting of builtin options behaves # # Find all tables inside this subsection tables = re.finditer(r"^\| (\w+) .* \|\n\| *[-|\s]+ *\|$", subcontent2, re.MULTILINE) # Get the table we want using the header of the first column table = self._get_section_content('buildtype', tables, subcontent2) # Get table row data rows = re.finditer(r"^\|(?: (\w+)\s+\| (\w+)\s+\| (\w+) .* | *-+ *)\|", table, re.MULTILINE) env = get_fake_env() for m in rows: buildtype, debug, opt = m.groups() if debug == 'true': debug = True elif debug == 'false': debug = False else: raise RuntimeError('Invalid debug value {!r} in row:\n{}'.format(debug, m.group())) env.coredata.set_option(OptionKey('buildtype'), buildtype) self.assertEqual(env.coredata.options[OptionKey('buildtype')].value, buildtype) self.assertEqual(env.coredata.options[OptionKey('optimization')].value, opt) self.assertEqual(env.coredata.options[OptionKey('debug')].value, debug) def test_cpu_families_documented(self): with open("docs/markdown/Reference-tables.md", encoding='utf-8') as f: md = f.read() self.assertIsNotNone(md) sections = re.finditer(r"^## (.+)$", md, re.MULTILINE) content = self._get_section_content("CPU families", sections, md) # Find the list entries arches = [m.group(1) for m in re.finditer(r"^\| (\w+) +\|", content, re.MULTILINE)] # Drop the header arches = set(arches[1:]) self.assertEqual(arches, set(mesonbuild.environment.known_cpu_families)) def test_markdown_files_in_sitemap(self): ''' Test that each markdown files in docs/markdown is referenced in sitemap.txt ''' with open("docs/sitemap.txt", encoding='utf-8') as f: md = f.read() self.assertIsNotNone(md) toc = list(m.group(1) for m in re.finditer(r"^\s*(\w.*)$", md, re.MULTILINE)) markdownfiles = [f.name for f in Path("docs/markdown").iterdir() if f.is_file() and f.suffix == '.md'] exceptions = ['_Sidebar.md'] for f in markdownfiles: if f not in exceptions: self.assertIn(f, toc) def test_vim_syntax_highlighting(self): ''' Ensure that vim syntax highlighting files were updated for new functions in the global namespace in build files. ''' env = get_fake_env() interp = Interpreter(FakeBuild(env), mock=True) with open('data/syntax-highlighting/vim/syntax/meson.vim') as f: res = re.search(r'syn keyword mesonBuiltin(\s+\\\s\w+)+', f.read(), re.MULTILINE) defined = set([a.strip() for a in res.group().split('\\')][1:]) self.assertEqual(defined, set(chain(interp.funcs.keys(), interp.builtin.keys()))) def test_all_functions_defined_in_ast_interpreter(self): ''' Ensure that the all functions defined in the Interpreter are also defined in the AstInterpreter (and vice versa). ''' env = get_fake_env() interp = Interpreter(FakeBuild(env), mock=True) astint = AstInterpreter('.', '', '') self.assertEqual(set(interp.funcs.keys()), set(astint.funcs.keys())) def test_mesondata_is_up_to_date(self): from mesonbuild.mesondata import mesondata err_msg = textwrap.dedent(''' ########################################################### ### mesonbuild.mesondata is not up-to-date ### ### Please regenerate it by running tools/gen_data.py ### ########################################################### ''') root_dir = Path(__file__).resolve().parent mesonbuild_dir = root_dir / 'mesonbuild' data_dirs = mesonbuild_dir.glob('**/data') data_files = [] # type: T.List[T.Tuple(str, str)] for i in data_dirs: for p in i.iterdir(): data_files += [(p.relative_to(mesonbuild_dir).as_posix(), hashlib.sha256(p.read_bytes()).hexdigest())] current_files = set(mesondata.keys()) scanned_files = set([x[0] for x in data_files]) self.assertSetEqual(current_files, scanned_files, err_msg + 'Data files were added or removed\n') errors = [] for i in data_files: if mesondata[i[0]].sha256sum != i[1]: errors += [i[0]] self.assertListEqual(errors, [], err_msg + 'Files were changed') class BasePlatformTests(unittest.TestCase): prefix = '/usr' libdir = 'lib' def setUp(self): super().setUp() self.maxDiff = None src_root = os.path.dirname(__file__) src_root = os.path.join(os.getcwd(), src_root) self.src_root = src_root # Get the backend # FIXME: Extract this from argv? self.backend = getattr(Backend, os.environ.get('MESON_UNIT_TEST_BACKEND', 'ninja')) self.meson_args = ['--backend=' + self.backend.name] self.meson_native_file = None self.meson_cross_file = None self.meson_command = python_command + [get_meson_script()] self.setup_command = self.meson_command + self.meson_args self.mconf_command = self.meson_command + ['configure'] self.mintro_command = self.meson_command + ['introspect'] self.wrap_command = self.meson_command + ['wrap'] self.rewrite_command = self.meson_command + ['rewrite'] # Backend-specific build commands self.build_command, self.clean_command, self.test_command, self.install_command, \ self.uninstall_command = get_backend_commands(self.backend) # Test directories self.common_test_dir = os.path.join(src_root, 'test cases/common') self.vala_test_dir = os.path.join(src_root, 'test cases/vala') self.framework_test_dir = os.path.join(src_root, 'test cases/frameworks') self.unit_test_dir = os.path.join(src_root, 'test cases/unit') self.rewrite_test_dir = os.path.join(src_root, 'test cases/rewrite') self.linuxlike_test_dir = os.path.join(src_root, 'test cases/linuxlike') # Misc stuff self.orig_env = os.environ.copy() if self.backend is Backend.ninja: self.no_rebuild_stdout = ['ninja: no work to do.', 'samu: nothing to do'] else: # VS doesn't have a stable output when no changes are done # XCode backend is untested with unit tests, help welcome! self.no_rebuild_stdout = ['UNKNOWN BACKEND {!r}'.format(self.backend.name)] self.builddirs = [] self.new_builddir() def change_builddir(self, newdir): self.builddir = newdir self.privatedir = os.path.join(self.builddir, 'meson-private') self.logdir = os.path.join(self.builddir, 'meson-logs') self.installdir = os.path.join(self.builddir, 'install') self.distdir = os.path.join(self.builddir, 'meson-dist') self.mtest_command = self.meson_command + ['test', '-C', self.builddir] self.builddirs.append(self.builddir) def new_builddir(self): if not is_cygwin(): # Keep builddirs inside the source tree so that virus scanners # don't complain newdir = tempfile.mkdtemp(dir=os.getcwd()) else: # But not on Cygwin because that breaks the umask tests. See: # https://github.com/mesonbuild/meson/pull/5546#issuecomment-509666523 newdir = tempfile.mkdtemp() # In case the directory is inside a symlinked directory, find the real # path otherwise we might not find the srcdir from inside the builddir. newdir = os.path.realpath(newdir) self.change_builddir(newdir) def _print_meson_log(self): log = os.path.join(self.logdir, 'meson-log.txt') if not os.path.isfile(log): print("{!r} doesn't exist".format(log)) return with open(log, 'r', encoding='utf-8') as f: print(f.read()) def tearDown(self): for path in self.builddirs: try: windows_proof_rmtree(path) except FileNotFoundError: pass os.environ.clear() os.environ.update(self.orig_env) super().tearDown() def _run(self, command, *, workdir=None, override_envvars=None): ''' Run a command while printing the stdout and stderr to stdout, and also return a copy of it ''' # If this call hangs CI will just abort. It is very hard to distinguish # between CI issue and test bug in that case. Set timeout and fail loud # instead. if override_envvars is None: env = None else: env = os.environ.copy() env.update(override_envvars) p = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, encoding='utf-8', universal_newlines=True, cwd=workdir, timeout=60 * 5) print(p.stdout) if p.returncode != 0: if 'MESON_SKIP_TEST' in p.stdout: raise unittest.SkipTest('Project requested skipping.') raise subprocess.CalledProcessError(p.returncode, command, output=p.stdout) return p.stdout def init(self, srcdir, *, extra_args=None, default_args=True, inprocess=False, override_envvars=None, workdir=None): self.assertPathExists(srcdir) if extra_args is None: extra_args = [] if not isinstance(extra_args, list): extra_args = [extra_args] args = [srcdir, self.builddir] if default_args: args += ['--prefix', self.prefix] if self.libdir: args += ['--libdir', self.libdir] if self.meson_native_file: args += ['--native-file', self.meson_native_file] if self.meson_cross_file: args += ['--cross-file', self.meson_cross_file] self.privatedir = os.path.join(self.builddir, 'meson-private') if inprocess: try: (returncode, out, err) = run_configure_inprocess(self.meson_args + args + extra_args, override_envvars) if 'MESON_SKIP_TEST' in out: raise unittest.SkipTest('Project requested skipping.') if returncode != 0: self._print_meson_log() print('Stdout:\n') print(out) print('Stderr:\n') print(err) raise RuntimeError('Configure failed') except Exception: self._print_meson_log() raise finally: # Close log file to satisfy Windows file locking mesonbuild.mlog.shutdown() mesonbuild.mlog.log_dir = None mesonbuild.mlog.log_file = None else: try: out = self._run(self.setup_command + args + extra_args, override_envvars=override_envvars, workdir=workdir) except unittest.SkipTest: raise unittest.SkipTest('Project requested skipping: ' + srcdir) except Exception: self._print_meson_log() raise return out def build(self, target=None, *, extra_args=None, override_envvars=None): if extra_args is None: extra_args = [] # Add arguments for building the target (if specified), # and using the build dir (if required, with VS) args = get_builddir_target_args(self.backend, self.builddir, target) return self._run(self.build_command + args + extra_args, workdir=self.builddir, override_envvars=override_envvars) def clean(self, *, override_envvars=None): dir_args = get_builddir_target_args(self.backend, self.builddir, None) self._run(self.clean_command + dir_args, workdir=self.builddir, override_envvars=override_envvars) def run_tests(self, *, inprocess=False, override_envvars=None): if not inprocess: self._run(self.test_command, workdir=self.builddir, override_envvars=override_envvars) else: with mock.patch.dict(os.environ, override_envvars): run_mtest_inprocess(['-C', self.builddir]) def install(self, *, use_destdir=True, override_envvars=None): if self.backend is not Backend.ninja: raise unittest.SkipTest('{!r} backend can\'t install files'.format(self.backend.name)) if use_destdir: destdir = {'DESTDIR': self.installdir} if override_envvars is None: override_envvars = destdir else: override_envvars.update(destdir) self._run(self.install_command, workdir=self.builddir, override_envvars=override_envvars) def uninstall(self, *, override_envvars=None): self._run(self.uninstall_command, workdir=self.builddir, override_envvars=override_envvars) def run_target(self, target, *, override_envvars=None): ''' Run a Ninja target while printing the stdout and stderr to stdout, and also return a copy of it ''' return self.build(target=target, override_envvars=override_envvars) def setconf(self, arg, will_build=True): if not isinstance(arg, list): arg = [arg] if will_build: ensure_backend_detects_changes(self.backend) self._run(self.mconf_command + arg + [self.builddir]) def wipe(self): windows_proof_rmtree(self.builddir) def utime(self, f): ensure_backend_detects_changes(self.backend) os.utime(f) def get_compdb(self): if self.backend is not Backend.ninja: raise unittest.SkipTest('Compiler db not available with {} backend'.format(self.backend.name)) try: with open(os.path.join(self.builddir, 'compile_commands.json')) as ifile: contents = json.load(ifile) except FileNotFoundError: raise unittest.SkipTest('Compiler db not found') # If Ninja is using .rsp files, generate them, read their contents, and # replace it as the command for all compile commands in the parsed json. if len(contents) > 0 and contents[0]['command'].endswith('.rsp'): # Pretend to build so that the rsp files are generated self.build(extra_args=['-d', 'keeprsp', '-n']) for each in contents: # Extract the actual command from the rsp file compiler, rsp = each['command'].split(' @') rsp = os.path.join(self.builddir, rsp) # Replace the command with its contents with open(rsp, 'r', encoding='utf-8') as f: each['command'] = compiler + ' ' + f.read() return contents def get_meson_log(self): with open(os.path.join(self.builddir, 'meson-logs', 'meson-log.txt')) as f: return f.readlines() def get_meson_log_compiler_checks(self): ''' Fetch a list command-lines run by meson for compiler checks. Each command-line is returned as a list of arguments. ''' log = self.get_meson_log() prefix = 'Command line:' cmds = [l[len(prefix):].split() for l in log if l.startswith(prefix)] return cmds def get_meson_log_sanitychecks(self): ''' Same as above, but for the sanity checks that were run ''' log = self.get_meson_log() prefix = 'Sanity check compiler command line:' cmds = [l[len(prefix):].split() for l in log if l.startswith(prefix)] return cmds def introspect(self, args): if isinstance(args, str): args = [args] out = subprocess.check_output(self.mintro_command + args + [self.builddir], universal_newlines=True) return json.loads(out) def introspect_directory(self, directory, args): if isinstance(args, str): args = [args] out = subprocess.check_output(self.mintro_command + args + [directory], universal_newlines=True) try: obj = json.loads(out) except Exception as e: print(out) raise e return obj def assertPathEqual(self, path1, path2): ''' Handles a lot of platform-specific quirks related to paths such as separator, case-sensitivity, etc. ''' self.assertEqual(PurePath(path1), PurePath(path2)) def assertPathListEqual(self, pathlist1, pathlist2): self.assertEqual(len(pathlist1), len(pathlist2)) worklist = list(zip(pathlist1, pathlist2)) for i in worklist: if i[0] is None: self.assertEqual(i[0], i[1]) else: self.assertPathEqual(i[0], i[1]) def assertPathBasenameEqual(self, path, basename): msg = '{!r} does not end with {!r}'.format(path, basename) # We cannot use os.path.basename because it returns '' when the path # ends with '/' for some silly reason. This is not how the UNIX utility # `basename` works. path_basename = PurePath(path).parts[-1] self.assertEqual(PurePath(path_basename), PurePath(basename), msg) def assertReconfiguredBuildIsNoop(self): 'Assert that we reconfigured and then there was nothing to do' ret = self.build() self.assertIn('The Meson build system', ret) if self.backend is Backend.ninja: for line in ret.split('\n'): if line in self.no_rebuild_stdout: break else: raise AssertionError('build was reconfigured, but was not no-op') elif self.backend is Backend.vs: # Ensure that some target said that no rebuild was done # XXX: Note CustomBuild did indeed rebuild, because of the regen checker! self.assertIn('ClCompile:\n All outputs are up-to-date.', ret) self.assertIn('Link:\n All outputs are up-to-date.', ret) # Ensure that no targets were built self.assertNotRegex(ret, re.compile('ClCompile:\n [^\n]*cl', flags=re.IGNORECASE)) self.assertNotRegex(ret, re.compile('Link:\n [^\n]*link', flags=re.IGNORECASE)) elif self.backend is Backend.xcode: raise unittest.SkipTest('Please help us fix this test on the xcode backend') else: raise RuntimeError('Invalid backend: {!r}'.format(self.backend.name)) def assertBuildIsNoop(self): ret = self.build() if self.backend is Backend.ninja: self.assertIn(ret.split('\n')[-2], self.no_rebuild_stdout) elif self.backend is Backend.vs: # Ensure that some target of each type said that no rebuild was done # We always have at least one CustomBuild target for the regen checker self.assertIn('CustomBuild:\n All outputs are up-to-date.', ret) self.assertIn('ClCompile:\n All outputs are up-to-date.', ret) self.assertIn('Link:\n All outputs are up-to-date.', ret) # Ensure that no targets were built self.assertNotRegex(ret, re.compile('CustomBuild:\n [^\n]*cl', flags=re.IGNORECASE)) self.assertNotRegex(ret, re.compile('ClCompile:\n [^\n]*cl', flags=re.IGNORECASE)) self.assertNotRegex(ret, re.compile('Link:\n [^\n]*link', flags=re.IGNORECASE)) elif self.backend is Backend.xcode: raise unittest.SkipTest('Please help us fix this test on the xcode backend') else: raise RuntimeError('Invalid backend: {!r}'.format(self.backend.name)) def assertRebuiltTarget(self, target): ret = self.build() if self.backend is Backend.ninja: self.assertIn('Linking target {}'.format(target), ret) elif self.backend is Backend.vs: # Ensure that this target was rebuilt linkre = re.compile('Link:\n [^\n]*link[^\n]*' + target, flags=re.IGNORECASE) self.assertRegex(ret, linkre) elif self.backend is Backend.xcode: raise unittest.SkipTest('Please help us fix this test on the xcode backend') else: raise RuntimeError('Invalid backend: {!r}'.format(self.backend.name)) @staticmethod def get_target_from_filename(filename): base = os.path.splitext(filename)[0] if base.startswith(('lib', 'cyg')): return base[3:] return base def assertBuildRelinkedOnlyTarget(self, target): ret = self.build() if self.backend is Backend.ninja: linked_targets = [] for line in ret.split('\n'): if 'Linking target' in line: fname = line.rsplit('target ')[-1] linked_targets.append(self.get_target_from_filename(fname)) self.assertEqual(linked_targets, [target]) elif self.backend is Backend.vs: # Ensure that this target was rebuilt linkre = re.compile(r'Link:\n [^\n]*link.exe[^\n]*/OUT:".\\([^"]*)"', flags=re.IGNORECASE) matches = linkre.findall(ret) self.assertEqual(len(matches), 1, msg=matches) self.assertEqual(self.get_target_from_filename(matches[0]), target) elif self.backend is Backend.xcode: raise unittest.SkipTest('Please help us fix this test on the xcode backend') else: raise RuntimeError('Invalid backend: {!r}'.format(self.backend.name)) def assertPathExists(self, path): m = 'Path {!r} should exist'.format(path) self.assertTrue(os.path.exists(path), msg=m) def assertPathDoesNotExist(self, path): m = 'Path {!r} should not exist'.format(path) self.assertFalse(os.path.exists(path), msg=m) class AllPlatformTests(BasePlatformTests): ''' Tests that should run on all platforms ''' def test_default_options_prefix(self): ''' Tests that setting a prefix in default_options in project() works. Can't be an ordinary test because we pass --prefix to meson there. https://github.com/mesonbuild/meson/issues/1349 ''' testdir = os.path.join(self.common_test_dir, '88 default options') self.init(testdir, default_args=False, inprocess=True) opts = self.introspect('--buildoptions') for opt in opts: if opt['name'] == 'prefix': prefix = opt['value'] break else: raise self.fail('Did not find option "prefix"') self.assertEqual(prefix, '/absoluteprefix') def test_do_conf_file_preserve_newlines(self): def conf_file(in_data, confdata): with temp_filename() as fin: with open(fin, 'wb') as fobj: fobj.write(in_data.encode('utf-8')) with temp_filename() as fout: mesonbuild.mesonlib.do_conf_file(fin, fout, confdata, 'meson') with open(fout, 'rb') as fobj: return fobj.read().decode('utf-8') confdata = {'VAR': ('foo', 'bar')} self.assertEqual(conf_file('@VAR@\n@VAR@\n', confdata), 'foo\nfoo\n') self.assertEqual(conf_file('@VAR@\r\n@VAR@\r\n', confdata), 'foo\r\nfoo\r\n') def test_do_conf_file_by_format(self): def conf_str(in_data, confdata, vformat): (result, missing_variables, confdata_useless) = mesonbuild.mesonlib.do_conf_str(in_data, confdata, variable_format = vformat) return '\n'.join(result) def check_formats(confdata, result): self.assertEqual(conf_str(['#mesondefine VAR'], confdata, 'meson'), result) self.assertEqual(conf_str(['#cmakedefine VAR ${VAR}'], confdata, 'cmake'), result) self.assertEqual(conf_str(['#cmakedefine VAR @VAR@'], confdata, 'cmake@'), result) confdata = ConfigurationData() # Key error as they do not exists check_formats(confdata, '/* #undef VAR */\n') # Check boolean confdata.values = {'VAR': (False, 'description')} check_formats(confdata, '#undef VAR\n') confdata.values = {'VAR': (True, 'description')} check_formats(confdata, '#define VAR\n') # Check string confdata.values = {'VAR': ('value', 'description')} check_formats(confdata, '#define VAR value\n') # Check integer confdata.values = {'VAR': (10, 'description')} check_formats(confdata, '#define VAR 10\n') # Check multiple string with cmake formats confdata.values = {'VAR': ('value', 'description')} self.assertEqual(conf_str(['#cmakedefine VAR xxx @VAR@ yyy @VAR@'], confdata, 'cmake@'), '#define VAR xxx value yyy value\n') self.assertEqual(conf_str(['#define VAR xxx @VAR@ yyy @VAR@'], confdata, 'cmake@'), '#define VAR xxx value yyy value') self.assertEqual(conf_str(['#cmakedefine VAR xxx ${VAR} yyy ${VAR}'], confdata, 'cmake'), '#define VAR xxx value yyy value\n') self.assertEqual(conf_str(['#define VAR xxx ${VAR} yyy ${VAR}'], confdata, 'cmake'), '#define VAR xxx value yyy value') # Handles meson format exceptions # Unknown format self.assertRaises(mesonbuild.mesonlib.MesonException, conf_str, ['#mesondefine VAR xxx'], confdata, 'unknown_format') # More than 2 params in mesondefine self.assertRaises(mesonbuild.mesonlib.MesonException, conf_str, ['#mesondefine VAR xxx'], confdata, 'meson') # Mismatched line with format self.assertRaises(mesonbuild.mesonlib.MesonException, conf_str, ['#cmakedefine VAR'], confdata, 'meson') self.assertRaises(mesonbuild.mesonlib.MesonException, conf_str, ['#mesondefine VAR'], confdata, 'cmake') self.assertRaises(mesonbuild.mesonlib.MesonException, conf_str, ['#mesondefine VAR'], confdata, 'cmake@') # Dict value in confdata confdata.values = {'VAR': (['value'], 'description')} self.assertRaises(mesonbuild.mesonlib.MesonException, conf_str, ['#mesondefine VAR'], confdata, 'meson') def test_absolute_prefix_libdir(self): ''' Tests that setting absolute paths for --prefix and --libdir work. Can't be an ordinary test because these are set via the command-line. https://github.com/mesonbuild/meson/issues/1341 https://github.com/mesonbuild/meson/issues/1345 ''' testdir = os.path.join(self.common_test_dir, '88 default options') # on Windows, /someabs is *not* an absolute path prefix = 'x:/someabs' if is_windows() else '/someabs' libdir = 'libdir' extra_args = ['--prefix=' + prefix, # This can just be a relative path, but we want to test # that passing this as an absolute path also works '--libdir=' + prefix + '/' + libdir] self.init(testdir, extra_args=extra_args, default_args=False) opts = self.introspect('--buildoptions') for opt in opts: if opt['name'] == 'prefix': self.assertEqual(prefix, opt['value']) elif opt['name'] == 'libdir': self.assertEqual(libdir, opt['value']) def test_libdir_must_be_inside_prefix(self): ''' Tests that libdir is forced to be inside prefix no matter how it is set. Must be a unit test for obvious reasons. ''' testdir = os.path.join(self.common_test_dir, '1 trivial') # libdir being inside prefix is ok if is_windows(): args = ['--prefix', 'x:/opt', '--libdir', 'x:/opt/lib32'] else: args = ['--prefix', '/opt', '--libdir', '/opt/lib32'] self.init(testdir, extra_args=args) self.wipe() # libdir not being inside prefix is not ok if is_windows(): args = ['--prefix', 'x:/usr', '--libdir', 'x:/opt/lib32'] else: args = ['--prefix', '/usr', '--libdir', '/opt/lib32'] self.assertRaises(subprocess.CalledProcessError, self.init, testdir, extra_args=args) self.wipe() # libdir must be inside prefix even when set via mesonconf self.init(testdir) if is_windows(): self.assertRaises(subprocess.CalledProcessError, self.setconf, '-Dlibdir=x:/opt', False) else: self.assertRaises(subprocess.CalledProcessError, self.setconf, '-Dlibdir=/opt', False) def test_prefix_dependent_defaults(self): ''' Tests that configured directory paths are set to prefix dependent defaults. ''' testdir = os.path.join(self.common_test_dir, '1 trivial') expected = { '/opt': {'prefix': '/opt', 'bindir': 'bin', 'datadir': 'share', 'includedir': 'include', 'infodir': 'share/info', 'libexecdir': 'libexec', 'localedir': 'share/locale', 'localstatedir': 'var', 'mandir': 'share/man', 'sbindir': 'sbin', 'sharedstatedir': 'com', 'sysconfdir': 'etc'}, '/usr': {'prefix': '/usr', 'bindir': 'bin', 'datadir': 'share', 'includedir': 'include', 'infodir': 'share/info', 'libexecdir': 'libexec', 'localedir': 'share/locale', 'localstatedir': '/var', 'mandir': 'share/man', 'sbindir': 'sbin', 'sharedstatedir': '/var/lib', 'sysconfdir': '/etc'}, '/usr/local': {'prefix': '/usr/local', 'bindir': 'bin', 'datadir': 'share', 'includedir': 'include', 'infodir': 'share/info', 'libexecdir': 'libexec', 'localedir': 'share/locale', 'localstatedir': '/var/local', 'mandir': 'share/man', 'sbindir': 'sbin', 'sharedstatedir': '/var/local/lib', 'sysconfdir': 'etc'}, # N.B. We don't check 'libdir' as it's platform dependent, see # default_libdir(): } if mesonbuild.mesonlib.default_prefix() == '/usr/local': expected[None] = expected['/usr/local'] for prefix in expected: args = [] if prefix: args += ['--prefix', prefix] self.init(testdir, extra_args=args, default_args=False) opts = self.introspect('--buildoptions') for opt in opts: name = opt['name'] value = opt['value'] if name in expected[prefix]: self.assertEqual(value, expected[prefix][name]) self.wipe() def test_default_options_prefix_dependent_defaults(self): ''' Tests that setting a prefix in default_options in project() sets prefix dependent defaults for other options, and that those defaults can be overridden in default_options or by the command line. ''' testdir = os.path.join(self.common_test_dir, '164 default options prefix dependent defaults') expected = { '': {'prefix': '/usr', 'sysconfdir': '/etc', 'localstatedir': '/var', 'sharedstatedir': '/sharedstate'}, '--prefix=/usr': {'prefix': '/usr', 'sysconfdir': '/etc', 'localstatedir': '/var', 'sharedstatedir': '/sharedstate'}, '--sharedstatedir=/var/state': {'prefix': '/usr', 'sysconfdir': '/etc', 'localstatedir': '/var', 'sharedstatedir': '/var/state'}, '--sharedstatedir=/var/state --prefix=/usr --sysconfdir=sysconf': {'prefix': '/usr', 'sysconfdir': 'sysconf', 'localstatedir': '/var', 'sharedstatedir': '/var/state'}, } for args in expected: self.init(testdir, extra_args=args.split(), default_args=False) opts = self.introspect('--buildoptions') for opt in opts: name = opt['name'] value = opt['value'] if name in expected[args]: self.assertEqual(value, expected[args][name]) self.wipe() def test_clike_get_library_dirs(self): env = get_fake_env() cc = env.detect_c_compiler(MachineChoice.HOST) for d in cc.get_library_dirs(env): self.assertTrue(os.path.exists(d)) self.assertTrue(os.path.isdir(d)) self.assertTrue(os.path.isabs(d)) def test_static_library_overwrite(self): ''' Tests that static libraries are never appended to, always overwritten. Has to be a unit test because this involves building a project, reconfiguring, and building it again so that `ar` is run twice on the same static library. https://github.com/mesonbuild/meson/issues/1355 ''' testdir = os.path.join(self.common_test_dir, '3 static') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) static_linker = env.detect_static_linker(cc) if is_windows(): raise unittest.SkipTest('https://github.com/mesonbuild/meson/issues/1526') if not isinstance(static_linker, mesonbuild.linkers.ArLinker): raise unittest.SkipTest('static linker is not `ar`') # Configure self.init(testdir) # Get name of static library targets = self.introspect('--targets') self.assertEqual(len(targets), 1) libname = targets[0]['filename'][0] # Build and get contents of static library self.build() before = self._run(['ar', 't', os.path.join(self.builddir, libname)]).split() # Filter out non-object-file contents before = [f for f in before if f.endswith(('.o', '.obj'))] # Static library should contain only one object self.assertEqual(len(before), 1, msg=before) # Change the source to be built into the static library self.setconf('-Dsource=libfile2.c') self.build() after = self._run(['ar', 't', os.path.join(self.builddir, libname)]).split() # Filter out non-object-file contents after = [f for f in after if f.endswith(('.o', '.obj'))] # Static library should contain only one object self.assertEqual(len(after), 1, msg=after) # and the object must have changed self.assertNotEqual(before, after) def test_static_compile_order(self): ''' Test that the order of files in a compiler command-line while compiling and linking statically is deterministic. This can't be an ordinary test case because we need to inspect the compiler database. https://github.com/mesonbuild/meson/pull/951 ''' testdir = os.path.join(self.common_test_dir, '5 linkstatic') self.init(testdir) compdb = self.get_compdb() # Rules will get written out in this order self.assertTrue(compdb[0]['file'].endswith("libfile.c")) self.assertTrue(compdb[1]['file'].endswith("libfile2.c")) self.assertTrue(compdb[2]['file'].endswith("libfile3.c")) self.assertTrue(compdb[3]['file'].endswith("libfile4.c")) # FIXME: We don't have access to the linker command def test_run_target_files_path(self): ''' Test that run_targets are run from the correct directory https://github.com/mesonbuild/meson/issues/957 ''' testdir = os.path.join(self.common_test_dir, '52 run target') self.init(testdir) self.run_target('check_exists') self.run_target('check-env') self.run_target('check-env-ct') def test_install_introspection(self): ''' Tests that the Meson introspection API exposes install filenames correctly https://github.com/mesonbuild/meson/issues/829 ''' if self.backend is not Backend.ninja: raise unittest.SkipTest('{!r} backend can\'t install files'.format(self.backend.name)) testdir = os.path.join(self.common_test_dir, '8 install') self.init(testdir) intro = self.introspect('--targets') if intro[0]['type'] == 'executable': intro = intro[::-1] self.assertPathListEqual(intro[0]['install_filename'], ['/usr/lib/libstat.a']) self.assertPathListEqual(intro[1]['install_filename'], ['/usr/bin/prog' + exe_suffix]) def test_install_subdir_introspection(self): ''' Test that the Meson introspection API also contains subdir install information https://github.com/mesonbuild/meson/issues/5556 ''' testdir = os.path.join(self.common_test_dir, '60 install subdir') self.init(testdir) intro = self.introspect('--installed') expected = { 'sub2': 'share/sub2', 'subdir/sub1': 'share/sub1', 'subdir/sub_elided': 'share', 'sub1': 'share/sub1', 'sub/sub1': 'share/sub1', 'sub_elided': 'share', 'nested_elided/sub': 'share', 'new_directory': 'share/new_directory', } self.assertEqual(len(intro), len(expected)) # Convert expected to PurePath expected_converted = {PurePath(os.path.join(testdir, key)): PurePath(os.path.join(self.prefix, val)) for key, val in expected.items()} intro_converted = {PurePath(key): PurePath(val) for key, val in intro.items()} for src, dst in expected_converted.items(): self.assertIn(src, intro_converted) self.assertEqual(dst, intro_converted[src]) def test_install_introspection_multiple_outputs(self): ''' Tests that the Meson introspection API exposes multiple install filenames correctly without crashing https://github.com/mesonbuild/meson/pull/4555 Reverted to the first file only because of https://github.com/mesonbuild/meson/pull/4547#discussion_r244173438 TODO Change the format to a list officially in a followup PR ''' if self.backend is not Backend.ninja: raise unittest.SkipTest('{!r} backend can\'t install files'.format(self.backend.name)) testdir = os.path.join(self.common_test_dir, '141 custom target multiple outputs') self.init(testdir) intro = self.introspect('--targets') if intro[0]['type'] == 'executable': intro = intro[::-1] self.assertPathListEqual(intro[0]['install_filename'], ['/usr/include/diff.h', '/usr/bin/diff.sh']) self.assertPathListEqual(intro[1]['install_filename'], ['/opt/same.h', '/opt/same.sh']) self.assertPathListEqual(intro[2]['install_filename'], ['/usr/include/first.h', None]) self.assertPathListEqual(intro[3]['install_filename'], [None, '/usr/bin/second.sh']) def test_install_log_content(self): ''' Tests that the install-log.txt is consistent with the installed files and directories. Specifically checks that the log file only contains one entry per file/directory. https://github.com/mesonbuild/meson/issues/4499 ''' testdir = os.path.join(self.common_test_dir, '60 install subdir') self.init(testdir) self.install() installpath = Path(self.installdir) # Find installed files and directories expected = {installpath: 0} for name in installpath.rglob('*'): expected[name] = 0 def read_logs(): # Find logged files and directories with Path(self.builddir, 'meson-logs', 'install-log.txt').open() as f: return list(map(lambda l: Path(l.strip()), filter(lambda l: not l.startswith('#'), f.readlines()))) logged = read_logs() for name in logged: self.assertTrue(name in expected, 'Log contains extra entry {}'.format(name)) expected[name] += 1 for name, count in expected.items(): self.assertGreater(count, 0, 'Log is missing entry for {}'.format(name)) self.assertLess(count, 2, 'Log has multiple entries for {}'.format(name)) # Verify that with --dry-run we obtain the same logs but with nothing # actually installed windows_proof_rmtree(self.installdir) self._run(self.meson_command + ['install', '--dry-run', '--destdir', self.installdir], workdir=self.builddir) self.assertEqual(logged, read_logs()) self.assertFalse(os.path.exists(self.installdir)) def test_uninstall(self): exename = os.path.join(self.installdir, 'usr/bin/prog' + exe_suffix) testdir = os.path.join(self.common_test_dir, '8 install') self.init(testdir) self.assertPathDoesNotExist(exename) self.install() self.assertPathExists(exename) self.uninstall() self.assertPathDoesNotExist(exename) def test_forcefallback(self): testdir = os.path.join(self.unit_test_dir, '31 forcefallback') self.init(testdir, extra_args=['--wrap-mode=forcefallback']) self.build() self.run_tests() def test_nopromote(self): testdir = os.path.join(self.common_test_dir, '99 subproject subdir') with self.assertRaises(subprocess.CalledProcessError) as cm: self.init(testdir, extra_args=['--wrap-mode=nopromote']) self.assertIn('Dependency "subsub" not found', cm.exception.stdout) def test_force_fallback_for(self): testdir = os.path.join(self.unit_test_dir, '31 forcefallback') self.init(testdir, extra_args=['--force-fallback-for=zlib,foo']) self.build() self.run_tests() def test_env_ops_dont_stack(self): ''' Test that env ops prepend/append do not stack, and that this usage issues a warning ''' testdir = os.path.join(self.unit_test_dir, '63 test env does not stack') out = self.init(testdir) self.assertRegex(out, r'WARNING: Overriding.*TEST_VAR_APPEND') self.assertRegex(out, r'WARNING: Overriding.*TEST_VAR_PREPEND') self.assertNotRegex(out, r'WARNING: Overriding.*TEST_VAR_SET') self.run_tests() def test_testsetups(self): if not shutil.which('valgrind'): raise unittest.SkipTest('Valgrind not installed.') testdir = os.path.join(self.unit_test_dir, '2 testsetups') self.init(testdir) self.build() # Run tests without setup self.run_tests() with open(os.path.join(self.logdir, 'testlog.txt'), encoding='utf-8') as f: basic_log = f.read() # Run buggy test with setup that has env that will make it fail self.assertRaises(subprocess.CalledProcessError, self._run, self.mtest_command + ['--setup=valgrind']) with open(os.path.join(self.logdir, 'testlog-valgrind.txt'), encoding='utf-8') as f: vg_log = f.read() self.assertFalse('TEST_ENV is set' in basic_log) self.assertFalse('Memcheck' in basic_log) self.assertTrue('TEST_ENV is set' in vg_log) self.assertTrue('Memcheck' in vg_log) # Run buggy test with setup without env that will pass self._run(self.mtest_command + ['--setup=wrapper']) # Setup with no properties works self._run(self.mtest_command + ['--setup=empty']) # Setup with only env works self._run(self.mtest_command + ['--setup=onlyenv']) self._run(self.mtest_command + ['--setup=onlyenv2']) self._run(self.mtest_command + ['--setup=onlyenv3']) # Setup with only a timeout works self._run(self.mtest_command + ['--setup=timeout']) # Setup that does not define a wrapper works with --wrapper self._run(self.mtest_command + ['--setup=timeout', '--wrapper', shutil.which('valgrind')]) # Setup that skips test works self._run(self.mtest_command + ['--setup=good']) with open(os.path.join(self.logdir, 'testlog-good.txt'), encoding='utf-8') as f: exclude_suites_log = f.read() self.assertFalse('buggy' in exclude_suites_log) # --suite overrides add_test_setup(xclude_suites) self._run(self.mtest_command + ['--setup=good', '--suite', 'buggy']) with open(os.path.join(self.logdir, 'testlog-good.txt'), encoding='utf-8') as f: include_suites_log = f.read() self.assertTrue('buggy' in include_suites_log) def test_testsetup_selection(self): testdir = os.path.join(self.unit_test_dir, '14 testsetup selection') self.init(testdir) self.build() # Run tests without setup self.run_tests() self.assertRaises(subprocess.CalledProcessError, self._run, self.mtest_command + ['--setup=missingfromfoo']) self._run(self.mtest_command + ['--setup=missingfromfoo', '--no-suite=foo:']) self._run(self.mtest_command + ['--setup=worksforall']) self._run(self.mtest_command + ['--setup=main:worksforall']) self.assertRaises(subprocess.CalledProcessError, self._run, self.mtest_command + ['--setup=onlyinbar']) self.assertRaises(subprocess.CalledProcessError, self._run, self.mtest_command + ['--setup=onlyinbar', '--no-suite=main:']) self._run(self.mtest_command + ['--setup=onlyinbar', '--no-suite=main:', '--no-suite=foo:']) self._run(self.mtest_command + ['--setup=bar:onlyinbar']) self.assertRaises(subprocess.CalledProcessError, self._run, self.mtest_command + ['--setup=foo:onlyinbar']) self.assertRaises(subprocess.CalledProcessError, self._run, self.mtest_command + ['--setup=main:onlyinbar']) def test_testsetup_default(self): testdir = os.path.join(self.unit_test_dir, '49 testsetup default') self.init(testdir) self.build() # Run tests without --setup will cause the default setup to be used self.run_tests() with open(os.path.join(self.logdir, 'testlog.txt'), encoding='utf-8') as f: default_log = f.read() # Run tests with explicitly using the same setup that is set as default self._run(self.mtest_command + ['--setup=mydefault']) with open(os.path.join(self.logdir, 'testlog-mydefault.txt'), encoding='utf-8') as f: mydefault_log = f.read() # Run tests with another setup self._run(self.mtest_command + ['--setup=other']) with open(os.path.join(self.logdir, 'testlog-other.txt'), encoding='utf-8') as f: other_log = f.read() self.assertTrue('ENV_A is 1' in default_log) self.assertTrue('ENV_B is 2' in default_log) self.assertTrue('ENV_C is 2' in default_log) self.assertTrue('ENV_A is 1' in mydefault_log) self.assertTrue('ENV_B is 2' in mydefault_log) self.assertTrue('ENV_C is 2' in mydefault_log) self.assertTrue('ENV_A is 1' in other_log) self.assertTrue('ENV_B is 3' in other_log) self.assertTrue('ENV_C is 2' in other_log) def assertFailedTestCount(self, failure_count, command): try: self._run(command) self.assertEqual(0, failure_count, 'Expected %d tests to fail.' % failure_count) except subprocess.CalledProcessError as e: self.assertEqual(e.returncode, failure_count) def test_suite_selection(self): testdir = os.path.join(self.unit_test_dir, '4 suite selection') self.init(testdir) self.build() self.assertFailedTestCount(4, self.mtest_command) self.assertFailedTestCount(0, self.mtest_command + ['--suite', ':success']) self.assertFailedTestCount(3, self.mtest_command + ['--suite', ':fail']) self.assertFailedTestCount(4, self.mtest_command + ['--no-suite', ':success']) self.assertFailedTestCount(1, self.mtest_command + ['--no-suite', ':fail']) self.assertFailedTestCount(1, self.mtest_command + ['--suite', 'mainprj']) self.assertFailedTestCount(0, self.mtest_command + ['--suite', 'subprjsucc']) self.assertFailedTestCount(1, self.mtest_command + ['--suite', 'subprjfail']) self.assertFailedTestCount(1, self.mtest_command + ['--suite', 'subprjmix']) self.assertFailedTestCount(3, self.mtest_command + ['--no-suite', 'mainprj']) self.assertFailedTestCount(4, self.mtest_command + ['--no-suite', 'subprjsucc']) self.assertFailedTestCount(3, self.mtest_command + ['--no-suite', 'subprjfail']) self.assertFailedTestCount(3, self.mtest_command + ['--no-suite', 'subprjmix']) self.assertFailedTestCount(1, self.mtest_command + ['--suite', 'mainprj:fail']) self.assertFailedTestCount(0, self.mtest_command + ['--suite', 'mainprj:success']) self.assertFailedTestCount(3, self.mtest_command + ['--no-suite', 'mainprj:fail']) self.assertFailedTestCount(4, self.mtest_command + ['--no-suite', 'mainprj:success']) self.assertFailedTestCount(1, self.mtest_command + ['--suite', 'subprjfail:fail']) self.assertFailedTestCount(0, self.mtest_command + ['--suite', 'subprjfail:success']) self.assertFailedTestCount(3, self.mtest_command + ['--no-suite', 'subprjfail:fail']) self.assertFailedTestCount(4, self.mtest_command + ['--no-suite', 'subprjfail:success']) self.assertFailedTestCount(0, self.mtest_command + ['--suite', 'subprjsucc:fail']) self.assertFailedTestCount(0, self.mtest_command + ['--suite', 'subprjsucc:success']) self.assertFailedTestCount(4, self.mtest_command + ['--no-suite', 'subprjsucc:fail']) self.assertFailedTestCount(4, self.mtest_command + ['--no-suite', 'subprjsucc:success']) self.assertFailedTestCount(1, self.mtest_command + ['--suite', 'subprjmix:fail']) self.assertFailedTestCount(0, self.mtest_command + ['--suite', 'subprjmix:success']) self.assertFailedTestCount(3, self.mtest_command + ['--no-suite', 'subprjmix:fail']) self.assertFailedTestCount(4, self.mtest_command + ['--no-suite', 'subprjmix:success']) self.assertFailedTestCount(2, self.mtest_command + ['--suite', 'subprjfail', '--suite', 'subprjmix:fail']) self.assertFailedTestCount(3, self.mtest_command + ['--suite', 'subprjfail', '--suite', 'subprjmix', '--suite', 'mainprj']) self.assertFailedTestCount(2, self.mtest_command + ['--suite', 'subprjfail', '--suite', 'subprjmix', '--suite', 'mainprj', '--no-suite', 'subprjmix:fail']) self.assertFailedTestCount(1, self.mtest_command + ['--suite', 'subprjfail', '--suite', 'subprjmix', '--suite', 'mainprj', '--no-suite', 'subprjmix:fail', 'mainprj-failing_test']) self.assertFailedTestCount(2, self.mtest_command + ['--no-suite', 'subprjfail:fail', '--no-suite', 'subprjmix:fail']) def test_build_by_default(self): testdir = os.path.join(self.common_test_dir, '130 build by default') self.init(testdir) self.build() genfile1 = os.path.join(self.builddir, 'generated1.dat') genfile2 = os.path.join(self.builddir, 'generated2.dat') exe1 = os.path.join(self.builddir, 'fooprog' + exe_suffix) exe2 = os.path.join(self.builddir, 'barprog' + exe_suffix) self.assertPathExists(genfile1) self.assertPathExists(genfile2) self.assertPathDoesNotExist(exe1) self.assertPathDoesNotExist(exe2) self.build(target=('fooprog' + exe_suffix)) self.assertPathExists(exe1) self.build(target=('barprog' + exe_suffix)) self.assertPathExists(exe2) def test_internal_include_order(self): if mesonbuild.environment.detect_msys2_arch() and ('MESON_RSP_THRESHOLD' in os.environ): raise unittest.SkipTest('Test does not yet support gcc rsp files on msys2') testdir = os.path.join(self.common_test_dir, '131 include order') self.init(testdir) execmd = fxecmd = None for cmd in self.get_compdb(): if 'someexe' in cmd['command']: execmd = cmd['command'] continue if 'somefxe' in cmd['command']: fxecmd = cmd['command'] continue if not execmd or not fxecmd: raise Exception('Could not find someexe and somfxe commands') # Check include order for 'someexe' incs = [a for a in split_args(execmd) if a.startswith("-I")] self.assertEqual(len(incs), 9) # Need to run the build so the private dir is created. self.build() pdirs = glob(os.path.join(self.builddir, 'sub4/someexe*.p')) self.assertEqual(len(pdirs), 1) privdir = pdirs[0][len(self.builddir)+1:] self.assertPathEqual(incs[0], "-I" + privdir) # target build subdir self.assertPathEqual(incs[1], "-Isub4") # target source subdir self.assertPathBasenameEqual(incs[2], 'sub4') # include paths added via per-target c_args: ['-I'...] self.assertPathBasenameEqual(incs[3], 'sub3') # target include_directories: build dir self.assertPathEqual(incs[4], "-Isub2") # target include_directories: source dir self.assertPathBasenameEqual(incs[5], 'sub2') # target internal dependency include_directories: build dir self.assertPathEqual(incs[6], "-Isub1") # target internal dependency include_directories: source dir self.assertPathBasenameEqual(incs[7], 'sub1') # custom target include dir self.assertPathEqual(incs[8], '-Ictsub') # Check include order for 'somefxe' incs = [a for a in split_args(fxecmd) if a.startswith('-I')] self.assertEqual(len(incs), 9) # target private dir pdirs = glob(os.path.join(self.builddir, 'somefxe*.p')) self.assertEqual(len(pdirs), 1) privdir = pdirs[0][len(self.builddir)+1:] self.assertPathEqual(incs[0], '-I' + privdir) # target build dir self.assertPathEqual(incs[1], '-I.') # target source dir self.assertPathBasenameEqual(incs[2], os.path.basename(testdir)) # target internal dependency correct include_directories: build dir self.assertPathEqual(incs[3], "-Isub4") # target internal dependency correct include_directories: source dir self.assertPathBasenameEqual(incs[4], 'sub4') # target internal dependency dep include_directories: build dir self.assertPathEqual(incs[5], "-Isub1") # target internal dependency dep include_directories: source dir self.assertPathBasenameEqual(incs[6], 'sub1') # target internal dependency wrong include_directories: build dir self.assertPathEqual(incs[7], "-Isub2") # target internal dependency wrong include_directories: source dir self.assertPathBasenameEqual(incs[8], 'sub2') def test_compiler_detection(self): ''' Test that automatic compiler detection and setting from the environment both work just fine. This is needed because while running project tests and other unit tests, we always read CC/CXX/etc from the environment. ''' gnu = mesonbuild.compilers.GnuCompiler clang = mesonbuild.compilers.ClangCompiler intel = mesonbuild.compilers.IntelGnuLikeCompiler msvc = (mesonbuild.compilers.VisualStudioCCompiler, mesonbuild.compilers.VisualStudioCPPCompiler) clangcl = (mesonbuild.compilers.ClangClCCompiler, mesonbuild.compilers.ClangClCPPCompiler) ar = mesonbuild.linkers.ArLinker lib = mesonbuild.linkers.VisualStudioLinker langs = [('c', 'CC'), ('cpp', 'CXX')] if not is_windows() and platform.machine().lower() != 'e2k': langs += [('objc', 'OBJC'), ('objcpp', 'OBJCXX')] testdir = os.path.join(self.unit_test_dir, '5 compiler detection') env = get_fake_env(testdir, self.builddir, self.prefix) for lang, evar in langs: # Detect with evar and do sanity checks on that if evar in os.environ: ecc = getattr(env, 'detect_{}_compiler'.format(lang))(MachineChoice.HOST) self.assertTrue(ecc.version) elinker = env.detect_static_linker(ecc) # Pop it so we don't use it for the next detection evalue = os.environ.pop(evar) # Very rough/strict heuristics. Would never work for actual # compiler detection, but should be ok for the tests. ebase = os.path.basename(evalue) if ebase.startswith('g') or ebase.endswith(('-gcc', '-g++')): self.assertIsInstance(ecc, gnu) self.assertIsInstance(elinker, ar) elif 'clang-cl' in ebase: self.assertIsInstance(ecc, clangcl) self.assertIsInstance(elinker, lib) elif 'clang' in ebase: self.assertIsInstance(ecc, clang) self.assertIsInstance(elinker, ar) elif ebase.startswith('ic'): self.assertIsInstance(ecc, intel) self.assertIsInstance(elinker, ar) elif ebase.startswith('cl'): self.assertIsInstance(ecc, msvc) self.assertIsInstance(elinker, lib) else: raise AssertionError('Unknown compiler {!r}'.format(evalue)) # Check that we actually used the evalue correctly as the compiler self.assertEqual(ecc.get_exelist(), split_args(evalue)) # Do auto-detection of compiler based on platform, PATH, etc. cc = getattr(env, 'detect_{}_compiler'.format(lang))(MachineChoice.HOST) self.assertTrue(cc.version) linker = env.detect_static_linker(cc) # Check compiler type if isinstance(cc, gnu): self.assertIsInstance(linker, ar) if is_osx(): self.assertIsInstance(cc.linker, mesonbuild.linkers.AppleDynamicLinker) elif is_sunos(): self.assertIsInstance(cc.linker, (mesonbuild.linkers.SolarisDynamicLinker, mesonbuild.linkers.GnuLikeDynamicLinkerMixin)) else: self.assertIsInstance(cc.linker, mesonbuild.linkers.GnuLikeDynamicLinkerMixin) if isinstance(cc, clangcl): self.assertIsInstance(linker, lib) self.assertIsInstance(cc.linker, mesonbuild.linkers.ClangClDynamicLinker) if isinstance(cc, clang): self.assertIsInstance(linker, ar) if is_osx(): self.assertIsInstance(cc.linker, mesonbuild.linkers.AppleDynamicLinker) elif is_windows(): # This is clang, not clang-cl. This can be either an # ld-like linker of link.exe-like linker (usually the # former for msys2, the latter otherwise) self.assertIsInstance(cc.linker, (mesonbuild.linkers.MSVCDynamicLinker, mesonbuild.linkers.GnuLikeDynamicLinkerMixin)) else: self.assertIsInstance(cc.linker, mesonbuild.linkers.GnuLikeDynamicLinkerMixin) if isinstance(cc, intel): self.assertIsInstance(linker, ar) if is_osx(): self.assertIsInstance(cc.linker, mesonbuild.linkers.AppleDynamicLinker) elif is_windows(): self.assertIsInstance(cc.linker, mesonbuild.linkers.XilinkDynamicLinker) else: self.assertIsInstance(cc.linker, mesonbuild.linkers.GnuDynamicLinker) if isinstance(cc, msvc): self.assertTrue(is_windows()) self.assertIsInstance(linker, lib) self.assertEqual(cc.id, 'msvc') self.assertTrue(hasattr(cc, 'is_64')) self.assertIsInstance(cc.linker, mesonbuild.linkers.MSVCDynamicLinker) # If we're on Windows CI, we know what the compiler will be if 'arch' in os.environ: if os.environ['arch'] == 'x64': self.assertTrue(cc.is_64) else: self.assertFalse(cc.is_64) # Set evar ourselves to a wrapper script that just calls the same # exelist + some argument. This is meant to test that setting # something like `ccache gcc -pipe` or `distcc ccache gcc` works. wrapper = os.path.join(testdir, 'compiler wrapper.py') wrappercc = python_command + [wrapper] + cc.get_exelist() + ['-DSOME_ARG'] os.environ[evar] = ' '.join(quote_arg(w) for w in wrappercc) # Check static linker too wrapperlinker = python_command + [wrapper] + linker.get_exelist() + linker.get_always_args() os.environ['AR'] = ' '.join(quote_arg(w) for w in wrapperlinker) # Need a new env to re-run environment loading env = get_fake_env(testdir, self.builddir, self.prefix) wcc = getattr(env, 'detect_{}_compiler'.format(lang))(MachineChoice.HOST) wlinker = env.detect_static_linker(wcc) # Pop it so we don't use it for the next detection evalue = os.environ.pop('AR') # Must be the same type since it's a wrapper around the same exelist self.assertIs(type(cc), type(wcc)) self.assertIs(type(linker), type(wlinker)) # Ensure that the exelist is correct self.assertEqual(wcc.get_exelist(), wrappercc) self.assertEqual(wlinker.get_exelist(), wrapperlinker) # Ensure that the version detection worked correctly self.assertEqual(cc.version, wcc.version) if hasattr(cc, 'is_64'): self.assertEqual(cc.is_64, wcc.is_64) def test_always_prefer_c_compiler_for_asm(self): testdir = os.path.join(self.common_test_dir, '134 c cpp and asm') # Skip if building with MSVC env = get_fake_env(testdir, self.builddir, self.prefix) if env.detect_c_compiler(MachineChoice.HOST).get_id() == 'msvc': raise unittest.SkipTest('MSVC can\'t compile assembly') self.init(testdir) commands = {'c-asm': {}, 'cpp-asm': {}, 'cpp-c-asm': {}, 'c-cpp-asm': {}} for cmd in self.get_compdb(): # Get compiler split = split_args(cmd['command']) if split[0] == 'ccache': compiler = split[1] else: compiler = split[0] # Classify commands if 'Ic-asm' in cmd['command']: if cmd['file'].endswith('.S'): commands['c-asm']['asm'] = compiler elif cmd['file'].endswith('.c'): commands['c-asm']['c'] = compiler else: raise AssertionError('{!r} found in cpp-asm?'.format(cmd['command'])) elif 'Icpp-asm' in cmd['command']: if cmd['file'].endswith('.S'): commands['cpp-asm']['asm'] = compiler elif cmd['file'].endswith('.cpp'): commands['cpp-asm']['cpp'] = compiler else: raise AssertionError('{!r} found in cpp-asm?'.format(cmd['command'])) elif 'Ic-cpp-asm' in cmd['command']: if cmd['file'].endswith('.S'): commands['c-cpp-asm']['asm'] = compiler elif cmd['file'].endswith('.c'): commands['c-cpp-asm']['c'] = compiler elif cmd['file'].endswith('.cpp'): commands['c-cpp-asm']['cpp'] = compiler else: raise AssertionError('{!r} found in c-cpp-asm?'.format(cmd['command'])) elif 'Icpp-c-asm' in cmd['command']: if cmd['file'].endswith('.S'): commands['cpp-c-asm']['asm'] = compiler elif cmd['file'].endswith('.c'): commands['cpp-c-asm']['c'] = compiler elif cmd['file'].endswith('.cpp'): commands['cpp-c-asm']['cpp'] = compiler else: raise AssertionError('{!r} found in cpp-c-asm?'.format(cmd['command'])) else: raise AssertionError('Unknown command {!r} found'.format(cmd['command'])) # Check that .S files are always built with the C compiler self.assertEqual(commands['c-asm']['asm'], commands['c-asm']['c']) self.assertEqual(commands['c-asm']['asm'], commands['cpp-asm']['asm']) self.assertEqual(commands['cpp-asm']['asm'], commands['c-cpp-asm']['c']) self.assertEqual(commands['c-cpp-asm']['asm'], commands['c-cpp-asm']['c']) self.assertEqual(commands['cpp-c-asm']['asm'], commands['cpp-c-asm']['c']) self.assertNotEqual(commands['cpp-asm']['asm'], commands['cpp-asm']['cpp']) self.assertNotEqual(commands['c-cpp-asm']['c'], commands['c-cpp-asm']['cpp']) self.assertNotEqual(commands['cpp-c-asm']['c'], commands['cpp-c-asm']['cpp']) # Check that the c-asm target is always linked with the C linker build_ninja = os.path.join(self.builddir, 'build.ninja') with open(build_ninja, 'r', encoding='utf-8') as f: contents = f.read() m = re.search('build c-asm.*: c_LINKER', contents) self.assertIsNotNone(m, msg=contents) def test_preprocessor_checks_CPPFLAGS(self): ''' Test that preprocessor compiler checks read CPPFLAGS and also CFLAGS but not LDFLAGS. ''' testdir = os.path.join(self.common_test_dir, '133 get define') define = 'MESON_TEST_DEFINE_VALUE' # NOTE: this list can't have \n, ' or " # \n is never substituted by the GNU pre-processor via a -D define # ' and " confuse split_args() even when they are escaped # % and # confuse the MSVC preprocessor # !, ^, *, and < confuse lcc preprocessor value = 'spaces and fun@$&()-=_+{}[]:;>?,./~`' for env_var in ['CPPFLAGS', 'CFLAGS']: env = {} env[env_var] = '-D{}="{}"'.format(define, value) env['LDFLAGS'] = '-DMESON_FAIL_VALUE=cflags-read' self.init(testdir, extra_args=['-D{}={}'.format(define, value)], override_envvars=env) def test_custom_target_exe_data_deterministic(self): testdir = os.path.join(self.common_test_dir, '110 custom target capture') self.init(testdir) meson_exe_dat1 = glob(os.path.join(self.privatedir, 'meson_exe*.dat')) self.wipe() self.init(testdir) meson_exe_dat2 = glob(os.path.join(self.privatedir, 'meson_exe*.dat')) self.assertListEqual(meson_exe_dat1, meson_exe_dat2) def test_noop_changes_cause_no_rebuilds(self): ''' Test that no-op changes to the build files such as mtime do not cause a rebuild of anything. ''' testdir = os.path.join(self.common_test_dir, '6 linkshared') self.init(testdir) self.build() # Immediately rebuilding should not do anything self.assertBuildIsNoop() # Changing mtime of meson.build should not rebuild anything self.utime(os.path.join(testdir, 'meson.build')) self.assertReconfiguredBuildIsNoop() # Changing mtime of libefile.c should rebuild the library, but not relink the executable self.utime(os.path.join(testdir, 'libfile.c')) self.assertBuildRelinkedOnlyTarget('mylib') def test_source_changes_cause_rebuild(self): ''' Test that changes to sources and headers cause rebuilds, but not changes to unused files (as determined by the dependency file) in the input files list. ''' testdir = os.path.join(self.common_test_dir, '20 header in file list') self.init(testdir) self.build() # Immediately rebuilding should not do anything self.assertBuildIsNoop() # Changing mtime of header.h should rebuild everything self.utime(os.path.join(testdir, 'header.h')) self.assertBuildRelinkedOnlyTarget('prog') def test_custom_target_changes_cause_rebuild(self): ''' Test that in a custom target, changes to the input files, the ExternalProgram, and any File objects on the command-line cause a rebuild. ''' testdir = os.path.join(self.common_test_dir, '58 custom header generator') self.init(testdir) self.build() # Immediately rebuilding should not do anything self.assertBuildIsNoop() # Changing mtime of these should rebuild everything for f in ('input.def', 'makeheader.py', 'somefile.txt'): self.utime(os.path.join(testdir, f)) self.assertBuildRelinkedOnlyTarget('prog') def test_source_generator_program_cause_rebuild(self): ''' Test that changes to generator programs in the source tree cause a rebuild. ''' testdir = os.path.join(self.common_test_dir, '91 gen extra') self.init(testdir) self.build() # Immediately rebuilding should not do anything self.assertBuildIsNoop() # Changing mtime of generator should rebuild the executable self.utime(os.path.join(testdir, 'srcgen.py')) self.assertRebuiltTarget('basic') def test_static_library_lto(self): ''' Test that static libraries can be built with LTO and linked to executables. On Linux, this requires the use of gcc-ar. https://github.com/mesonbuild/meson/issues/1646 ''' testdir = os.path.join(self.common_test_dir, '5 linkstatic') env = get_fake_env(testdir, self.builddir, self.prefix) if env.detect_c_compiler(MachineChoice.HOST).get_id() == 'clang' and is_windows(): raise unittest.SkipTest('LTO not (yet) supported by windows clang') self.init(testdir, extra_args='-Db_lto=true') self.build() self.run_tests() @skip_if_not_base_option('b_lto_threads') def test_lto_threads(self): if is_cygwin(): raise unittest.SkipTest('LTO is broken on Cygwin.') testdir = os.path.join(self.common_test_dir, '6 linkshared') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) extra_args: T.List[str] = [] if cc.get_id() == 'clang': if is_windows(): raise unittest.SkipTest('LTO not (yet) supported by windows clang') else: extra_args.append('-D_cargs=-Werror=unused-command-line-argument') self.init(testdir, extra_args=['-Db_lto=true', '-Db_lto_threads=8'] + extra_args) self.build() self.run_tests() expected = set(cc.get_lto_compile_args(threads=8)) targets = self.introspect('--targets') # This assumes all of the targets support lto for t in targets: for s in t['target_sources']: for e in expected: self.assertIn(e, s['parameters']) @skip_if_not_base_option('b_lto_mode') @skip_if_not_base_option('b_lto_threads') def test_lto_mode(self): testdir = os.path.join(self.common_test_dir, '6 linkshared') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) if cc.get_id() != 'clang': raise unittest.SkipTest('Only clang currently supports thinLTO') if cc.linker.id not in {'ld.lld', 'ld.gold', 'ld64', 'lld-link'}: raise unittest.SkipTest('thinLTO requires ld.lld, ld.gold, ld64, or lld-link') elif is_windows(): raise unittest.SkipTest('LTO not (yet) supported by windows clang') self.init(testdir, extra_args=['-Db_lto=true', '-Db_lto_mode=thin', '-Db_lto_threads=8', '-Dc_args=-Werror=unused-command-line-argument']) self.build() self.run_tests() expected = set(cc.get_lto_compile_args(threads=8, mode='thin')) targets = self.introspect('--targets') # This assumes all of the targets support lto for t in targets: for s in t['target_sources']: self.assertTrue(expected.issubset(set(s['parameters'])), f'Incorrect values for {t["name"]}') def test_dist_git(self): if not shutil.which('git'): raise unittest.SkipTest('Git not found') if self.backend is not Backend.ninja: raise unittest.SkipTest('Dist is only supported with Ninja') try: self.dist_impl(_git_init, _git_add_all) except PermissionError: # When run under Windows CI, something (virus scanner?) # holds on to the git files so cleaning up the dir # fails sometimes. pass def has_working_hg(self): if not shutil.which('hg'): return False try: # This check should not be necessary, but # CI under macOS passes the above test even # though Mercurial is not installed. if subprocess.call(['hg', '--version'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) != 0: return False return True except FileNotFoundError: return False def test_dist_hg(self): if not self.has_working_hg(): raise unittest.SkipTest('Mercurial not found or broken.') if self.backend is not Backend.ninja: raise unittest.SkipTest('Dist is only supported with Ninja') def hg_init(project_dir): subprocess.check_call(['hg', 'init'], cwd=project_dir) with open(os.path.join(project_dir, '.hg', 'hgrc'), 'w') as f: print('[ui]', file=f) print('username=Author Person <teh_coderz@example.com>', file=f) subprocess.check_call(['hg', 'add', 'meson.build', 'distexe.c'], cwd=project_dir) subprocess.check_call(['hg', 'commit', '-m', 'I am a project'], cwd=project_dir) try: self.dist_impl(hg_init, include_subprojects=False) except PermissionError: # When run under Windows CI, something (virus scanner?) # holds on to the hg files so cleaning up the dir # fails sometimes. pass def test_dist_git_script(self): if not shutil.which('git'): raise unittest.SkipTest('Git not found') if self.backend is not Backend.ninja: raise unittest.SkipTest('Dist is only supported with Ninja') try: with tempfile.TemporaryDirectory() as tmpdir: project_dir = os.path.join(tmpdir, 'a') shutil.copytree(os.path.join(self.unit_test_dir, '35 dist script'), project_dir) _git_init(project_dir) self.init(project_dir) self.build('dist') except PermissionError: # When run under Windows CI, something (virus scanner?) # holds on to the git files so cleaning up the dir # fails sometimes. pass def create_dummy_subproject(self, project_dir, name): path = os.path.join(project_dir, 'subprojects', name) os.makedirs(path) with open(os.path.join(path, 'meson.build'), 'w') as ofile: ofile.write("project('{}', version: '1.0')".format(name)) return path def dist_impl(self, vcs_init, vcs_add_all=None, include_subprojects=True): # Create this on the fly because having rogue .git directories inside # the source tree leads to all kinds of trouble. with tempfile.TemporaryDirectory() as project_dir: with open(os.path.join(project_dir, 'meson.build'), 'w') as ofile: ofile.write(textwrap.dedent('''\ project('disttest', 'c', version : '1.4.3') e = executable('distexe', 'distexe.c') test('dist test', e) subproject('vcssub', required : false) subproject('tarballsub', required : false) subproject('samerepo', required : false) ''')) with open(os.path.join(project_dir, 'distexe.c'), 'w') as ofile: ofile.write(textwrap.dedent('''\ #include<stdio.h> int main(int argc, char **argv) { printf("I am a distribution test.\\n"); return 0; } ''')) xz_distfile = os.path.join(self.distdir, 'disttest-1.4.3.tar.xz') xz_checksumfile = xz_distfile + '.sha256sum' zip_distfile = os.path.join(self.distdir, 'disttest-1.4.3.zip') zip_checksumfile = zip_distfile + '.sha256sum' vcs_init(project_dir) if include_subprojects: vcs_init(self.create_dummy_subproject(project_dir, 'vcssub')) self.create_dummy_subproject(project_dir, 'tarballsub') self.create_dummy_subproject(project_dir, 'unusedsub') if vcs_add_all: vcs_add_all(self.create_dummy_subproject(project_dir, 'samerepo')) self.init(project_dir) self.build('dist') self.assertPathExists(xz_distfile) self.assertPathExists(xz_checksumfile) self.assertPathDoesNotExist(zip_distfile) self.assertPathDoesNotExist(zip_checksumfile) self._run(self.meson_command + ['dist', '--formats', 'zip'], workdir=self.builddir) self.assertPathExists(zip_distfile) self.assertPathExists(zip_checksumfile) if include_subprojects: # Verify that without --include-subprojects we have files from # the main project and also files from subprojects part of the # main vcs repository. z = zipfile.ZipFile(zip_distfile) expected = ['disttest-1.4.3/', 'disttest-1.4.3/meson.build', 'disttest-1.4.3/distexe.c'] if vcs_add_all: expected += ['disttest-1.4.3/subprojects/', 'disttest-1.4.3/subprojects/samerepo/', 'disttest-1.4.3/subprojects/samerepo/meson.build'] self.assertEqual(sorted(expected), sorted(z.namelist())) # Verify that with --include-subprojects we now also have files # from tarball and separate vcs subprojects. But not files from # unused subprojects. self._run(self.meson_command + ['dist', '--formats', 'zip', '--include-subprojects'], workdir=self.builddir) z = zipfile.ZipFile(zip_distfile) expected += ['disttest-1.4.3/subprojects/tarballsub/', 'disttest-1.4.3/subprojects/tarballsub/meson.build', 'disttest-1.4.3/subprojects/vcssub/', 'disttest-1.4.3/subprojects/vcssub/meson.build'] self.assertEqual(sorted(expected), sorted(z.namelist())) if vcs_add_all: # Verify we can distribute separately subprojects in the same vcs # repository as the main project. subproject_dir = os.path.join(project_dir, 'subprojects', 'samerepo') self.new_builddir() self.init(subproject_dir) self.build('dist') xz_distfile = os.path.join(self.distdir, 'samerepo-1.0.tar.xz') xz_checksumfile = xz_distfile + '.sha256sum' self.assertPathExists(xz_distfile) self.assertPathExists(xz_checksumfile) tar = tarfile.open(xz_distfile, "r:xz") self.assertEqual(sorted(['samerepo-1.0', 'samerepo-1.0/meson.build']), sorted([i.name for i in tar])) def test_rpath_uses_ORIGIN(self): ''' Test that built targets use $ORIGIN in rpath, which ensures that they are relocatable and ensures that builds are reproducible since the build directory won't get embedded into the built binaries. ''' if is_windows() or is_cygwin(): raise unittest.SkipTest('Windows PE/COFF binaries do not use RPATH') testdir = os.path.join(self.common_test_dir, '40 library chain') self.init(testdir) self.build() for each in ('prog', 'subdir/liblib1.so', ): rpath = get_rpath(os.path.join(self.builddir, each)) self.assertTrue(rpath, 'Rpath could not be determined for {}.'.format(each)) if is_dragonflybsd(): # DragonflyBSD will prepend /usr/lib/gccVERSION to the rpath, # so ignore that. self.assertTrue(rpath.startswith('/usr/lib/gcc')) rpaths = rpath.split(':')[1:] else: rpaths = rpath.split(':') for path in rpaths: self.assertTrue(path.startswith('$ORIGIN'), msg=(each, path)) # These two don't link to anything else, so they do not need an rpath entry. for each in ('subdir/subdir2/liblib2.so', 'subdir/subdir3/liblib3.so'): rpath = get_rpath(os.path.join(self.builddir, each)) if is_dragonflybsd(): # The rpath should be equal to /usr/lib/gccVERSION self.assertTrue(rpath.startswith('/usr/lib/gcc')) self.assertEqual(len(rpath.split(':')), 1) else: self.assertTrue(rpath is None) def test_dash_d_dedup(self): testdir = os.path.join(self.unit_test_dir, '9 d dedup') self.init(testdir) cmd = self.get_compdb()[0]['command'] self.assertTrue('-D FOO -D BAR' in cmd or '"-D" "FOO" "-D" "BAR"' in cmd or '/D FOO /D BAR' in cmd or '"/D" "FOO" "/D" "BAR"' in cmd) def test_all_forbidden_targets_tested(self): ''' Test that all forbidden targets are tested in the '151 reserved targets' test. Needs to be a unit test because it accesses Meson internals. ''' testdir = os.path.join(self.common_test_dir, '151 reserved targets') targets = mesonbuild.coredata.FORBIDDEN_TARGET_NAMES # We don't actually define a target with this name targets.pop('build.ninja') # Remove this to avoid multiple entries with the same name # but different case. targets.pop('PHONY') for i in targets: self.assertPathExists(os.path.join(testdir, i)) def detect_prebuild_env(self): env = get_fake_env() cc = env.detect_c_compiler(MachineChoice.HOST) stlinker = env.detect_static_linker(cc) if mesonbuild.mesonlib.is_windows(): object_suffix = 'obj' shared_suffix = 'dll' elif mesonbuild.mesonlib.is_cygwin(): object_suffix = 'o' shared_suffix = 'dll' elif mesonbuild.mesonlib.is_osx(): object_suffix = 'o' shared_suffix = 'dylib' else: object_suffix = 'o' shared_suffix = 'so' return (cc, stlinker, object_suffix, shared_suffix) def pbcompile(self, compiler, source, objectfile, extra_args=None): cmd = compiler.get_exelist() extra_args = extra_args or [] if compiler.get_argument_syntax() == 'msvc': cmd += ['/nologo', '/Fo' + objectfile, '/c', source] + extra_args else: cmd += ['-c', source, '-o', objectfile] + extra_args subprocess.check_call(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) def test_prebuilt_object(self): (compiler, _, object_suffix, _) = self.detect_prebuild_env() tdir = os.path.join(self.unit_test_dir, '15 prebuilt object') source = os.path.join(tdir, 'source.c') objectfile = os.path.join(tdir, 'prebuilt.' + object_suffix) self.pbcompile(compiler, source, objectfile) try: self.init(tdir) self.build() self.run_tests() finally: os.unlink(objectfile) def build_static_lib(self, compiler, linker, source, objectfile, outfile, extra_args=None): if extra_args is None: extra_args = [] if compiler.get_argument_syntax() == 'msvc': link_cmd = ['lib', '/NOLOGO', '/OUT:' + outfile, objectfile] else: link_cmd = ['ar', 'csr', outfile, objectfile] link_cmd = linker.get_exelist() link_cmd += linker.get_always_args() link_cmd += linker.get_std_link_args() link_cmd += linker.get_output_args(outfile) link_cmd += [objectfile] self.pbcompile(compiler, source, objectfile, extra_args=extra_args) try: subprocess.check_call(link_cmd) finally: os.unlink(objectfile) def test_prebuilt_static_lib(self): (cc, stlinker, object_suffix, _) = self.detect_prebuild_env() tdir = os.path.join(self.unit_test_dir, '16 prebuilt static') source = os.path.join(tdir, 'libdir/best.c') objectfile = os.path.join(tdir, 'libdir/best.' + object_suffix) stlibfile = os.path.join(tdir, 'libdir/libbest.a') self.build_static_lib(cc, stlinker, source, objectfile, stlibfile) # Run the test try: self.init(tdir) self.build() self.run_tests() finally: os.unlink(stlibfile) def build_shared_lib(self, compiler, source, objectfile, outfile, impfile, extra_args=None): if extra_args is None: extra_args = [] if compiler.get_argument_syntax() == 'msvc': link_cmd = compiler.get_linker_exelist() + [ '/NOLOGO', '/DLL', '/DEBUG', '/IMPLIB:' + impfile, '/OUT:' + outfile, objectfile] else: if not (compiler.info.is_windows() or compiler.info.is_cygwin() or compiler.info.is_darwin()): extra_args += ['-fPIC'] link_cmd = compiler.get_exelist() + ['-shared', '-o', outfile, objectfile] if not mesonbuild.mesonlib.is_osx(): link_cmd += ['-Wl,-soname=' + os.path.basename(outfile)] self.pbcompile(compiler, source, objectfile, extra_args=extra_args) try: subprocess.check_call(link_cmd) finally: os.unlink(objectfile) def test_prebuilt_shared_lib(self): (cc, _, object_suffix, shared_suffix) = self.detect_prebuild_env() tdir = os.path.join(self.unit_test_dir, '17 prebuilt shared') source = os.path.join(tdir, 'alexandria.c') objectfile = os.path.join(tdir, 'alexandria.' + object_suffix) impfile = os.path.join(tdir, 'alexandria.lib') if cc.get_argument_syntax() == 'msvc': shlibfile = os.path.join(tdir, 'alexandria.' + shared_suffix) elif is_cygwin(): shlibfile = os.path.join(tdir, 'cygalexandria.' + shared_suffix) else: shlibfile = os.path.join(tdir, 'libalexandria.' + shared_suffix) self.build_shared_lib(cc, source, objectfile, shlibfile, impfile) # Run the test try: self.init(tdir) self.build() self.run_tests() finally: os.unlink(shlibfile) if mesonbuild.mesonlib.is_windows(): # Clean up all the garbage MSVC writes in the # source tree. for fname in glob(os.path.join(tdir, 'alexandria.*')): if os.path.splitext(fname)[1] not in ['.c', '.h']: os.unlink(fname) @skipIfNoPkgconfig def test_pkgconfig_static(self): ''' Test that the we prefer static libraries when `static: true` is passed to dependency() with pkg-config. Can't be an ordinary test because we need to build libs and try to find them from meson.build Also test that it's not a hard error to have unsatisfiable library deps since system libraries -lm will never be found statically. https://github.com/mesonbuild/meson/issues/2785 ''' (cc, stlinker, objext, shext) = self.detect_prebuild_env() testdir = os.path.join(self.unit_test_dir, '18 pkgconfig static') source = os.path.join(testdir, 'foo.c') objectfile = os.path.join(testdir, 'foo.' + objext) stlibfile = os.path.join(testdir, 'libfoo.a') impfile = os.path.join(testdir, 'foo.lib') if cc.get_argument_syntax() == 'msvc': shlibfile = os.path.join(testdir, 'foo.' + shext) elif is_cygwin(): shlibfile = os.path.join(testdir, 'cygfoo.' + shext) else: shlibfile = os.path.join(testdir, 'libfoo.' + shext) # Build libs self.build_static_lib(cc, stlinker, source, objectfile, stlibfile, extra_args=['-DFOO_STATIC']) self.build_shared_lib(cc, source, objectfile, shlibfile, impfile) # Run test try: self.init(testdir, override_envvars={'PKG_CONFIG_LIBDIR': self.builddir}) self.build() self.run_tests() finally: os.unlink(stlibfile) os.unlink(shlibfile) if mesonbuild.mesonlib.is_windows(): # Clean up all the garbage MSVC writes in the # source tree. for fname in glob(os.path.join(testdir, 'foo.*')): if os.path.splitext(fname)[1] not in ['.c', '.h', '.in']: os.unlink(fname) @skipIfNoPkgconfig @mock.patch.dict(os.environ) def test_pkgconfig_gen_escaping(self): testdir = os.path.join(self.common_test_dir, '45 pkgconfig-gen') prefix = '/usr/with spaces' libdir = 'lib' self.init(testdir, extra_args=['--prefix=' + prefix, '--libdir=' + libdir]) # Find foo dependency os.environ['PKG_CONFIG_LIBDIR'] = self.privatedir env = get_fake_env(testdir, self.builddir, self.prefix) kwargs = {'required': True, 'silent': True} foo_dep = PkgConfigDependency('libfoo', env, kwargs) # Ensure link_args are properly quoted libdir = PurePath(prefix) / PurePath(libdir) link_args = ['-L' + libdir.as_posix(), '-lfoo'] self.assertEqual(foo_dep.get_link_args(), link_args) # Ensure include args are properly quoted incdir = PurePath(prefix) / PurePath('include') cargs = ['-I' + incdir.as_posix(), '-DLIBFOO'] # pkg-config and pkgconf does not respect the same order self.assertEqual(sorted(foo_dep.get_compile_args()), sorted(cargs)) def test_array_option_change(self): def get_opt(): opts = self.introspect('--buildoptions') for x in opts: if x.get('name') == 'list': return x raise Exception(opts) expected = { 'name': 'list', 'description': 'list', 'section': 'user', 'type': 'array', 'value': ['foo', 'bar'], 'machine': 'any', } tdir = os.path.join(self.unit_test_dir, '19 array option') self.init(tdir) original = get_opt() self.assertDictEqual(original, expected) expected['value'] = ['oink', 'boink'] self.setconf('-Dlist=oink,boink') changed = get_opt() self.assertEqual(changed, expected) def test_array_option_bad_change(self): def get_opt(): opts = self.introspect('--buildoptions') for x in opts: if x.get('name') == 'list': return x raise Exception(opts) expected = { 'name': 'list', 'description': 'list', 'section': 'user', 'type': 'array', 'value': ['foo', 'bar'], 'machine': 'any', } tdir = os.path.join(self.unit_test_dir, '19 array option') self.init(tdir) original = get_opt() self.assertDictEqual(original, expected) with self.assertRaises(subprocess.CalledProcessError): self.setconf('-Dlist=bad') changed = get_opt() self.assertDictEqual(changed, expected) def test_array_option_empty_equivalents(self): """Array options treat -Dopt=[] and -Dopt= as equivalent.""" def get_opt(): opts = self.introspect('--buildoptions') for x in opts: if x.get('name') == 'list': return x raise Exception(opts) expected = { 'name': 'list', 'description': 'list', 'section': 'user', 'type': 'array', 'value': [], 'machine': 'any', } tdir = os.path.join(self.unit_test_dir, '19 array option') self.init(tdir, extra_args='-Dlist=') original = get_opt() self.assertDictEqual(original, expected) def opt_has(self, name, value): res = self.introspect('--buildoptions') found = False for i in res: if i['name'] == name: self.assertEqual(i['value'], value) found = True break self.assertTrue(found, "Array option not found in introspect data.") def test_free_stringarray_setting(self): testdir = os.path.join(self.common_test_dir, '41 options') self.init(testdir) self.opt_has('free_array_opt', []) self.setconf('-Dfree_array_opt=foo,bar', will_build=False) self.opt_has('free_array_opt', ['foo', 'bar']) self.setconf("-Dfree_array_opt=['a,b', 'c,d']", will_build=False) self.opt_has('free_array_opt', ['a,b', 'c,d']) # When running under Travis Mac CI, the file updates seem to happen # too fast so the timestamps do not get properly updated. # Call this method before file operations in appropriate places # to make things work. def mac_ci_delay(self): if is_osx() and is_ci(): import time time.sleep(1) def test_options_with_choices_changing(self) -> None: """Detect when options like arrays or combos have their choices change.""" testdir = Path(os.path.join(self.unit_test_dir, '85 change option choices')) options1 = str(testdir / 'meson_options.1.txt') options2 = str(testdir / 'meson_options.2.txt') # Test that old options are changed to the new defaults if they are not valid real_options = str(testdir / 'meson_options.txt') self.addCleanup(os.unlink, real_options) shutil.copy(options1, real_options) self.init(str(testdir)) self.mac_ci_delay() shutil.copy(options2, real_options) self.build() opts = self.introspect('--buildoptions') for item in opts: if item['name'] == 'combo': self.assertEqual(item['value'], 'b') self.assertEqual(item['choices'], ['b', 'c', 'd']) elif item['name'] == 'arr': self.assertEqual(item['value'], ['b']) self.assertEqual(item['choices'], ['b', 'c', 'd']) self.wipe() self.mac_ci_delay() # When the old options are valid they should remain shutil.copy(options1, real_options) self.init(str(testdir), extra_args=['-Dcombo=c', '-Darray=b,c']) self.mac_ci_delay() shutil.copy(options2, real_options) self.build() opts = self.introspect('--buildoptions') for item in opts: if item['name'] == 'combo': self.assertEqual(item['value'], 'c') self.assertEqual(item['choices'], ['b', 'c', 'd']) elif item['name'] == 'arr': self.assertEqual(item['value'], ['b', 'c']) self.assertEqual(item['choices'], ['b', 'c', 'd']) def test_subproject_promotion(self): testdir = os.path.join(self.unit_test_dir, '12 promote') workdir = os.path.join(self.builddir, 'work') shutil.copytree(testdir, workdir) spdir = os.path.join(workdir, 'subprojects') s3dir = os.path.join(spdir, 's3') scommondir = os.path.join(spdir, 'scommon') self.assertFalse(os.path.isdir(s3dir)) subprocess.check_call(self.wrap_command + ['promote', 's3'], cwd=workdir, stdout=subprocess.DEVNULL) self.assertTrue(os.path.isdir(s3dir)) self.assertFalse(os.path.isdir(scommondir)) self.assertNotEqual(subprocess.call(self.wrap_command + ['promote', 'scommon'], cwd=workdir, stderr=subprocess.DEVNULL), 0) self.assertNotEqual(subprocess.call(self.wrap_command + ['promote', 'invalid/path/to/scommon'], cwd=workdir, stderr=subprocess.DEVNULL), 0) self.assertFalse(os.path.isdir(scommondir)) subprocess.check_call(self.wrap_command + ['promote', 'subprojects/s2/subprojects/scommon'], cwd=workdir) self.assertTrue(os.path.isdir(scommondir)) promoted_wrap = os.path.join(spdir, 'athing.wrap') self.assertFalse(os.path.isfile(promoted_wrap)) subprocess.check_call(self.wrap_command + ['promote', 'athing'], cwd=workdir) self.assertTrue(os.path.isfile(promoted_wrap)) self.init(workdir) self.build() def test_subproject_promotion_wrap(self): testdir = os.path.join(self.unit_test_dir, '44 promote wrap') workdir = os.path.join(self.builddir, 'work') shutil.copytree(testdir, workdir) spdir = os.path.join(workdir, 'subprojects') ambiguous_wrap = os.path.join(spdir, 'ambiguous.wrap') self.assertNotEqual(subprocess.call(self.wrap_command + ['promote', 'ambiguous'], cwd=workdir, stderr=subprocess.DEVNULL), 0) self.assertFalse(os.path.isfile(ambiguous_wrap)) subprocess.check_call(self.wrap_command + ['promote', 'subprojects/s2/subprojects/ambiguous.wrap'], cwd=workdir) self.assertTrue(os.path.isfile(ambiguous_wrap)) def test_warning_location(self): tdir = os.path.join(self.unit_test_dir, '22 warning location') out = self.init(tdir) for expected in [ r'meson.build:4: WARNING: Keyword argument "link_with" defined multiple times.', r'sub' + os.path.sep + r'meson.build:3: WARNING: Keyword argument "link_with" defined multiple times.', r'meson.build:6: WARNING: a warning of some sort', r'sub' + os.path.sep + r'meson.build:4: WARNING: subdir warning', r'meson.build:7: WARNING: Module unstable-simd has no backwards or forwards compatibility and might not exist in future releases.', r"meson.build:11: WARNING: The variable(s) 'MISSING' in the input file 'conf.in' are not present in the given configuration data.", r'meson.build:1: WARNING: Passed invalid keyword argument "invalid".', ]: self.assertRegex(out, re.escape(expected)) for wd in [ self.src_root, self.builddir, os.getcwd(), ]: self.new_builddir() out = self.init(tdir, workdir=wd) expected = os.path.join(relpath(tdir, self.src_root), 'meson.build') relwd = relpath(self.src_root, wd) if relwd != '.': expected = os.path.join(relwd, expected) expected = '\n' + expected + ':' self.assertIn(expected, out) def test_error_location_path(self): '''Test locations in meson errors contain correct paths''' # this list contains errors from all the different steps in the # lexer/parser/interpreter we have tests for. for (t, f) in [ ('10 out of bounds', 'meson.build'), ('18 wrong plusassign', 'meson.build'), ('61 bad option argument', 'meson_options.txt'), ('102 subdir parse error', os.path.join('subdir', 'meson.build')), ('103 invalid option file', 'meson_options.txt'), ]: tdir = os.path.join(self.src_root, 'test cases', 'failing', t) for wd in [ self.src_root, self.builddir, os.getcwd(), ]: try: self.init(tdir, workdir=wd) except subprocess.CalledProcessError as e: expected = os.path.join('test cases', 'failing', t, f) relwd = relpath(self.src_root, wd) if relwd != '.': expected = os.path.join(relwd, expected) expected = '\n' + expected + ':' self.assertIn(expected, e.output) else: self.fail('configure unexpectedly succeeded') def test_permitted_method_kwargs(self): tdir = os.path.join(self.unit_test_dir, '25 non-permitted kwargs') out = self.init(tdir) for expected in [ r'WARNING: Passed invalid keyword argument "prefixxx".', r'WARNING: Passed invalid keyword argument "argsxx".', r'WARNING: Passed invalid keyword argument "invalidxx".', ]: self.assertRegex(out, re.escape(expected)) def test_templates(self): ninja = detect_ninja() if ninja is None: raise unittest.SkipTest('This test currently requires ninja. Fix this once "meson build" works.') langs = ['c'] env = get_fake_env() for l in ['cpp', 'cs', 'd', 'java', 'cuda', 'fortran', 'objc', 'objcpp', 'rust']: try: comp = env.detect_compiler_for(l, MachineChoice.HOST) with tempfile.TemporaryDirectory() as d: comp.sanity_check(d, env) langs.append(l) except EnvironmentException: pass for lang in langs: for target_type in ('executable', 'library'): # test empty directory with tempfile.TemporaryDirectory() as tmpdir: self._run(self.meson_command + ['init', '--language', lang, '--type', target_type], workdir=tmpdir) self._run(self.setup_command + ['--backend=ninja', 'builddir'], workdir=tmpdir) self._run(ninja, workdir=os.path.join(tmpdir, 'builddir')) # test directory with existing code file if lang in {'c', 'cpp', 'd'}: with tempfile.TemporaryDirectory() as tmpdir: with open(os.path.join(tmpdir, 'foo.' + lang), 'w') as f: f.write('int main(void) {}') self._run(self.meson_command + ['init', '-b'], workdir=tmpdir) elif lang in {'java'}: with tempfile.TemporaryDirectory() as tmpdir: with open(os.path.join(tmpdir, 'Foo.' + lang), 'w') as f: f.write('public class Foo { public static void main() {} }') self._run(self.meson_command + ['init', '-b'], workdir=tmpdir) def test_compiler_run_command(self): ''' The test checks that the compiler object can be passed to run_command(). ''' testdir = os.path.join(self.unit_test_dir, '24 compiler run_command') self.init(testdir) def test_identical_target_name_in_subproject_flat_layout(self): ''' Test that identical targets in different subprojects do not collide if layout is flat. ''' testdir = os.path.join(self.common_test_dir, '173 identical target name in subproject flat layout') self.init(testdir, extra_args=['--layout=flat']) self.build() def test_identical_target_name_in_subdir_flat_layout(self): ''' Test that identical targets in different subdirs do not collide if layout is flat. ''' testdir = os.path.join(self.common_test_dir, '182 same target name flat layout') self.init(testdir, extra_args=['--layout=flat']) self.build() def test_flock(self): exception_raised = False with tempfile.TemporaryDirectory() as tdir: os.mkdir(os.path.join(tdir, 'meson-private')) with BuildDirLock(tdir): try: with BuildDirLock(tdir): pass except MesonException: exception_raised = True self.assertTrue(exception_raised, 'Double locking did not raise exception.') @unittest.skipIf(is_osx(), 'Test not applicable to OSX') def test_check_module_linking(self): """ Test that link_with: a shared module issues a warning https://github.com/mesonbuild/meson/issues/2865 (That an error is raised on OSX is exercised by test failing/78) """ tdir = os.path.join(self.unit_test_dir, '30 shared_mod linking') out = self.init(tdir) msg = ('WARNING: target links against shared modules. This is not ' 'recommended as it is not supported on some platforms') self.assertIn(msg, out) def test_ndebug_if_release_disabled(self): testdir = os.path.join(self.unit_test_dir, '28 ndebug if-release') self.init(testdir, extra_args=['--buildtype=release', '-Db_ndebug=if-release']) self.build() exe = os.path.join(self.builddir, 'main') self.assertEqual(b'NDEBUG=1', subprocess.check_output(exe).strip()) def test_ndebug_if_release_enabled(self): testdir = os.path.join(self.unit_test_dir, '28 ndebug if-release') self.init(testdir, extra_args=['--buildtype=debugoptimized', '-Db_ndebug=if-release']) self.build() exe = os.path.join(self.builddir, 'main') self.assertEqual(b'NDEBUG=0', subprocess.check_output(exe).strip()) def test_guessed_linker_dependencies(self): ''' Test that meson adds dependencies for libraries based on the final linker command line. ''' testdirbase = os.path.join(self.unit_test_dir, '29 guessed linker dependencies') testdirlib = os.path.join(testdirbase, 'lib') extra_args = None libdir_flags = ['-L'] env = get_fake_env(testdirlib, self.builddir, self.prefix) if env.detect_c_compiler(MachineChoice.HOST).get_id() in {'msvc', 'clang-cl', 'intel-cl'}: # msvc-like compiler, also test it with msvc-specific flags libdir_flags += ['/LIBPATH:', '-LIBPATH:'] else: # static libraries are not linkable with -l with msvc because meson installs them # as .a files which unix_args_to_native will not know as it expects libraries to use # .lib as extension. For a DLL the import library is installed as .lib. Thus for msvc # this tests needs to use shared libraries to test the path resolving logic in the # dependency generation code path. extra_args = ['--default-library', 'static'] initial_builddir = self.builddir initial_installdir = self.installdir for libdir_flag in libdir_flags: # build library self.new_builddir() self.init(testdirlib, extra_args=extra_args) self.build() self.install() libbuilddir = self.builddir installdir = self.installdir libdir = os.path.join(self.installdir, self.prefix.lstrip('/').lstrip('\\'), 'lib') # build user of library self.new_builddir() # replace is needed because meson mangles platform paths passed via LDFLAGS self.init(os.path.join(testdirbase, 'exe'), override_envvars={"LDFLAGS": '{}{}'.format(libdir_flag, libdir.replace('\\', '/'))}) self.build() self.assertBuildIsNoop() # rebuild library exebuilddir = self.builddir self.installdir = installdir self.builddir = libbuilddir # Microsoft's compiler is quite smart about touching import libs on changes, # so ensure that there is actually a change in symbols. self.setconf('-Dmore_exports=true') self.build() self.install() # no ensure_backend_detects_changes needed because self.setconf did that already # assert user of library will be rebuild self.builddir = exebuilddir self.assertRebuiltTarget('app') # restore dirs for the next test case self.installdir = initial_builddir self.builddir = initial_installdir def test_conflicting_d_dash_option(self): testdir = os.path.join(self.unit_test_dir, '37 mixed command line args') with self.assertRaises((subprocess.CalledProcessError, RuntimeError)) as e: self.init(testdir, extra_args=['-Dbindir=foo', '--bindir=bar']) # Just to ensure that we caught the correct error self.assertIn('as both', e.stderr) def _test_same_option_twice(self, arg, args): testdir = os.path.join(self.unit_test_dir, '37 mixed command line args') self.init(testdir, extra_args=args) opts = self.introspect('--buildoptions') for item in opts: if item['name'] == arg: self.assertEqual(item['value'], 'bar') return raise Exception('Missing {} value?'.format(arg)) def test_same_dash_option_twice(self): self._test_same_option_twice('bindir', ['--bindir=foo', '--bindir=bar']) def test_same_d_option_twice(self): self._test_same_option_twice('bindir', ['-Dbindir=foo', '-Dbindir=bar']) def test_same_project_d_option_twice(self): self._test_same_option_twice('one', ['-Done=foo', '-Done=bar']) def _test_same_option_twice_configure(self, arg, args): testdir = os.path.join(self.unit_test_dir, '37 mixed command line args') self.init(testdir) self.setconf(args) opts = self.introspect('--buildoptions') for item in opts: if item['name'] == arg: self.assertEqual(item['value'], 'bar') return raise Exception('Missing {} value?'.format(arg)) def test_same_dash_option_twice_configure(self): self._test_same_option_twice_configure( 'bindir', ['--bindir=foo', '--bindir=bar']) def test_same_d_option_twice_configure(self): self._test_same_option_twice_configure( 'bindir', ['-Dbindir=foo', '-Dbindir=bar']) def test_same_project_d_option_twice_configure(self): self._test_same_option_twice_configure( 'one', ['-Done=foo', '-Done=bar']) def test_command_line(self): testdir = os.path.join(self.unit_test_dir, '34 command line') # Verify default values when passing no args that affect the # configuration, and as a bonus, test that --profile-self works. self.init(testdir, extra_args=['--profile-self', '--fatal-meson-warnings']) obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('default_library')].value, 'static') self.assertEqual(obj.options[OptionKey('warning_level')].value, '1') self.assertEqual(obj.options[OptionKey('set_sub_opt')].value, True) self.assertEqual(obj.options[OptionKey('subp_opt', 'subp')].value, 'default3') self.wipe() # warning_level is special, it's --warnlevel instead of --warning-level # for historical reasons self.init(testdir, extra_args=['--warnlevel=2', '--fatal-meson-warnings']) obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('warning_level')].value, '2') self.setconf('--warnlevel=3') obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('warning_level')].value, '3') self.wipe() # But when using -D syntax, it should be 'warning_level' self.init(testdir, extra_args=['-Dwarning_level=2', '--fatal-meson-warnings']) obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('warning_level')].value, '2') self.setconf('-Dwarning_level=3') obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('warning_level')].value, '3') self.wipe() # Mixing --option and -Doption is forbidden with self.assertRaises((subprocess.CalledProcessError, RuntimeError)) as cm: self.init(testdir, extra_args=['--warnlevel=1', '-Dwarning_level=3']) if isinstance(cm.exception, subprocess.CalledProcessError): self.assertNotEqual(0, cm.exception.returncode) self.assertIn('as both', cm.exception.output) else: self.assertIn('as both', str(cm.exception)) self.init(testdir) with self.assertRaises((subprocess.CalledProcessError, RuntimeError)) as cm: self.setconf(['--warnlevel=1', '-Dwarning_level=3']) if isinstance(cm.exception, subprocess.CalledProcessError): self.assertNotEqual(0, cm.exception.returncode) self.assertIn('as both', cm.exception.output) else: self.assertIn('as both', str(cm.exception)) self.wipe() # --default-library should override default value from project() self.init(testdir, extra_args=['--default-library=both', '--fatal-meson-warnings']) obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('default_library')].value, 'both') self.setconf('--default-library=shared') obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('default_library')].value, 'shared') if self.backend is Backend.ninja: # reconfigure target works only with ninja backend self.build('reconfigure') obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('default_library')].value, 'shared') self.wipe() # Should warn on unknown options out = self.init(testdir, extra_args=['-Dbad=1', '-Dfoo=2', '-Dwrong_link_args=foo']) self.assertIn('Unknown options: "bad, foo, wrong_link_args"', out) self.wipe() # Should fail on malformed option msg = "Option 'foo' must have a value separated by equals sign." with self.assertRaises((subprocess.CalledProcessError, RuntimeError)) as cm: self.init(testdir, extra_args=['-Dfoo']) if isinstance(cm.exception, subprocess.CalledProcessError): self.assertNotEqual(0, cm.exception.returncode) self.assertIn(msg, cm.exception.output) else: self.assertIn(msg, str(cm.exception)) self.init(testdir) with self.assertRaises((subprocess.CalledProcessError, RuntimeError)) as cm: self.setconf('-Dfoo') if isinstance(cm.exception, subprocess.CalledProcessError): self.assertNotEqual(0, cm.exception.returncode) self.assertIn(msg, cm.exception.output) else: self.assertIn(msg, str(cm.exception)) self.wipe() # It is not an error to set wrong option for unknown subprojects or # language because we don't have control on which one will be selected. self.init(testdir, extra_args=['-Dc_wrong=1', '-Dwrong:bad=1', '-Db_wrong=1']) self.wipe() # Test we can set subproject option self.init(testdir, extra_args=['-Dsubp:subp_opt=foo', '--fatal-meson-warnings']) obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('subp_opt', 'subp')].value, 'foo') self.wipe() # c_args value should be parsed with split_args self.init(testdir, extra_args=['-Dc_args=-Dfoo -Dbar "-Dthird=one two"', '--fatal-meson-warnings']) obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('args', lang='c')].value, ['-Dfoo', '-Dbar', '-Dthird=one two']) self.setconf('-Dc_args="foo bar" one two') obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('args', lang='c')].value, ['foo bar', 'one', 'two']) self.wipe() self.init(testdir, extra_args=['-Dset_percent_opt=myoption%', '--fatal-meson-warnings']) obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('set_percent_opt')].value, 'myoption%') self.wipe() # Setting a 2nd time the same option should override the first value try: self.init(testdir, extra_args=['--bindir=foo', '--bindir=bar', '-Dbuildtype=plain', '-Dbuildtype=release', '-Db_sanitize=address', '-Db_sanitize=thread', '-Dc_args=-Dfoo', '-Dc_args=-Dbar', '-Db_lundef=false', '--fatal-meson-warnings']) obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('bindir')].value, 'bar') self.assertEqual(obj.options[OptionKey('buildtype')].value, 'release') self.assertEqual(obj.options[OptionKey('b_sanitize')].value, 'thread') self.assertEqual(obj.options[OptionKey('args', lang='c')].value, ['-Dbar']) self.setconf(['--bindir=bar', '--bindir=foo', '-Dbuildtype=release', '-Dbuildtype=plain', '-Db_sanitize=thread', '-Db_sanitize=address', '-Dc_args=-Dbar', '-Dc_args=-Dfoo']) obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('bindir')].value, 'foo') self.assertEqual(obj.options[OptionKey('buildtype')].value, 'plain') self.assertEqual(obj.options[OptionKey('b_sanitize')].value, 'address') self.assertEqual(obj.options[OptionKey('args', lang='c')].value, ['-Dfoo']) self.wipe() except KeyError: # Ignore KeyError, it happens on CI for compilers that does not # support b_sanitize. We have to test with a base option because # they used to fail this test with Meson 0.46 an earlier versions. pass def test_warning_level_0(self): testdir = os.path.join(self.common_test_dir, '208 warning level 0') # Verify default values when passing no args self.init(testdir) obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('warning_level')].value, '0') self.wipe() # verify we can override w/ --warnlevel self.init(testdir, extra_args=['--warnlevel=1']) obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('warning_level')].value, '1') self.setconf('--warnlevel=0') obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('warning_level')].value, '0') self.wipe() # verify we can override w/ -Dwarning_level self.init(testdir, extra_args=['-Dwarning_level=1']) obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('warning_level')].value, '1') self.setconf('-Dwarning_level=0') obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('warning_level')].value, '0') self.wipe() def test_feature_check_usage_subprojects(self): testdir = os.path.join(self.unit_test_dir, '41 featurenew subprojects') out = self.init(testdir) # Parent project warns correctly self.assertRegex(out, "WARNING: Project targeting '>=0.45'.*'0.47.0': dict") # Subprojects warn correctly self.assertRegex(out, r"\|WARNING: Project targeting '>=0.40'.*'0.44.0': disabler") self.assertRegex(out, r"\|WARNING: Project targeting '!=0.40'.*'0.44.0': disabler") # Subproject has a new-enough meson_version, no warning self.assertNotRegex(out, "WARNING: Project targeting.*Python") # Ensure a summary is printed in the subproject and the outer project self.assertRegex(out, r"\|WARNING: Project specifies a minimum meson_version '>=0.40'") self.assertRegex(out, r"\| \* 0.44.0: {'disabler'}") self.assertRegex(out, "WARNING: Project specifies a minimum meson_version '>=0.45'") self.assertRegex(out, " * 0.47.0: {'dict'}") def test_configure_file_warnings(self): testdir = os.path.join(self.common_test_dir, "14 configure file") out = self.init(testdir) self.assertRegex(out, "WARNING:.*'empty'.*config.h.in.*not present.*") self.assertRegex(out, "WARNING:.*'FOO_BAR'.*nosubst-nocopy2.txt.in.*not present.*") self.assertRegex(out, "WARNING:.*'empty'.*config.h.in.*not present.*") self.assertRegex(out, "WARNING:.*empty configuration_data.*test.py.in") # Warnings for configuration files that are overwritten. self.assertRegex(out, "WARNING:.*\"double_output.txt\".*overwrites") self.assertRegex(out, "WARNING:.*\"subdir.double_output2.txt\".*overwrites") self.assertNotRegex(out, "WARNING:.*no_write_conflict.txt.*overwrites") self.assertNotRegex(out, "WARNING:.*@BASENAME@.*overwrites") self.assertRegex(out, "WARNING:.*\"sameafterbasename\".*overwrites") # No warnings about empty configuration data objects passed to files with substitutions self.assertNotRegex(out, "WARNING:.*empty configuration_data.*nosubst-nocopy1.txt.in") self.assertNotRegex(out, "WARNING:.*empty configuration_data.*nosubst-nocopy2.txt.in") with open(os.path.join(self.builddir, 'nosubst-nocopy1.txt'), 'rb') as f: self.assertEqual(f.read().strip(), b'/* #undef FOO_BAR */') with open(os.path.join(self.builddir, 'nosubst-nocopy2.txt'), 'rb') as f: self.assertEqual(f.read().strip(), b'') self.assertRegex(out, r"DEPRECATION:.*\['array'\] is invalid.*dict") def test_dirs(self): with tempfile.TemporaryDirectory() as containing: with tempfile.TemporaryDirectory(dir=containing) as srcdir: mfile = os.path.join(srcdir, 'meson.build') of = open(mfile, 'w') of.write("project('foobar', 'c')\n") of.close() pc = subprocess.run(self.setup_command, cwd=srcdir, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) self.assertIn(b'Must specify at least one directory name', pc.stdout) with tempfile.TemporaryDirectory(dir=srcdir) as builddir: subprocess.run(self.setup_command, check=True, cwd=builddir, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) def get_opts_as_dict(self): result = {} for i in self.introspect('--buildoptions'): result[i['name']] = i['value'] return result def test_buildtype_setting(self): testdir = os.path.join(self.common_test_dir, '1 trivial') self.init(testdir) opts = self.get_opts_as_dict() self.assertEqual(opts['buildtype'], 'debug') self.assertEqual(opts['debug'], True) self.setconf('-Ddebug=false') opts = self.get_opts_as_dict() self.assertEqual(opts['debug'], False) self.assertEqual(opts['buildtype'], 'debug') self.assertEqual(opts['optimization'], '0') self.setconf('-Doptimization=g') opts = self.get_opts_as_dict() self.assertEqual(opts['debug'], False) self.assertEqual(opts['buildtype'], 'debug') self.assertEqual(opts['optimization'], 'g') @skipIfNoPkgconfig @unittest.skipIf(is_windows(), 'Help needed with fixing this test on windows') def test_native_dep_pkgconfig(self): testdir = os.path.join(self.unit_test_dir, '46 native dep pkgconfig var') with tempfile.NamedTemporaryFile(mode='w', delete=False) as crossfile: crossfile.write(textwrap.dedent( '''[binaries] pkgconfig = '{0}' [properties] [host_machine] system = 'linux' cpu_family = 'arm' cpu = 'armv7' endian = 'little' '''.format(os.path.join(testdir, 'cross_pkgconfig.py')))) crossfile.flush() self.meson_cross_file = crossfile.name env = {'PKG_CONFIG_LIBDIR': os.path.join(testdir, 'native_pkgconfig')} self.init(testdir, extra_args=['-Dstart_native=false'], override_envvars=env) self.wipe() self.init(testdir, extra_args=['-Dstart_native=true'], override_envvars=env) @skipIfNoPkgconfig @unittest.skipIf(is_windows(), 'Help needed with fixing this test on windows') def test_pkg_config_libdir(self): testdir = os.path.join(self.unit_test_dir, '46 native dep pkgconfig var') with tempfile.NamedTemporaryFile(mode='w', delete=False) as crossfile: crossfile.write(textwrap.dedent( '''[binaries] pkgconfig = 'pkg-config' [properties] pkg_config_libdir = ['{0}'] [host_machine] system = 'linux' cpu_family = 'arm' cpu = 'armv7' endian = 'little' '''.format(os.path.join(testdir, 'cross_pkgconfig')))) crossfile.flush() self.meson_cross_file = crossfile.name env = {'PKG_CONFIG_LIBDIR': os.path.join(testdir, 'native_pkgconfig')} self.init(testdir, extra_args=['-Dstart_native=false'], override_envvars=env) self.wipe() self.init(testdir, extra_args=['-Dstart_native=true'], override_envvars=env) def __reconfigure(self, change_minor=False): # Set an older version to force a reconfigure from scratch filename = os.path.join(self.privatedir, 'coredata.dat') with open(filename, 'rb') as f: obj = pickle.load(f) if change_minor: v = mesonbuild.coredata.version.split('.') obj.version = '.'.join(v[0:2] + [str(int(v[2]) + 1)]) else: obj.version = '0.47.0' with open(filename, 'wb') as f: pickle.dump(obj, f) def test_reconfigure(self): testdir = os.path.join(self.unit_test_dir, '48 reconfigure') self.init(testdir, extra_args=['-Dopt1=val1']) self.setconf('-Dopt2=val2') self.__reconfigure() out = self.init(testdir, extra_args=['--reconfigure', '-Dopt3=val3']) self.assertRegex(out, 'Regenerating configuration from scratch') self.assertRegex(out, 'opt1 val1') self.assertRegex(out, 'opt2 val2') self.assertRegex(out, 'opt3 val3') self.assertRegex(out, 'opt4 default4') self.build() self.run_tests() # Create a file in builddir and verify wipe command removes it filename = os.path.join(self.builddir, 'something') open(filename, 'w').close() self.assertTrue(os.path.exists(filename)) out = self.init(testdir, extra_args=['--wipe', '-Dopt4=val4']) self.assertFalse(os.path.exists(filename)) self.assertRegex(out, 'opt1 val1') self.assertRegex(out, 'opt2 val2') self.assertRegex(out, 'opt3 val3') self.assertRegex(out, 'opt4 val4') self.build() self.run_tests() def test_wipe_from_builddir(self): testdir = os.path.join(self.common_test_dir, '158 custom target subdir depend files') self.init(testdir) self.__reconfigure() with Path(self.builddir): self.init(testdir, extra_args=['--wipe']) def test_minor_version_does_not_reconfigure_wipe(self): testdir = os.path.join(self.unit_test_dir, '48 reconfigure') self.init(testdir, extra_args=['-Dopt1=val1']) self.setconf('-Dopt2=val2') self.__reconfigure(change_minor=True) out = self.init(testdir, extra_args=['--reconfigure', '-Dopt3=val3']) self.assertNotRegex(out, 'Regenerating configuration from scratch') self.assertRegex(out, 'opt1 val1') self.assertRegex(out, 'opt2 val2') self.assertRegex(out, 'opt3 val3') self.assertRegex(out, 'opt4 default4') self.build() self.run_tests() def test_target_construct_id_from_path(self): # This id is stable but not guessable. # The test is supposed to prevent unintentional # changes of target ID generation. target_id = Target.construct_id_from_path('some/obscure/subdir', 'target-id', '@suffix') self.assertEqual('5e002d3@@target-id@suffix', target_id) target_id = Target.construct_id_from_path('subproject/foo/subdir/bar', 'target2-id', '@other') self.assertEqual('81d46d1@@target2-id@other', target_id) def test_introspect_projectinfo_without_configured_build(self): testfile = os.path.join(self.common_test_dir, '34 run program', 'meson.build') res = self.introspect_directory(testfile, '--projectinfo') self.assertEqual(set(res['buildsystem_files']), set(['meson.build'])) self.assertEqual(res['version'], 'undefined') self.assertEqual(res['descriptive_name'], 'run command') self.assertEqual(res['subprojects'], []) testfile = os.path.join(self.common_test_dir, '41 options', 'meson.build') res = self.introspect_directory(testfile, '--projectinfo') self.assertEqual(set(res['buildsystem_files']), set(['meson_options.txt', 'meson.build'])) self.assertEqual(res['version'], 'undefined') self.assertEqual(res['descriptive_name'], 'options') self.assertEqual(res['subprojects'], []) testfile = os.path.join(self.common_test_dir, '44 subproject options', 'meson.build') res = self.introspect_directory(testfile, '--projectinfo') self.assertEqual(set(res['buildsystem_files']), set(['meson_options.txt', 'meson.build'])) self.assertEqual(res['version'], 'undefined') self.assertEqual(res['descriptive_name'], 'suboptions') self.assertEqual(len(res['subprojects']), 1) subproject_files = set(f.replace('\\', '/') for f in res['subprojects'][0]['buildsystem_files']) self.assertEqual(subproject_files, set(['subprojects/subproject/meson_options.txt', 'subprojects/subproject/meson.build'])) self.assertEqual(res['subprojects'][0]['name'], 'subproject') self.assertEqual(res['subprojects'][0]['version'], 'undefined') self.assertEqual(res['subprojects'][0]['descriptive_name'], 'subproject') def test_introspect_projectinfo_subprojects(self): testdir = os.path.join(self.common_test_dir, '99 subproject subdir') self.init(testdir) res = self.introspect('--projectinfo') expected = { 'descriptive_name': 'proj', 'version': 'undefined', 'subproject_dir': 'subprojects', 'subprojects': [ { 'descriptive_name': 'sub', 'name': 'sub', 'version': '1.0' }, { 'descriptive_name': 'sub_implicit', 'name': 'sub_implicit', 'version': '1.0', }, { 'descriptive_name': 'sub-novar', 'name': 'sub_novar', 'version': '1.0', }, { 'descriptive_name': 'subsub', 'name': 'subsub', 'version': 'undefined' }, { 'descriptive_name': 'subsubsub', 'name': 'subsubsub', 'version': 'undefined' }, ] } res['subprojects'] = sorted(res['subprojects'], key=lambda i: i['name']) self.assertDictEqual(expected, res) def test_introspection_target_subproject(self): testdir = os.path.join(self.common_test_dir, '43 subproject') self.init(testdir) res = self.introspect('--targets') expected = { 'sublib': 'sublib', 'simpletest': 'sublib', 'user': None } for entry in res: name = entry['name'] self.assertEqual(entry['subproject'], expected[name]) def test_introspect_projectinfo_subproject_dir(self): testdir = os.path.join(self.common_test_dir, '76 custom subproject dir') self.init(testdir) res = self.introspect('--projectinfo') self.assertEqual(res['subproject_dir'], 'custom_subproject_dir') def test_introspect_projectinfo_subproject_dir_from_source(self): testfile = os.path.join(self.common_test_dir, '76 custom subproject dir', 'meson.build') res = self.introspect_directory(testfile, '--projectinfo') self.assertEqual(res['subproject_dir'], 'custom_subproject_dir') @skipIfNoExecutable('clang-format') def test_clang_format(self): if self.backend is not Backend.ninja: raise unittest.SkipTest('Clang-format is for now only supported on Ninja, not {}'.format(self.backend.name)) testdir = os.path.join(self.unit_test_dir, '54 clang-format') testfile = os.path.join(testdir, 'prog.c') badfile = os.path.join(testdir, 'prog_orig_c') goodfile = os.path.join(testdir, 'prog_expected_c') testheader = os.path.join(testdir, 'header.h') badheader = os.path.join(testdir, 'header_orig_h') goodheader = os.path.join(testdir, 'header_expected_h') try: shutil.copyfile(badfile, testfile) shutil.copyfile(badheader, testheader) self.init(testdir) self.assertNotEqual(Path(testfile).read_text(), Path(goodfile).read_text()) self.assertNotEqual(Path(testheader).read_text(), Path(goodheader).read_text()) self.run_target('clang-format') self.assertEqual(Path(testheader).read_text(), Path(goodheader).read_text()) finally: if os.path.exists(testfile): os.unlink(testfile) if os.path.exists(testheader): os.unlink(testheader) @skipIfNoExecutable('clang-tidy') def test_clang_tidy(self): if self.backend is not Backend.ninja: raise unittest.SkipTest('Clang-tidy is for now only supported on Ninja, not {}'.format(self.backend.name)) if shutil.which('c++') is None: raise unittest.SkipTest('Clang-tidy breaks when ccache is used and "c++" not in path.') if is_osx(): raise unittest.SkipTest('Apple ships a broken clang-tidy that chokes on -pipe.') testdir = os.path.join(self.unit_test_dir, '70 clang-tidy') dummydir = os.path.join(testdir, 'dummydir.h') self.init(testdir, override_envvars={'CXX': 'c++'}) out = self.run_target('clang-tidy') self.assertIn('cttest.cpp:4:20', out) self.assertNotIn(dummydir, out) def test_identity_cross(self): testdir = os.path.join(self.unit_test_dir, '71 cross') # Do a build to generate a cross file where the host is this target self.init(testdir, extra_args=['-Dgenerate=true']) self.meson_cross_file = os.path.join(self.builddir, "crossfile") self.assertTrue(os.path.exists(self.meson_cross_file)) # Now verify that this is detected as cross self.new_builddir() self.init(testdir) def test_introspect_buildoptions_without_configured_build(self): testdir = os.path.join(self.unit_test_dir, '59 introspect buildoptions') testfile = os.path.join(testdir, 'meson.build') res_nb = self.introspect_directory(testfile, ['--buildoptions'] + self.meson_args) self.init(testdir, default_args=False) res_wb = self.introspect('--buildoptions') self.maxDiff = None # XXX: These now generate in a different order, is that okay? self.assertListEqual(sorted(res_nb, key=lambda x: x['name']), sorted(res_wb, key=lambda x: x['name'])) def test_meson_configure_from_source_does_not_crash(self): testdir = os.path.join(self.unit_test_dir, '59 introspect buildoptions') self._run(self.mconf_command + [testdir]) def test_introspect_buildoptions_cross_only(self): testdir = os.path.join(self.unit_test_dir, '84 cross only introspect') testfile = os.path.join(testdir, 'meson.build') res = self.introspect_directory(testfile, ['--buildoptions'] + self.meson_args) optnames = [o['name'] for o in res] self.assertIn('c_args', optnames) self.assertNotIn('build.c_args', optnames) def test_introspect_json_dump(self): testdir = os.path.join(self.unit_test_dir, '57 introspection') self.init(testdir) infodir = os.path.join(self.builddir, 'meson-info') self.assertPathExists(infodir) def assertKeyTypes(key_type_list, obj, strict: bool = True): for i in key_type_list: if isinstance(i[1], (list, tuple)) and None in i[1]: i = (i[0], tuple([x for x in i[1] if x is not None])) if i[0] not in obj or obj[i[0]] is None: continue self.assertIn(i[0], obj) self.assertIsInstance(obj[i[0]], i[1]) if strict: for k in obj.keys(): found = False for i in key_type_list: if k == i[0]: found = True break self.assertTrue(found, 'Key "{}" not in expected list'.format(k)) root_keylist = [ ('benchmarks', list), ('buildoptions', list), ('buildsystem_files', list), ('dependencies', list), ('installed', dict), ('projectinfo', dict), ('targets', list), ('tests', list), ] test_keylist = [ ('cmd', list), ('env', dict), ('name', str), ('timeout', int), ('suite', list), ('is_parallel', bool), ('protocol', str), ('depends', list), ('workdir', (str, None)), ('priority', int), ] buildoptions_keylist = [ ('name', str), ('section', str), ('type', str), ('description', str), ('machine', str), ('choices', (list, None)), ('value', (str, int, bool, list)), ] buildoptions_typelist = [ ('combo', str, [('choices', list)]), ('string', str, []), ('boolean', bool, []), ('integer', int, []), ('array', list, []), ] buildoptions_sections = ['core', 'backend', 'base', 'compiler', 'directory', 'user', 'test'] buildoptions_machines = ['any', 'build', 'host'] dependencies_typelist = [ ('name', str), ('version', str), ('compile_args', list), ('link_args', list), ] targets_typelist = [ ('name', str), ('id', str), ('type', str), ('defined_in', str), ('filename', list), ('build_by_default', bool), ('target_sources', list), ('extra_files', list), ('subproject', (str, None)), ('install_filename', (list, None)), ('installed', bool), ] targets_sources_typelist = [ ('language', str), ('compiler', list), ('parameters', list), ('sources', list), ('generated_sources', list), ] # First load all files res = {} for i in root_keylist: curr = os.path.join(infodir, 'intro-{}.json'.format(i[0])) self.assertPathExists(curr) with open(curr, 'r') as fp: res[i[0]] = json.load(fp) assertKeyTypes(root_keylist, res) # Match target ids to input and output files for ease of reference src_to_id = {} out_to_id = {} for i in res['targets']: print(json.dump(i, sys.stdout)) out_to_id.update({os.path.relpath(out, self.builddir): i['id'] for out in i['filename']}) for group in i['target_sources']: src_to_id.update({os.path.relpath(src, testdir): i['id'] for src in group['sources']}) # Check Tests and benchmarks tests_to_find = ['test case 1', 'test case 2', 'benchmark 1'] deps_to_find = {'test case 1': [src_to_id['t1.cpp']], 'test case 2': [src_to_id['t2.cpp'], src_to_id['t3.cpp']], 'benchmark 1': [out_to_id['file2'], src_to_id['t3.cpp']]} for i in res['benchmarks'] + res['tests']: assertKeyTypes(test_keylist, i) if i['name'] in tests_to_find: tests_to_find.remove(i['name']) self.assertEqual(sorted(i['depends']), sorted(deps_to_find[i['name']])) self.assertListEqual(tests_to_find, []) # Check buildoptions buildopts_to_find = {'cpp_std': 'c++11'} for i in res['buildoptions']: assertKeyTypes(buildoptions_keylist, i) valid_type = False for j in buildoptions_typelist: if i['type'] == j[0]: self.assertIsInstance(i['value'], j[1]) assertKeyTypes(j[2], i, strict=False) valid_type = True break self.assertIn(i['section'], buildoptions_sections) self.assertIn(i['machine'], buildoptions_machines) self.assertTrue(valid_type) if i['name'] in buildopts_to_find: self.assertEqual(i['value'], buildopts_to_find[i['name']]) buildopts_to_find.pop(i['name'], None) self.assertDictEqual(buildopts_to_find, {}) # Check buildsystem_files bs_files = ['meson.build', 'meson_options.txt', 'sharedlib/meson.build', 'staticlib/meson.build'] bs_files = [os.path.join(testdir, x) for x in bs_files] self.assertPathListEqual(list(sorted(res['buildsystem_files'])), list(sorted(bs_files))) # Check dependencies dependencies_to_find = ['threads'] for i in res['dependencies']: assertKeyTypes(dependencies_typelist, i) if i['name'] in dependencies_to_find: dependencies_to_find.remove(i['name']) self.assertListEqual(dependencies_to_find, []) # Check projectinfo self.assertDictEqual(res['projectinfo'], {'version': '1.2.3', 'descriptive_name': 'introspection', 'subproject_dir': 'subprojects', 'subprojects': []}) # Check targets targets_to_find = { 'sharedTestLib': ('shared library', True, False, 'sharedlib/meson.build'), 'staticTestLib': ('static library', True, False, 'staticlib/meson.build'), 'test1': ('executable', True, True, 'meson.build'), 'test2': ('executable', True, False, 'meson.build'), 'test3': ('executable', True, False, 'meson.build'), } for i in res['targets']: assertKeyTypes(targets_typelist, i) if i['name'] in targets_to_find: tgt = targets_to_find[i['name']] self.assertEqual(i['type'], tgt[0]) self.assertEqual(i['build_by_default'], tgt[1]) self.assertEqual(i['installed'], tgt[2]) self.assertPathEqual(i['defined_in'], os.path.join(testdir, tgt[3])) targets_to_find.pop(i['name'], None) for j in i['target_sources']: assertKeyTypes(targets_sources_typelist, j) self.assertDictEqual(targets_to_find, {}) def test_introspect_file_dump_equals_all(self): testdir = os.path.join(self.unit_test_dir, '57 introspection') self.init(testdir) res_all = self.introspect('--all') res_file = {} root_keylist = [ 'benchmarks', 'buildoptions', 'buildsystem_files', 'dependencies', 'installed', 'projectinfo', 'targets', 'tests', ] infodir = os.path.join(self.builddir, 'meson-info') self.assertPathExists(infodir) for i in root_keylist: curr = os.path.join(infodir, 'intro-{}.json'.format(i)) self.assertPathExists(curr) with open(curr, 'r') as fp: res_file[i] = json.load(fp) self.assertEqual(res_all, res_file) def test_introspect_meson_info(self): testdir = os.path.join(self.unit_test_dir, '57 introspection') introfile = os.path.join(self.builddir, 'meson-info', 'meson-info.json') self.init(testdir) self.assertPathExists(introfile) with open(introfile, 'r') as fp: res1 = json.load(fp) for i in ['meson_version', 'directories', 'introspection', 'build_files_updated', 'error']: self.assertIn(i, res1) self.assertEqual(res1['error'], False) self.assertEqual(res1['build_files_updated'], True) def test_introspect_config_update(self): testdir = os.path.join(self.unit_test_dir, '57 introspection') introfile = os.path.join(self.builddir, 'meson-info', 'intro-buildoptions.json') self.init(testdir) self.assertPathExists(introfile) with open(introfile, 'r') as fp: res1 = json.load(fp) for i in res1: if i['name'] == 'cpp_std': i['value'] = 'c++14' if i['name'] == 'build.cpp_std': i['value'] = 'c++14' if i['name'] == 'buildtype': i['value'] = 'release' if i['name'] == 'optimization': i['value'] = '3' if i['name'] == 'debug': i['value'] = False self.setconf('-Dcpp_std=c++14') self.setconf('-Dbuildtype=release') with open(introfile, 'r') as fp: res2 = json.load(fp) self.assertListEqual(res1, res2) def test_introspect_targets_from_source(self): testdir = os.path.join(self.unit_test_dir, '57 introspection') testfile = os.path.join(testdir, 'meson.build') introfile = os.path.join(self.builddir, 'meson-info', 'intro-targets.json') self.init(testdir) self.assertPathExists(introfile) with open(introfile, 'r') as fp: res_wb = json.load(fp) res_nb = self.introspect_directory(testfile, ['--targets'] + self.meson_args) # Account for differences in output res_wb = [i for i in res_wb if i['type'] != 'custom'] for i in res_wb: i['filename'] = [os.path.relpath(x, self.builddir) for x in i['filename']] if 'install_filename' in i: del i['install_filename'] sources = [] for j in i['target_sources']: sources += j['sources'] i['target_sources'] = [{ 'language': 'unknown', 'compiler': [], 'parameters': [], 'sources': sources, 'generated_sources': [] }] self.maxDiff = None self.assertListEqual(res_nb, res_wb) def test_introspect_ast_source(self): testdir = os.path.join(self.unit_test_dir, '57 introspection') testfile = os.path.join(testdir, 'meson.build') res_nb = self.introspect_directory(testfile, ['--ast'] + self.meson_args) node_counter = {} def accept_node(json_node): self.assertIsInstance(json_node, dict) for i in ['lineno', 'colno', 'end_lineno', 'end_colno']: self.assertIn(i, json_node) self.assertIsInstance(json_node[i], int) self.assertIn('node', json_node) n = json_node['node'] self.assertIsInstance(n, str) self.assertIn(n, nodes) if n not in node_counter: node_counter[n] = 0 node_counter[n] = node_counter[n] + 1 for nodeDesc in nodes[n]: key = nodeDesc[0] func = nodeDesc[1] self.assertIn(key, json_node) if func is None: tp = nodeDesc[2] self.assertIsInstance(json_node[key], tp) continue func(json_node[key]) def accept_node_list(node_list): self.assertIsInstance(node_list, list) for i in node_list: accept_node(i) def accept_kwargs(kwargs): self.assertIsInstance(kwargs, list) for i in kwargs: self.assertIn('key', i) self.assertIn('val', i) accept_node(i['key']) accept_node(i['val']) nodes = { 'BooleanNode': [('value', None, bool)], 'IdNode': [('value', None, str)], 'NumberNode': [('value', None, int)], 'StringNode': [('value', None, str)], 'ContinueNode': [], 'BreakNode': [], 'ArgumentNode': [('positional', accept_node_list), ('kwargs', accept_kwargs)], 'ArrayNode': [('args', accept_node)], 'DictNode': [('args', accept_node)], 'EmptyNode': [], 'OrNode': [('left', accept_node), ('right', accept_node)], 'AndNode': [('left', accept_node), ('right', accept_node)], 'ComparisonNode': [('left', accept_node), ('right', accept_node), ('ctype', None, str)], 'ArithmeticNode': [('left', accept_node), ('right', accept_node), ('op', None, str)], 'NotNode': [('right', accept_node)], 'CodeBlockNode': [('lines', accept_node_list)], 'IndexNode': [('object', accept_node), ('index', accept_node)], 'MethodNode': [('object', accept_node), ('args', accept_node), ('name', None, str)], 'FunctionNode': [('args', accept_node), ('name', None, str)], 'AssignmentNode': [('value', accept_node), ('var_name', None, str)], 'PlusAssignmentNode': [('value', accept_node), ('var_name', None, str)], 'ForeachClauseNode': [('items', accept_node), ('block', accept_node), ('varnames', None, list)], 'IfClauseNode': [('ifs', accept_node_list), ('else', accept_node)], 'IfNode': [('condition', accept_node), ('block', accept_node)], 'UMinusNode': [('right', accept_node)], 'TernaryNode': [('condition', accept_node), ('true', accept_node), ('false', accept_node)], } accept_node(res_nb) for n, c in [('ContinueNode', 2), ('BreakNode', 1), ('NotNode', 3)]: self.assertIn(n, node_counter) self.assertEqual(node_counter[n], c) def test_introspect_dependencies_from_source(self): testdir = os.path.join(self.unit_test_dir, '57 introspection') testfile = os.path.join(testdir, 'meson.build') res_nb = self.introspect_directory(testfile, ['--scan-dependencies'] + self.meson_args) expected = [ { 'name': 'threads', 'required': True, 'version': [], 'has_fallback': False, 'conditional': False }, { 'name': 'zlib', 'required': False, 'version': [], 'has_fallback': False, 'conditional': False }, { 'name': 'bugDep1', 'required': True, 'version': [], 'has_fallback': False, 'conditional': False }, { 'name': 'somethingthatdoesnotexist', 'required': True, 'version': ['>=1.2.3'], 'has_fallback': False, 'conditional': True }, { 'name': 'look_i_have_a_fallback', 'required': True, 'version': ['>=1.0.0', '<=99.9.9'], 'has_fallback': True, 'conditional': True } ] self.maxDiff = None self.assertListEqual(res_nb, expected) def test_unstable_coredata(self): testdir = os.path.join(self.common_test_dir, '1 trivial') self.init(testdir) # just test that the command does not fail (e.g. because it throws an exception) self._run([*self.meson_command, 'unstable-coredata', self.builddir]) @skip_if_no_cmake def test_cmake_prefix_path(self): testdir = os.path.join(self.unit_test_dir, '64 cmake_prefix_path') self.init(testdir, extra_args=['-Dcmake_prefix_path=' + os.path.join(testdir, 'prefix')]) @skip_if_no_cmake def test_cmake_parser(self): testdir = os.path.join(self.unit_test_dir, '65 cmake parser') self.init(testdir, extra_args=['-Dcmake_prefix_path=' + os.path.join(testdir, 'prefix')]) def test_alias_target(self): if self.backend is Backend.vs: # FIXME: This unit test is broken with vs backend, needs investigation raise unittest.SkipTest('Skipping alias_target test with {} backend'.format(self.backend.name)) testdir = os.path.join(self.unit_test_dir, '66 alias target') self.init(testdir) self.build() self.assertPathDoesNotExist(os.path.join(self.builddir, 'prog' + exe_suffix)) self.assertPathDoesNotExist(os.path.join(self.builddir, 'hello.txt')) self.run_target('build-all') self.assertPathExists(os.path.join(self.builddir, 'prog' + exe_suffix)) self.assertPathExists(os.path.join(self.builddir, 'hello.txt')) def test_configure(self): testdir = os.path.join(self.common_test_dir, '2 cpp') self.init(testdir) self._run(self.mconf_command + [self.builddir]) def test_summary(self): testdir = os.path.join(self.unit_test_dir, '73 summary') out = self.init(testdir) expected = textwrap.dedent(r''' Some Subproject 2.0 string : bar integer: 1 boolean: True My Project 1.0 Configuration Some boolean : False Another boolean: True Some string : Hello World A list : string 1 True empty list : enabled_opt : enabled A number : 1 yes : YES no : NO coma list : a, b, c Stuff missing prog : NO existing prog : ''' + sys.executable + ''' missing dep : NO internal dep : YES Plugins long coma list : alpha, alphacolor, apetag, audiofx, audioparsers, auparse, autodetect, avi Subprojects sub : YES sub2 : NO Problem encountered: This subproject failed ''') expected_lines = expected.split('\n')[1:] out_start = out.find(expected_lines[0]) out_lines = out[out_start:].split('\n')[:len(expected_lines)] if sys.version_info < (3, 7, 0): # Dictionary order is not stable in Python <3.7, so sort the lines # while comparing self.assertEqual(sorted(expected_lines), sorted(out_lines)) else: self.assertEqual(expected_lines, out_lines) def test_meson_compile(self): """Test the meson compile command.""" def get_exe_name(basename: str) -> str: if is_windows(): return '{}.exe'.format(basename) else: return basename def get_shared_lib_name(basename: str) -> str: if mesonbuild.environment.detect_msys2_arch(): return 'lib{}.dll'.format(basename) elif is_windows(): return '{}.dll'.format(basename) elif is_cygwin(): return 'cyg{}.dll'.format(basename) elif is_osx(): return 'lib{}.dylib'.format(basename) else: return 'lib{}.so'.format(basename) def get_static_lib_name(basename: str) -> str: return 'lib{}.a'.format(basename) # Base case (no targets or additional arguments) testdir = os.path.join(self.common_test_dir, '1 trivial') self.init(testdir) self._run([*self.meson_command, 'compile', '-C', self.builddir]) self.assertPathExists(os.path.join(self.builddir, get_exe_name('trivialprog'))) # `--clean` self._run([*self.meson_command, 'compile', '-C', self.builddir, '--clean']) self.assertPathDoesNotExist(os.path.join(self.builddir, get_exe_name('trivialprog'))) # Target specified in a project with unique names testdir = os.path.join(self.common_test_dir, '6 linkshared') self.init(testdir, extra_args=['--wipe']) # Multiple targets and target type specified self._run([*self.meson_command, 'compile', '-C', self.builddir, 'mylib', 'mycpplib:shared_library']) # Check that we have a shared lib, but not an executable, i.e. check that target actually worked self.assertPathExists(os.path.join(self.builddir, get_shared_lib_name('mylib'))) self.assertPathDoesNotExist(os.path.join(self.builddir, get_exe_name('prog'))) self.assertPathExists(os.path.join(self.builddir, get_shared_lib_name('mycpplib'))) self.assertPathDoesNotExist(os.path.join(self.builddir, get_exe_name('cppprog'))) # Target specified in a project with non unique names testdir = os.path.join(self.common_test_dir, '186 same target name') self.init(testdir, extra_args=['--wipe']) self._run([*self.meson_command, 'compile', '-C', self.builddir, './foo']) self.assertPathExists(os.path.join(self.builddir, get_static_lib_name('foo'))) self._run([*self.meson_command, 'compile', '-C', self.builddir, 'sub/foo']) self.assertPathExists(os.path.join(self.builddir, 'sub', get_static_lib_name('foo'))) # run_target testdir = os.path.join(self.common_test_dir, '52 run target') self.init(testdir, extra_args=['--wipe']) out = self._run([*self.meson_command, 'compile', '-C', self.builddir, 'py3hi']) self.assertIn('I am Python3.', out) # `--$BACKEND-args` testdir = os.path.join(self.common_test_dir, '1 trivial') if self.backend is Backend.ninja: self.init(testdir, extra_args=['--wipe']) # Dry run - should not create a program self._run([*self.meson_command, 'compile', '-C', self.builddir, '--ninja-args=-n']) self.assertPathDoesNotExist(os.path.join(self.builddir, get_exe_name('trivialprog'))) elif self.backend is Backend.vs: self.init(testdir, extra_args=['--wipe']) self._run([*self.meson_command, 'compile', '-C', self.builddir]) # Explicitly clean the target through msbuild interface self._run([*self.meson_command, 'compile', '-C', self.builddir, '--vs-args=-t:{}:Clean'.format(re.sub(r'[\%\$\@\;\.\(\)\']', '_', get_exe_name('trivialprog')))]) self.assertPathDoesNotExist(os.path.join(self.builddir, get_exe_name('trivialprog'))) def test_spurious_reconfigure_built_dep_file(self): testdir = os.path.join(self.unit_test_dir, '75 dep files') # Regression test: Spurious reconfigure was happening when build # directory is inside source directory. # See https://gitlab.freedesktop.org/gstreamer/gst-build/-/issues/85. srcdir = os.path.join(self.builddir, 'srctree') shutil.copytree(testdir, srcdir) builddir = os.path.join(srcdir, '_build') self.change_builddir(builddir) self.init(srcdir) self.build() # During first configure the file did not exist so no dependency should # have been set. A rebuild should not trigger a reconfigure. self.clean() out = self.build() self.assertNotIn('Project configured', out) self.init(srcdir, extra_args=['--reconfigure']) # During the reconfigure the file did exist, but is inside build # directory, so no dependency should have been set. A rebuild should not # trigger a reconfigure. self.clean() out = self.build() self.assertNotIn('Project configured', out) def _test_junit(self, case: str) -> None: try: import lxml.etree as et except ImportError: raise unittest.SkipTest('lxml required, but not found.') schema = et.XMLSchema(et.parse(str(Path(__file__).parent / 'data' / 'schema.xsd'))) self.init(case) self.run_tests() junit = et.parse(str(Path(self.builddir) / 'meson-logs' / 'testlog.junit.xml')) try: schema.assertValid(junit) except et.DocumentInvalid as e: self.fail(e.error_log) def test_junit_valid_tap(self): self._test_junit(os.path.join(self.common_test_dir, '207 tap tests')) def test_junit_valid_exitcode(self): self._test_junit(os.path.join(self.common_test_dir, '42 test args')) def test_junit_valid_gtest(self): self._test_junit(os.path.join(self.framework_test_dir, '2 gtest')) def test_link_language_linker(self): # TODO: there should be some way to query how we're linking things # without resorting to reading the ninja.build file if self.backend is not Backend.ninja: raise unittest.SkipTest('This test reads the ninja file') testdir = os.path.join(self.common_test_dir, '226 link language') self.init(testdir) build_ninja = os.path.join(self.builddir, 'build.ninja') with open(build_ninja, 'r', encoding='utf-8') as f: contents = f.read() self.assertRegex(contents, r'build main(\.exe)?.*: c_LINKER') self.assertRegex(contents, r'build (lib|cyg)?mylib.*: c_LINKER') def test_commands_documented(self): ''' Test that all listed meson commands are documented in Commands.md. ''' # The docs directory is not in release tarballs. if not os.path.isdir('docs'): raise unittest.SkipTest('Doc directory does not exist.') doc_path = 'docs/markdown/Commands.md' md = None with open(doc_path, encoding='utf-8') as f: md = f.read() self.assertIsNotNone(md) ## Get command sections section_pattern = re.compile(r'^### (.+)$', re.MULTILINE) md_command_section_matches = [i for i in section_pattern.finditer(md)] md_command_sections = dict() for i, s in enumerate(md_command_section_matches): section_end = len(md) if i == len(md_command_section_matches) - 1 else md_command_section_matches[i + 1].start() md_command_sections[s.group(1)] = (s.start(), section_end) ## Validate commands md_commands = set(k for k,v in md_command_sections.items()) help_output = self._run(self.meson_command + ['--help']) help_commands = set(c.strip() for c in re.findall(r'usage:(?:.+)?{((?:[a-z]+,*)+?)}', help_output, re.MULTILINE|re.DOTALL)[0].split(',')) self.assertEqual(md_commands | {'help'}, help_commands, 'Doc file: `{}`'.format(doc_path)) ## Validate that each section has proper placeholders def get_data_pattern(command): return re.compile( r'{{ ' + command + r'_usage.inc }}[\r\n]' r'.*?' r'{{ ' + command + r'_arguments.inc }}[\r\n]', flags = re.MULTILINE|re.DOTALL) for command in md_commands: m = get_data_pattern(command).search(md, pos=md_command_sections[command][0], endpos=md_command_sections[command][1]) self.assertIsNotNone(m, 'Command `{}` is missing placeholders for dynamic data. Doc file: `{}`'.format(command, doc_path)) def _check_coverage_files(self, types=('text', 'xml', 'html')): covdir = Path(self.builddir) / 'meson-logs' files = [] if 'text' in types: files.append('coverage.txt') if 'xml' in types: files.append('coverage.xml') if 'html' in types: files.append('coveragereport/index.html') for f in files: self.assertTrue((covdir / f).is_file(), msg='{} is not a file'.format(f)) def test_coverage(self): if mesonbuild.environment.detect_msys2_arch(): raise unittest.SkipTest('Skipped due to problems with coverage on MSYS2') gcovr_exe, gcovr_new_rootdir = mesonbuild.environment.detect_gcovr() if not gcovr_exe: raise unittest.SkipTest('gcovr not found, or too old') testdir = os.path.join(self.common_test_dir, '1 trivial') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) if cc.get_id() == 'clang': if not mesonbuild.environment.detect_llvm_cov(): raise unittest.SkipTest('llvm-cov not found') if cc.get_id() == 'msvc': raise unittest.SkipTest('Test only applies to non-MSVC compilers') self.init(testdir, extra_args=['-Db_coverage=true']) self.build() self.run_tests() self.run_target('coverage') self._check_coverage_files() def test_coverage_complex(self): if mesonbuild.environment.detect_msys2_arch(): raise unittest.SkipTest('Skipped due to problems with coverage on MSYS2') gcovr_exe, gcovr_new_rootdir = mesonbuild.environment.detect_gcovr() if not gcovr_exe: raise unittest.SkipTest('gcovr not found, or too old') testdir = os.path.join(self.common_test_dir, '106 generatorcustom') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) if cc.get_id() == 'clang': if not mesonbuild.environment.detect_llvm_cov(): raise unittest.SkipTest('llvm-cov not found') if cc.get_id() == 'msvc': raise unittest.SkipTest('Test only applies to non-MSVC compilers') self.init(testdir, extra_args=['-Db_coverage=true']) self.build() self.run_tests() self.run_target('coverage') self._check_coverage_files() def test_coverage_html(self): if mesonbuild.environment.detect_msys2_arch(): raise unittest.SkipTest('Skipped due to problems with coverage on MSYS2') gcovr_exe, gcovr_new_rootdir = mesonbuild.environment.detect_gcovr() if not gcovr_exe: raise unittest.SkipTest('gcovr not found, or too old') testdir = os.path.join(self.common_test_dir, '1 trivial') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) if cc.get_id() == 'clang': if not mesonbuild.environment.detect_llvm_cov(): raise unittest.SkipTest('llvm-cov not found') if cc.get_id() == 'msvc': raise unittest.SkipTest('Test only applies to non-MSVC compilers') self.init(testdir, extra_args=['-Db_coverage=true']) self.build() self.run_tests() self.run_target('coverage-html') self._check_coverage_files(['html']) def test_coverage_text(self): if mesonbuild.environment.detect_msys2_arch(): raise unittest.SkipTest('Skipped due to problems with coverage on MSYS2') gcovr_exe, gcovr_new_rootdir = mesonbuild.environment.detect_gcovr() if not gcovr_exe: raise unittest.SkipTest('gcovr not found, or too old') testdir = os.path.join(self.common_test_dir, '1 trivial') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) if cc.get_id() == 'clang': if not mesonbuild.environment.detect_llvm_cov(): raise unittest.SkipTest('llvm-cov not found') if cc.get_id() == 'msvc': raise unittest.SkipTest('Test only applies to non-MSVC compilers') self.init(testdir, extra_args=['-Db_coverage=true']) self.build() self.run_tests() self.run_target('coverage-text') self._check_coverage_files(['text']) def test_coverage_xml(self): if mesonbuild.environment.detect_msys2_arch(): raise unittest.SkipTest('Skipped due to problems with coverage on MSYS2') gcovr_exe, gcovr_new_rootdir = mesonbuild.environment.detect_gcovr() if not gcovr_exe: raise unittest.SkipTest('gcovr not found, or too old') testdir = os.path.join(self.common_test_dir, '1 trivial') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) if cc.get_id() == 'clang': if not mesonbuild.environment.detect_llvm_cov(): raise unittest.SkipTest('llvm-cov not found') if cc.get_id() == 'msvc': raise unittest.SkipTest('Test only applies to non-MSVC compilers') self.init(testdir, extra_args=['-Db_coverage=true']) self.build() self.run_tests() self.run_target('coverage-xml') self._check_coverage_files(['xml']) def test_cross_file_constants(self): with temp_filename() as crossfile1, temp_filename() as crossfile2: with open(crossfile1, 'w') as f: f.write(textwrap.dedent( ''' [constants] compiler = 'gcc' ''')) with open(crossfile2, 'w') as f: f.write(textwrap.dedent( ''' [constants] toolchain = '/toolchain/' common_flags = ['--sysroot=' + toolchain / 'sysroot'] [properties] c_args = common_flags + ['-DSOMETHING'] cpp_args = c_args + ['-DSOMETHING_ELSE'] [binaries] c = toolchain / compiler ''')) values = mesonbuild.coredata.parse_machine_files([crossfile1, crossfile2]) self.assertEqual(values['binaries']['c'], '/toolchain/gcc') self.assertEqual(values['properties']['c_args'], ['--sysroot=/toolchain/sysroot', '-DSOMETHING']) self.assertEqual(values['properties']['cpp_args'], ['--sysroot=/toolchain/sysroot', '-DSOMETHING', '-DSOMETHING_ELSE']) @unittest.skipIf(is_windows(), 'Directory cleanup fails for some reason') def test_wrap_git(self): with tempfile.TemporaryDirectory() as tmpdir: srcdir = os.path.join(tmpdir, 'src') shutil.copytree(os.path.join(self.unit_test_dir, '82 wrap-git'), srcdir) upstream = os.path.join(srcdir, 'subprojects', 'wrap_git_upstream') upstream_uri = Path(upstream).as_uri() _git_init(upstream) with open(os.path.join(srcdir, 'subprojects', 'wrap_git.wrap'), 'w') as f: f.write(textwrap.dedent(''' [wrap-git] url = {} patch_directory = wrap_git_builddef revision = master '''.format(upstream_uri))) self.init(srcdir) self.build() self.run_tests() def test_multi_output_custom_target_no_warning(self): testdir = os.path.join(self.common_test_dir, '229 custom_target source') out = self.init(testdir) self.assertNotRegex(out, 'WARNING:.*Using the first one.') self.build() self.run_tests() @unittest.skipUnless(is_linux() and (re.search('^i.86$|^x86$|^x64$|^x86_64$|^amd64$', platform.processor()) is not None), 'Requires ASM compiler for x86 or x86_64 platform currently only available on Linux CI runners') def test_nostdlib(self): testdir = os.path.join(self.unit_test_dir, '79 nostdlib') machinefile = os.path.join(self.builddir, 'machine.txt') with open(machinefile, 'w') as f: f.write(textwrap.dedent(''' [properties] c_stdlib = 'mylibc' ''')) # Test native C stdlib self.meson_native_file = machinefile self.init(testdir) self.build() # Test cross C stdlib self.new_builddir() self.meson_native_file = None self.meson_cross_file = machinefile self.init(testdir) self.build() def test_meson_version_compare(self): testdir = os.path.join(self.unit_test_dir, '83 meson version compare') out = self.init(testdir) self.assertNotRegex(out, r'WARNING') def test_wrap_redirect(self): redirect_wrap = os.path.join(self.builddir, 'redirect.wrap') real_wrap = os.path.join(self.builddir, 'foo/subprojects/real.wrap') os.makedirs(os.path.dirname(real_wrap)) # Invalid redirect, filename must have .wrap extension with open(redirect_wrap, 'w') as f: f.write(textwrap.dedent(''' [wrap-redirect] filename = foo/subprojects/real.wrapper ''')) with self.assertRaisesRegex(WrapException, 'wrap-redirect filename must be a .wrap file'): PackageDefinition(redirect_wrap) # Invalid redirect, filename cannot be in parent directory with open(redirect_wrap, 'w') as f: f.write(textwrap.dedent(''' [wrap-redirect] filename = ../real.wrap ''')) with self.assertRaisesRegex(WrapException, 'wrap-redirect filename cannot contain ".."'): PackageDefinition(redirect_wrap) # Invalid redirect, filename must be in foo/subprojects/real.wrap with open(redirect_wrap, 'w') as f: f.write(textwrap.dedent(''' [wrap-redirect] filename = foo/real.wrap ''')) with self.assertRaisesRegex(WrapException, 'wrap-redirect filename must be in the form foo/subprojects/bar.wrap'): wrap = PackageDefinition(redirect_wrap) # Correct redirect with open(redirect_wrap, 'w') as f: f.write(textwrap.dedent(''' [wrap-redirect] filename = foo/subprojects/real.wrap ''')) with open(real_wrap, 'w') as f: f.write(textwrap.dedent(''' [wrap-git] url = http://invalid ''')) wrap = PackageDefinition(redirect_wrap) self.assertEqual(wrap.get('url'), 'http://invalid') @skip_if_no_cmake def test_nested_cmake_rebuild(self) -> None: # This checks a bug where if a non-meson project is used as a third # level (or deeper) subproject it doesn't cause a rebuild if the build # files for that project are changed testdir = os.path.join(self.unit_test_dir, '86 nested subproject regenerate depends') cmakefile = Path(testdir) / 'subprojects' / 'sub2' / 'CMakeLists.txt' self.init(testdir) self.build() with cmakefile.open('a') as f: os.utime(str(cmakefile)) self.assertReconfiguredBuildIsNoop() def test_version_file(self): srcdir = os.path.join(self.common_test_dir, '2 cpp') self.init(srcdir) projinfo = self.introspect('--projectinfo') self.assertEqual(projinfo['version'], '1.0.0') def test_cflags_cppflags(self): envs = {'CPPFLAGS': '-DCPPFLAG', 'CFLAGS': '-DCFLAG', 'CXXFLAGS': '-DCXXFLAG'} srcdir = os.path.join(self.unit_test_dir, '90 multiple envvars') self.init(srcdir, override_envvars=envs) self.build() def test_build_b_options(self) -> None: # Currently (0.57) these do nothing, but they've always been allowed srcdir = os.path.join(self.common_test_dir, '2 cpp') self.init(srcdir, extra_args=['-Dbuild.b_lto=true']) def test_install_skip_subprojects(self): testdir = os.path.join(self.unit_test_dir, '91 install skip subprojects') self.init(testdir) self.build() main_expected = [ '', 'share', 'include', 'foo', 'bin', 'share/foo', 'share/foo/foo.dat', 'include/foo.h', 'foo/foofile', 'bin/foo' + exe_suffix, ] bar_expected = [ 'bar', 'share/foo/bar.dat', 'include/bar.h', 'bin/bar' + exe_suffix, 'bar/barfile' ] env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) if cc.get_argument_syntax() == 'msvc': main_expected.append('bin/foo.pdb') bar_expected.append('bin/bar.pdb') prefix = destdir_join(self.installdir, self.prefix) main_expected = [Path(prefix, p) for p in main_expected] bar_expected = [Path(prefix, p) for p in bar_expected] all_expected = main_expected + bar_expected def check_installed_files(extra_args, expected): args = ['install', '--destdir', self.installdir] + extra_args self._run(self.meson_command + args, workdir=self.builddir) all_files = [p for p in Path(self.installdir).rglob('*')] self.assertEqual(sorted(expected), sorted(all_files)) windows_proof_rmtree(self.installdir) check_installed_files([], all_expected) check_installed_files(['--skip-subprojects'], main_expected) check_installed_files(['--skip-subprojects', 'bar'], main_expected) check_installed_files(['--skip-subprojects', 'another'], all_expected) class FailureTests(BasePlatformTests): ''' Tests that test failure conditions. Build files here should be dynamically generated and static tests should go into `test cases/failing*`. This is useful because there can be many ways in which a particular function can fail, and creating failing tests for all of them is tedious and slows down testing. ''' dnf = "[Dd]ependency.*not found(:.*)?" nopkg = '[Pp]kg-config.*not found' def setUp(self): super().setUp() self.srcdir = os.path.realpath(tempfile.mkdtemp()) self.mbuild = os.path.join(self.srcdir, 'meson.build') self.moptions = os.path.join(self.srcdir, 'meson_options.txt') def tearDown(self): super().tearDown() windows_proof_rmtree(self.srcdir) def assertMesonRaises(self, contents, match, *, extra_args=None, langs=None, meson_version=None, options=None, override_envvars=None): ''' Assert that running meson configure on the specified @contents raises a error message matching regex @match. ''' if langs is None: langs = [] with open(self.mbuild, 'w') as f: f.write("project('failure test', 'c', 'cpp'") if meson_version: f.write(", meson_version: '{}'".format(meson_version)) f.write(")\n") for lang in langs: f.write("add_languages('{}', required : false)\n".format(lang)) f.write(contents) if options is not None: with open(self.moptions, 'w') as f: f.write(options) o = {'MESON_FORCE_BACKTRACE': '1'} if override_envvars is None: override_envvars = o else: override_envvars.update(o) # Force tracebacks so we can detect them properly with self.assertRaisesRegex(MesonException, match, msg=contents): # Must run in-process or we'll get a generic CalledProcessError self.init(self.srcdir, extra_args=extra_args, inprocess=True, override_envvars = override_envvars) def obtainMesonOutput(self, contents, match, extra_args, langs, meson_version=None): if langs is None: langs = [] with open(self.mbuild, 'w') as f: f.write("project('output test', 'c', 'cpp'") if meson_version: f.write(", meson_version: '{}'".format(meson_version)) f.write(")\n") for lang in langs: f.write("add_languages('{}', required : false)\n".format(lang)) f.write(contents) # Run in-process for speed and consistency with assertMesonRaises return self.init(self.srcdir, extra_args=extra_args, inprocess=True) def assertMesonOutputs(self, contents, match, extra_args=None, langs=None, meson_version=None): ''' Assert that running meson configure on the specified @contents outputs something that matches regex @match. ''' out = self.obtainMesonOutput(contents, match, extra_args, langs, meson_version) self.assertRegex(out, match) def assertMesonDoesNotOutput(self, contents, match, extra_args=None, langs=None, meson_version=None): ''' Assert that running meson configure on the specified @contents does not output something that matches regex @match. ''' out = self.obtainMesonOutput(contents, match, extra_args, langs, meson_version) self.assertNotRegex(out, match) @skipIfNoPkgconfig def test_dependency(self): if subprocess.call(['pkg-config', '--exists', 'zlib']) != 0: raise unittest.SkipTest('zlib not found with pkg-config') a = (("dependency('zlib', method : 'fail')", "'fail' is invalid"), ("dependency('zlib', static : '1')", "[Ss]tatic.*boolean"), ("dependency('zlib', version : 1)", "Item must be a list or one of <class 'str'>"), ("dependency('zlib', required : 1)", "[Rr]equired.*boolean"), ("dependency('zlib', method : 1)", "[Mm]ethod.*string"), ("dependency('zlibfail')", self.dnf),) for contents, match in a: self.assertMesonRaises(contents, match) def test_apple_frameworks_dependency(self): if not is_osx(): raise unittest.SkipTest('only run on macOS') self.assertMesonRaises("dependency('appleframeworks')", "requires at least one module") def test_extraframework_dependency_method(self): code = "dependency('python', method : 'extraframework')" if not is_osx(): self.assertMesonRaises(code, self.dnf) else: # Python2 framework is always available on macOS self.assertMesonOutputs(code, '[Dd]ependency.*python.*found.*YES') def test_sdl2_notfound_dependency(self): # Want to test failure, so skip if available if shutil.which('sdl2-config'): raise unittest.SkipTest('sdl2-config found') self.assertMesonRaises("dependency('sdl2', method : 'sdlconfig')", self.dnf) if shutil.which('pkg-config'): self.assertMesonRaises("dependency('sdl2', method : 'pkg-config')", self.dnf) with no_pkgconfig(): # Look for pkg-config, cache it, then # Use cached pkg-config without erroring out, then # Use cached pkg-config to error out code = "dependency('foobarrr', method : 'pkg-config', required : false)\n" \ "dependency('foobarrr2', method : 'pkg-config', required : false)\n" \ "dependency('sdl2', method : 'pkg-config')" self.assertMesonRaises(code, self.nopkg) def test_gnustep_notfound_dependency(self): # Want to test failure, so skip if available if shutil.which('gnustep-config'): raise unittest.SkipTest('gnustep-config found') self.assertMesonRaises("dependency('gnustep')", "(requires a Objc compiler|{})".format(self.dnf), langs = ['objc']) def test_wx_notfound_dependency(self): # Want to test failure, so skip if available if shutil.which('wx-config-3.0') or shutil.which('wx-config') or shutil.which('wx-config-gtk3'): raise unittest.SkipTest('wx-config, wx-config-3.0 or wx-config-gtk3 found') self.assertMesonRaises("dependency('wxwidgets')", self.dnf) self.assertMesonOutputs("dependency('wxwidgets', required : false)", "Run-time dependency .*WxWidgets.* found: .*NO.*") def test_wx_dependency(self): if not shutil.which('wx-config-3.0') and not shutil.which('wx-config') and not shutil.which('wx-config-gtk3'): raise unittest.SkipTest('Neither wx-config, wx-config-3.0 nor wx-config-gtk3 found') self.assertMesonRaises("dependency('wxwidgets', modules : 1)", "module argument is not a string") def test_llvm_dependency(self): self.assertMesonRaises("dependency('llvm', modules : 'fail')", "(required.*fail|{})".format(self.dnf)) def test_boost_notfound_dependency(self): # Can be run even if Boost is found or not self.assertMesonRaises("dependency('boost', modules : 1)", "module.*not a string") self.assertMesonRaises("dependency('boost', modules : 'fail')", "(fail.*not found|{})".format(self.dnf)) def test_boost_BOOST_ROOT_dependency(self): # Test BOOST_ROOT; can be run even if Boost is found or not self.assertMesonRaises("dependency('boost')", "(boost_root.*absolute|{})".format(self.dnf), override_envvars = {'BOOST_ROOT': 'relative/path'}) def test_dependency_invalid_method(self): code = '''zlib_dep = dependency('zlib', required : false) zlib_dep.get_configtool_variable('foo') ''' self.assertMesonRaises(code, ".* is not a config-tool dependency") code = '''zlib_dep = dependency('zlib', required : false) dep = declare_dependency(dependencies : zlib_dep) dep.get_pkgconfig_variable('foo') ''' self.assertMesonRaises(code, "Method.*pkgconfig.*is invalid.*internal") code = '''zlib_dep = dependency('zlib', required : false) dep = declare_dependency(dependencies : zlib_dep) dep.get_configtool_variable('foo') ''' self.assertMesonRaises(code, "Method.*configtool.*is invalid.*internal") def test_objc_cpp_detection(self): ''' Test that when we can't detect objc or objcpp, we fail gracefully. ''' env = get_fake_env() try: env.detect_objc_compiler(MachineChoice.HOST) env.detect_objcpp_compiler(MachineChoice.HOST) except EnvironmentException: code = "add_languages('objc')\nadd_languages('objcpp')" self.assertMesonRaises(code, "Unknown compiler") return raise unittest.SkipTest("objc and objcpp found, can't test detection failure") def test_subproject_variables(self): ''' Test that: 1. The correct message is outputted when a not-required dep is not found and the fallback subproject is also not found. 2. A not-required fallback dependency is not found because the subproject failed to parse. 3. A not-found not-required dep with a fallback subproject outputs the correct message when the fallback subproject is found but the variable inside it is not. 4. A fallback dependency is found from the subproject parsed in (3) 5. A wrap file from a subproject is used but fails because it does not contain required keys. ''' tdir = os.path.join(self.unit_test_dir, '20 subproj dep variables') out = self.init(tdir, inprocess=True) self.assertRegex(out, r"Neither a subproject directory nor a .*nosubproj.wrap.* file was found") self.assertRegex(out, r'Function does not take positional arguments.') self.assertRegex(out, r'Dependency .*somenotfounddep.* from subproject .*subprojects/somesubproj.* found: .*NO.*') self.assertRegex(out, r'Dependency .*zlibproxy.* from subproject .*subprojects.*somesubproj.* found: .*YES.*') self.assertRegex(out, r'Missing key .*source_filename.* in subsubproject.wrap') def test_exception_exit_status(self): ''' Test exit status on python exception ''' tdir = os.path.join(self.unit_test_dir, '21 exit status') with self.assertRaises(subprocess.CalledProcessError) as cm: self.init(tdir, inprocess=False, override_envvars = {'MESON_UNIT_TEST': '1'}) self.assertEqual(cm.exception.returncode, 2) self.wipe() def test_dict_requires_key_value_pairs(self): self.assertMesonRaises("dict = {3, 'foo': 'bar'}", 'Only key:value pairs are valid in dict construction.') self.assertMesonRaises("{'foo': 'bar', 3}", 'Only key:value pairs are valid in dict construction.') def test_dict_forbids_duplicate_keys(self): self.assertMesonRaises("dict = {'a': 41, 'a': 42}", 'Duplicate dictionary key: a.*') def test_dict_forbids_integer_key(self): self.assertMesonRaises("dict = {3: 'foo'}", 'Key must be a string.*') def test_using_too_recent_feature(self): # Here we use a dict, which was introduced in 0.47.0 self.assertMesonOutputs("dict = {}", ".*WARNING.*Project targeting.*but.*", meson_version='>= 0.46.0') def test_using_recent_feature(self): # Same as above, except the meson version is now appropriate self.assertMesonDoesNotOutput("dict = {}", ".*WARNING.*Project targeting.*but.*", meson_version='>= 0.47') def test_using_too_recent_feature_dependency(self): self.assertMesonOutputs("dependency('pcap', required: false)", ".*WARNING.*Project targeting.*but.*", meson_version='>= 0.41.0') def test_vcs_tag_featurenew_build_always_stale(self): 'https://github.com/mesonbuild/meson/issues/3904' vcs_tag = '''version_data = configuration_data() version_data.set('PROJVER', '@VCS_TAG@') vf = configure_file(output : 'version.h.in', configuration: version_data) f = vcs_tag(input : vf, output : 'version.h') ''' msg = '.*WARNING:.*feature.*build_always_stale.*custom_target.*' self.assertMesonDoesNotOutput(vcs_tag, msg, meson_version='>=0.43') def test_missing_subproject_not_required_and_required(self): self.assertMesonRaises("sub1 = subproject('not-found-subproject', required: false)\n" + "sub2 = subproject('not-found-subproject', required: true)", """.*Subproject "subprojects/not-found-subproject" required but not found.*""") def test_get_variable_on_not_found_project(self): self.assertMesonRaises("sub1 = subproject('not-found-subproject', required: false)\n" + "sub1.get_variable('naaa')", """Subproject "subprojects/not-found-subproject" disabled can't get_variable on it.""") def test_version_checked_before_parsing_options(self): ''' https://github.com/mesonbuild/meson/issues/5281 ''' options = "option('some-option', type: 'foo', value: '')" match = 'Meson version is.*but project requires >=2000' self.assertMesonRaises("", match, meson_version='>=2000', options=options) def test_assert_default_message(self): self.assertMesonRaises("k1 = 'a'\n" + "assert({\n" + " k1: 1,\n" + "}['a'] == 2)\n", r"Assert failed: {k1 : 1}\['a'\] == 2") def test_wrap_nofallback(self): self.assertMesonRaises("dependency('notfound', fallback : ['foo', 'foo_dep'])", r"Dependency \'notfound\' not found and fallback is disabled", extra_args=['--wrap-mode=nofallback']) def test_message(self): self.assertMesonOutputs("message('Array:', ['a', 'b'])", r"Message:.* Array: \['a', 'b'\]") def test_warning(self): self.assertMesonOutputs("warning('Array:', ['a', 'b'])", r"WARNING:.* Array: \['a', 'b'\]") def test_override_dependency_twice(self): self.assertMesonRaises("meson.override_dependency('foo', declare_dependency())\n" + "meson.override_dependency('foo', declare_dependency())", """Tried to override dependency 'foo' which has already been resolved or overridden""") @unittest.skipIf(is_windows(), 'zlib is not available on Windows') def test_override_resolved_dependency(self): self.assertMesonRaises("dependency('zlib')\n" + "meson.override_dependency('zlib', declare_dependency())", """Tried to override dependency 'zlib' which has already been resolved or overridden""") def test_error_func(self): self.assertMesonRaises("error('a', 'b', ['c', ['d', {'e': 'f'}]], 'g')", "Problem encountered: a b \['c', \['d', {'e' : 'f'}\]\] g") @unittest.skipUnless(is_windows() or is_cygwin(), "requires Windows (or Windows via Cygwin)") class WindowsTests(BasePlatformTests): ''' Tests that should run on Cygwin, MinGW, and MSVC ''' def setUp(self): super().setUp() self.platform_test_dir = os.path.join(self.src_root, 'test cases/windows') @unittest.skipIf(is_cygwin(), 'Test only applicable to Windows') @mock.patch.dict(os.environ) def test_find_program(self): ''' Test that Windows-specific edge-cases in find_program are functioning correctly. Cannot be an ordinary test because it involves manipulating PATH to point to a directory with Python scripts. ''' testdir = os.path.join(self.platform_test_dir, '8 find program') # Find `cmd` and `cmd.exe` prog1 = ExternalProgram('cmd') self.assertTrue(prog1.found(), msg='cmd not found') prog2 = ExternalProgram('cmd.exe') self.assertTrue(prog2.found(), msg='cmd.exe not found') self.assertPathEqual(prog1.get_path(), prog2.get_path()) # Find cmd.exe with args without searching prog = ExternalProgram('cmd', command=['cmd', '/C']) self.assertTrue(prog.found(), msg='cmd not found with args') self.assertPathEqual(prog.get_command()[0], 'cmd') # Find cmd with an absolute path that's missing the extension cmd_path = prog2.get_path()[:-4] prog = ExternalProgram(cmd_path) self.assertTrue(prog.found(), msg='{!r} not found'.format(cmd_path)) # Finding a script with no extension inside a directory works prog = ExternalProgram(os.path.join(testdir, 'test-script')) self.assertTrue(prog.found(), msg='test-script not found') # Finding a script with an extension inside a directory works prog = ExternalProgram(os.path.join(testdir, 'test-script-ext.py')) self.assertTrue(prog.found(), msg='test-script-ext.py not found') # Finding a script in PATH os.environ['PATH'] += os.pathsep + testdir # If `.PY` is in PATHEXT, scripts can be found as programs if '.PY' in [ext.upper() for ext in os.environ['PATHEXT'].split(';')]: # Finding a script in PATH w/o extension works and adds the interpreter prog = ExternalProgram('test-script-ext') self.assertTrue(prog.found(), msg='test-script-ext not found in PATH') self.assertPathEqual(prog.get_command()[0], python_command[0]) self.assertPathBasenameEqual(prog.get_path(), 'test-script-ext.py') # Finding a script in PATH with extension works and adds the interpreter prog = ExternalProgram('test-script-ext.py') self.assertTrue(prog.found(), msg='test-script-ext.py not found in PATH') self.assertPathEqual(prog.get_command()[0], python_command[0]) self.assertPathBasenameEqual(prog.get_path(), 'test-script-ext.py') # Using a script with an extension directly via command= works and adds the interpreter prog = ExternalProgram('test-script-ext.py', command=[os.path.join(testdir, 'test-script-ext.py'), '--help']) self.assertTrue(prog.found(), msg='test-script-ext.py with full path not picked up via command=') self.assertPathEqual(prog.get_command()[0], python_command[0]) self.assertPathEqual(prog.get_command()[2], '--help') self.assertPathBasenameEqual(prog.get_path(), 'test-script-ext.py') # Using a script without an extension directly via command= works and adds the interpreter prog = ExternalProgram('test-script', command=[os.path.join(testdir, 'test-script'), '--help']) self.assertTrue(prog.found(), msg='test-script with full path not picked up via command=') self.assertPathEqual(prog.get_command()[0], python_command[0]) self.assertPathEqual(prog.get_command()[2], '--help') self.assertPathBasenameEqual(prog.get_path(), 'test-script') # Ensure that WindowsApps gets removed from PATH path = os.environ['PATH'] if 'WindowsApps' not in path: username = os.environ['USERNAME'] appstore_dir = r'C:\Users\{}\AppData\Local\Microsoft\WindowsApps'.format(username) path = os.pathsep + appstore_dir path = ExternalProgram._windows_sanitize_path(path) self.assertNotIn('WindowsApps', path) def test_ignore_libs(self): ''' Test that find_library on libs that are to be ignored returns an empty array of arguments. Must be a unit test because we cannot inspect ExternalLibraryHolder from build files. ''' testdir = os.path.join(self.platform_test_dir, '1 basic') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) if cc.get_argument_syntax() != 'msvc': raise unittest.SkipTest('Not using MSVC') # To force people to update this test, and also test self.assertEqual(set(cc.ignore_libs), {'c', 'm', 'pthread', 'dl', 'rt', 'execinfo'}) for l in cc.ignore_libs: self.assertEqual(cc.find_library(l, env, []), []) def test_rc_depends_files(self): testdir = os.path.join(self.platform_test_dir, '5 resources') # resource compiler depfile generation is not yet implemented for msvc env = get_fake_env(testdir, self.builddir, self.prefix) depfile_works = env.detect_c_compiler(MachineChoice.HOST).get_id() not in {'msvc', 'clang-cl', 'intel-cl'} self.init(testdir) self.build() # Immediately rebuilding should not do anything self.assertBuildIsNoop() # Test compile_resources(depend_file:) # Changing mtime of sample.ico should rebuild prog self.utime(os.path.join(testdir, 'res', 'sample.ico')) self.assertRebuiltTarget('prog') # Test depfile generation by compile_resources # Changing mtime of resource.h should rebuild myres.rc and then prog if depfile_works: self.utime(os.path.join(testdir, 'inc', 'resource', 'resource.h')) self.assertRebuiltTarget('prog') self.wipe() if depfile_works: testdir = os.path.join(self.platform_test_dir, '12 resources with custom targets') self.init(testdir) self.build() # Immediately rebuilding should not do anything self.assertBuildIsNoop() # Changing mtime of resource.h should rebuild myres_1.rc and then prog_1 self.utime(os.path.join(testdir, 'res', 'resource.h')) self.assertRebuiltTarget('prog_1') def test_msvc_cpp17(self): testdir = os.path.join(self.unit_test_dir, '45 vscpp17') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) if cc.get_argument_syntax() != 'msvc': raise unittest.SkipTest('Test only applies to MSVC-like compilers') try: self.init(testdir) except subprocess.CalledProcessError: # According to Python docs, output is only stored when # using check_output. We don't use it, so we can't check # that the output is correct (i.e. that it failed due # to the right reason). return self.build() def test_install_pdb_introspection(self): testdir = os.path.join(self.platform_test_dir, '1 basic') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) if cc.get_argument_syntax() != 'msvc': raise unittest.SkipTest('Test only applies to MSVC-like compilers') self.init(testdir) installed = self.introspect('--installed') files = [os.path.basename(path) for path in installed.values()] self.assertTrue('prog.pdb' in files) def _check_ld(self, name: str, lang: str, expected: str) -> None: if not shutil.which(name): raise unittest.SkipTest('Could not find {}.'.format(name)) envvars = [mesonbuild.envconfig.ENV_VAR_PROG_MAP['{}_ld'.format(lang)]] # Also test a deprecated variable if there is one. if f'{lang}_ld' in mesonbuild.envconfig.DEPRECATED_ENV_PROG_MAP: envvars.append( mesonbuild.envconfig.DEPRECATED_ENV_PROG_MAP[f'{lang}_ld']) for envvar in envvars: with mock.patch.dict(os.environ, {envvar: name}): env = get_fake_env() try: comp = getattr(env, 'detect_{}_compiler'.format(lang))(MachineChoice.HOST) except EnvironmentException: raise unittest.SkipTest('Could not find a compiler for {}'.format(lang)) self.assertEqual(comp.linker.id, expected) def test_link_environment_variable_lld_link(self): env = get_fake_env() comp = getattr(env, 'detect_c_compiler')(MachineChoice.HOST) if isinstance(comp, mesonbuild.compilers.GnuLikeCompiler): raise unittest.SkipTest('GCC cannot be used with link compatible linkers.') self._check_ld('lld-link', 'c', 'lld-link') def test_link_environment_variable_link(self): env = get_fake_env() comp = getattr(env, 'detect_c_compiler')(MachineChoice.HOST) if isinstance(comp, mesonbuild.compilers.GnuLikeCompiler): raise unittest.SkipTest('GCC cannot be used with link compatible linkers.') self._check_ld('link', 'c', 'link') def test_link_environment_variable_optlink(self): env = get_fake_env() comp = getattr(env, 'detect_c_compiler')(MachineChoice.HOST) if isinstance(comp, mesonbuild.compilers.GnuLikeCompiler): raise unittest.SkipTest('GCC cannot be used with link compatible linkers.') self._check_ld('optlink', 'c', 'optlink') @skip_if_not_language('rust') def test_link_environment_variable_rust(self): self._check_ld('link', 'rust', 'link') @skip_if_not_language('d') def test_link_environment_variable_d(self): env = get_fake_env() comp = getattr(env, 'detect_d_compiler')(MachineChoice.HOST) if comp.id == 'dmd': raise unittest.SkipTest('meson cannot reliably make DMD use a different linker.') self._check_ld('lld-link', 'd', 'lld-link') def test_pefile_checksum(self): try: import pefile except ImportError: if is_ci(): raise raise unittest.SkipTest('pefile module not found') testdir = os.path.join(self.common_test_dir, '6 linkshared') self.init(testdir, extra_args=['--buildtype=release']) self.build() # Test that binaries have a non-zero checksum env = get_fake_env() cc = env.detect_c_compiler(MachineChoice.HOST) cc_id = cc.get_id() ld_id = cc.get_linker_id() dll = glob(os.path.join(self.builddir, '*mycpplib.dll'))[0] exe = os.path.join(self.builddir, 'cppprog.exe') for f in (dll, exe): pe = pefile.PE(f) msg = 'PE file: {!r}, compiler: {!r}, linker: {!r}'.format(f, cc_id, ld_id) if cc_id == 'clang-cl': # Latest clang-cl tested (7.0) does not write checksums out self.assertFalse(pe.verify_checksum(), msg=msg) else: # Verify that a valid checksum was written by all other compilers self.assertTrue(pe.verify_checksum(), msg=msg) def test_qt5dependency_vscrt(self): ''' Test that qt5 dependencies use the debug module suffix when b_vscrt is set to 'mdd' ''' # Verify that the `b_vscrt` option is available env = get_fake_env() cc = env.detect_c_compiler(MachineChoice.HOST) if OptionKey('b_vscrt') not in cc.base_options: raise unittest.SkipTest('Compiler does not support setting the VS CRT') # Verify that qmake is for Qt5 if not shutil.which('qmake-qt5'): if not shutil.which('qmake') and not is_ci(): raise unittest.SkipTest('QMake not found') output = subprocess.getoutput('qmake --version') if 'Qt version 5' not in output and not is_ci(): raise unittest.SkipTest('Qmake found, but it is not for Qt 5.') # Setup with /MDd testdir = os.path.join(self.framework_test_dir, '4 qt') self.init(testdir, extra_args=['-Db_vscrt=mdd']) # Verify that we're linking to the debug versions of Qt DLLs build_ninja = os.path.join(self.builddir, 'build.ninja') with open(build_ninja, 'r', encoding='utf-8') as f: contents = f.read() m = re.search('build qt5core.exe: cpp_LINKER.*Qt5Cored.lib', contents) self.assertIsNotNone(m, msg=contents) def test_compiler_checks_vscrt(self): ''' Test that the correct VS CRT is used when running compiler checks ''' # Verify that the `b_vscrt` option is available env = get_fake_env() cc = env.detect_c_compiler(MachineChoice.HOST) if OptionKey('b_vscrt') not in cc.base_options: raise unittest.SkipTest('Compiler does not support setting the VS CRT') def sanitycheck_vscrt(vscrt): checks = self.get_meson_log_sanitychecks() self.assertTrue(len(checks) > 0) for check in checks: self.assertIn(vscrt, check) testdir = os.path.join(self.common_test_dir, '1 trivial') self.init(testdir) sanitycheck_vscrt('/MDd') self.new_builddir() self.init(testdir, extra_args=['-Dbuildtype=debugoptimized']) sanitycheck_vscrt('/MD') self.new_builddir() self.init(testdir, extra_args=['-Dbuildtype=release']) sanitycheck_vscrt('/MD') self.new_builddir() self.init(testdir, extra_args=['-Db_vscrt=md']) sanitycheck_vscrt('/MD') self.new_builddir() self.init(testdir, extra_args=['-Db_vscrt=mdd']) sanitycheck_vscrt('/MDd') self.new_builddir() self.init(testdir, extra_args=['-Db_vscrt=mt']) sanitycheck_vscrt('/MT') self.new_builddir() self.init(testdir, extra_args=['-Db_vscrt=mtd']) sanitycheck_vscrt('/MTd') def test_modules(self): if self.backend is not Backend.ninja: raise unittest.SkipTest('C++ modules only work with the Ninja backend (not {}).'.format(self.backend.name)) if 'VSCMD_VER' not in os.environ: raise unittest.SkipTest('C++ modules is only supported with Visual Studio.') if version_compare(os.environ['VSCMD_VER'], '<16.9.0'): raise unittest.SkipTest('C++ modules are only supported with VS 2019 Preview or newer.') self.init(os.path.join(self.unit_test_dir, '87 cpp modules')) self.build() @unittest.skipUnless(is_osx(), "requires Darwin") class DarwinTests(BasePlatformTests): ''' Tests that should run on macOS ''' def setUp(self): super().setUp() self.platform_test_dir = os.path.join(self.src_root, 'test cases/osx') def test_apple_bitcode(self): ''' Test that -fembed-bitcode is correctly added while compiling and -bitcode_bundle is added while linking when b_bitcode is true and not when it is false. This can't be an ordinary test case because we need to inspect the compiler database. ''' testdir = os.path.join(self.platform_test_dir, '7 bitcode') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) if cc.id != 'clang': raise unittest.SkipTest('Not using Clang on OSX') # Try with bitcode enabled out = self.init(testdir, extra_args='-Db_bitcode=true') # Warning was printed self.assertRegex(out, 'WARNING:.*b_bitcode') # Compiler options were added for compdb in self.get_compdb(): if 'module' in compdb['file']: self.assertNotIn('-fembed-bitcode', compdb['command']) else: self.assertIn('-fembed-bitcode', compdb['command']) build_ninja = os.path.join(self.builddir, 'build.ninja') # Linker options were added with open(build_ninja, 'r', encoding='utf-8') as f: contents = f.read() m = re.search('LINK_ARGS =.*-bitcode_bundle', contents) self.assertIsNotNone(m, msg=contents) # Try with bitcode disabled self.setconf('-Db_bitcode=false') # Regenerate build self.build() for compdb in self.get_compdb(): self.assertNotIn('-fembed-bitcode', compdb['command']) build_ninja = os.path.join(self.builddir, 'build.ninja') with open(build_ninja, 'r', encoding='utf-8') as f: contents = f.read() m = re.search('LINK_ARGS =.*-bitcode_bundle', contents) self.assertIsNone(m, msg=contents) def test_apple_bitcode_modules(self): ''' Same as above, just for shared_module() ''' testdir = os.path.join(self.common_test_dir, '149 shared module resolving symbol in executable') # Ensure that it builds even with bitcode enabled self.init(testdir, extra_args='-Db_bitcode=true') self.build() self.run_tests() def _get_darwin_versions(self, fname): fname = os.path.join(self.builddir, fname) out = subprocess.check_output(['otool', '-L', fname], universal_newlines=True) m = re.match(r'.*version (.*), current version (.*)\)', out.split('\n')[1]) self.assertIsNotNone(m, msg=out) return m.groups() @skipIfNoPkgconfig def test_library_versioning(self): ''' Ensure that compatibility_version and current_version are set correctly ''' testdir = os.path.join(self.platform_test_dir, '2 library versions') self.init(testdir) self.build() targets = {} for t in self.introspect('--targets'): targets[t['name']] = t['filename'][0] if isinstance(t['filename'], list) else t['filename'] self.assertEqual(self._get_darwin_versions(targets['some']), ('7.0.0', '7.0.0')) self.assertEqual(self._get_darwin_versions(targets['noversion']), ('0.0.0', '0.0.0')) self.assertEqual(self._get_darwin_versions(targets['onlyversion']), ('1.0.0', '1.0.0')) self.assertEqual(self._get_darwin_versions(targets['onlysoversion']), ('5.0.0', '5.0.0')) self.assertEqual(self._get_darwin_versions(targets['intver']), ('2.0.0', '2.0.0')) self.assertEqual(self._get_darwin_versions(targets['stringver']), ('2.3.0', '2.3.0')) self.assertEqual(self._get_darwin_versions(targets['stringlistver']), ('2.4.0', '2.4.0')) self.assertEqual(self._get_darwin_versions(targets['intstringver']), ('1111.0.0', '2.5.0')) self.assertEqual(self._get_darwin_versions(targets['stringlistvers']), ('2.6.0', '2.6.1')) def test_duplicate_rpath(self): testdir = os.path.join(self.unit_test_dir, '10 build_rpath') # We purposely pass a duplicate rpath to Meson, in order # to ascertain that Meson does not call install_name_tool # with duplicate -delete_rpath arguments, which would # lead to erroring out on installation env = {"LDFLAGS": "-Wl,-rpath,/foo/bar"} self.init(testdir, override_envvars=env) self.build() self.install() def test_removing_unused_linker_args(self): testdir = os.path.join(self.common_test_dir, '105 has arg') env = {'CFLAGS': '-L/tmp -L /var/tmp -headerpad_max_install_names -Wl,-export_dynamic -framework Foundation'} self.init(testdir, override_envvars=env) @unittest.skipUnless(not is_windows(), "requires something Unix-like") class LinuxlikeTests(BasePlatformTests): ''' Tests that should run on Linux, macOS, and *BSD ''' def test_basic_soname(self): ''' Test that the soname is set correctly for shared libraries. This can't be an ordinary test case because we need to run `readelf` and actually check the soname. https://github.com/mesonbuild/meson/issues/785 ''' testdir = os.path.join(self.common_test_dir, '4 shared') self.init(testdir) self.build() lib1 = os.path.join(self.builddir, 'libmylib.so') soname = get_soname(lib1) self.assertEqual(soname, 'libmylib.so') def test_custom_soname(self): ''' Test that the soname is set correctly for shared libraries when a custom prefix and/or suffix is used. This can't be an ordinary test case because we need to run `readelf` and actually check the soname. https://github.com/mesonbuild/meson/issues/785 ''' testdir = os.path.join(self.common_test_dir, '25 library versions') self.init(testdir) self.build() lib1 = os.path.join(self.builddir, 'prefixsomelib.suffix') soname = get_soname(lib1) self.assertEqual(soname, 'prefixsomelib.suffix') def test_pic(self): ''' Test that -fPIC is correctly added to static libraries when b_staticpic is true and not when it is false. This can't be an ordinary test case because we need to inspect the compiler database. ''' if is_windows() or is_cygwin() or is_osx(): raise unittest.SkipTest('PIC not relevant') testdir = os.path.join(self.common_test_dir, '3 static') self.init(testdir) compdb = self.get_compdb() self.assertIn('-fPIC', compdb[0]['command']) self.setconf('-Db_staticpic=false') # Regenerate build self.build() compdb = self.get_compdb() self.assertNotIn('-fPIC', compdb[0]['command']) @mock.patch.dict(os.environ) def test_pkgconfig_gen(self): ''' Test that generated pkg-config files can be found and have the correct version and link args. This can't be an ordinary test case because we need to run pkg-config outside of a Meson build file. https://github.com/mesonbuild/meson/issues/889 ''' testdir = os.path.join(self.common_test_dir, '45 pkgconfig-gen') self.init(testdir) env = get_fake_env(testdir, self.builddir, self.prefix) kwargs = {'required': True, 'silent': True} os.environ['PKG_CONFIG_LIBDIR'] = self.privatedir foo_dep = PkgConfigDependency('libfoo', env, kwargs) self.assertTrue(foo_dep.found()) self.assertEqual(foo_dep.get_version(), '1.0') self.assertIn('-lfoo', foo_dep.get_link_args()) self.assertEqual(foo_dep.get_pkgconfig_variable('foo', {}), 'bar') self.assertPathEqual(foo_dep.get_pkgconfig_variable('datadir', {}), '/usr/data') libhello_nolib = PkgConfigDependency('libhello_nolib', env, kwargs) self.assertTrue(libhello_nolib.found()) self.assertEqual(libhello_nolib.get_link_args(), []) self.assertEqual(libhello_nolib.get_compile_args(), []) self.assertEqual(libhello_nolib.get_pkgconfig_variable('foo', {}), 'bar') def test_pkgconfig_gen_deps(self): ''' Test that generated pkg-config files correctly handle dependencies ''' testdir = os.path.join(self.common_test_dir, '45 pkgconfig-gen') self.init(testdir) privatedir1 = self.privatedir self.new_builddir() testdir = os.path.join(self.common_test_dir, '45 pkgconfig-gen', 'dependencies') self.init(testdir, override_envvars={'PKG_CONFIG_LIBDIR': privatedir1}) privatedir2 = self.privatedir env = { 'PKG_CONFIG_LIBDIR': os.pathsep.join([privatedir1, privatedir2]), 'PKG_CONFIG_SYSTEM_LIBRARY_PATH': '/usr/lib', } self._run(['pkg-config', 'dependency-test', '--validate'], override_envvars=env) # pkg-config strips some duplicated flags so we have to parse the # generated file ourself. expected = { 'Requires': 'libexposed', 'Requires.private': 'libfoo >= 1.0', 'Libs': '-L${libdir} -llibmain -pthread -lcustom', 'Libs.private': '-lcustom2 -L${libdir} -llibinternal', 'Cflags': '-I${includedir} -pthread -DCUSTOM', } if is_osx() or is_haiku(): expected['Cflags'] = expected['Cflags'].replace('-pthread ', '') with open(os.path.join(privatedir2, 'dependency-test.pc')) as f: matched_lines = 0 for line in f: parts = line.split(':', 1) if parts[0] in expected: key = parts[0] val = parts[1].strip() expected_val = expected[key] self.assertEqual(expected_val, val) matched_lines += 1 self.assertEqual(len(expected), matched_lines) cmd = ['pkg-config', 'requires-test'] out = self._run(cmd + ['--print-requires'], override_envvars=env).strip().split('\n') if not is_openbsd(): self.assertEqual(sorted(out), sorted(['libexposed', 'libfoo >= 1.0', 'libhello'])) else: self.assertEqual(sorted(out), sorted(['libexposed', 'libfoo>=1.0', 'libhello'])) cmd = ['pkg-config', 'requires-private-test'] out = self._run(cmd + ['--print-requires-private'], override_envvars=env).strip().split('\n') if not is_openbsd(): self.assertEqual(sorted(out), sorted(['libexposed', 'libfoo >= 1.0', 'libhello'])) else: self.assertEqual(sorted(out), sorted(['libexposed', 'libfoo>=1.0', 'libhello'])) cmd = ['pkg-config', 'pub-lib-order'] out = self._run(cmd + ['--libs'], override_envvars=env).strip().split() self.assertEqual(out, ['-llibmain2', '-llibinternal']) # See common/45 pkgconfig-gen/meson.build for description of the case this test with open(os.path.join(privatedir1, 'simple2.pc')) as f: content = f.read() self.assertIn('Libs: -L${libdir} -lsimple2 -lsimple1', content) self.assertIn('Libs.private: -lz', content) with open(os.path.join(privatedir1, 'simple3.pc')) as f: content = f.read() self.assertEqual(1, content.count('-lsimple3')) with open(os.path.join(privatedir1, 'simple5.pc')) as f: content = f.read() self.assertNotIn('-lstat2', content) @mock.patch.dict(os.environ) def test_pkgconfig_uninstalled(self): testdir = os.path.join(self.common_test_dir, '45 pkgconfig-gen') self.init(testdir) self.build() os.environ['PKG_CONFIG_LIBDIR'] = os.path.join(self.builddir, 'meson-uninstalled') if is_cygwin(): os.environ['PATH'] += os.pathsep + self.builddir self.new_builddir() testdir = os.path.join(self.common_test_dir, '45 pkgconfig-gen', 'dependencies') self.init(testdir) self.build() self.run_tests() def test_pkg_unfound(self): testdir = os.path.join(self.unit_test_dir, '23 unfound pkgconfig') self.init(testdir) with open(os.path.join(self.privatedir, 'somename.pc')) as f: pcfile = f.read() self.assertFalse('blub_blob_blib' in pcfile) def test_vala_c_warnings(self): ''' Test that no warnings are emitted for C code generated by Vala. This can't be an ordinary test case because we need to inspect the compiler database. https://github.com/mesonbuild/meson/issues/864 ''' if not shutil.which('valac'): raise unittest.SkipTest('valac not installed.') testdir = os.path.join(self.vala_test_dir, '5 target glib') self.init(testdir) compdb = self.get_compdb() vala_command = None c_command = None for each in compdb: if each['file'].endswith('GLib.Thread.c'): vala_command = each['command'] elif each['file'].endswith('GLib.Thread.vala'): continue elif each['file'].endswith('retcode.c'): c_command = each['command'] else: m = 'Unknown file {!r} in vala_c_warnings test'.format(each['file']) raise AssertionError(m) self.assertIsNotNone(vala_command) self.assertIsNotNone(c_command) # -w suppresses all warnings, should be there in Vala but not in C self.assertIn(" -w ", vala_command) self.assertNotIn(" -w ", c_command) # -Wall enables all warnings, should be there in C but not in Vala self.assertNotIn(" -Wall ", vala_command) self.assertIn(" -Wall ", c_command) # -Werror converts warnings to errors, should always be there since it's # injected by an unrelated piece of code and the project has werror=true self.assertIn(" -Werror ", vala_command) self.assertIn(" -Werror ", c_command) @skipIfNoPkgconfig def test_qtdependency_pkgconfig_detection(self): ''' Test that qt4 and qt5 detection with pkgconfig works. ''' # Verify Qt4 or Qt5 can be found with pkg-config qt4 = subprocess.call(['pkg-config', '--exists', 'QtCore']) qt5 = subprocess.call(['pkg-config', '--exists', 'Qt5Core']) testdir = os.path.join(self.framework_test_dir, '4 qt') self.init(testdir, extra_args=['-Dmethod=pkg-config']) # Confirm that the dependency was found with pkg-config mesonlog = self.get_meson_log() if qt4 == 0: self.assertRegex('\n'.join(mesonlog), r'Run-time dependency qt4 \(modules: Core\) found: YES 4.* \(pkg-config\)\n') if qt5 == 0: self.assertRegex('\n'.join(mesonlog), r'Run-time dependency qt5 \(modules: Core\) found: YES 5.* \(pkg-config\)\n') @skip_if_not_base_option('b_sanitize') def test_generate_gir_with_address_sanitizer(self): if is_cygwin(): raise unittest.SkipTest('asan not available on Cygwin') if is_openbsd(): raise unittest.SkipTest('-fsanitize=address is not supported on OpenBSD') testdir = os.path.join(self.framework_test_dir, '7 gnome') self.init(testdir, extra_args=['-Db_sanitize=address', '-Db_lundef=false']) self.build() def test_qt5dependency_qmake_detection(self): ''' Test that qt5 detection with qmake works. This can't be an ordinary test case because it involves setting the environment. ''' # Verify that qmake is for Qt5 if not shutil.which('qmake-qt5'): if not shutil.which('qmake'): raise unittest.SkipTest('QMake not found') output = subprocess.getoutput('qmake --version') if 'Qt version 5' not in output: raise unittest.SkipTest('Qmake found, but it is not for Qt 5.') # Disable pkg-config codepath and force searching with qmake/qmake-qt5 testdir = os.path.join(self.framework_test_dir, '4 qt') self.init(testdir, extra_args=['-Dmethod=qmake']) # Confirm that the dependency was found with qmake mesonlog = self.get_meson_log() self.assertRegex('\n'.join(mesonlog), r'Run-time dependency qt5 \(modules: Core\) found: YES .* \((qmake|qmake-qt5)\)\n') def test_qt6dependency_qmake_detection(self): ''' Test that qt6 detection with qmake works. This can't be an ordinary test case because it involves setting the environment. ''' # Verify that qmake is for Qt5 if not shutil.which('qmake-qt6'): if not shutil.which('qmake'): raise unittest.SkipTest('QMake not found') output = subprocess.getoutput('qmake --version') if 'Qt version 6' not in output: raise unittest.SkipTest('Qmake found, but it is not for Qt 6.') # Disable pkg-config codepath and force searching with qmake/qmake-qt6 testdir = os.path.join(self.framework_test_dir, '4 qt') self.init(testdir, extra_args=['-Dmethod=qmake']) # Confirm that the dependency was found with qmake mesonlog = self.get_meson_log() self.assertRegex('\n'.join(mesonlog), r'Run-time dependency qt6 \(modules: Core\) found: YES .* \((qmake|qmake-qt6)\)\n') def glob_sofiles_without_privdir(self, g): files = glob(g) return [f for f in files if not f.endswith('.p')] def _test_soname_impl(self, libpath, install): if is_cygwin() or is_osx(): raise unittest.SkipTest('Test only applicable to ELF and linuxlike sonames') testdir = os.path.join(self.unit_test_dir, '1 soname') self.init(testdir) self.build() if install: self.install() # File without aliases set. nover = os.path.join(libpath, 'libnover.so') self.assertPathExists(nover) self.assertFalse(os.path.islink(nover)) self.assertEqual(get_soname(nover), 'libnover.so') self.assertEqual(len(self.glob_sofiles_without_privdir(nover[:-3] + '*')), 1) # File with version set verset = os.path.join(libpath, 'libverset.so') self.assertPathExists(verset + '.4.5.6') self.assertEqual(os.readlink(verset), 'libverset.so.4') self.assertEqual(get_soname(verset), 'libverset.so.4') self.assertEqual(len(self.glob_sofiles_without_privdir(verset[:-3] + '*')), 3) # File with soversion set soverset = os.path.join(libpath, 'libsoverset.so') self.assertPathExists(soverset + '.1.2.3') self.assertEqual(os.readlink(soverset), 'libsoverset.so.1.2.3') self.assertEqual(get_soname(soverset), 'libsoverset.so.1.2.3') self.assertEqual(len(self.glob_sofiles_without_privdir(soverset[:-3] + '*')), 2) # File with version and soversion set to same values settosame = os.path.join(libpath, 'libsettosame.so') self.assertPathExists(settosame + '.7.8.9') self.assertEqual(os.readlink(settosame), 'libsettosame.so.7.8.9') self.assertEqual(get_soname(settosame), 'libsettosame.so.7.8.9') self.assertEqual(len(self.glob_sofiles_without_privdir(settosame[:-3] + '*')), 2) # File with version and soversion set to different values bothset = os.path.join(libpath, 'libbothset.so') self.assertPathExists(bothset + '.1.2.3') self.assertEqual(os.readlink(bothset), 'libbothset.so.1.2.3') self.assertEqual(os.readlink(bothset + '.1.2.3'), 'libbothset.so.4.5.6') self.assertEqual(get_soname(bothset), 'libbothset.so.1.2.3') self.assertEqual(len(self.glob_sofiles_without_privdir(bothset[:-3] + '*')), 3) def test_soname(self): self._test_soname_impl(self.builddir, False) def test_installed_soname(self): libdir = self.installdir + os.path.join(self.prefix, self.libdir) self._test_soname_impl(libdir, True) def test_compiler_check_flags_order(self): ''' Test that compiler check flags override all other flags. This can't be an ordinary test case because it needs the environment to be set. ''' testdir = os.path.join(self.common_test_dir, '37 has function') env = get_fake_env(testdir, self.builddir, self.prefix) cpp = env.detect_cpp_compiler(MachineChoice.HOST) Oflag = '-O3' OflagCPP = Oflag if cpp.get_id() in ('clang', 'gcc'): # prevent developers from adding "int main(int argc, char **argv)" # to small Meson checks unless these parameters are actually used OflagCPP += ' -Werror=unused-parameter' env = {'CFLAGS': Oflag, 'CXXFLAGS': OflagCPP} self.init(testdir, override_envvars=env) cmds = self.get_meson_log_compiler_checks() for cmd in cmds: if cmd[0] == 'ccache': cmd = cmd[1:] # Verify that -I flags from the `args` kwarg are first # This is set in the '37 has function' test case self.assertEqual(cmd[1], '-I/tmp') # Verify that -O3 set via the environment is overridden by -O0 Oargs = [arg for arg in cmd if arg.startswith('-O')] self.assertEqual(Oargs, [Oflag, '-O0']) def _test_stds_impl(self, testdir: str, compiler: 'Compiler') -> None: has_cpp17 = (compiler.get_id() not in {'clang', 'gcc'} or compiler.get_id() == 'clang' and _clang_at_least(compiler, '>=5.0.0', '>=9.1') or compiler.get_id() == 'gcc' and version_compare(compiler.version, '>=5.0.0')) has_cpp2a_c17 = (compiler.get_id() not in {'clang', 'gcc'} or compiler.get_id() == 'clang' and _clang_at_least(compiler, '>=6.0.0', '>=10.0') or compiler.get_id() == 'gcc' and version_compare(compiler.version, '>=8.0.0')) has_cpp20 = (compiler.get_id() not in {'clang', 'gcc'} or compiler.get_id() == 'clang' and _clang_at_least(compiler, '>=10.0.0', None) or compiler.get_id() == 'gcc' and version_compare(compiler.version, '>=10.0.0')) has_c18 = (compiler.get_id() not in {'clang', 'gcc'} or compiler.get_id() == 'clang' and _clang_at_least(compiler, '>=8.0.0', '>=11.0') or compiler.get_id() == 'gcc' and version_compare(compiler.version, '>=8.0.0')) # Check that all the listed -std=xxx options for this compiler work just fine when used # https://en.wikipedia.org/wiki/Xcode#Latest_versions # https://www.gnu.org/software/gcc/projects/cxx-status.html key = OptionKey('std', lang=compiler.language) for v in compiler.get_options()[key].choices: # we do it like this to handle gnu++17,c++17 and gnu17,c17 cleanly # thus, C++ first if '++17' in v and not has_cpp17: continue elif '++2a' in v and not has_cpp2a_c17: # https://en.cppreference.com/w/cpp/compiler_support continue elif '++20' in v and not has_cpp20: continue # now C elif '17' in v and not has_cpp2a_c17: continue elif '18' in v and not has_c18: continue self.init(testdir, extra_args=[f'-D{key!s}={v}']) cmd = self.get_compdb()[0]['command'] # c++03 and gnu++03 are not understood by ICC, don't try to look for them skiplist = frozenset([ ('intel', 'c++03'), ('intel', 'gnu++03')]) if v != 'none' and not (compiler.get_id(), v) in skiplist: cmd_std = " -std={} ".format(v) self.assertIn(cmd_std, cmd) try: self.build() except Exception: print(f'{key!s} was {v!r}') raise self.wipe() # Check that an invalid std option in CFLAGS/CPPFLAGS fails # Needed because by default ICC ignores invalid options cmd_std = '-std=FAIL' if compiler.language == 'c': env_flag_name = 'CFLAGS' elif compiler.language == 'cpp': env_flag_name = 'CXXFLAGS' else: raise NotImplementedError('Language {} not defined.'.format(compiler.language)) env = {} env[env_flag_name] = cmd_std with self.assertRaises((subprocess.CalledProcessError, mesonbuild.mesonlib.EnvironmentException), msg='C compiler should have failed with -std=FAIL'): self.init(testdir, override_envvars = env) # ICC won't fail in the above because additional flags are needed to # make unknown -std=... options errors. self.build() def test_compiler_c_stds(self): ''' Test that C stds specified for this compiler can all be used. Can't be an ordinary test because it requires passing options to meson. ''' testdir = os.path.join(self.common_test_dir, '1 trivial') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) self._test_stds_impl(testdir, cc) def test_compiler_cpp_stds(self): ''' Test that C++ stds specified for this compiler can all be used. Can't be an ordinary test because it requires passing options to meson. ''' testdir = os.path.join(self.common_test_dir, '2 cpp') env = get_fake_env(testdir, self.builddir, self.prefix) cpp = env.detect_cpp_compiler(MachineChoice.HOST) self._test_stds_impl(testdir, cpp) def test_unity_subproj(self): testdir = os.path.join(self.common_test_dir, '43 subproject') self.init(testdir, extra_args='--unity=subprojects') pdirs = glob(os.path.join(self.builddir, 'subprojects/sublib/simpletest*.p')) self.assertEqual(len(pdirs), 1) self.assertPathExists(os.path.join(pdirs[0], 'simpletest-unity0.c')) sdirs = glob(os.path.join(self.builddir, 'subprojects/sublib/*sublib*.p')) self.assertEqual(len(sdirs), 1) self.assertPathExists(os.path.join(sdirs[0], 'sublib-unity0.c')) self.assertPathDoesNotExist(os.path.join(self.builddir, 'user@exe/user-unity.c')) self.build() def test_installed_modes(self): ''' Test that files installed by these tests have the correct permissions. Can't be an ordinary test because our installed_files.txt is very basic. ''' # Test file modes testdir = os.path.join(self.common_test_dir, '12 data') self.init(testdir) self.install() f = os.path.join(self.installdir, 'etc', 'etcfile.dat') found_mode = stat.filemode(os.stat(f).st_mode) want_mode = 'rw------T' self.assertEqual(want_mode, found_mode[1:]) f = os.path.join(self.installdir, 'usr', 'bin', 'runscript.sh') statf = os.stat(f) found_mode = stat.filemode(statf.st_mode) want_mode = 'rwxr-sr-x' self.assertEqual(want_mode, found_mode[1:]) if os.getuid() == 0: # The chown failed nonfatally if we're not root self.assertEqual(0, statf.st_uid) self.assertEqual(0, statf.st_gid) f = os.path.join(self.installdir, 'usr', 'share', 'progname', 'fileobject_datafile.dat') orig = os.path.join(testdir, 'fileobject_datafile.dat') statf = os.stat(f) statorig = os.stat(orig) found_mode = stat.filemode(statf.st_mode) orig_mode = stat.filemode(statorig.st_mode) self.assertEqual(orig_mode[1:], found_mode[1:]) self.assertEqual(os.getuid(), statf.st_uid) if os.getuid() == 0: # The chown failed nonfatally if we're not root self.assertEqual(0, statf.st_gid) self.wipe() # Test directory modes testdir = os.path.join(self.common_test_dir, '60 install subdir') self.init(testdir) self.install() f = os.path.join(self.installdir, 'usr', 'share', 'sub1', 'second.dat') statf = os.stat(f) found_mode = stat.filemode(statf.st_mode) want_mode = 'rwxr-x--t' self.assertEqual(want_mode, found_mode[1:]) if os.getuid() == 0: # The chown failed nonfatally if we're not root self.assertEqual(0, statf.st_uid) def test_installed_modes_extended(self): ''' Test that files are installed with correct permissions using install_mode. ''' testdir = os.path.join(self.common_test_dir, '191 install_mode') self.init(testdir) self.build() self.install() for fsobj, want_mode in [ ('bin', 'drwxr-x---'), ('bin/runscript.sh', '-rwxr-sr-x'), ('bin/trivialprog', '-rwxr-sr-x'), ('include', 'drwxr-x---'), ('include/config.h', '-rw-rwSr--'), ('include/rootdir.h', '-r--r--r-T'), ('lib', 'drwxr-x---'), ('lib/libstat.a', '-rw---Sr--'), ('share', 'drwxr-x---'), ('share/man', 'drwxr-x---'), ('share/man/man1', 'drwxr-x---'), ('share/man/man1/foo.1', '-r--r--r-T'), ('share/sub1', 'drwxr-x---'), ('share/sub1/second.dat', '-rwxr-x--t'), ('subdir', 'drwxr-x---'), ('subdir/data.dat', '-rw-rwSr--'), ]: f = os.path.join(self.installdir, 'usr', *fsobj.split('/')) found_mode = stat.filemode(os.stat(f).st_mode) self.assertEqual(want_mode, found_mode, msg=('Expected file %s to have mode %s but found %s instead.' % (fsobj, want_mode, found_mode))) # Ensure that introspect --installed works on all types of files # FIXME: also verify the files list self.introspect('--installed') def test_install_umask(self): ''' Test that files are installed with correct permissions using default install umask of 022, regardless of the umask at time the worktree was checked out or the build was executed. ''' # Copy source tree to a temporary directory and change permissions # there to simulate a checkout with umask 002. orig_testdir = os.path.join(self.unit_test_dir, '26 install umask') # Create a new testdir under tmpdir. tmpdir = os.path.realpath(tempfile.mkdtemp()) self.addCleanup(windows_proof_rmtree, tmpdir) testdir = os.path.join(tmpdir, '26 install umask') # Copy the tree using shutil.copyfile, which will use the current umask # instead of preserving permissions of the old tree. save_umask = os.umask(0o002) self.addCleanup(os.umask, save_umask) shutil.copytree(orig_testdir, testdir, copy_function=shutil.copyfile) # Preserve the executable status of subdir/sayhello though. os.chmod(os.path.join(testdir, 'subdir', 'sayhello'), 0o775) self.init(testdir) # Run the build under a 027 umask now. os.umask(0o027) self.build() # And keep umask 027 for the install step too. self.install() for executable in [ 'bin/prog', 'share/subdir/sayhello', ]: f = os.path.join(self.installdir, 'usr', *executable.split('/')) found_mode = stat.filemode(os.stat(f).st_mode) want_mode = '-rwxr-xr-x' self.assertEqual(want_mode, found_mode, msg=('Expected file %s to have mode %s but found %s instead.' % (executable, want_mode, found_mode))) for directory in [ 'usr', 'usr/bin', 'usr/include', 'usr/share', 'usr/share/man', 'usr/share/man/man1', 'usr/share/subdir', ]: f = os.path.join(self.installdir, *directory.split('/')) found_mode = stat.filemode(os.stat(f).st_mode) want_mode = 'drwxr-xr-x' self.assertEqual(want_mode, found_mode, msg=('Expected directory %s to have mode %s but found %s instead.' % (directory, want_mode, found_mode))) for datafile in [ 'include/sample.h', 'share/datafile.cat', 'share/file.dat', 'share/man/man1/prog.1', 'share/subdir/datafile.dog', ]: f = os.path.join(self.installdir, 'usr', *datafile.split('/')) found_mode = stat.filemode(os.stat(f).st_mode) want_mode = '-rw-r--r--' self.assertEqual(want_mode, found_mode, msg=('Expected file %s to have mode %s but found %s instead.' % (datafile, want_mode, found_mode))) def test_cpp_std_override(self): testdir = os.path.join(self.unit_test_dir, '6 std override') self.init(testdir) compdb = self.get_compdb() # Don't try to use -std=c++03 as a check for the # presence of a compiler flag, as ICC does not # support it. for i in compdb: if 'prog98' in i['file']: c98_comp = i['command'] if 'prog11' in i['file']: c11_comp = i['command'] if 'progp' in i['file']: plain_comp = i['command'] self.assertNotEqual(len(plain_comp), 0) self.assertIn('-std=c++98', c98_comp) self.assertNotIn('-std=c++11', c98_comp) self.assertIn('-std=c++11', c11_comp) self.assertNotIn('-std=c++98', c11_comp) self.assertNotIn('-std=c++98', plain_comp) self.assertNotIn('-std=c++11', plain_comp) # Now werror self.assertIn('-Werror', plain_comp) self.assertNotIn('-Werror', c98_comp) def test_run_installed(self): if is_cygwin() or is_osx(): raise unittest.SkipTest('LD_LIBRARY_PATH and RPATH not applicable') testdir = os.path.join(self.unit_test_dir, '7 run installed') self.init(testdir) self.build() self.install() installed_exe = os.path.join(self.installdir, 'usr/bin/prog') installed_libdir = os.path.join(self.installdir, 'usr/foo') installed_lib = os.path.join(installed_libdir, 'libfoo.so') self.assertTrue(os.path.isfile(installed_exe)) self.assertTrue(os.path.isdir(installed_libdir)) self.assertTrue(os.path.isfile(installed_lib)) # Must fail when run without LD_LIBRARY_PATH to ensure that # rpath has been properly stripped rather than pointing to the builddir. self.assertNotEqual(subprocess.call(installed_exe, stderr=subprocess.DEVNULL), 0) # When LD_LIBRARY_PATH is set it should start working. # For some reason setting LD_LIBRARY_PATH in os.environ fails # when all tests are run (but works when only this test is run), # but doing this explicitly works. env = os.environ.copy() env['LD_LIBRARY_PATH'] = ':'.join([installed_libdir, env.get('LD_LIBRARY_PATH', '')]) self.assertEqual(subprocess.call(installed_exe, env=env), 0) # Ensure that introspect --installed works installed = self.introspect('--installed') for v in installed.values(): self.assertTrue('prog' in v or 'foo' in v) @skipIfNoPkgconfig def test_order_of_l_arguments(self): testdir = os.path.join(self.unit_test_dir, '8 -L -l order') self.init(testdir, override_envvars={'PKG_CONFIG_PATH': testdir}) # NOTE: .pc file has -Lfoo -lfoo -Lbar -lbar but pkg-config reorders # the flags before returning them to -Lfoo -Lbar -lfoo -lbar # but pkgconf seems to not do that. Sigh. Support both. expected_order = [('-L/me/first', '-lfoo1'), ('-L/me/second', '-lfoo2'), ('-L/me/first', '-L/me/second'), ('-lfoo1', '-lfoo2'), ('-L/me/second', '-L/me/third'), ('-L/me/third', '-L/me/fourth',), ('-L/me/third', '-lfoo3'), ('-L/me/fourth', '-lfoo4'), ('-lfoo3', '-lfoo4'), ] with open(os.path.join(self.builddir, 'build.ninja')) as ifile: for line in ifile: if expected_order[0][0] in line: for first, second in expected_order: self.assertLess(line.index(first), line.index(second)) return raise RuntimeError('Linker entries not found in the Ninja file.') def test_introspect_dependencies(self): ''' Tests that mesonintrospect --dependencies returns expected output. ''' testdir = os.path.join(self.framework_test_dir, '7 gnome') self.init(testdir) glib_found = False gobject_found = False deps = self.introspect('--dependencies') self.assertIsInstance(deps, list) for dep in deps: self.assertIsInstance(dep, dict) self.assertIn('name', dep) self.assertIn('compile_args', dep) self.assertIn('link_args', dep) if dep['name'] == 'glib-2.0': glib_found = True elif dep['name'] == 'gobject-2.0': gobject_found = True self.assertTrue(glib_found) self.assertTrue(gobject_found) if subprocess.call(['pkg-config', '--exists', 'glib-2.0 >= 2.56.2']) != 0: raise unittest.SkipTest('glib >= 2.56.2 needed for the rest') targets = self.introspect('--targets') docbook_target = None for t in targets: if t['name'] == 'generated-gdbus-docbook': docbook_target = t break self.assertIsInstance(docbook_target, dict) self.assertEqual(os.path.basename(t['filename'][0]), 'generated-gdbus-doc-' + os.path.basename(t['target_sources'][0]['sources'][0])) def test_introspect_installed(self): testdir = os.path.join(self.linuxlike_test_dir, '7 library versions') self.init(testdir) install = self.introspect('--installed') install = {os.path.basename(k): v for k, v in install.items()} print(install) if is_osx(): the_truth = { 'libmodule.dylib': '/usr/lib/libmodule.dylib', 'libnoversion.dylib': '/usr/lib/libnoversion.dylib', 'libonlysoversion.5.dylib': '/usr/lib/libonlysoversion.5.dylib', 'libonlysoversion.dylib': '/usr/lib/libonlysoversion.dylib', 'libonlyversion.1.dylib': '/usr/lib/libonlyversion.1.dylib', 'libonlyversion.dylib': '/usr/lib/libonlyversion.dylib', 'libsome.0.dylib': '/usr/lib/libsome.0.dylib', 'libsome.dylib': '/usr/lib/libsome.dylib', } the_truth_2 = {'/usr/lib/libsome.dylib', '/usr/lib/libsome.0.dylib', } else: the_truth = { 'libmodule.so': '/usr/lib/libmodule.so', 'libnoversion.so': '/usr/lib/libnoversion.so', 'libonlysoversion.so': '/usr/lib/libonlysoversion.so', 'libonlysoversion.so.5': '/usr/lib/libonlysoversion.so.5', 'libonlyversion.so': '/usr/lib/libonlyversion.so', 'libonlyversion.so.1': '/usr/lib/libonlyversion.so.1', 'libonlyversion.so.1.4.5': '/usr/lib/libonlyversion.so.1.4.5', 'libsome.so': '/usr/lib/libsome.so', 'libsome.so.0': '/usr/lib/libsome.so.0', 'libsome.so.1.2.3': '/usr/lib/libsome.so.1.2.3', } the_truth_2 = {'/usr/lib/libsome.so', '/usr/lib/libsome.so.0', '/usr/lib/libsome.so.1.2.3'} self.assertDictEqual(install, the_truth) targets = self.introspect('--targets') for t in targets: if t['name'] != 'some': continue self.assertSetEqual(the_truth_2, set(t['install_filename'])) def test_build_rpath(self): if is_cygwin(): raise unittest.SkipTest('Windows PE/COFF binaries do not use RPATH') testdir = os.path.join(self.unit_test_dir, '10 build_rpath') self.init(testdir) self.build() build_rpath = get_rpath(os.path.join(self.builddir, 'prog')) self.assertEqual(build_rpath, '$ORIGIN/sub:/foo/bar') build_rpath = get_rpath(os.path.join(self.builddir, 'progcxx')) self.assertEqual(build_rpath, '$ORIGIN/sub:/foo/bar') self.install() install_rpath = get_rpath(os.path.join(self.installdir, 'usr/bin/prog')) self.assertEqual(install_rpath, '/baz') install_rpath = get_rpath(os.path.join(self.installdir, 'usr/bin/progcxx')) self.assertEqual(install_rpath, 'baz') @skipIfNoPkgconfig def test_build_rpath_pkgconfig(self): ''' Test that current build artefacts (libs) are found first on the rpath, manually specified rpath comes second and additional rpath elements (from pkg-config files) come last ''' if is_cygwin(): raise unittest.SkipTest('Windows PE/COFF binaries do not use RPATH') testdir = os.path.join(self.unit_test_dir, '90 pkgconfig build rpath order') self.init(testdir, override_envvars={'PKG_CONFIG_PATH': testdir}) self.build() build_rpath = get_rpath(os.path.join(self.builddir, 'prog')) self.assertEqual(build_rpath, '$ORIGIN/sub:/foo/bar:/foo/dummy') build_rpath = get_rpath(os.path.join(self.builddir, 'progcxx')) self.assertEqual(build_rpath, '$ORIGIN/sub:/foo/bar:/foo/dummy') self.install() install_rpath = get_rpath(os.path.join(self.installdir, 'usr/bin/prog')) self.assertEqual(install_rpath, '/baz:/foo/dummy') install_rpath = get_rpath(os.path.join(self.installdir, 'usr/bin/progcxx')) self.assertEqual(install_rpath, 'baz:/foo/dummy') def test_global_rpath(self): if is_cygwin(): raise unittest.SkipTest('Windows PE/COFF binaries do not use RPATH') if is_osx(): raise unittest.SkipTest('Global RPATHs via LDFLAGS not yet supported on MacOS (does anybody need it?)') testdir = os.path.join(self.unit_test_dir, '81 global-rpath') oldinstalldir = self.installdir # Build and install an external library without DESTDIR. # The external library generates a .pc file without an rpath. yonder_dir = os.path.join(testdir, 'yonder') yonder_prefix = os.path.join(oldinstalldir, 'yonder') yonder_libdir = os.path.join(yonder_prefix, self.libdir) self.prefix = yonder_prefix self.installdir = yonder_prefix self.init(yonder_dir) self.build() self.install(use_destdir=False) # Since rpath has multiple valid formats we need to # test that they are all properly used. rpath_formats = [ ('-Wl,-rpath=', False), ('-Wl,-rpath,', False), ('-Wl,--just-symbols=', True), ('-Wl,--just-symbols,', True), ('-Wl,-R', False), ('-Wl,-R,', False) ] for rpath_format, exception in rpath_formats: # Build an app that uses that installed library. # Supply the rpath to the installed library via LDFLAGS # (as systems like buildroot and guix are wont to do) # and verify install preserves that rpath. self.new_builddir() env = {'LDFLAGS': rpath_format + yonder_libdir, 'PKG_CONFIG_PATH': os.path.join(yonder_libdir, 'pkgconfig')} if exception: with self.assertRaises(subprocess.CalledProcessError): self.init(testdir, override_envvars=env) continue self.init(testdir, override_envvars=env) self.build() self.install(use_destdir=False) got_rpath = get_rpath(os.path.join(yonder_prefix, 'bin/rpathified')) self.assertEqual(got_rpath, yonder_libdir, rpath_format) @skip_if_not_base_option('b_sanitize') def test_pch_with_address_sanitizer(self): if is_cygwin(): raise unittest.SkipTest('asan not available on Cygwin') if is_openbsd(): raise unittest.SkipTest('-fsanitize=address is not supported on OpenBSD') testdir = os.path.join(self.common_test_dir, '13 pch') self.init(testdir, extra_args=['-Db_sanitize=address', '-Db_lundef=false']) self.build() compdb = self.get_compdb() for i in compdb: self.assertIn("-fsanitize=address", i["command"]) def test_cross_find_program(self): testdir = os.path.join(self.unit_test_dir, '11 cross prog') crossfile = tempfile.NamedTemporaryFile(mode='w') print(os.path.join(testdir, 'some_cross_tool.py')) tool_path = os.path.join(testdir, 'some_cross_tool.py') crossfile.write(textwrap.dedent(f'''\ [binaries] c = '{shutil.which('gcc' if is_sunos() else 'cc')}' ar = '{shutil.which('ar')}' strip = '{shutil.which('strip')}' sometool.py = ['{tool_path}'] someothertool.py = '{tool_path}' [properties] [host_machine] system = 'linux' cpu_family = 'arm' cpu = 'armv7' # Not sure if correct. endian = 'little' ''')) crossfile.flush() self.meson_cross_file = crossfile.name self.init(testdir) def test_reconfigure(self): testdir = os.path.join(self.unit_test_dir, '13 reconfigure') self.init(testdir, extra_args=['-Db_coverage=true'], default_args=False) self.build('reconfigure') def test_vala_generated_source_buildir_inside_source_tree(self): ''' Test that valac outputs generated C files in the expected location when the builddir is a subdir of the source tree. ''' if not shutil.which('valac'): raise unittest.SkipTest('valac not installed.') testdir = os.path.join(self.vala_test_dir, '8 generated sources') newdir = os.path.join(self.builddir, 'srctree') shutil.copytree(testdir, newdir) testdir = newdir # New builddir builddir = os.path.join(testdir, 'subdir/_build') os.makedirs(builddir, exist_ok=True) self.change_builddir(builddir) self.init(testdir) self.build() def test_old_gnome_module_codepaths(self): ''' A lot of code in the GNOME module is conditional on the version of the glib tools that are installed, and breakages in the old code can slip by once the CI has a newer glib version. So we force the GNOME module to pretend that it's running on an ancient glib so the fallback code is also tested. ''' testdir = os.path.join(self.framework_test_dir, '7 gnome') mesonbuild.modules.gnome.native_glib_version = '2.20' env = {'MESON_UNIT_TEST_PRETEND_GLIB_OLD': "1"} try: self.init(testdir, inprocess=True, override_envvars=env) self.build(override_envvars=env) finally: mesonbuild.modules.gnome.native_glib_version = None @skipIfNoPkgconfig def test_pkgconfig_usage(self): testdir1 = os.path.join(self.unit_test_dir, '27 pkgconfig usage/dependency') testdir2 = os.path.join(self.unit_test_dir, '27 pkgconfig usage/dependee') if subprocess.call(['pkg-config', '--cflags', 'glib-2.0'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) != 0: raise unittest.SkipTest('Glib 2.0 dependency not available.') with tempfile.TemporaryDirectory() as tempdirname: self.init(testdir1, extra_args=['--prefix=' + tempdirname, '--libdir=lib'], default_args=False) self.install(use_destdir=False) shutil.rmtree(self.builddir) os.mkdir(self.builddir) pkg_dir = os.path.join(tempdirname, 'lib/pkgconfig') self.assertTrue(os.path.exists(os.path.join(pkg_dir, 'libpkgdep.pc'))) lib_dir = os.path.join(tempdirname, 'lib') myenv = os.environ.copy() myenv['PKG_CONFIG_PATH'] = pkg_dir # Private internal libraries must not leak out. pkg_out = subprocess.check_output(['pkg-config', '--static', '--libs', 'libpkgdep'], env=myenv) self.assertFalse(b'libpkgdep-int' in pkg_out, 'Internal library leaked out.') # Dependencies must not leak to cflags when building only a shared library. pkg_out = subprocess.check_output(['pkg-config', '--cflags', 'libpkgdep'], env=myenv) self.assertFalse(b'glib' in pkg_out, 'Internal dependency leaked to headers.') # Test that the result is usable. self.init(testdir2, override_envvars=myenv) self.build(override_envvars=myenv) myenv = os.environ.copy() myenv['LD_LIBRARY_PATH'] = ':'.join([lib_dir, myenv.get('LD_LIBRARY_PATH', '')]) if is_cygwin(): bin_dir = os.path.join(tempdirname, 'bin') myenv['PATH'] = bin_dir + os.pathsep + myenv['PATH'] self.assertTrue(os.path.isdir(lib_dir)) test_exe = os.path.join(self.builddir, 'pkguser') self.assertTrue(os.path.isfile(test_exe)) subprocess.check_call(test_exe, env=myenv) @skipIfNoPkgconfig def test_pkgconfig_relative_paths(self): testdir = os.path.join(self.unit_test_dir, '62 pkgconfig relative paths') pkg_dir = os.path.join(testdir, 'pkgconfig') self.assertTrue(os.path.exists(os.path.join(pkg_dir, 'librelativepath.pc'))) env = get_fake_env(testdir, self.builddir, self.prefix) env.coredata.set_options({OptionKey('pkg_config_path'): pkg_dir}, subproject='') kwargs = {'required': True, 'silent': True} relative_path_dep = PkgConfigDependency('librelativepath', env, kwargs) self.assertTrue(relative_path_dep.found()) # Ensure link_args are properly quoted libpath = Path(self.builddir) / '../relativepath/lib' link_args = ['-L' + libpath.as_posix(), '-lrelativepath'] self.assertEqual(relative_path_dep.get_link_args(), link_args) @skipIfNoPkgconfig def test_pkgconfig_internal_libraries(self): ''' ''' with tempfile.TemporaryDirectory() as tempdirname: # build library testdirbase = os.path.join(self.unit_test_dir, '32 pkgconfig use libraries') testdirlib = os.path.join(testdirbase, 'lib') self.init(testdirlib, extra_args=['--prefix=' + tempdirname, '--libdir=lib', '--default-library=static'], default_args=False) self.build() self.install(use_destdir=False) # build user of library pkg_dir = os.path.join(tempdirname, 'lib/pkgconfig') self.new_builddir() self.init(os.path.join(testdirbase, 'app'), override_envvars={'PKG_CONFIG_PATH': pkg_dir}) self.build() @skipIfNoPkgconfig def test_static_archive_stripping(self): ''' Check that Meson produces valid static archives with --strip enabled ''' with tempfile.TemporaryDirectory() as tempdirname: testdirbase = os.path.join(self.unit_test_dir, '67 static archive stripping') # build lib self.new_builddir() testdirlib = os.path.join(testdirbase, 'lib') testlibprefix = os.path.join(tempdirname, 'libprefix') self.init(testdirlib, extra_args=['--prefix=' + testlibprefix, '--libdir=lib', '--default-library=static', '--buildtype=debug', '--strip'], default_args=False) self.build() self.install(use_destdir=False) # build executable (uses lib, fails if static archive has been stripped incorrectly) pkg_dir = os.path.join(testlibprefix, 'lib/pkgconfig') self.new_builddir() self.init(os.path.join(testdirbase, 'app'), override_envvars={'PKG_CONFIG_PATH': pkg_dir}) self.build() @skipIfNoPkgconfig def test_pkgconfig_formatting(self): testdir = os.path.join(self.unit_test_dir, '38 pkgconfig format') self.init(testdir) myenv = os.environ.copy() myenv['PKG_CONFIG_PATH'] = self.privatedir stdo = subprocess.check_output(['pkg-config', '--libs-only-l', 'libsomething'], env=myenv) deps = [b'-lgobject-2.0', b'-lgio-2.0', b'-lglib-2.0', b'-lsomething'] if is_windows() or is_cygwin() or is_osx() or is_openbsd(): # On Windows, libintl is a separate library deps.append(b'-lintl') self.assertEqual(set(deps), set(stdo.split())) @skipIfNoPkgconfig @skip_if_not_language('cs') def test_pkgconfig_csharp_library(self): testdir = os.path.join(self.unit_test_dir, '50 pkgconfig csharp library') self.init(testdir) myenv = os.environ.copy() myenv['PKG_CONFIG_PATH'] = self.privatedir stdo = subprocess.check_output(['pkg-config', '--libs', 'libsomething'], env=myenv) self.assertEqual("-r/usr/lib/libsomething.dll", str(stdo.decode('ascii')).strip()) @skipIfNoPkgconfig def test_pkgconfig_link_order(self): ''' Test that libraries are listed before their dependencies. ''' testdir = os.path.join(self.unit_test_dir, '53 pkgconfig static link order') self.init(testdir) myenv = os.environ.copy() myenv['PKG_CONFIG_PATH'] = self.privatedir stdo = subprocess.check_output(['pkg-config', '--libs', 'libsomething'], env=myenv) deps = stdo.split() self.assertTrue(deps.index(b'-lsomething') < deps.index(b'-ldependency')) def test_deterministic_dep_order(self): ''' Test that the dependencies are always listed in a deterministic order. ''' testdir = os.path.join(self.unit_test_dir, '43 dep order') self.init(testdir) with open(os.path.join(self.builddir, 'build.ninja')) as bfile: for line in bfile: if 'build myexe:' in line or 'build myexe.exe:' in line: self.assertIn('liblib1.a liblib2.a', line) return raise RuntimeError('Could not find the build rule') def test_deterministic_rpath_order(self): ''' Test that the rpaths are always listed in a deterministic order. ''' if is_cygwin(): raise unittest.SkipTest('rpath are not used on Cygwin') testdir = os.path.join(self.unit_test_dir, '42 rpath order') self.init(testdir) if is_osx(): rpathre = re.compile(r'-rpath,.*/subprojects/sub1.*-rpath,.*/subprojects/sub2') else: rpathre = re.compile(r'-rpath,\$\$ORIGIN/subprojects/sub1:\$\$ORIGIN/subprojects/sub2') with open(os.path.join(self.builddir, 'build.ninja')) as bfile: for line in bfile: if '-rpath' in line: self.assertRegex(line, rpathre) return raise RuntimeError('Could not find the rpath') def test_override_with_exe_dep(self): ''' Test that we produce the correct dependencies when a program is overridden with an executable. ''' testdir = os.path.join(self.src_root, 'test cases', 'native', '9 override with exe') self.init(testdir) with open(os.path.join(self.builddir, 'build.ninja')) as bfile: for line in bfile: if 'main1.c:' in line or 'main2.c:' in line: self.assertIn('| subprojects/sub/foobar', line) @skipIfNoPkgconfig def test_usage_external_library(self): ''' Test that uninstalled usage of an external library (from the system or PkgConfigDependency) works. On macOS, this workflow works out of the box. On Linux, BSDs, Windows, etc, you need to set extra arguments such as LD_LIBRARY_PATH, etc, so this test is skipped. The system library is found with cc.find_library() and pkg-config deps. ''' oldprefix = self.prefix # Install external library so we can find it testdir = os.path.join(self.unit_test_dir, '40 external, internal library rpath', 'external library') # install into installdir without using DESTDIR installdir = self.installdir self.prefix = installdir self.init(testdir) self.prefix = oldprefix self.build() self.install(use_destdir=False) ## New builddir for the consumer self.new_builddir() env = {'LIBRARY_PATH': os.path.join(installdir, self.libdir), 'PKG_CONFIG_PATH': os.path.join(installdir, self.libdir, 'pkgconfig')} testdir = os.path.join(self.unit_test_dir, '40 external, internal library rpath', 'built library') # install into installdir without using DESTDIR self.prefix = self.installdir self.init(testdir, override_envvars=env) self.prefix = oldprefix self.build(override_envvars=env) # test uninstalled self.run_tests(override_envvars=env) if not (is_osx() or is_linux()): return # test running after installation self.install(use_destdir=False) prog = os.path.join(self.installdir, 'bin', 'prog') self._run([prog]) if not is_osx(): # Rest of the workflow only works on macOS return out = self._run(['otool', '-L', prog]) self.assertNotIn('@rpath', out) ## New builddir for testing that DESTDIR is not added to install_name self.new_builddir() # install into installdir with DESTDIR self.init(testdir, override_envvars=env) self.build(override_envvars=env) # test running after installation self.install(override_envvars=env) prog = self.installdir + os.path.join(self.prefix, 'bin', 'prog') lib = self.installdir + os.path.join(self.prefix, 'lib', 'libbar_built.dylib') for f in prog, lib: out = self._run(['otool', '-L', f]) # Ensure that the otool output does not contain self.installdir self.assertNotRegex(out, self.installdir + '.*dylib ') @skipIfNoPkgconfig def test_usage_pkgconfig_prefixes(self): ''' Build and install two external libraries, to different prefixes, then build and install a client program that finds them via pkgconfig, and verify the installed client program runs. ''' oldinstalldir = self.installdir # Build and install both external libraries without DESTDIR val1dir = os.path.join(self.unit_test_dir, '76 pkgconfig prefixes', 'val1') val1prefix = os.path.join(oldinstalldir, 'val1') self.prefix = val1prefix self.installdir = val1prefix self.init(val1dir) self.build() self.install(use_destdir=False) self.new_builddir() env1 = {} env1['PKG_CONFIG_PATH'] = os.path.join(val1prefix, self.libdir, 'pkgconfig') val2dir = os.path.join(self.unit_test_dir, '76 pkgconfig prefixes', 'val2') val2prefix = os.path.join(oldinstalldir, 'val2') self.prefix = val2prefix self.installdir = val2prefix self.init(val2dir, override_envvars=env1) self.build() self.install(use_destdir=False) self.new_builddir() # Build, install, and run the client program env2 = {} env2['PKG_CONFIG_PATH'] = os.path.join(val2prefix, self.libdir, 'pkgconfig') testdir = os.path.join(self.unit_test_dir, '76 pkgconfig prefixes', 'client') testprefix = os.path.join(oldinstalldir, 'client') self.prefix = testprefix self.installdir = testprefix self.init(testdir, override_envvars=env2) self.build() self.install(use_destdir=False) prog = os.path.join(self.installdir, 'bin', 'client') env3 = {} if is_cygwin(): env3['PATH'] = os.path.join(val1prefix, 'bin') + \ os.pathsep + \ os.path.join(val2prefix, 'bin') + \ os.pathsep + os.environ['PATH'] out = self._run([prog], override_envvars=env3).strip() # Expected output is val1 + val2 = 3 self.assertEqual(out, '3') def install_subdir_invalid_symlinks(self, testdir, subdir_path): ''' Test that installation of broken symlinks works fine. https://github.com/mesonbuild/meson/issues/3914 ''' testdir = os.path.join(self.common_test_dir, testdir) subdir = os.path.join(testdir, subdir_path) with chdir(subdir): # Can't distribute broken symlinks in the source tree because it breaks # the creation of zipapps. Create it dynamically and run the test by # hand. src = '../../nonexistent.txt' os.symlink(src, 'invalid-symlink.txt') try: self.init(testdir) self.build() self.install() install_path = subdir_path.split(os.path.sep)[-1] link = os.path.join(self.installdir, 'usr', 'share', install_path, 'invalid-symlink.txt') self.assertTrue(os.path.islink(link), msg=link) self.assertEqual(src, os.readlink(link)) self.assertFalse(os.path.isfile(link), msg=link) finally: os.remove(os.path.join(subdir, 'invalid-symlink.txt')) def test_install_subdir_symlinks(self): self.install_subdir_invalid_symlinks('60 install subdir', os.path.join('sub', 'sub1')) def test_install_subdir_symlinks_with_default_umask(self): self.install_subdir_invalid_symlinks('191 install_mode', 'sub2') def test_install_subdir_symlinks_with_default_umask_and_mode(self): self.install_subdir_invalid_symlinks('191 install_mode', 'sub1') @skipIfNoPkgconfigDep('gmodule-2.0') def test_ldflag_dedup(self): testdir = os.path.join(self.unit_test_dir, '52 ldflagdedup') if is_cygwin() or is_osx(): raise unittest.SkipTest('Not applicable on Cygwin or OSX.') env = get_fake_env() cc = env.detect_c_compiler(MachineChoice.HOST) linker = cc.linker if not linker.export_dynamic_args(env): raise unittest.SkipTest('Not applicable for linkers without --export-dynamic') self.init(testdir) build_ninja = os.path.join(self.builddir, 'build.ninja') max_count = 0 search_term = '-Wl,--export-dynamic' with open(build_ninja, 'r', encoding='utf-8') as f: for line in f: max_count = max(max_count, line.count(search_term)) self.assertEqual(max_count, 1, 'Export dynamic incorrectly deduplicated.') def test_compiler_libs_static_dedup(self): testdir = os.path.join(self.unit_test_dir, '56 dedup compiler libs') self.init(testdir) build_ninja = os.path.join(self.builddir, 'build.ninja') with open(build_ninja, 'r', encoding='utf-8') as f: lines = f.readlines() for lib in ('-ldl', '-lm', '-lc', '-lrt'): for line in lines: if lib not in line: continue # Assert that self.assertEqual(len(line.split(lib)), 2, msg=(lib, line)) @skipIfNoPkgconfig def test_noncross_options(self): # C_std defined in project options must be in effect also when native compiling. testdir = os.path.join(self.unit_test_dir, '51 noncross options') self.init(testdir, extra_args=['-Dpkg_config_path=' + testdir]) compdb = self.get_compdb() self.assertEqual(len(compdb), 2) self.assertRegex(compdb[0]['command'], '-std=c99') self.assertRegex(compdb[1]['command'], '-std=c99') self.build() def test_identity_cross(self): testdir = os.path.join(self.unit_test_dir, '61 identity cross') nativefile = tempfile.NamedTemporaryFile(mode='w') nativefile.write(textwrap.dedent('''\ [binaries] c = ['{0}'] '''.format(os.path.join(testdir, 'build_wrapper.py')))) nativefile.flush() self.meson_native_file = nativefile.name crossfile = tempfile.NamedTemporaryFile(mode='w') crossfile.write(textwrap.dedent('''\ [binaries] c = ['{0}'] '''.format(os.path.join(testdir, 'host_wrapper.py')))) crossfile.flush() self.meson_cross_file = crossfile.name # TODO should someday be explicit about build platform only here self.init(testdir) def test_identity_cross_env(self): testdir = os.path.join(self.unit_test_dir, '61 identity cross') env = { 'CC_FOR_BUILD': '"' + os.path.join(testdir, 'build_wrapper.py') + '"', } crossfile = tempfile.NamedTemporaryFile(mode='w') crossfile.write(textwrap.dedent('''\ [binaries] c = ['{0}'] '''.format(os.path.join(testdir, 'host_wrapper.py')))) crossfile.flush() self.meson_cross_file = crossfile.name # TODO should someday be explicit about build platform only here self.init(testdir, override_envvars=env) @skipIfNoPkgconfig def test_static_link(self): if is_cygwin(): raise unittest.SkipTest("Cygwin doesn't support LD_LIBRARY_PATH.") # Build some libraries and install them testdir = os.path.join(self.unit_test_dir, '68 static link/lib') libdir = os.path.join(self.installdir, self.libdir) oldprefix = self.prefix self.prefix = self.installdir self.init(testdir) self.install(use_destdir=False) # Test that installed libraries works self.new_builddir() self.prefix = oldprefix meson_args = ['-Dc_link_args=-L{}'.format(libdir), '--fatal-meson-warnings'] testdir = os.path.join(self.unit_test_dir, '68 static link') env = {'PKG_CONFIG_LIBDIR': os.path.join(libdir, 'pkgconfig')} self.init(testdir, extra_args=meson_args, override_envvars=env) self.build() self.run_tests() def _check_ld(self, check: str, name: str, lang: str, expected: str) -> None: if is_sunos(): raise unittest.SkipTest('Solaris currently cannot override the linker.') if not shutil.which(check): raise unittest.SkipTest('Could not find {}.'.format(check)) envvars = [mesonbuild.envconfig.ENV_VAR_PROG_MAP['{}_ld'.format(lang)]] # Also test a deprecated variable if there is one. if f'{lang}_ld' in mesonbuild.envconfig.DEPRECATED_ENV_PROG_MAP: envvars.append( mesonbuild.envconfig.DEPRECATED_ENV_PROG_MAP[f'{lang}_ld']) for envvar in envvars: with mock.patch.dict(os.environ, {envvar: name}): env = get_fake_env() comp = getattr(env, 'detect_{}_compiler'.format(lang))(MachineChoice.HOST) if isinstance(comp, (mesonbuild.compilers.AppleClangCCompiler, mesonbuild.compilers.AppleClangCPPCompiler, mesonbuild.compilers.AppleClangObjCCompiler, mesonbuild.compilers.AppleClangObjCPPCompiler)): raise unittest.SkipTest('AppleClang is currently only supported with ld64') if lang != 'rust' and comp.use_linker_args('bfd') == []: raise unittest.SkipTest( 'Compiler {} does not support using alternative linkers'.format(comp.id)) self.assertEqual(comp.linker.id, expected) def test_ld_environment_variable_bfd(self): self._check_ld('ld.bfd', 'bfd', 'c', 'ld.bfd') def test_ld_environment_variable_gold(self): self._check_ld('ld.gold', 'gold', 'c', 'ld.gold') def test_ld_environment_variable_lld(self): self._check_ld('ld.lld', 'lld', 'c', 'ld.lld') @skip_if_not_language('rust') @skipIfNoExecutable('ld.gold') # need an additional check here because _check_ld checks for gcc def test_ld_environment_variable_rust(self): self._check_ld('gcc', 'gcc -fuse-ld=gold', 'rust', 'ld.gold') def test_ld_environment_variable_cpp(self): self._check_ld('ld.gold', 'gold', 'cpp', 'ld.gold') @skip_if_not_language('objc') def test_ld_environment_variable_objc(self): self._check_ld('ld.gold', 'gold', 'objc', 'ld.gold') @skip_if_not_language('objcpp') def test_ld_environment_variable_objcpp(self): self._check_ld('ld.gold', 'gold', 'objcpp', 'ld.gold') @skip_if_not_language('fortran') def test_ld_environment_variable_fortran(self): self._check_ld('ld.gold', 'gold', 'fortran', 'ld.gold') @skip_if_not_language('d') def test_ld_environment_variable_d(self): # At least for me, ldc defaults to gold, and gdc defaults to bfd, so # let's pick lld, which isn't the default for either (currently) self._check_ld('ld.lld', 'lld', 'd', 'ld.lld') def compute_sha256(self, filename): with open(filename, 'rb') as f: return hashlib.sha256(f.read()).hexdigest() def test_wrap_with_file_url(self): testdir = os.path.join(self.unit_test_dir, '74 wrap file url') source_filename = os.path.join(testdir, 'subprojects', 'foo.tar.xz') patch_filename = os.path.join(testdir, 'subprojects', 'foo-patch.tar.xz') wrap_filename = os.path.join(testdir, 'subprojects', 'foo.wrap') source_hash = self.compute_sha256(source_filename) patch_hash = self.compute_sha256(patch_filename) wrap = textwrap.dedent("""\ [wrap-file] directory = foo source_url = http://server.invalid/foo source_fallback_url = file://{} source_filename = foo.tar.xz source_hash = {} patch_url = http://server.invalid/foo patch_fallback_url = file://{} patch_filename = foo-patch.tar.xz patch_hash = {} """.format(source_filename, source_hash, patch_filename, patch_hash)) with open(wrap_filename, 'w') as f: f.write(wrap) self.init(testdir) self.build() self.run_tests() windows_proof_rmtree(os.path.join(testdir, 'subprojects', 'packagecache')) windows_proof_rmtree(os.path.join(testdir, 'subprojects', 'foo')) os.unlink(wrap_filename) def test_no_rpath_for_static(self): testdir = os.path.join(self.common_test_dir, '5 linkstatic') self.init(testdir) self.build() build_rpath = get_rpath(os.path.join(self.builddir, 'prog')) self.assertIsNone(build_rpath) def test_lookup_system_after_broken_fallback(self): # Just to generate libfoo.pc so we can test system dependency lookup. testdir = os.path.join(self.common_test_dir, '45 pkgconfig-gen') self.init(testdir) privatedir = self.privatedir # Write test project where the first dependency() returns not-found # because 'broken' subproject does not exit, but that should not prevent # the 2nd dependency() to lookup on system. self.new_builddir() with tempfile.TemporaryDirectory() as d: with open(os.path.join(d, 'meson.build'), 'w') as f: f.write(textwrap.dedent('''\ project('test') dependency('notfound', fallback: 'broken', required: false) dependency('libfoo', fallback: 'broken', required: true) ''')) self.init(d, override_envvars={'PKG_CONFIG_LIBDIR': privatedir}) def test_as_link_whole(self): testdir = os.path.join(self.unit_test_dir, '78 as link whole') self.init(testdir) with open(os.path.join(self.privatedir, 'bar1.pc')) as f: content = f.read() self.assertIn('-lfoo', content) with open(os.path.join(self.privatedir, 'bar2.pc')) as f: content = f.read() self.assertNotIn('-lfoo', content) def test_prelinking(self): # Prelinking currently only works on recently new GNU toolchains. # Skip everything else. When support for other toolchains is added, # remove limitations as necessary. if is_osx(): raise unittest.SkipTest('Prelinking not supported on Darwin.') if 'clang' in os.environ.get('CC', 'dummy'): raise unittest.SkipTest('Prelinking not supported with Clang.') gccver = subprocess.check_output(['cc', '--version']) if b'7.5.0' in gccver: raise unittest.SkipTest('GCC on Bionic is too old to be supported.') testdir = os.path.join(self.unit_test_dir, '88 prelinking') self.init(testdir) self.build() outlib = os.path.join(self.builddir, 'libprelinked.a') ar = shutil.which('ar') self.assertTrue(os.path.exists(outlib)) self.assertTrue(ar is not None) p = subprocess.run([ar, 't', outlib], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, universal_newlines=True, timeout=1) obj_files = p.stdout.strip().split('\n') self.assertEqual(len(obj_files), 1) self.assertTrue(obj_files[0].endswith('-prelink.o')) class BaseLinuxCrossTests(BasePlatformTests): # Don't pass --libdir when cross-compiling. We have tests that # check whether meson auto-detects it correctly. libdir = None def should_run_cross_arm_tests(): return shutil.which('arm-linux-gnueabihf-gcc') and not platform.machine().lower().startswith('arm') @unittest.skipUnless(not is_windows() and should_run_cross_arm_tests(), "requires ability to cross compile to ARM") class LinuxCrossArmTests(BaseLinuxCrossTests): ''' Tests that cross-compilation to Linux/ARM works ''' def setUp(self): super().setUp() src_root = os.path.dirname(__file__) self.meson_cross_file = os.path.join(src_root, 'cross', 'ubuntu-armhf.txt') def test_cflags_cross_environment_pollution(self): ''' Test that the CFLAGS environment variable does not pollute the cross environment. This can't be an ordinary test case because we need to inspect the compiler database. ''' testdir = os.path.join(self.common_test_dir, '3 static') self.init(testdir, override_envvars={'CFLAGS': '-DBUILD_ENVIRONMENT_ONLY'}) compdb = self.get_compdb() self.assertNotIn('-DBUILD_ENVIRONMENT_ONLY', compdb[0]['command']) def test_cross_file_overrides_always_args(self): ''' Test that $lang_args in cross files always override get_always_args(). Needed for overriding the default -D_FILE_OFFSET_BITS=64 on some architectures such as some Android versions and Raspbian. https://github.com/mesonbuild/meson/issues/3049 https://github.com/mesonbuild/meson/issues/3089 ''' testdir = os.path.join(self.unit_test_dir, '33 cross file overrides always args') self.meson_cross_file = os.path.join(testdir, 'ubuntu-armhf-overrides.txt') self.init(testdir) compdb = self.get_compdb() self.assertRegex(compdb[0]['command'], '-D_FILE_OFFSET_BITS=64.*-U_FILE_OFFSET_BITS') self.build() def test_cross_libdir(self): # When cross compiling "libdir" should default to "lib" # rather than "lib/x86_64-linux-gnu" or something like that. testdir = os.path.join(self.common_test_dir, '1 trivial') self.init(testdir) for i in self.introspect('--buildoptions'): if i['name'] == 'libdir': self.assertEqual(i['value'], 'lib') return self.assertTrue(False, 'Option libdir not in introspect data.') def test_cross_libdir_subproject(self): # Guard against a regression where calling "subproject" # would reset the value of libdir to its default value. testdir = os.path.join(self.unit_test_dir, '77 subdir libdir') self.init(testdir, extra_args=['--libdir=fuf']) for i in self.introspect('--buildoptions'): if i['name'] == 'libdir': self.assertEqual(i['value'], 'fuf') return self.assertTrue(False, 'Libdir specified on command line gets reset.') def test_std_remains(self): # C_std defined in project options must be in effect also when cross compiling. testdir = os.path.join(self.unit_test_dir, '51 noncross options') self.init(testdir) compdb = self.get_compdb() self.assertRegex(compdb[0]['command'], '-std=c99') self.build() @skipIfNoPkgconfig def test_pkg_config_option(self): if not shutil.which('arm-linux-gnueabihf-pkg-config'): raise unittest.SkipTest('Cross-pkgconfig not found.') testdir = os.path.join(self.unit_test_dir, '58 pkg_config_path option') self.init(testdir, extra_args=[ '-Dbuild.pkg_config_path=' + os.path.join(testdir, 'build_extra_path'), '-Dpkg_config_path=' + os.path.join(testdir, 'host_extra_path'), ]) def test_run_native_test(self): ''' https://github.com/mesonbuild/meson/issues/7997 check run native test in crossbuild without exe wrapper ''' testdir = os.path.join(self.unit_test_dir, '89 run native test') stamp_file = os.path.join(self.builddir, 'native_test_has_run.stamp') self.init(testdir) self.build() self.assertPathDoesNotExist(stamp_file) self.run_tests() self.assertPathExists(stamp_file) def should_run_cross_mingw_tests(): return shutil.which('x86_64-w64-mingw32-gcc') and not (is_windows() or is_cygwin()) @unittest.skipUnless(not is_windows() and should_run_cross_mingw_tests(), "requires ability to cross compile with MinGW") class LinuxCrossMingwTests(BaseLinuxCrossTests): ''' Tests that cross-compilation to Windows/MinGW works ''' def setUp(self): super().setUp() src_root = os.path.dirname(__file__) self.meson_cross_file = os.path.join(src_root, 'cross', 'linux-mingw-w64-64bit.txt') def test_exe_wrapper_behaviour(self): ''' Test that an exe wrapper that isn't found doesn't cause compiler sanity checks and compiler checks to fail, but causes configure to fail if it requires running a cross-built executable (custom_target or run_target) and causes the tests to be skipped if they are run. ''' testdir = os.path.join(self.unit_test_dir, '36 exe_wrapper behaviour') # Configures, builds, and tests fine by default self.init(testdir) self.build() self.run_tests() self.wipe() os.mkdir(self.builddir) # Change cross file to use a non-existing exe_wrapper and it should fail self.meson_cross_file = os.path.join(testdir, 'broken-cross.txt') # Force tracebacks so we can detect them properly env = {'MESON_FORCE_BACKTRACE': '1'} error_message = "An exe_wrapper is needed but was not found. Please define one in cross file and check the command and/or add it to PATH." with self.assertRaises(MesonException) as cm: # Must run in-process or we'll get a generic CalledProcessError self.init(testdir, extra_args='-Drun-target=false', inprocess=True, override_envvars=env) self.assertEqual(str(cm.exception), error_message) with self.assertRaises(MesonException) as cm: # Must run in-process or we'll get a generic CalledProcessError self.init(testdir, extra_args='-Dcustom-target=false', inprocess=True, override_envvars=env) self.assertEqual(str(cm.exception), error_message) self.init(testdir, extra_args=['-Dcustom-target=false', '-Drun-target=false'], override_envvars=env) self.build() with self.assertRaises(MesonException) as cm: # Must run in-process or we'll get a generic CalledProcessError self.run_tests(inprocess=True, override_envvars=env) self.assertEqual(str(cm.exception), "The exe_wrapper defined in the cross file 'broken' was not found. Please check the command and/or add it to PATH.") @skipIfNoPkgconfig def test_cross_pkg_config_option(self): testdir = os.path.join(self.unit_test_dir, '58 pkg_config_path option') self.init(testdir, extra_args=[ '-Dbuild.pkg_config_path=' + os.path.join(testdir, 'build_extra_path'), '-Dpkg_config_path=' + os.path.join(testdir, 'host_extra_path'), ]) class PythonTests(BasePlatformTests): ''' Tests that verify compilation of python extension modules ''' def test_versions(self): if self.backend is not Backend.ninja: raise unittest.SkipTest('Skipping python tests with {} backend'.format(self.backend.name)) testdir = os.path.join(self.src_root, 'test cases', 'unit', '39 python extmodule') # No python version specified, this will use meson's python self.init(testdir) self.build() self.run_tests() self.wipe() # When specifying a known name, (python2 / python3) the module # will also try 'python' as a fallback and use it if the major # version matches try: self.init(testdir, extra_args=['-Dpython=python2']) self.build() self.run_tests() except unittest.SkipTest: # python2 is not necessarily installed on the test machine, # if it is not, or the python headers can't be found, the test # will raise MESON_SKIP_TEST, we could check beforehand what version # of python is available, but it's a bit of a chicken and egg situation, # as that is the job of the module, so we just ask for forgiveness rather # than permission. pass self.wipe() for py in ('pypy', 'pypy3'): try: self.init(testdir, extra_args=['-Dpython=%s' % py]) except unittest.SkipTest: # Same as above, pypy2 and pypy3 are not expected to be present # on the test system, the test project only raises in these cases continue # We have a pypy, this is expected to work self.build() self.run_tests() self.wipe() # The test is configured to error out with MESON_SKIP_TEST # in case it could not find python with self.assertRaises(unittest.SkipTest): self.init(testdir, extra_args=['-Dpython=not-python']) self.wipe() # While dir is an external command on both Windows and Linux, # it certainly isn't python with self.assertRaises(unittest.SkipTest): self.init(testdir, extra_args=['-Dpython=dir']) self.wipe() class RewriterTests(BasePlatformTests): def setUp(self): super().setUp() self.maxDiff = None def prime(self, dirname): copy_tree(os.path.join(self.rewrite_test_dir, dirname), self.builddir) def rewrite_raw(self, directory, args): if isinstance(args, str): args = [args] command = self.rewrite_command + ['--verbose', '--skip', '--sourcedir', directory] + args p = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, timeout=60) print('STDOUT:') print(p.stdout) print('STDERR:') print(p.stderr) if p.returncode != 0: if 'MESON_SKIP_TEST' in p.stdout: raise unittest.SkipTest('Project requested skipping.') raise subprocess.CalledProcessError(p.returncode, command, output=p.stdout) if not p.stderr: return {} return json.loads(p.stderr) def rewrite(self, directory, args): if isinstance(args, str): args = [args] return self.rewrite_raw(directory, ['command'] + args) def test_target_source_list(self): self.prime('1 basic') out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = { 'target': { 'trivialprog0@exe': {'name': 'trivialprog0', 'sources': ['main.cpp', 'fileA.cpp', 'fileB.cpp', 'fileC.cpp']}, 'trivialprog1@exe': {'name': 'trivialprog1', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog2@exe': {'name': 'trivialprog2', 'sources': ['fileB.cpp', 'fileC.cpp']}, 'trivialprog3@exe': {'name': 'trivialprog3', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog4@exe': {'name': 'trivialprog4', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog5@exe': {'name': 'trivialprog5', 'sources': ['main.cpp', 'fileB.cpp', 'fileC.cpp']}, 'trivialprog6@exe': {'name': 'trivialprog6', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog7@exe': {'name': 'trivialprog7', 'sources': ['fileB.cpp', 'fileC.cpp', 'main.cpp', 'fileA.cpp']}, 'trivialprog8@exe': {'name': 'trivialprog8', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog9@exe': {'name': 'trivialprog9', 'sources': ['main.cpp', 'fileA.cpp']}, } } self.assertDictEqual(out, expected) def test_target_add_sources(self): self.prime('1 basic') out = self.rewrite(self.builddir, os.path.join(self.builddir, 'addSrc.json')) expected = { 'target': { 'trivialprog0@exe': {'name': 'trivialprog0', 'sources': ['a1.cpp', 'a2.cpp', 'a6.cpp', 'fileA.cpp', 'main.cpp', 'a7.cpp', 'fileB.cpp', 'fileC.cpp']}, 'trivialprog1@exe': {'name': 'trivialprog1', 'sources': ['a1.cpp', 'a2.cpp', 'a6.cpp', 'fileA.cpp', 'main.cpp']}, 'trivialprog2@exe': {'name': 'trivialprog2', 'sources': ['a7.cpp', 'fileB.cpp', 'fileC.cpp']}, 'trivialprog3@exe': {'name': 'trivialprog3', 'sources': ['a5.cpp', 'fileA.cpp', 'main.cpp']}, 'trivialprog4@exe': {'name': 'trivialprog4', 'sources': ['a5.cpp', 'main.cpp', 'fileA.cpp']}, 'trivialprog5@exe': {'name': 'trivialprog5', 'sources': ['a3.cpp', 'main.cpp', 'a7.cpp', 'fileB.cpp', 'fileC.cpp']}, 'trivialprog6@exe': {'name': 'trivialprog6', 'sources': ['main.cpp', 'fileA.cpp', 'a4.cpp']}, 'trivialprog7@exe': {'name': 'trivialprog7', 'sources': ['fileB.cpp', 'fileC.cpp', 'a1.cpp', 'a2.cpp', 'a6.cpp', 'fileA.cpp', 'main.cpp']}, 'trivialprog8@exe': {'name': 'trivialprog8', 'sources': ['a1.cpp', 'a2.cpp', 'a6.cpp', 'fileA.cpp', 'main.cpp']}, 'trivialprog9@exe': {'name': 'trivialprog9', 'sources': ['a1.cpp', 'a2.cpp', 'a6.cpp', 'fileA.cpp', 'main.cpp']}, } } self.assertDictEqual(out, expected) # Check the written file out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) self.assertDictEqual(out, expected) def test_target_add_sources_abs(self): self.prime('1 basic') abs_src = [os.path.join(self.builddir, x) for x in ['a1.cpp', 'a2.cpp', 'a6.cpp']] add = json.dumps([{"type": "target", "target": "trivialprog1", "operation": "src_add", "sources": abs_src}]) inf = json.dumps([{"type": "target", "target": "trivialprog1", "operation": "info"}]) self.rewrite(self.builddir, add) out = self.rewrite(self.builddir, inf) expected = {'target': {'trivialprog1@exe': {'name': 'trivialprog1', 'sources': ['a1.cpp', 'a2.cpp', 'a6.cpp', 'fileA.cpp', 'main.cpp']}}} self.assertDictEqual(out, expected) def test_target_remove_sources(self): self.prime('1 basic') out = self.rewrite(self.builddir, os.path.join(self.builddir, 'rmSrc.json')) expected = { 'target': { 'trivialprog0@exe': {'name': 'trivialprog0', 'sources': ['main.cpp', 'fileC.cpp']}, 'trivialprog1@exe': {'name': 'trivialprog1', 'sources': ['main.cpp']}, 'trivialprog2@exe': {'name': 'trivialprog2', 'sources': ['fileC.cpp']}, 'trivialprog3@exe': {'name': 'trivialprog3', 'sources': ['main.cpp']}, 'trivialprog4@exe': {'name': 'trivialprog4', 'sources': ['main.cpp']}, 'trivialprog5@exe': {'name': 'trivialprog5', 'sources': ['main.cpp', 'fileC.cpp']}, 'trivialprog6@exe': {'name': 'trivialprog6', 'sources': ['main.cpp']}, 'trivialprog7@exe': {'name': 'trivialprog7', 'sources': ['fileC.cpp', 'main.cpp']}, 'trivialprog8@exe': {'name': 'trivialprog8', 'sources': ['main.cpp']}, 'trivialprog9@exe': {'name': 'trivialprog9', 'sources': ['main.cpp']}, } } self.assertDictEqual(out, expected) # Check the written file out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) self.assertDictEqual(out, expected) def test_target_subdir(self): self.prime('2 subdirs') out = self.rewrite(self.builddir, os.path.join(self.builddir, 'addSrc.json')) expected = {'name': 'something', 'sources': ['first.c', 'second.c', 'third.c']} self.assertDictEqual(list(out['target'].values())[0], expected) # Check the written file out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) self.assertDictEqual(list(out['target'].values())[0], expected) def test_target_remove(self): self.prime('1 basic') self.rewrite(self.builddir, os.path.join(self.builddir, 'rmTgt.json')) out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = { 'target': { 'trivialprog2@exe': {'name': 'trivialprog2', 'sources': ['fileB.cpp', 'fileC.cpp']}, 'trivialprog3@exe': {'name': 'trivialprog3', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog4@exe': {'name': 'trivialprog4', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog5@exe': {'name': 'trivialprog5', 'sources': ['main.cpp', 'fileB.cpp', 'fileC.cpp']}, 'trivialprog6@exe': {'name': 'trivialprog6', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog7@exe': {'name': 'trivialprog7', 'sources': ['fileB.cpp', 'fileC.cpp', 'main.cpp', 'fileA.cpp']}, 'trivialprog8@exe': {'name': 'trivialprog8', 'sources': ['main.cpp', 'fileA.cpp']}, } } self.assertDictEqual(out, expected) def test_tatrget_add(self): self.prime('1 basic') self.rewrite(self.builddir, os.path.join(self.builddir, 'addTgt.json')) out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = { 'target': { 'trivialprog0@exe': {'name': 'trivialprog0', 'sources': ['main.cpp', 'fileA.cpp', 'fileB.cpp', 'fileC.cpp']}, 'trivialprog1@exe': {'name': 'trivialprog1', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog2@exe': {'name': 'trivialprog2', 'sources': ['fileB.cpp', 'fileC.cpp']}, 'trivialprog3@exe': {'name': 'trivialprog3', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog4@exe': {'name': 'trivialprog4', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog5@exe': {'name': 'trivialprog5', 'sources': ['main.cpp', 'fileB.cpp', 'fileC.cpp']}, 'trivialprog6@exe': {'name': 'trivialprog6', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog7@exe': {'name': 'trivialprog7', 'sources': ['fileB.cpp', 'fileC.cpp', 'main.cpp', 'fileA.cpp']}, 'trivialprog8@exe': {'name': 'trivialprog8', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog9@exe': {'name': 'trivialprog9', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog10@sha': {'name': 'trivialprog10', 'sources': ['new1.cpp', 'new2.cpp']}, } } self.assertDictEqual(out, expected) def test_target_remove_subdir(self): self.prime('2 subdirs') self.rewrite(self.builddir, os.path.join(self.builddir, 'rmTgt.json')) out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) self.assertDictEqual(out, {}) def test_target_add_subdir(self): self.prime('2 subdirs') self.rewrite(self.builddir, os.path.join(self.builddir, 'addTgt.json')) out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = {'name': 'something', 'sources': ['first.c', 'second.c']} self.assertDictEqual(out['target']['94b671c@@something@exe'], expected) def test_target_source_sorting(self): self.prime('5 sorting') add_json = json.dumps([{'type': 'target', 'target': 'exe1', 'operation': 'src_add', 'sources': ['a666.c']}]) inf_json = json.dumps([{'type': 'target', 'target': 'exe1', 'operation': 'info'}]) out = self.rewrite(self.builddir, add_json) out = self.rewrite(self.builddir, inf_json) expected = { 'target': { 'exe1@exe': { 'name': 'exe1', 'sources': [ 'aaa/a/a1.c', 'aaa/b/b1.c', 'aaa/b/b2.c', 'aaa/f1.c', 'aaa/f2.c', 'aaa/f3.c', 'bbb/a/b1.c', 'bbb/b/b2.c', 'bbb/c1/b5.c', 'bbb/c2/b7.c', 'bbb/c10/b6.c', 'bbb/a4.c', 'bbb/b3.c', 'bbb/b4.c', 'bbb/b5.c', 'a1.c', 'a2.c', 'a3.c', 'a10.c', 'a20.c', 'a30.c', 'a100.c', 'a101.c', 'a110.c', 'a210.c', 'a666.c', 'b1.c', 'c2.c' ] } } } self.assertDictEqual(out, expected) def test_target_same_name_skip(self): self.prime('4 same name targets') out = self.rewrite(self.builddir, os.path.join(self.builddir, 'addSrc.json')) out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = {'name': 'myExe', 'sources': ['main.cpp']} self.assertEqual(len(out['target']), 2) for val in out['target'].values(): self.assertDictEqual(expected, val) def test_kwargs_info(self): self.prime('3 kwargs') out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = { 'kwargs': { 'project#/': {'version': '0.0.1'}, 'target#tgt1': {'build_by_default': True}, 'dependency#dep1': {'required': False} } } self.assertDictEqual(out, expected) def test_kwargs_set(self): self.prime('3 kwargs') self.rewrite(self.builddir, os.path.join(self.builddir, 'set.json')) out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = { 'kwargs': { 'project#/': {'version': '0.0.2', 'meson_version': '0.50.0', 'license': ['GPL', 'MIT']}, 'target#tgt1': {'build_by_default': False, 'build_rpath': '/usr/local', 'dependencies': 'dep1'}, 'dependency#dep1': {'required': True, 'method': 'cmake'} } } self.assertDictEqual(out, expected) def test_kwargs_add(self): self.prime('3 kwargs') self.rewrite(self.builddir, os.path.join(self.builddir, 'add.json')) out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = { 'kwargs': { 'project#/': {'version': '0.0.1', 'license': ['GPL', 'MIT', 'BSD', 'Boost']}, 'target#tgt1': {'build_by_default': True}, 'dependency#dep1': {'required': False} } } self.assertDictEqual(out, expected) def test_kwargs_remove(self): self.prime('3 kwargs') self.rewrite(self.builddir, os.path.join(self.builddir, 'remove.json')) out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = { 'kwargs': { 'project#/': {'version': '0.0.1', 'license': 'GPL'}, 'target#tgt1': {'build_by_default': True}, 'dependency#dep1': {'required': False} } } self.assertDictEqual(out, expected) def test_kwargs_remove_regex(self): self.prime('3 kwargs') self.rewrite(self.builddir, os.path.join(self.builddir, 'remove_regex.json')) out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = { 'kwargs': { 'project#/': {'version': '0.0.1', 'default_options': 'debug=true'}, 'target#tgt1': {'build_by_default': True}, 'dependency#dep1': {'required': False} } } self.assertDictEqual(out, expected) def test_kwargs_delete(self): self.prime('3 kwargs') self.rewrite(self.builddir, os.path.join(self.builddir, 'delete.json')) out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = { 'kwargs': { 'project#/': {}, 'target#tgt1': {}, 'dependency#dep1': {'required': False} } } self.assertDictEqual(out, expected) def test_default_options_set(self): self.prime('3 kwargs') self.rewrite(self.builddir, os.path.join(self.builddir, 'defopts_set.json')) out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = { 'kwargs': { 'project#/': {'version': '0.0.1', 'default_options': ['buildtype=release', 'debug=True', 'cpp_std=c++11']}, 'target#tgt1': {'build_by_default': True}, 'dependency#dep1': {'required': False} } } self.assertDictEqual(out, expected) def test_default_options_delete(self): self.prime('3 kwargs') self.rewrite(self.builddir, os.path.join(self.builddir, 'defopts_delete.json')) out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = { 'kwargs': { 'project#/': {'version': '0.0.1', 'default_options': ['cpp_std=c++14', 'debug=true']}, 'target#tgt1': {'build_by_default': True}, 'dependency#dep1': {'required': False} } } self.assertDictEqual(out, expected) class NativeFileTests(BasePlatformTests): def setUp(self): super().setUp() self.testcase = os.path.join(self.unit_test_dir, '47 native file binary') self.current_config = 0 self.current_wrapper = 0 def helper_create_native_file(self, values): """Create a config file as a temporary file. values should be a nested dictionary structure of {section: {key: value}} """ filename = os.path.join(self.builddir, 'generated{}.config'.format(self.current_config)) self.current_config += 1 with open(filename, 'wt') as f: for section, entries in values.items(): f.write('[{}]\n'.format(section)) for k, v in entries.items(): if isinstance(v, (bool, int, float)): f.write("{}={}\n".format(k, v)) elif isinstance(v, list): f.write("{}=[{}]\n".format(k, ', '.join(["'{}'".format(w) for w in v]))) else: f.write("{}='{}'\n".format(k, v)) return filename def helper_create_binary_wrapper(self, binary, dir_=None, extra_args=None, **kwargs): """Creates a wrapper around a binary that overrides specific values.""" filename = os.path.join(dir_ or self.builddir, 'binary_wrapper{}.py'.format(self.current_wrapper)) extra_args = extra_args or {} self.current_wrapper += 1 if is_haiku(): chbang = '#!/bin/env python3' else: chbang = '#!/usr/bin/env python3' with open(filename, 'wt') as f: f.write(textwrap.dedent('''\ {} import argparse import subprocess import sys def main(): parser = argparse.ArgumentParser() '''.format(chbang))) for name in chain(extra_args, kwargs): f.write(' parser.add_argument("-{0}", "--{0}", action="store_true")\n'.format(name)) f.write(' args, extra_args = parser.parse_known_args()\n') for name, value in chain(extra_args.items(), kwargs.items()): f.write(' if args.{}:\n'.format(name)) f.write(' print("{}", file=sys.{})\n'.format(value, kwargs.get('outfile', 'stdout'))) f.write(' sys.exit(0)\n') f.write(textwrap.dedent(''' ret = subprocess.run( ["{}"] + extra_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) print(ret.stdout.decode('utf-8')) print(ret.stderr.decode('utf-8'), file=sys.stderr) sys.exit(ret.returncode) if __name__ == '__main__': main() '''.format(binary))) if not is_windows(): os.chmod(filename, 0o755) return filename # On windows we need yet another level of indirection, as cmd cannot # invoke python files itself, so instead we generate a .bat file, which # invokes our python wrapper batfile = os.path.join(self.builddir, 'binary_wrapper{}.bat'.format(self.current_wrapper)) with open(batfile, 'wt') as f: f.write(r'@{} {} %*'.format(sys.executable, filename)) return batfile def helper_for_compiler(self, lang, cb, for_machine = MachineChoice.HOST): """Helper for generating tests for overriding compilers for langaugages with more than one implementation, such as C, C++, ObjC, ObjC++, and D. """ env = get_fake_env() getter = getattr(env, 'detect_{}_compiler'.format(lang)) getter = functools.partial(getter, for_machine) cc = getter() binary, newid = cb(cc) env.binaries[for_machine].binaries[lang] = binary compiler = getter() self.assertEqual(compiler.id, newid) def test_multiple_native_files_override(self): wrapper = self.helper_create_binary_wrapper('bash', version='foo') config = self.helper_create_native_file({'binaries': {'bash': wrapper}}) wrapper = self.helper_create_binary_wrapper('bash', version='12345') config2 = self.helper_create_native_file({'binaries': {'bash': wrapper}}) self.init(self.testcase, extra_args=[ '--native-file', config, '--native-file', config2, '-Dcase=find_program']) # This test hangs on cygwin. @unittest.skipIf(os.name != 'posix' or is_cygwin(), 'Uses fifos, which are not available on non Unix OSes.') def test_native_file_is_pipe(self): fifo = os.path.join(self.builddir, 'native.file') os.mkfifo(fifo) with tempfile.TemporaryDirectory() as d: wrapper = self.helper_create_binary_wrapper('bash', d, version='12345') def filler(): with open(fifo, 'w') as f: f.write('[binaries]\n') f.write("bash = '{}'\n".format(wrapper)) thread = threading.Thread(target=filler) thread.start() self.init(self.testcase, extra_args=['--native-file', fifo, '-Dcase=find_program']) thread.join() os.unlink(fifo) self.init(self.testcase, extra_args=['--wipe']) def test_multiple_native_files(self): wrapper = self.helper_create_binary_wrapper('bash', version='12345') config = self.helper_create_native_file({'binaries': {'bash': wrapper}}) wrapper = self.helper_create_binary_wrapper('python') config2 = self.helper_create_native_file({'binaries': {'python': wrapper}}) self.init(self.testcase, extra_args=[ '--native-file', config, '--native-file', config2, '-Dcase=find_program']) def _simple_test(self, case, binary, entry=None): wrapper = self.helper_create_binary_wrapper(binary, version='12345') config = self.helper_create_native_file({'binaries': {entry or binary: wrapper}}) self.init(self.testcase, extra_args=['--native-file', config, '-Dcase={}'.format(case)]) def test_find_program(self): self._simple_test('find_program', 'bash') def test_config_tool_dep(self): # Do the skip at this level to avoid screwing up the cache if mesonbuild.environment.detect_msys2_arch(): raise unittest.SkipTest('Skipped due to problems with LLVM on MSYS2') if not shutil.which('llvm-config'): raise unittest.SkipTest('No llvm-installed, cannot test') self._simple_test('config_dep', 'llvm-config') def test_python3_module(self): self._simple_test('python3', 'python3') def test_python_module(self): if is_windows(): # Bat adds extra crap to stdout, so the version check logic in the # python module breaks. This is fine on other OSes because they # don't need the extra indirection. raise unittest.SkipTest('bat indirection breaks internal sanity checks.') elif is_osx(): binary = 'python' else: binary = 'python2' # We not have python2, check for it for v in ['2', '2.7', '-2.7']: rc = subprocess.call(['pkg-config', '--cflags', 'python{}'.format(v)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) if rc == 0: break else: raise unittest.SkipTest('Not running Python 2 tests because dev packages not installed.') self._simple_test('python', binary, entry='python') @unittest.skipIf(is_windows(), 'Setting up multiple compilers on windows is hard') @skip_if_env_set('CC') def test_c_compiler(self): def cb(comp): if comp.id == 'gcc': if not shutil.which('clang'): raise unittest.SkipTest('Only one compiler found, cannot test.') return 'clang', 'clang' if not is_real_gnu_compiler(shutil.which('gcc')): raise unittest.SkipTest('Only one compiler found, cannot test.') return 'gcc', 'gcc' self.helper_for_compiler('c', cb) @unittest.skipIf(is_windows(), 'Setting up multiple compilers on windows is hard') @skip_if_env_set('CXX') def test_cpp_compiler(self): def cb(comp): if comp.id == 'gcc': if not shutil.which('clang++'): raise unittest.SkipTest('Only one compiler found, cannot test.') return 'clang++', 'clang' if not is_real_gnu_compiler(shutil.which('g++')): raise unittest.SkipTest('Only one compiler found, cannot test.') return 'g++', 'gcc' self.helper_for_compiler('cpp', cb) @skip_if_not_language('objc') @skip_if_env_set('OBJC') def test_objc_compiler(self): def cb(comp): if comp.id == 'gcc': if not shutil.which('clang'): raise unittest.SkipTest('Only one compiler found, cannot test.') return 'clang', 'clang' if not is_real_gnu_compiler(shutil.which('gcc')): raise unittest.SkipTest('Only one compiler found, cannot test.') return 'gcc', 'gcc' self.helper_for_compiler('objc', cb) @skip_if_not_language('objcpp') @skip_if_env_set('OBJCXX') def test_objcpp_compiler(self): def cb(comp): if comp.id == 'gcc': if not shutil.which('clang++'): raise unittest.SkipTest('Only one compiler found, cannot test.') return 'clang++', 'clang' if not is_real_gnu_compiler(shutil.which('g++')): raise unittest.SkipTest('Only one compiler found, cannot test.') return 'g++', 'gcc' self.helper_for_compiler('objcpp', cb) @skip_if_not_language('d') @skip_if_env_set('DC') def test_d_compiler(self): def cb(comp): if comp.id == 'dmd': if shutil.which('ldc'): return 'ldc', 'ldc' elif shutil.which('gdc'): return 'gdc', 'gdc' else: raise unittest.SkipTest('No alternative dlang compiler found.') if shutil.which('dmd'): return 'dmd', 'dmd' raise unittest.SkipTest('No alternative dlang compiler found.') self.helper_for_compiler('d', cb) @skip_if_not_language('cs') @skip_if_env_set('CSC') def test_cs_compiler(self): def cb(comp): if comp.id == 'csc': if not shutil.which('mcs'): raise unittest.SkipTest('No alternate C# implementation.') return 'mcs', 'mcs' if not shutil.which('csc'): raise unittest.SkipTest('No alternate C# implementation.') return 'csc', 'csc' self.helper_for_compiler('cs', cb) @skip_if_not_language('fortran') @skip_if_env_set('FC') def test_fortran_compiler(self): def cb(comp): if comp.id == 'lcc': if shutil.which('lfortran'): return 'lfortran', 'lcc' raise unittest.SkipTest('No alternate Fortran implementation.') elif comp.id == 'gcc': if shutil.which('ifort'): # There is an ICC for windows (windows build, linux host), # but we don't support that ATM so lets not worry about it. if is_windows(): return 'ifort', 'intel-cl' return 'ifort', 'intel' elif shutil.which('flang'): return 'flang', 'flang' elif shutil.which('pgfortran'): return 'pgfortran', 'pgi' # XXX: there are several other fortran compilers meson # supports, but I don't have any of them to test with raise unittest.SkipTest('No alternate Fortran implementation.') if not shutil.which('gfortran'): raise unittest.SkipTest('No alternate Fortran implementation.') return 'gfortran', 'gcc' self.helper_for_compiler('fortran', cb) def _single_implementation_compiler(self, lang: str, binary: str, version_str: str, version: str) -> None: """Helper for languages with a single (supported) implementation. Builds a wrapper around the compiler to override the version. """ wrapper = self.helper_create_binary_wrapper(binary, version=version_str) env = get_fake_env() getter = getattr(env, 'detect_{}_compiler'.format(lang)) getter = functools.partial(getter, MachineChoice.HOST) env.binaries.host.binaries[lang] = [wrapper] compiler = getter() self.assertEqual(compiler.version, version) @skip_if_not_language('vala') @skip_if_env_set('VALAC') def test_vala_compiler(self): self._single_implementation_compiler( 'vala', 'valac', 'Vala 1.2345', '1.2345') @skip_if_not_language('rust') @skip_if_env_set('RUSTC') def test_rust_compiler(self): self._single_implementation_compiler( 'rust', 'rustc', 'rustc 1.2345', '1.2345') @skip_if_not_language('java') def test_java_compiler(self): self._single_implementation_compiler( 'java', 'javac', 'javac 9.99.77', '9.99.77') @skip_if_not_language('swift') def test_swift_compiler(self): wrapper = self.helper_create_binary_wrapper( 'swiftc', version='Swift 1.2345', outfile='stderr', extra_args={'Xlinker': 'macosx_version. PROJECT:ld - 1.2.3'}) env = get_fake_env() env.binaries.host.binaries['swift'] = [wrapper] compiler = env.detect_swift_compiler(MachineChoice.HOST) self.assertEqual(compiler.version, '1.2345') def test_native_file_dirs(self): testcase = os.path.join(self.unit_test_dir, '60 native file override') self.init(testcase, default_args=False, extra_args=['--native-file', os.path.join(testcase, 'nativefile')]) def test_native_file_dirs_overridden(self): testcase = os.path.join(self.unit_test_dir, '60 native file override') self.init(testcase, default_args=False, extra_args=['--native-file', os.path.join(testcase, 'nativefile'), '-Ddef_libdir=liblib', '-Dlibdir=liblib']) def test_compile_sys_path(self): """Compiling with a native file stored in a system path works. There was a bug which caused the paths to be stored incorrectly and would result in ninja invoking meson in an infinite loop. This tests for that by actually invoking ninja. """ testcase = os.path.join(self.common_test_dir, '1 trivial') # It really doesn't matter what's in the native file, just that it exists config = self.helper_create_native_file({'binaries': {'bash': 'false'}}) self.init(testcase, extra_args=['--native-file', config]) self.build() def test_user_options(self): testcase = os.path.join(self.common_test_dir, '41 options') for opt, value in [('testoption', 'some other val'), ('other_one', True), ('combo_opt', 'one'), ('array_opt', ['two']), ('integer_opt', 0), ('CaseSenSiTivE', 'SOME other Value'), ('CASESENSITIVE', 'some other Value')]: config = self.helper_create_native_file({'project options': {opt: value}}) with self.assertRaises(subprocess.CalledProcessError) as cm: self.init(testcase, extra_args=['--native-file', config]) self.assertRegex(cm.exception.stdout, r'Incorrect value to [a-z]+ option') def test_user_options_command_line_overrides(self): testcase = os.path.join(self.common_test_dir, '41 options') config = self.helper_create_native_file({'project options': {'other_one': True}}) self.init(testcase, extra_args=['--native-file', config, '-Dother_one=false']) def test_user_options_subproject(self): testcase = os.path.join(self.unit_test_dir, '80 user options for subproject') s = os.path.join(testcase, 'subprojects') if not os.path.exists(s): os.mkdir(s) s = os.path.join(s, 'sub') if not os.path.exists(s): sub = os.path.join(self.common_test_dir, '41 options') shutil.copytree(sub, s) for opt, value in [('testoption', 'some other val'), ('other_one', True), ('combo_opt', 'one'), ('array_opt', ['two']), ('integer_opt', 0)]: config = self.helper_create_native_file({'sub:project options': {opt: value}}) with self.assertRaises(subprocess.CalledProcessError) as cm: self.init(testcase, extra_args=['--native-file', config]) self.assertRegex(cm.exception.stdout, r'Incorrect value to [a-z]+ option') def test_option_bool(self): # Bools are allowed to be unquoted testcase = os.path.join(self.common_test_dir, '1 trivial') config = self.helper_create_native_file({'built-in options': {'werror': True}}) self.init(testcase, extra_args=['--native-file', config]) configuration = self.introspect('--buildoptions') for each in configuration: # Test that no-per subproject options are inherited from the parent if 'werror' in each['name']: self.assertEqual(each['value'], True) break else: self.fail('Did not find werror in build options?') def test_option_integer(self): # Bools are allowed to be unquoted testcase = os.path.join(self.common_test_dir, '1 trivial') config = self.helper_create_native_file({'built-in options': {'unity_size': 100}}) self.init(testcase, extra_args=['--native-file', config]) configuration = self.introspect('--buildoptions') for each in configuration: # Test that no-per subproject options are inherited from the parent if 'unity_size' in each['name']: self.assertEqual(each['value'], 100) break else: self.fail('Did not find unity_size in build options?') def test_builtin_options(self): testcase = os.path.join(self.common_test_dir, '2 cpp') config = self.helper_create_native_file({'built-in options': {'cpp_std': 'c++14'}}) self.init(testcase, extra_args=['--native-file', config]) configuration = self.introspect('--buildoptions') for each in configuration: if each['name'] == 'cpp_std': self.assertEqual(each['value'], 'c++14') break else: self.fail('Did not find werror in build options?') def test_builtin_options_conf_overrides_env(self): testcase = os.path.join(self.common_test_dir, '2 cpp') config = self.helper_create_native_file({'built-in options': {'pkg_config_path': '/foo'}}) self.init(testcase, extra_args=['--native-file', config], override_envvars={'PKG_CONFIG_PATH': '/bar'}) configuration = self.introspect('--buildoptions') for each in configuration: if each['name'] == 'pkg_config_path': self.assertEqual(each['value'], ['/foo']) break else: self.fail('Did not find pkg_config_path in build options?') def test_builtin_options_subprojects(self): testcase = os.path.join(self.common_test_dir, '99 subproject subdir') config = self.helper_create_native_file({'built-in options': {'default_library': 'both', 'c_args': ['-Dfoo']}, 'sub:built-in options': {'default_library': 'static'}}) self.init(testcase, extra_args=['--native-file', config]) configuration = self.introspect('--buildoptions') found = 0 for each in configuration: # Test that no-per subproject options are inherited from the parent if 'c_args' in each['name']: # This path will be hit twice, once for build and once for host, self.assertEqual(each['value'], ['-Dfoo']) found += 1 elif each['name'] == 'default_library': self.assertEqual(each['value'], 'both') found += 1 elif each['name'] == 'sub:default_library': self.assertEqual(each['value'], 'static') found += 1 self.assertEqual(found, 4, 'Did not find all three sections') def test_builtin_options_subprojects_overrides_buildfiles(self): # If the buildfile says subproject(... default_library: shared), ensure that's overwritten testcase = os.path.join(self.common_test_dir, '224 persubproject options') config = self.helper_create_native_file({'sub2:built-in options': {'default_library': 'shared'}}) with self.assertRaises((RuntimeError, subprocess.CalledProcessError)) as cm: self.init(testcase, extra_args=['--native-file', config]) if isinstance(cm, RuntimeError): check = str(cm.exception) else: check = cm.exception.stdout self.assertIn(check, 'Parent should override default_library') def test_builtin_options_subprojects_dont_inherits_parent_override(self): # If the buildfile says subproject(... default_library: shared), ensure that's overwritten testcase = os.path.join(self.common_test_dir, '224 persubproject options') config = self.helper_create_native_file({'built-in options': {'default_library': 'both'}}) self.init(testcase, extra_args=['--native-file', config]) def test_builtin_options_compiler_properties(self): # the properties section can have lang_args, and those need to be # overwritten by the built-in options testcase = os.path.join(self.common_test_dir, '1 trivial') config = self.helper_create_native_file({ 'built-in options': {'c_args': ['-DFOO']}, 'properties': {'c_args': ['-DBAR']}, }) self.init(testcase, extra_args=['--native-file', config]) configuration = self.introspect('--buildoptions') for each in configuration: if each['name'] == 'c_args': self.assertEqual(each['value'], ['-DFOO']) break else: self.fail('Did not find c_args in build options?') def test_builtin_options_compiler_properties_legacy(self): # The legacy placement in properties is still valid if a 'built-in # options' setting is present, but doesn't have the lang_args testcase = os.path.join(self.common_test_dir, '1 trivial') config = self.helper_create_native_file({ 'built-in options': {'default_library': 'static'}, 'properties': {'c_args': ['-DBAR']}, }) self.init(testcase, extra_args=['--native-file', config]) configuration = self.introspect('--buildoptions') for each in configuration: if each['name'] == 'c_args': self.assertEqual(each['value'], ['-DBAR']) break else: self.fail('Did not find c_args in build options?') def test_builtin_options_paths(self): # the properties section can have lang_args, and those need to be # overwritten by the built-in options testcase = os.path.join(self.common_test_dir, '1 trivial') config = self.helper_create_native_file({ 'built-in options': {'bindir': 'foo'}, 'paths': {'bindir': 'bar'}, }) self.init(testcase, extra_args=['--native-file', config]) configuration = self.introspect('--buildoptions') for each in configuration: if each['name'] == 'bindir': self.assertEqual(each['value'], 'foo') break else: self.fail('Did not find bindir in build options?') def test_builtin_options_paths_legacy(self): testcase = os.path.join(self.common_test_dir, '1 trivial') config = self.helper_create_native_file({ 'built-in options': {'default_library': 'static'}, 'paths': {'bindir': 'bar'}, }) self.init(testcase, extra_args=['--native-file', config]) configuration = self.introspect('--buildoptions') for each in configuration: if each['name'] == 'bindir': self.assertEqual(each['value'], 'bar') break else: self.fail('Did not find bindir in build options?') class CrossFileTests(BasePlatformTests): """Tests for cross file functionality not directly related to cross compiling. This is mainly aimed to testing overrides from cross files. """ def setUp(self): super().setUp() self.current_config = 0 self.current_wrapper = 0 def _cross_file_generator(self, *, needs_exe_wrapper: bool = False, exe_wrapper: T.Optional[T.List[str]] = None) -> str: if is_windows(): raise unittest.SkipTest('Cannot run this test on non-mingw/non-cygwin windows') return textwrap.dedent(f"""\ [binaries] c = '{shutil.which('gcc' if is_sunos() else 'cc')}' ar = '{shutil.which('ar')}' strip = '{shutil.which('strip')}' exe_wrapper = {str(exe_wrapper) if exe_wrapper is not None else '[]'} [properties] needs_exe_wrapper = {needs_exe_wrapper} [host_machine] system = 'linux' cpu_family = 'x86' cpu = 'i686' endian = 'little' """) def _stub_exe_wrapper(self) -> str: return textwrap.dedent('''\ #!/usr/bin/env python3 import subprocess import sys sys.exit(subprocess.run(sys.argv[1:]).returncode) ''') def test_needs_exe_wrapper_true(self): testdir = os.path.join(self.unit_test_dir, '72 cross test passed') with tempfile.TemporaryDirectory() as d: p = Path(d) / 'crossfile' with p.open('wt') as f: f.write(self._cross_file_generator(needs_exe_wrapper=True)) self.init(testdir, extra_args=['--cross-file=' + str(p)]) out = self.run_target('test') self.assertRegex(out, r'Skipped:\s*1\s*\n') def test_needs_exe_wrapper_false(self): testdir = os.path.join(self.unit_test_dir, '72 cross test passed') with tempfile.TemporaryDirectory() as d: p = Path(d) / 'crossfile' with p.open('wt') as f: f.write(self._cross_file_generator(needs_exe_wrapper=False)) self.init(testdir, extra_args=['--cross-file=' + str(p)]) out = self.run_target('test') self.assertNotRegex(out, r'Skipped:\s*1\n') def test_needs_exe_wrapper_true_wrapper(self): testdir = os.path.join(self.unit_test_dir, '72 cross test passed') with tempfile.TemporaryDirectory() as d: s = Path(d) / 'wrapper.py' with s.open('wt') as f: f.write(self._stub_exe_wrapper()) s.chmod(0o774) p = Path(d) / 'crossfile' with p.open('wt') as f: f.write(self._cross_file_generator( needs_exe_wrapper=True, exe_wrapper=[str(s)])) self.init(testdir, extra_args=['--cross-file=' + str(p), '-Dexpect=true']) out = self.run_target('test') self.assertRegex(out, r'Ok:\s*3\s*\n') def test_cross_exe_passed_no_wrapper(self): testdir = os.path.join(self.unit_test_dir, '72 cross test passed') with tempfile.TemporaryDirectory() as d: p = Path(d) / 'crossfile' with p.open('wt') as f: f.write(self._cross_file_generator(needs_exe_wrapper=True)) self.init(testdir, extra_args=['--cross-file=' + str(p)]) self.build() out = self.run_target('test') self.assertRegex(out, r'Skipped:\s*1\s*\n') # The test uses mocking and thus requires that the current process is the # one to run the Meson steps. If we are using an external test executable # (most commonly in Debian autopkgtests) then the mocking won't work. @unittest.skipIf('MESON_EXE' in os.environ, 'MESON_EXE is defined, can not use mocking.') def test_cross_file_system_paths(self): if is_windows(): raise unittest.SkipTest('system crossfile paths not defined for Windows (yet)') testdir = os.path.join(self.common_test_dir, '1 trivial') cross_content = self._cross_file_generator() with tempfile.TemporaryDirectory() as d: dir_ = os.path.join(d, 'meson', 'cross') os.makedirs(dir_) with tempfile.NamedTemporaryFile('w', dir=dir_, delete=False) as f: f.write(cross_content) name = os.path.basename(f.name) with mock.patch.dict(os.environ, {'XDG_DATA_HOME': d}): self.init(testdir, extra_args=['--cross-file=' + name], inprocess=True) self.wipe() with mock.patch.dict(os.environ, {'XDG_DATA_DIRS': d}): os.environ.pop('XDG_DATA_HOME', None) self.init(testdir, extra_args=['--cross-file=' + name], inprocess=True) self.wipe() with tempfile.TemporaryDirectory() as d: dir_ = os.path.join(d, '.local', 'share', 'meson', 'cross') os.makedirs(dir_) with tempfile.NamedTemporaryFile('w', dir=dir_, delete=False) as f: f.write(cross_content) name = os.path.basename(f.name) # If XDG_DATA_HOME is set in the environment running the # tests this test will fail, os mock the environment, pop # it, then test with mock.patch.dict(os.environ): os.environ.pop('XDG_DATA_HOME', None) with mock.patch('mesonbuild.coredata.os.path.expanduser', lambda x: x.replace('~', d)): self.init(testdir, extra_args=['--cross-file=' + name], inprocess=True) self.wipe() def helper_create_cross_file(self, values): """Create a config file as a temporary file. values should be a nested dictionary structure of {section: {key: value}} """ filename = os.path.join(self.builddir, 'generated{}.config'.format(self.current_config)) self.current_config += 1 with open(filename, 'wt') as f: for section, entries in values.items(): f.write('[{}]\n'.format(section)) for k, v in entries.items(): f.write("{}='{}'\n".format(k, v)) return filename def test_cross_file_dirs(self): testcase = os.path.join(self.unit_test_dir, '60 native file override') self.init(testcase, default_args=False, extra_args=['--native-file', os.path.join(testcase, 'nativefile'), '--cross-file', os.path.join(testcase, 'crossfile'), '-Ddef_bindir=binbar', '-Ddef_datadir=databar', '-Ddef_includedir=includebar', '-Ddef_infodir=infobar', '-Ddef_libdir=libbar', '-Ddef_libexecdir=libexecbar', '-Ddef_localedir=localebar', '-Ddef_localstatedir=localstatebar', '-Ddef_mandir=manbar', '-Ddef_sbindir=sbinbar', '-Ddef_sharedstatedir=sharedstatebar', '-Ddef_sysconfdir=sysconfbar']) def test_cross_file_dirs_overridden(self): testcase = os.path.join(self.unit_test_dir, '60 native file override') self.init(testcase, default_args=False, extra_args=['--native-file', os.path.join(testcase, 'nativefile'), '--cross-file', os.path.join(testcase, 'crossfile'), '-Ddef_libdir=liblib', '-Dlibdir=liblib', '-Ddef_bindir=binbar', '-Ddef_datadir=databar', '-Ddef_includedir=includebar', '-Ddef_infodir=infobar', '-Ddef_libexecdir=libexecbar', '-Ddef_localedir=localebar', '-Ddef_localstatedir=localstatebar', '-Ddef_mandir=manbar', '-Ddef_sbindir=sbinbar', '-Ddef_sharedstatedir=sharedstatebar', '-Ddef_sysconfdir=sysconfbar']) def test_cross_file_dirs_chain(self): # crossfile2 overrides crossfile overrides nativefile testcase = os.path.join(self.unit_test_dir, '60 native file override') self.init(testcase, default_args=False, extra_args=['--native-file', os.path.join(testcase, 'nativefile'), '--cross-file', os.path.join(testcase, 'crossfile'), '--cross-file', os.path.join(testcase, 'crossfile2'), '-Ddef_bindir=binbar2', '-Ddef_datadir=databar', '-Ddef_includedir=includebar', '-Ddef_infodir=infobar', '-Ddef_libdir=libbar', '-Ddef_libexecdir=libexecbar', '-Ddef_localedir=localebar', '-Ddef_localstatedir=localstatebar', '-Ddef_mandir=manbar', '-Ddef_sbindir=sbinbar', '-Ddef_sharedstatedir=sharedstatebar', '-Ddef_sysconfdir=sysconfbar']) def test_user_options(self): # This is just a touch test for cross file, since the implementation # shares code after loading from the files testcase = os.path.join(self.common_test_dir, '41 options') config = self.helper_create_cross_file({'project options': {'testoption': 'some other value'}}) with self.assertRaises(subprocess.CalledProcessError) as cm: self.init(testcase, extra_args=['--cross-file', config]) self.assertRegex(cm.exception.stdout, r'Incorrect value to [a-z]+ option') def test_builtin_options(self): testcase = os.path.join(self.common_test_dir, '2 cpp') config = self.helper_create_cross_file({'built-in options': {'cpp_std': 'c++14'}}) self.init(testcase, extra_args=['--cross-file', config]) configuration = self.introspect('--buildoptions') for each in configuration: if each['name'] == 'cpp_std': self.assertEqual(each['value'], 'c++14') break else: self.fail('No c++ standard set?') def test_builtin_options_per_machine(self): """Test options that are allowed to be set on a per-machine basis. Such options could be passed twice, once for the build machine, and once for the host machine. I've picked pkg-config path, but any would do that can be set for both. """ testcase = os.path.join(self.common_test_dir, '2 cpp') cross = self.helper_create_cross_file({'built-in options': {'pkg_config_path': '/cross/path', 'cpp_std': 'c++17'}}) native = self.helper_create_cross_file({'built-in options': {'pkg_config_path': '/native/path', 'cpp_std': 'c++14'}}) # Ensure that PKG_CONFIG_PATH is not set in the environment with mock.patch.dict('os.environ'): for k in ['PKG_CONFIG_PATH', 'PKG_CONFIG_PATH_FOR_BUILD']: try: del os.environ[k] except KeyError: pass self.init(testcase, extra_args=['--cross-file', cross, '--native-file', native]) configuration = self.introspect('--buildoptions') found = 0 for each in configuration: if each['name'] == 'pkg_config_path': self.assertEqual(each['value'], ['/cross/path']) found += 1 elif each['name'] == 'cpp_std': self.assertEqual(each['value'], 'c++17') found += 1 elif each['name'] == 'build.pkg_config_path': self.assertEqual(each['value'], ['/native/path']) found += 1 elif each['name'] == 'build.cpp_std': self.assertEqual(each['value'], 'c++14') found += 1 if found == 4: break self.assertEqual(found, 4, 'Did not find all sections.') def test_builtin_options_conf_overrides_env(self): testcase = os.path.join(self.common_test_dir, '2 cpp') config = self.helper_create_cross_file({'built-in options': {'pkg_config_path': '/native'}}) cross = self.helper_create_cross_file({'built-in options': {'pkg_config_path': '/cross'}}) self.init(testcase, extra_args=['--native-file', config, '--cross-file', cross], override_envvars={'PKG_CONFIG_PATH': '/bar', 'PKG_CONFIG_PATH_FOR_BUILD': '/dir'}) configuration = self.introspect('--buildoptions') found = 0 for each in configuration: if each['name'] == 'pkg_config_path': self.assertEqual(each['value'], ['/cross']) found += 1 elif each['name'] == 'build.pkg_config_path': self.assertEqual(each['value'], ['/native']) found += 1 if found == 2: break self.assertEqual(found, 2, 'Did not find all sections.') class TAPParserTests(unittest.TestCase): def assert_test(self, events, **kwargs): if 'explanation' not in kwargs: kwargs['explanation'] = None self.assertEqual(next(events), TAPParser.Test(**kwargs)) def assert_plan(self, events, **kwargs): if 'skipped' not in kwargs: kwargs['skipped'] = False if 'explanation' not in kwargs: kwargs['explanation'] = None self.assertEqual(next(events), TAPParser.Plan(**kwargs)) def assert_version(self, events, **kwargs): self.assertEqual(next(events), TAPParser.Version(**kwargs)) def assert_error(self, events): self.assertEqual(type(next(events)), TAPParser.Error) def assert_bailout(self, events, **kwargs): self.assertEqual(next(events), TAPParser.Bailout(**kwargs)) def assert_last(self, events): with self.assertRaises(StopIteration): next(events) def parse_tap(self, s): parser = TAPParser() return iter(parser.parse(io.StringIO(s))) def parse_tap_v13(self, s): events = self.parse_tap('TAP version 13\n' + s) self.assert_version(events, version=13) return events def test_empty(self): events = self.parse_tap('') self.assert_last(events) def test_empty_plan(self): events = self.parse_tap('1..0') self.assert_plan(events, num_tests=0, late=False, skipped=True) self.assert_last(events) def test_plan_directive(self): events = self.parse_tap('1..0 # skipped for some reason') self.assert_plan(events, num_tests=0, late=False, skipped=True, explanation='for some reason') self.assert_last(events) events = self.parse_tap('1..1 # skipped for some reason\nok 1') self.assert_error(events) self.assert_plan(events, num_tests=1, late=False, skipped=True, explanation='for some reason') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_last(events) events = self.parse_tap('1..1 # todo not supported here\nok 1') self.assert_error(events) self.assert_plan(events, num_tests=1, late=False, skipped=False, explanation='not supported here') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_last(events) def test_one_test_ok(self): events = self.parse_tap('ok') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_last(events) def test_one_test_with_number(self): events = self.parse_tap('ok 1') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_last(events) def test_one_test_with_name(self): events = self.parse_tap('ok 1 abc') self.assert_test(events, number=1, name='abc', result=TestResult.OK) self.assert_last(events) def test_one_test_not_ok(self): events = self.parse_tap('not ok') self.assert_test(events, number=1, name='', result=TestResult.FAIL) self.assert_last(events) def test_one_test_todo(self): events = self.parse_tap('not ok 1 abc # TODO') self.assert_test(events, number=1, name='abc', result=TestResult.EXPECTEDFAIL) self.assert_last(events) events = self.parse_tap('ok 1 abc # TODO') self.assert_test(events, number=1, name='abc', result=TestResult.UNEXPECTEDPASS) self.assert_last(events) def test_one_test_skip(self): events = self.parse_tap('ok 1 abc # SKIP') self.assert_test(events, number=1, name='abc', result=TestResult.SKIP) self.assert_last(events) def test_one_test_skip_failure(self): events = self.parse_tap('not ok 1 abc # SKIP') self.assert_test(events, number=1, name='abc', result=TestResult.FAIL) self.assert_last(events) def test_many_early_plan(self): events = self.parse_tap('1..4\nok 1\nnot ok 2\nok 3\nnot ok 4') self.assert_plan(events, num_tests=4, late=False) self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_test(events, number=2, name='', result=TestResult.FAIL) self.assert_test(events, number=3, name='', result=TestResult.OK) self.assert_test(events, number=4, name='', result=TestResult.FAIL) self.assert_last(events) def test_many_late_plan(self): events = self.parse_tap('ok 1\nnot ok 2\nok 3\nnot ok 4\n1..4') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_test(events, number=2, name='', result=TestResult.FAIL) self.assert_test(events, number=3, name='', result=TestResult.OK) self.assert_test(events, number=4, name='', result=TestResult.FAIL) self.assert_plan(events, num_tests=4, late=True) self.assert_last(events) def test_directive_case(self): events = self.parse_tap('ok 1 abc # skip') self.assert_test(events, number=1, name='abc', result=TestResult.SKIP) self.assert_last(events) events = self.parse_tap('ok 1 abc # ToDo') self.assert_test(events, number=1, name='abc', result=TestResult.UNEXPECTEDPASS) self.assert_last(events) def test_directive_explanation(self): events = self.parse_tap('ok 1 abc # skip why') self.assert_test(events, number=1, name='abc', result=TestResult.SKIP, explanation='why') self.assert_last(events) events = self.parse_tap('ok 1 abc # ToDo Because') self.assert_test(events, number=1, name='abc', result=TestResult.UNEXPECTEDPASS, explanation='Because') self.assert_last(events) def test_one_test_early_plan(self): events = self.parse_tap('1..1\nok') self.assert_plan(events, num_tests=1, late=False) self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_last(events) def test_one_test_late_plan(self): events = self.parse_tap('ok\n1..1') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_plan(events, num_tests=1, late=True) self.assert_last(events) def test_out_of_order(self): events = self.parse_tap('ok 2') self.assert_error(events) self.assert_test(events, number=2, name='', result=TestResult.OK) self.assert_last(events) def test_middle_plan(self): events = self.parse_tap('ok 1\n1..2\nok 2') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_plan(events, num_tests=2, late=True) self.assert_error(events) self.assert_test(events, number=2, name='', result=TestResult.OK) self.assert_last(events) def test_too_many_plans(self): events = self.parse_tap('1..1\n1..2\nok 1') self.assert_plan(events, num_tests=1, late=False) self.assert_error(events) self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_last(events) def test_too_many(self): events = self.parse_tap('ok 1\nnot ok 2\n1..1') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_test(events, number=2, name='', result=TestResult.FAIL) self.assert_plan(events, num_tests=1, late=True) self.assert_error(events) self.assert_last(events) events = self.parse_tap('1..1\nok 1\nnot ok 2') self.assert_plan(events, num_tests=1, late=False) self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_test(events, number=2, name='', result=TestResult.FAIL) self.assert_error(events) self.assert_last(events) def test_too_few(self): events = self.parse_tap('ok 1\nnot ok 2\n1..3') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_test(events, number=2, name='', result=TestResult.FAIL) self.assert_plan(events, num_tests=3, late=True) self.assert_error(events) self.assert_last(events) events = self.parse_tap('1..3\nok 1\nnot ok 2') self.assert_plan(events, num_tests=3, late=False) self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_test(events, number=2, name='', result=TestResult.FAIL) self.assert_error(events) self.assert_last(events) def test_too_few_bailout(self): events = self.parse_tap('1..3\nok 1\nnot ok 2\nBail out! no third test') self.assert_plan(events, num_tests=3, late=False) self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_test(events, number=2, name='', result=TestResult.FAIL) self.assert_bailout(events, message='no third test') self.assert_last(events) def test_diagnostics(self): events = self.parse_tap('1..1\n# ignored\nok 1') self.assert_plan(events, num_tests=1, late=False) self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_last(events) events = self.parse_tap('# ignored\n1..1\nok 1\n# ignored too') self.assert_plan(events, num_tests=1, late=False) self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_last(events) events = self.parse_tap('# ignored\nok 1\n1..1\n# ignored too') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_plan(events, num_tests=1, late=True) self.assert_last(events) def test_empty_line(self): events = self.parse_tap('1..1\n\nok 1') self.assert_plan(events, num_tests=1, late=False) self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_last(events) def test_unexpected(self): events = self.parse_tap('1..1\ninvalid\nok 1') self.assert_plan(events, num_tests=1, late=False) self.assert_error(events) self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_last(events) def test_version(self): events = self.parse_tap('TAP version 13\n') self.assert_version(events, version=13) self.assert_last(events) events = self.parse_tap('TAP version 12\n') self.assert_error(events) self.assert_last(events) events = self.parse_tap('1..0\nTAP version 13\n') self.assert_plan(events, num_tests=0, late=False, skipped=True) self.assert_error(events) self.assert_last(events) def test_yaml(self): events = self.parse_tap_v13('ok\n ---\n foo: abc\n bar: def\n ...\nok 2') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_test(events, number=2, name='', result=TestResult.OK) self.assert_last(events) events = self.parse_tap_v13('ok\n ---\n foo: abc\n bar: def') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_error(events) self.assert_last(events) events = self.parse_tap_v13('ok 1\n ---\n foo: abc\n bar: def\nnot ok 2') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_error(events) self.assert_test(events, number=2, name='', result=TestResult.FAIL) self.assert_last(events) class SubprojectsCommandTests(BasePlatformTests): def setUp(self): super().setUp() self.root_dir = Path(self.builddir) self.project_dir = self.root_dir / 'src' self._create_project(self.project_dir) self.subprojects_dir = self.project_dir / 'subprojects' os.makedirs(str(self.subprojects_dir)) def _create_project(self, path, project_name='dummy'): os.makedirs(str(path), exist_ok=True) with open(str(path / 'meson.build'), 'w') as f: f.write("project('{}')".format(project_name)) def _git(self, cmd, workdir): return git(cmd, str(workdir), check=True)[1].strip() def _git_config(self, workdir): self._git(['config', 'user.name', 'Meson Test'], workdir) self._git(['config', 'user.email', 'meson.test@example.com'], workdir) def _git_remote(self, cmd, name): return self._git(cmd, self.root_dir / name) def _git_local(self, cmd, name): return self._git(cmd, self.subprojects_dir / name) def _git_local_branch(self, name): # Same as `git branch --show-current` but compatible with older git version branch = self._git_local(['rev-parse', '--abbrev-ref', 'HEAD'], name) return branch if branch != 'HEAD' else '' def _git_local_commit(self, name, ref='HEAD'): return self._git_local(['rev-parse', ref], name) def _git_remote_commit(self, name, ref='HEAD'): return self._git_remote(['rev-parse', ref], name) def _git_create_repo(self, path): # If a user has git configuration init.defaultBranch set we want to override that with tempfile.TemporaryDirectory() as d: out = git(['--version'], str(d))[1] if version_compare(mesonbuild.environment.search_version(out), '>= 2.28'): extra_cmd = ['--initial-branch', 'master'] else: extra_cmd = [] self._create_project(path) self._git(['init'] + extra_cmd, path) self._git_config(path) self._git(['add', '.'], path) self._git(['commit', '-m', 'Initial commit'], path) def _git_create_remote_repo(self, name): self._git_create_repo(self.root_dir / name) def _git_create_local_repo(self, name): self._git_create_repo(self.subprojects_dir / name) def _git_create_remote_commit(self, name, branch): self._git_remote(['checkout', branch], name) self._git_remote(['commit', '--allow-empty', '-m', 'initial {} commit'.format(branch)], name) def _git_create_remote_branch(self, name, branch): self._git_remote(['checkout', '-b', branch], name) self._git_remote(['commit', '--allow-empty', '-m', 'initial {} commit'.format(branch)], name) def _git_create_remote_tag(self, name, tag): self._git_remote(['commit', '--allow-empty', '-m', 'tag {} commit'.format(tag)], name) self._git_remote(['tag', tag], name) def _wrap_create_git(self, name, revision='master'): path = self.root_dir / name with open(str((self.subprojects_dir / name).with_suffix('.wrap')), 'w') as f: f.write(textwrap.dedent( ''' [wrap-git] url={} revision={} '''.format(os.path.abspath(str(path)), revision))) def _wrap_create_file(self, name, tarball='dummy.tar.gz'): path = self.root_dir / tarball with open(str((self.subprojects_dir / name).with_suffix('.wrap')), 'w') as f: f.write(textwrap.dedent( ''' [wrap-file] source_url={} '''.format(os.path.abspath(str(path))))) def _subprojects_cmd(self, args): return self._run(self.meson_command + ['subprojects'] + args, workdir=str(self.project_dir)) def test_git_update(self): subp_name = 'sub1' # Create a fake remote git repository and a wrap file. Checks that # "meson subprojects download" works. self._git_create_remote_repo(subp_name) self._wrap_create_git(subp_name) self._subprojects_cmd(['download']) self.assertPathExists(str(self.subprojects_dir / subp_name)) self._git_config(self.subprojects_dir / subp_name) # Create a new remote branch and update the wrap file. Checks that # "meson subprojects update --reset" checkout the new branch. self._git_create_remote_branch(subp_name, 'newbranch') self._wrap_create_git(subp_name, 'newbranch') self._subprojects_cmd(['update', '--reset']) self.assertEqual(self._git_local_branch(subp_name), 'newbranch') self.assertEqual(self._git_local_commit(subp_name), self._git_remote_commit(subp_name, 'newbranch')) # Update remote newbranch. Checks the new commit is pulled into existing # local newbranch. Make sure it does not print spurious 'git stash' message. self._git_create_remote_commit(subp_name, 'newbranch') out = self._subprojects_cmd(['update', '--reset']) self.assertNotIn('No local changes to save', out) self.assertEqual(self._git_local_branch(subp_name), 'newbranch') self.assertEqual(self._git_local_commit(subp_name), self._git_remote_commit(subp_name, 'newbranch')) # Update remote newbranch and switch to another branch. Checks that it # switch current branch to newbranch and pull latest commit. self._git_local(['checkout', 'master'], subp_name) self._git_create_remote_commit(subp_name, 'newbranch') self._subprojects_cmd(['update', '--reset']) self.assertEqual(self._git_local_branch(subp_name), 'newbranch') self.assertEqual(self._git_local_commit(subp_name), self._git_remote_commit(subp_name, 'newbranch')) # Stage some local changes then update. Checks that local changes got # stashed. self._create_project(self.subprojects_dir / subp_name, 'new_project_name') self._git_local(['add', '.'], subp_name) self._git_create_remote_commit(subp_name, 'newbranch') self._subprojects_cmd(['update', '--reset']) self.assertEqual(self._git_local_branch(subp_name), 'newbranch') self.assertEqual(self._git_local_commit(subp_name), self._git_remote_commit(subp_name, 'newbranch')) self.assertTrue(self._git_local(['stash', 'list'], subp_name)) # Create a new remote tag and update the wrap file. Checks that # "meson subprojects update --reset" checkout the new tag in detached mode. self._git_create_remote_tag(subp_name, 'newtag') self._wrap_create_git(subp_name, 'newtag') self._subprojects_cmd(['update', '--reset']) self.assertEqual(self._git_local_branch(subp_name), '') self.assertEqual(self._git_local_commit(subp_name), self._git_remote_commit(subp_name, 'newtag')) # Create a new remote commit and update the wrap file with the commit id. # Checks that "meson subprojects update --reset" checkout the new commit # in detached mode. self._git_local(['checkout', 'master'], subp_name) self._git_create_remote_commit(subp_name, 'newbranch') new_commit = self._git_remote(['rev-parse', 'HEAD'], subp_name) self._wrap_create_git(subp_name, new_commit) self._subprojects_cmd(['update', '--reset']) self.assertEqual(self._git_local_branch(subp_name), '') self.assertEqual(self._git_local_commit(subp_name), new_commit) # Create a local project not in a git repository, then update it with # a git wrap. Without --reset it should print error message and return # failure. With --reset it should delete existing project and clone the # new project. subp_name = 'sub2' self._create_project(self.subprojects_dir / subp_name) self._git_create_remote_repo(subp_name) self._wrap_create_git(subp_name) with self.assertRaises(subprocess.CalledProcessError) as cm: self._subprojects_cmd(['update']) self.assertIn('Not a git repository', cm.exception.output) self._subprojects_cmd(['update', '--reset']) self.assertEqual(self._git_local_commit(subp_name), self._git_remote_commit(subp_name)) @skipIfNoExecutable('true') def test_foreach(self): self._create_project(self.subprojects_dir / 'sub_file') self._wrap_create_file('sub_file') self._git_create_local_repo('sub_git') self._wrap_create_git('sub_git') self._git_create_local_repo('sub_git_no_wrap') def ran_in(s): ret = [] prefix = 'Executing command in ' for l in s.splitlines(): if l.startswith(prefix): ret.append(l[len(prefix):]) return sorted(ret) dummy_cmd = ['true'] out = self._subprojects_cmd(['foreach'] + dummy_cmd) self.assertEqual(ran_in(out), sorted(['subprojects/sub_file', 'subprojects/sub_git', 'subprojects/sub_git_no_wrap'])) out = self._subprojects_cmd(['foreach', '--types', 'git,file'] + dummy_cmd) self.assertEqual(ran_in(out), sorted(['subprojects/sub_file', 'subprojects/sub_git'])) out = self._subprojects_cmd(['foreach', '--types', 'file'] + dummy_cmd) self.assertEqual(ran_in(out), ['subprojects/sub_file']) out = self._subprojects_cmd(['foreach', '--types', 'git'] + dummy_cmd) self.assertEqual(ran_in(out), ['subprojects/sub_git']) def _clang_at_least(compiler: 'Compiler', minver: str, apple_minver: T.Optional[str]) -> bool: """ check that Clang compiler is at least a specified version, whether AppleClang or regular Clang Parameters ---------- compiler: Meson compiler object minver: str Clang minimum version apple_minver: str AppleCLang minimum version Returns ------- at_least: bool Clang is at least the specified version """ if isinstance(compiler, (mesonbuild.compilers.AppleClangCCompiler, mesonbuild.compilers.AppleClangCPPCompiler)): if apple_minver is None: return False return version_compare(compiler.version, apple_minver) return version_compare(compiler.version, minver) def unset_envs(): # For unit tests we must fully control all command lines # so that there are no unexpected changes coming from the # environment, for example when doing a package build. varnames = ['CPPFLAGS', 'LDFLAGS'] + list(mesonbuild.compilers.compilers.CFLAGS_MAPPING.values()) for v in varnames: if v in os.environ: del os.environ[v] def convert_args(argv): # If we got passed a list of tests, pass it on pytest_args = ['-v'] if '-v' in argv else [] test_list = [] for arg in argv: if arg.startswith('-'): if arg in ('-f', '--failfast'): arg = '--exitfirst' pytest_args.append(arg) continue # ClassName.test_name => 'ClassName and test_name' if '.' in arg: arg = ' and '.join(arg.split('.')) test_list.append(arg) if test_list: pytest_args += ['-k', ' or '.join(test_list)] return pytest_args def running_single_tests(argv, cases): ''' Check whether we only got arguments for running individual tests, not entire testcases, and not all testcases (no test args). ''' got_test_arg = False for arg in argv: if arg.startswith('-'): continue for case in cases: if not arg.startswith(case): continue if '.' not in arg: # Got a testcase, done return False got_test_arg = True return got_test_arg def main(): unset_envs() cases = ['InternalTests', 'DataTests', 'AllPlatformTests', 'FailureTests', 'PythonTests', 'NativeFileTests', 'RewriterTests', 'CrossFileTests', 'TAPParserTests', 'SubprojectsCommandTests', 'LinuxlikeTests', 'LinuxCrossArmTests', 'LinuxCrossMingwTests', 'WindowsTests', 'DarwinTests'] try: import pytest # noqa: F401 # Need pytest-xdist for `-n` arg import xdist # noqa: F401 pytest_args = [] # Don't use pytest-xdist when running single unit tests since it wastes # time spawning a lot of processes to distribute tests to in that case. if not running_single_tests(sys.argv, cases): pytest_args += ['-n', 'auto'] pytest_args += ['./run_unittests.py'] pytest_args += convert_args(sys.argv[1:]) return subprocess.run(python_command + ['-m', 'pytest'] + pytest_args).returncode except ImportError: print('pytest-xdist not found, using unittest instead') # Fallback to plain unittest. return unittest.main(defaultTest=cases, buffer=True) if __name__ == '__main__': print('Meson build system', mesonbuild.coredata.version, 'Unit Tests') start = time.monotonic() try: raise SystemExit(main()) finally: print('Total time: {:.3f} seconds'.format(time.monotonic() - start))
46.241985
199
0.587201
import time import stat import subprocess import re import json import tempfile import textwrap import os import shutil import sys import unittest import platform import pickle import functools import io import operator import threading import zipfile, tarfile import hashlib from itertools import chain from unittest import mock from configparser import ConfigParser from contextlib import contextmanager from glob import glob from pathlib import (PurePath, Path) from distutils.dir_util import copy_tree import typing as T import mesonbuild.mlog import mesonbuild.depfile import mesonbuild.dependencies.base import mesonbuild.compilers import mesonbuild.envconfig import mesonbuild.environment import mesonbuild.mesonlib import mesonbuild.coredata import mesonbuild.modules.gnome from mesonbuild.interpreter import Interpreter, ObjectHolder from mesonbuild.interpreterbase import typed_pos_args, InvalidArguments from mesonbuild.ast import AstInterpreter from mesonbuild.mesonlib import ( BuildDirLock, LibType, MachineChoice, PerMachine, Version, is_windows, is_osx, is_cygwin, is_dragonflybsd, is_openbsd, is_haiku, is_sunos, windows_proof_rmtree, python_command, version_compare, split_args, quote_arg, relpath, is_linux, git ) from mesonbuild.environment import detect_ninja from mesonbuild.mesonlib import MesonException, EnvironmentException, OptionKey from mesonbuild.dependencies import PkgConfigDependency, ExternalProgram import mesonbuild.dependencies.base from mesonbuild.build import Target, ConfigurationData import mesonbuild.modules.pkgconfig from mesonbuild.scripts import destdir_join from mesonbuild.mtest import TAPParser, TestResult from mesonbuild.wrap.wrap import PackageDefinition, WrapException from run_tests import ( Backend, FakeBuild, FakeCompilerOptions, ensure_backend_detects_changes, exe_suffix, get_backend_commands, get_builddir_target_args, get_fake_env, get_fake_options, get_meson_script, run_configure_inprocess, run_mtest_inprocess ) if T.TYPE_CHECKING: from mesonbuild.compilers import Compiler URLOPEN_TIMEOUT = 5 @contextmanager def chdir(path: str): curdir = os.getcwd() os.chdir(path) try: yield finally: os.chdir(curdir) def get_dynamic_section_entry(fname: str, entry: str) -> T.Optional[str]: if is_cygwin() or is_osx(): raise unittest.SkipTest('Test only applicable to ELF platforms') try: raw_out = subprocess.check_output(['readelf', '-d', fname], universal_newlines=True) except FileNotFoundError: raise unittest.SkipTest('readelf not found') pattern = re.compile(entry + r': \[(.*?)\]') for line in raw_out.split('\n'): m = pattern.search(line) if m is not None: return str(m.group(1)) return None def get_soname(fname: str) -> T.Optional[str]: return get_dynamic_section_entry(fname, 'soname') def get_rpath(fname: str) -> T.Optional[str]: raw = get_dynamic_section_entry(fname, r'(?:rpath|runpath)') if not raw: return None final = ':'.join([e for e in raw.split(':') if not e.startswith('/nix')]) return final def is_tarball(): if not os.path.isdir('docs'): return True return False def is_ci(): if 'CI' in os.environ: return True return False def _git_init(project_dir): # If a user has git configuration init.defaultBranch set we want to override that with tempfile.TemporaryDirectory() as d: out = git(['--version'], str(d))[1] if version_compare(mesonbuild.environment.search_version(out), '>= 2.28'): extra_cmd = ['--initial-branch', 'master'] else: extra_cmd = [] subprocess.check_call(['git', 'init'] + extra_cmd, cwd=project_dir, stdout=subprocess.DEVNULL) subprocess.check_call(['git', 'config', 'user.name', 'Author Person'], cwd=project_dir) subprocess.check_call(['git', 'config', 'user.email', 'teh_coderz@example.com'], cwd=project_dir) _git_add_all(project_dir) def _git_add_all(project_dir): subprocess.check_call('git add *', cwd=project_dir, shell=True, stdout=subprocess.DEVNULL) subprocess.check_call(['git', 'commit', '-a', '-m', 'I am a project'], cwd=project_dir, stdout=subprocess.DEVNULL) @functools.lru_cache() def is_real_gnu_compiler(path): if not path: return False out = subprocess.check_output([path, '--version'], universal_newlines=True, stderr=subprocess.STDOUT) return 'Free Software Foundation' in out def skipIfNoExecutable(exename): def wrapper(func): @functools.wraps(func) def wrapped(*args, **kwargs): if shutil.which(exename) is None: raise unittest.SkipTest(exename + ' not found') return func(*args, **kwargs) return wrapped return wrapper def skipIfNoPkgconfig(f): @functools.wraps(f) def wrapped(*args, **kwargs): if not is_ci() and shutil.which('pkg-config') is None: raise unittest.SkipTest('pkg-config not found') return f(*args, **kwargs) return wrapped def skipIfNoPkgconfigDep(depname): def wrapper(func): @functools.wraps(func) def wrapped(*args, **kwargs): if not is_ci() and shutil.which('pkg-config') is None: raise unittest.SkipTest('pkg-config not found') if not is_ci() and subprocess.call(['pkg-config', '--exists', depname]) != 0: raise unittest.SkipTest('pkg-config dependency {} not found.'.format(depname)) return func(*args, **kwargs) return wrapped return wrapper def skip_if_no_cmake(f): @functools.wraps(f) def wrapped(*args, **kwargs): if not is_ci() and shutil.which('cmake') is None: raise unittest.SkipTest('cmake not found') return f(*args, **kwargs) return wrapped def skip_if_not_language(lang): def wrapper(func): @functools.wraps(func) def wrapped(*args, **kwargs): try: env = get_fake_env() f = getattr(env, 'detect_{}_compiler'.format(lang)) f(MachineChoice.HOST) except EnvironmentException: raise unittest.SkipTest('No {} compiler found.'.format(lang)) return func(*args, **kwargs) return wrapped return wrapper def skip_if_env_set(key): def wrapper(func): @functools.wraps(func) def wrapped(*args, **kwargs): old = None if key in os.environ: if not is_ci(): raise unittest.SkipTest('Env var {!r} set, skipping'.format(key)) old = os.environ.pop(key) try: return func(*args, **kwargs) finally: if old is not None: os.environ[key] = old return wrapped return wrapper def skip_if_not_base_option(feature): def actual(f): @functools.wraps(f) def wrapped(*args, **kwargs): env = get_fake_env() cc = env.detect_c_compiler(MachineChoice.HOST) key = OptionKey(feature) if key not in cc.base_options: raise unittest.SkipTest( '{} not available with {}'.format(feature, cc.id)) return f(*args, **kwargs) return wrapped return actual @contextmanager def temp_filename(): fd, filename = tempfile.mkstemp() os.close(fd) try: yield filename finally: try: os.remove(filename) except OSError: pass @contextmanager def no_pkgconfig(): old_which = shutil.which old_search = ExternalProgram._search def new_search(self, name, search_dir): if name == 'pkg-config': return [None] return old_search(self, name, search_dir) def new_which(cmd, *kwargs): if cmd == 'pkg-config': return None return old_which(cmd, *kwargs) shutil.which = new_which ExternalProgram._search = new_search try: yield finally: shutil.which = old_which ExternalProgram._search = old_search class InternalTests(unittest.TestCase): def test_version_number(self): searchfunc = mesonbuild.environment.search_version self.assertEqual(searchfunc('foobar 1.2.3'), '1.2.3') self.assertEqual(searchfunc('1.2.3'), '1.2.3') self.assertEqual(searchfunc('foobar 2016.10.28 1.2.3'), '1.2.3') self.assertEqual(searchfunc('2016.10.28 1.2.3'), '1.2.3') self.assertEqual(searchfunc('foobar 2016.10.128'), '2016.10.128') self.assertEqual(searchfunc('2016.10.128'), '2016.10.128') self.assertEqual(searchfunc('2016.10'), '2016.10') self.assertEqual(searchfunc('2016.10 1.2.3'), '1.2.3') self.assertEqual(searchfunc('oops v1.2.3'), '1.2.3') self.assertEqual(searchfunc('2016.oops 1.2.3'), '1.2.3') self.assertEqual(searchfunc('2016.x'), 'unknown version') def test_mode_symbolic_to_bits(self): modefunc = mesonbuild.mesonlib.FileMode.perms_s_to_bits self.assertEqual(modefunc('---------'), 0) self.assertEqual(modefunc('r--------'), stat.S_IRUSR) self.assertEqual(modefunc('---r-----'), stat.S_IRGRP) self.assertEqual(modefunc('------r--'), stat.S_IROTH) self.assertEqual(modefunc('-w-------'), stat.S_IWUSR) self.assertEqual(modefunc('----w----'), stat.S_IWGRP) self.assertEqual(modefunc('-------w-'), stat.S_IWOTH) self.assertEqual(modefunc('--x------'), stat.S_IXUSR) self.assertEqual(modefunc('-----x---'), stat.S_IXGRP) self.assertEqual(modefunc('--------x'), stat.S_IXOTH) self.assertEqual(modefunc('--S------'), stat.S_ISUID) self.assertEqual(modefunc('-----S---'), stat.S_ISGID) self.assertEqual(modefunc('--------T'), stat.S_ISVTX) self.assertEqual(modefunc('--s------'), stat.S_ISUID | stat.S_IXUSR) self.assertEqual(modefunc('-----s---'), stat.S_ISGID | stat.S_IXGRP) self.assertEqual(modefunc('--------t'), stat.S_ISVTX | stat.S_IXOTH) self.assertEqual(modefunc('rwx------'), stat.S_IRWXU) self.assertEqual(modefunc('---rwx---'), stat.S_IRWXG) self.assertEqual(modefunc('------rwx'), stat.S_IRWXO) # We could keep listing combinations exhaustively but that seems # tedious and pointless. Just test a few more. self.assertEqual(modefunc('rwxr-xr-x'), stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH) self.assertEqual(modefunc('rw-r--r--'), stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH) self.assertEqual(modefunc('rwsr-x---'), stat.S_IRWXU | stat.S_ISUID | stat.S_IRGRP | stat.S_IXGRP) def test_compiler_args_class_none_flush(self): cc = mesonbuild.compilers.ClangCCompiler([], 'fake', MachineChoice.HOST, False, mock.Mock()) a = cc.compiler_args(['-I.']) #first we are checking if the tree construction deduplicates the correct -I argument a += ['-I..'] a += ['-I./tests/'] a += ['-I./tests2/'] #think this here as assertion, we cannot apply it, otherwise the CompilerArgs would already flush the changes: # assertEqual(a, ['-I.', '-I./tests2/', '-I./tests/', '-I..', '-I.']) a += ['-I.'] a += ['-I.', '-I./tests/'] self.assertEqual(a, ['-I.', '-I./tests/', '-I./tests2/', '-I..']) #then we are checking that when CompilerArgs already have a build container list, that the deduplication is taking the correct one a += ['-I.', '-I./tests2/'] self.assertEqual(a, ['-I.', '-I./tests2/', '-I./tests/', '-I..']) def test_compiler_args_class_d(self): d = mesonbuild.compilers.DmdDCompiler([], 'fake', MachineChoice.HOST, 'info', 'arch') # check include order is kept when deduplicating a = d.compiler_args(['-Ifirst', '-Isecond', '-Ithird']) a += ['-Ifirst'] self.assertEqual(a, ['-Ifirst', '-Isecond', '-Ithird']) def test_compiler_args_class_clike(self): cc = mesonbuild.compilers.ClangCCompiler([], 'fake', MachineChoice.HOST, False, mock.Mock()) # Test that empty initialization works a = cc.compiler_args() self.assertEqual(a, []) # Test that list initialization works a = cc.compiler_args(['-I.', '-I..']) self.assertEqual(a, ['-I.', '-I..']) # Test that there is no de-dup on initialization self.assertEqual(cc.compiler_args(['-I.', '-I.']), ['-I.', '-I.']) ## Test that appending works a.append('-I..') self.assertEqual(a, ['-I..', '-I.']) a.append('-O3') self.assertEqual(a, ['-I..', '-I.', '-O3']) ## Test that in-place addition works a += ['-O2', '-O2'] self.assertEqual(a, ['-I..', '-I.', '-O3', '-O2', '-O2']) # Test that removal works a.remove('-O2') self.assertEqual(a, ['-I..', '-I.', '-O3', '-O2']) # Test that de-dup happens on addition a += ['-Ifoo', '-Ifoo'] self.assertEqual(a, ['-Ifoo', '-I..', '-I.', '-O3', '-O2']) # .extend() is just +=, so we don't test it ['-Ifoo'] self.assertEqual(a, ['-Ifoo', '-I..', '-I.', '-O3', '-O2']) a = a + ['-Ifoo', '-Ibaz'] self.assertEqual(a, ['-Ifoo', '-Ibaz', '-I..', '-I.', '-O3', '-O2']) a = a + ['-Ibar', '-Wall'] self.assertEqual(a, ['-Ibar', '-Ifoo', '-Ibaz', '-I..', '-I.', '-O3', '-O2', '-Wall']) self.assertEqual(a, ['-Ibar', '-Ifoo', '-Ibaz', '-I..', '-I.', '-O3', '-O2', '-Wall']) a = ['-Werror'] + a self.assertEqual(a, ['-Ibar', '-Ifoo', '-Ibaz', '-I..', '-I.', '-Werror', '-O3', '-O2', '-Wall']) a = ['-Ldir', '-Lbah'] + a self.assertEqual(a, ['-Ibar', '-Ifoo', '-Ibaz', '-I..', '-I.', '-Ldir', '-Lbah', '-Werror', '-O3', '-O2', '-Wall']) a = ['-Ibar', '-Ibaz', '-Ifoo'] + a self.assertEqual(a, ['-Ibar', '-Ifoo', '-Ibaz', '-I..', '-I.', '-Ldir', '-Lbah', '-Werror', '-O3', '-O2', '-Wall']) foodir', '-lfoo']) self.assertEqual(l, ['-Lfoodir', '-lfoo']) l += ['-Lbardir', '-lbar'] self.assertEqual(l, ['-Lbardir', '-Lfoodir', '-lfoo', '-lbar']) l += ['-lbar'] self.assertEqual(l, ['-Lbardir', '-Lfoodir', '-lfoo', '-lbar']) -lfoo']) self.assertEqual(l, ['-Lfoodir', '-lfoo']) l.extend_direct(['-Lbardir', '-lbar']) self.assertEqual(l, ['-Lfoodir', '-lfoo', '-Lbardir', '-lbar']) l.append_direct('-lbar') self.assertEqual(l, ['-Lfoodir', '-lfoo', '-Lbardir', '-lbar', '-lbar']) l.append_direct('/libbaz.a') self.assertEqual(l, ['-Lfoodir', '-lfoo', '-Lbardir', '-lbar', '-lbar', '/libbaz.a']) l.append_direct('/libbaz.a') self.assertEqual(l, ['-Lfoodir', '-lfoo', '-Lbardir', '-lbar', '-lbar', '/libbaz.a']) def test_compiler_args_class_gnuld(self): uild.linkers.GnuBFDDynamicLinker([], MachineChoice.HOST, '-Wl,', []) gcc = mesonbuild.compilers.GnuCCompiler([], 'fake', False, MachineChoice.HOST, mock.Mock(), linker=linker) e', '/usr/local/include'] '-lfoo']) self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-Wl,--start-group', '-lfoo', '-Wl,--end-group']) l.extend_direct(['-Lbardir', '-lbar']) self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-Wl,--start-group', '-lfoo', '-Lbardir', '-lbar', '-Wl,--end-group']) l.append_direct('-lbar') self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-Wl,--start-group', '-lfoo', '-Lbardir', '-lbar', '-lbar', '-Wl,--end-group']) l.append_direct('/libbaz.a') self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-Wl,--start-group', '-lfoo', '-Lbardir', '-lbar', '-lbar', '/libbaz.a', '-Wl,--end-group']) l.append_direct('/libbaz.a') self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-Wl,--start-group', '-lfoo', '-Lbardir', '-lbar', '-lbar', '/libbaz.a', '-Wl,--end-group']) l += ['-Lfoo', '-Wl,--export-dynamic'] self.assertEqual(l.to_native(copy=True), ['-Lfoo', '-Lfoodir', '-Wl,--start-group', '-lfoo', '-Lbardir', '-lbar', '-lbar', '/libbaz.a', '-Wl,--end-group', '-Wl,--export-dynamic']) # -Wl,-lfoo is detected as a library and gets added to the group l.append('-Wl,-ldl') self.assertEqual(l.to_native(copy=True), ['-Lfoo', '-Lfoodir', '-Wl,--start-group', '-lfoo', '-Lbardir', '-lbar', '-lbar', '/libbaz.a', '-Wl,--export-dynamic', '-Wl,-ldl', '-Wl,--end-group']) def test_compiler_args_remove_system(self): ## Test --start/end-group linker = mesonbuild.linkers.GnuBFDDynamicLinker([], MachineChoice.HOST, '-Wl,', []) gcc = mesonbuild.compilers.GnuCCompiler([], 'fake', False, MachineChoice.HOST, mock.Mock(), linker=linker) ## Ensure that the fake compiler is never called by overriding the relevant function gcc.get_default_include_dirs = lambda: ['/usr/include', '/usr/share/include', '/usr/local/include'] ## Test that 'direct' append and extend works l = gcc.compiler_args(['-Lfoodir', '-lfoo']) self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-Wl,--start-group', '-lfoo', '-Wl,--end-group']) ## Test that to_native removes all system includes l += ['-isystem/usr/include', '-isystem=/usr/share/include', '-DSOMETHING_IMPORTANT=1', '-isystem', '/usr/local/include'] self.assertEqual(l.to_native(copy=True), ['-Lfoodir', '-Wl,--start-group', '-lfoo', '-Wl,--end-group', '-DSOMETHING_IMPORTANT=1']) def test_string_templates_substitution(self): dictfunc = mesonbuild.mesonlib.get_filenames_templates_dict substfunc = mesonbuild.mesonlib.substitute_values ME = mesonbuild.mesonlib.MesonException # Identity self.assertEqual(dictfunc([], []), {}) # One input, no outputs inputs = ['bar/foo.c.in'] outputs = [] ret = dictfunc(inputs, outputs) d = {'@INPUT@': inputs, '@INPUT0@': inputs[0], '@PLAINNAME@': 'foo.c.in', '@BASENAME@': 'foo.c'} # Check dictionary self.assertEqual(ret, d) # Check substitutions cmd = ['some', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), cmd) cmd = ['@INPUT@.out', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), [inputs[0] + '.out'] + cmd[1:]) cmd = ['@INPUT0@.out', '@PLAINNAME@.ok', 'strings'] self.assertEqual(substfunc(cmd, d), [inputs[0] + '.out'] + [d['@PLAINNAME@'] + '.ok'] + cmd[2:]) cmd = ['@INPUT@', '@BASENAME@.hah', 'strings'] self.assertEqual(substfunc(cmd, d), inputs + [d['@BASENAME@'] + '.hah'] + cmd[2:]) cmd = ['@OUTPUT@'] self.assertRaises(ME, substfunc, cmd, d) # One input, one output inputs = ['bar/foo.c.in'] outputs = ['out.c'] ret = dictfunc(inputs, outputs) d = {'@INPUT@': inputs, '@INPUT0@': inputs[0], '@PLAINNAME@': 'foo.c.in', '@BASENAME@': 'foo.c', '@OUTPUT@': outputs, '@OUTPUT0@': outputs[0], '@OUTDIR@': '.'} # Check dictionary self.assertEqual(ret, d) # Check substitutions cmd = ['some', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), cmd) cmd = ['@INPUT@.out', '@OUTPUT@', 'strings'] self.assertEqual(substfunc(cmd, d), [inputs[0] + '.out'] + outputs + cmd[2:]) cmd = ['@INPUT0@.out', '@PLAINNAME@.ok', '@OUTPUT0@'] self.assertEqual(substfunc(cmd, d), [inputs[0] + '.out', d['@PLAINNAME@'] + '.ok'] + outputs) cmd = ['@INPUT@', '@BASENAME@.hah', 'strings'] self.assertEqual(substfunc(cmd, d), inputs + [d['@BASENAME@'] + '.hah'] + cmd[2:]) # One input, one output with a subdir outputs = ['dir/out.c'] ret = dictfunc(inputs, outputs) d = {'@INPUT@': inputs, '@INPUT0@': inputs[0], '@PLAINNAME@': 'foo.c.in', '@BASENAME@': 'foo.c', '@OUTPUT@': outputs, '@OUTPUT0@': outputs[0], '@OUTDIR@': 'dir'} # Check dictionary self.assertEqual(ret, d) # Two inputs, no outputs inputs = ['bar/foo.c.in', 'baz/foo.c.in'] outputs = [] ret = dictfunc(inputs, outputs) d = {'@INPUT@': inputs, '@INPUT0@': inputs[0], '@INPUT1@': inputs[1]} # Check dictionary self.assertEqual(ret, d) # Check substitutions cmd = ['some', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), cmd) cmd = ['@INPUT@', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), inputs + cmd[1:]) cmd = ['@INPUT0@.out', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), [inputs[0] + '.out'] + cmd[1:]) cmd = ['@INPUT0@.out', '@INPUT1@.ok', 'strings'] self.assertEqual(substfunc(cmd, d), [inputs[0] + '.out', inputs[1] + '.ok'] + cmd[2:]) cmd = ['@INPUT0@', '@INPUT1@', 'strings'] self.assertEqual(substfunc(cmd, d), inputs + cmd[2:]) # Many inputs, can't use @INPUT@ like this cmd = ['@INPUT@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) cmd = ['@INPUT2@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) cmd = ['@PLAINNAME@'] self.assertRaises(ME, substfunc, cmd, d) cmd = ['@BASENAME@'] self.assertRaises(ME, substfunc, cmd, d) cmd = ['@OUTPUT@'] self.assertRaises(ME, substfunc, cmd, d) cmd = ['@OUTPUT0@'] self.assertRaises(ME, substfunc, cmd, d) cmd = ['@OUTDIR@'] self.assertRaises(ME, substfunc, cmd, d) outputs = ['dir/out.c'] ret = dictfunc(inputs, outputs) d = {'@INPUT@': inputs, '@INPUT0@': inputs[0], '@INPUT1@': inputs[1], '@OUTPUT@': outputs, '@OUTPUT0@': outputs[0], '@OUTDIR@': 'dir'} self.assertEqual(ret, d) cmd = ['some', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), cmd) cmd = ['@OUTPUT@', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), outputs + cmd[1:]) cmd = ['@OUTPUT@.out', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), [outputs[0] + '.out'] + cmd[1:]) cmd = ['@OUTPUT0@.out', '@INPUT1@.ok', 'strings'] self.assertEqual(substfunc(cmd, d), [outputs[0] + '.out', inputs[1] + '.ok'] + cmd[2:]) cmd = ['@INPUT@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) # Not enough inputs cmd = ['@INPUT2@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) # Not enough outputs cmd = ['@OUTPUT2@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) # Two inputs, two outputs outputs = ['dir/out.c', 'dir/out2.c'] ret = dictfunc(inputs, outputs) d = {'@INPUT@': inputs, '@INPUT0@': inputs[0], '@INPUT1@': inputs[1], '@OUTPUT@': outputs, '@OUTPUT0@': outputs[0], '@OUTPUT1@': outputs[1], '@OUTDIR@': 'dir'} # Check dictionary self.assertEqual(ret, d) # Check substitutions cmd = ['some', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), cmd) cmd = ['@OUTPUT@', 'ordinary', 'strings'] self.assertEqual(substfunc(cmd, d), outputs + cmd[1:]) cmd = ['@OUTPUT0@', '@OUTPUT1@', 'strings'] self.assertEqual(substfunc(cmd, d), outputs + cmd[2:]) cmd = ['@OUTPUT0@.out', '@INPUT1@.ok', '@OUTDIR@'] self.assertEqual(substfunc(cmd, d), [outputs[0] + '.out', inputs[1] + '.ok', 'dir']) # Many inputs, can't use @INPUT@ like this cmd = ['@INPUT@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) cmd = ['@INPUT2@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) cmd = ['@OUTPUT2@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) cmd = ['@OUTPUT@.out', 'ordinary', 'strings'] self.assertRaises(ME, substfunc, cmd, d) def test_needs_exe_wrapper_override(self): config = ConfigParser() config['binaries'] = { 'c': '\'/usr/bin/gcc\'', } config['host_machine'] = { 'system': '\'linux\'', 'cpu_family': '\'arm\'', 'cpu': '\'armv7\'', 'endian': '\'little\'', } # Can not be used as context manager because we need to # open it a second time and this is not possible on # Windows. configfile = tempfile.NamedTemporaryFile(mode='w+', delete=False) configfilename = configfile.name config.write(configfile) configfile.flush() configfile.close() opts = get_fake_options() opts.cross_file = (configfilename,) env = get_fake_env(opts=opts) detected_value = env.need_exe_wrapper() os.unlink(configfilename) desired_value = not detected_value config['properties'] = { 'needs_exe_wrapper': 'true' if desired_value else 'false' } configfile = tempfile.NamedTemporaryFile(mode='w+', delete=False) configfilename = configfile.name config.write(configfile) configfile.close() opts = get_fake_options() opts.cross_file = (configfilename,) env = get_fake_env(opts=opts) forced_value = env.need_exe_wrapper() os.unlink(configfilename) self.assertEqual(forced_value, desired_value) def test_listify(self): listify = mesonbuild.mesonlib.listify # Test sanity self.assertEqual([1], listify(1)) self.assertEqual([], listify([])) self.assertEqual([1], listify([1])) # Test flattening self.assertEqual([1, 2, 3], listify([1, [2, 3]])) self.assertEqual([1, 2, 3], listify([1, [2, [3]]])) self.assertEqual([1, [2, [3]]], listify([1, [2, [3]]], flatten=False)) # Test flattening and unholdering holder1 = ObjectHolder(1) self.assertEqual([holder1], listify(holder1)) self.assertEqual([holder1], listify([holder1])) self.assertEqual([holder1, 2], listify([holder1, 2])) self.assertEqual([holder1, 2, 3], listify([holder1, 2, [3]])) def test_unholder(self): unholder = mesonbuild.mesonlib.unholder holder1 = ObjectHolder(1) holder3 = ObjectHolder(3) holders = [holder1, holder3] self.assertEqual(1, unholder(holder1)) self.assertEqual([1], unholder([holder1])) self.assertEqual([1, 3], unholder(holders)) def test_extract_as_list(self): extract = mesonbuild.mesonlib.extract_as_list # Test sanity kwargs = {'sources': [1, 2, 3]} self.assertEqual([1, 2, 3], extract(kwargs, 'sources')) self.assertEqual(kwargs, {'sources': [1, 2, 3]}) self.assertEqual([1, 2, 3], extract(kwargs, 'sources', pop=True)) self.assertEqual(kwargs, {}) # Test unholding holder3 = ObjectHolder(3) kwargs = {'sources': [1, 2, holder3]} self.assertEqual(kwargs, {'sources': [1, 2, holder3]}) # flatten nested lists kwargs = {'sources': [1, [2, [3]]]} self.assertEqual([1, 2, 3], extract(kwargs, 'sources')) def test_pkgconfig_module(self): dummystate = mock.Mock() dummystate.subproject = 'dummy' _mock = mock.Mock(spec=mesonbuild.dependencies.ExternalDependency) _mock.pcdep = mock.Mock() _mock.pcdep.name = "some_name" _mock.version_reqs = [] _mock = mock.Mock(held_object=_mock) # pkgconfig dependency as lib deps = mesonbuild.modules.pkgconfig.DependenciesHelper(dummystate, "thislib") deps.add_pub_libs([_mock]) self.assertEqual(deps.format_reqs(deps.pub_reqs), "some_name") # pkgconfig dependency as requires deps = mesonbuild.modules.pkgconfig.DependenciesHelper(dummystate, "thislib") deps.add_pub_reqs([_mock]) self.assertEqual(deps.format_reqs(deps.pub_reqs), "some_name") def _test_all_naming(self, cc, env, patterns, platform): shr = patterns[platform]['shared'] stc = patterns[platform]['static'] shrstc = shr + tuple([x for x in stc if x not in shr]) stcshr = stc + tuple([x for x in shr if x not in stc]) p = cc.get_library_naming(env, LibType.SHARED) self.assertEqual(p, shr) p = cc.get_library_naming(env, LibType.STATIC) self.assertEqual(p, stc) p = cc.get_library_naming(env, LibType.PREFER_STATIC) self.assertEqual(p, stcshr) p = cc.get_library_naming(env, LibType.PREFER_SHARED) self.assertEqual(p, shrstc) # Test find library by mocking up openbsd if platform != 'openbsd': return with tempfile.TemporaryDirectory() as tmpdir: with open(os.path.join(tmpdir, 'libfoo.so.6.0'), 'w') as f: f.write('') with open(os.path.join(tmpdir, 'libfoo.so.5.0'), 'w') as f: f.write('') with open(os.path.join(tmpdir, 'libfoo.so.54.0'), 'w') as f: f.write('') with open(os.path.join(tmpdir, 'libfoo.so.66a.0b'), 'w') as f: f.write('') with open(os.path.join(tmpdir, 'libfoo.so.70.0.so.1'), 'w') as f: f.write('') found = cc._find_library_real('foo', env, [tmpdir], '', LibType.PREFER_SHARED) self.assertEqual(os.path.basename(found[0]), 'libfoo.so.54.0') def test_find_library_patterns(self): unix_static = ('lib{}.a', '{}.a') msvc_static = ('lib{}.a', 'lib{}.lib', '{}.a', '{}.lib') # This is the priority list of pattern matching for library searching patterns = {'openbsd': {'shared': ('lib{}.so', '{}.so', 'lib{}.so.[0-9]*.[0-9]*', '{}.so.[0-9]*.[0-9]*'), 'static': unix_static}, 'linux': {'shared': ('lib{}.so', '{}.so'), 'static': unix_static}, 'darwin': {'shared': ('lib{}.dylib', 'lib{}.so', '{}.dylib', '{}.so'), 'static': unix_static}, 'cygwin': {'shared': ('cyg{}.dll', 'cyg{}.dll.a', 'lib{}.dll', 'lib{}.dll.a', '{}.dll', '{}.dll.a'), 'static': ('cyg{}.a',) + unix_static}, 'windows-msvc': {'shared': ('lib{}.lib', '{}.lib'), 'static': msvc_static}, 'windows-mingw': {'shared': ('lib{}.dll.a', 'lib{}.lib', 'lib{}.dll', '{}.dll.a', '{}.lib', '{}.dll'), 'static': msvc_static}} env = get_fake_env() cc = env.detect_c_compiler(MachineChoice.HOST) if is_osx(): self._test_all_naming(cc, env, patterns, 'darwin') elif is_cygwin(): self._test_all_naming(cc, env, patterns, 'cygwin') elif is_windows(): if cc.get_argument_syntax() == 'msvc': self._test_all_naming(cc, env, patterns, 'windows-msvc') else: self._test_all_naming(cc, env, patterns, 'windows-mingw') elif is_openbsd(): self._test_all_naming(cc, env, patterns, 'openbsd') else: self._test_all_naming(cc, env, patterns, 'linux') env.machines.host.system = 'openbsd' self._test_all_naming(cc, env, patterns, 'openbsd') env.machines.host.system = 'darwin' self._test_all_naming(cc, env, patterns, 'darwin') env.machines.host.system = 'cygwin' self._test_all_naming(cc, env, patterns, 'cygwin') env.machines.host.system = 'windows' self._test_all_naming(cc, env, patterns, 'windows-mingw') @skipIfNoPkgconfig def test_pkgconfig_parse_libs(self): def create_static_lib(name): if not is_osx(): name.open('w').close() return src = name.with_suffix('.c') out = name.with_suffix('.o') with src.open('w') as f: f.write('int meson_foobar (void) { return 0; }') subprocess.check_call(['clang', '-c', str(src), '-o', str(out)]) subprocess.check_call(['ar', 'csr', str(name), str(out)]) with tempfile.TemporaryDirectory() as tmpdir: pkgbin = ExternalProgram('pkg-config', command=['pkg-config'], silent=True) env = get_fake_env() compiler = env.detect_c_compiler(MachineChoice.HOST) env.coredata.compilers.host = {'c': compiler} env.coredata.options[OptionKey('link_args', lang='c')] = FakeCompilerOptions() p1 = Path(tmpdir) / '1' p2 = Path(tmpdir) / '2' p1.mkdir() p2.mkdir() # libfoo.a is in one prefix create_static_lib(p1 / 'libfoo.a') # libbar.a is in both prefixes create_static_lib(p1 / 'libbar.a') create_static_lib(p2 / 'libbar.a') # Ensure that we never statically link to these create_static_lib(p1 / 'libpthread.a') create_static_lib(p1 / 'libm.a') create_static_lib(p1 / 'libc.a') create_static_lib(p1 / 'libdl.a') create_static_lib(p1 / 'librt.a') def fake_call_pkgbin(self, args, env=None): if '--libs' not in args: return 0, '', '' if args[-1] == 'foo': return 0, '-L{} -lfoo -L{} -lbar'.format(p2.as_posix(), p1.as_posix()), '' if args[-1] == 'bar': return 0, '-L{} -lbar'.format(p2.as_posix()), '' if args[-1] == 'internal': return 0, '-L{} -lpthread -lm -lc -lrt -ldl'.format(p1.as_posix()), '' old_call = PkgConfigDependency._call_pkgbin old_check = PkgConfigDependency.check_pkgconfig PkgConfigDependency._call_pkgbin = fake_call_pkgbin PkgConfigDependency.check_pkgconfig = lambda x, _: pkgbin # Test begins try: kwargs = {'required': True, 'silent': True} foo_dep = PkgConfigDependency('foo', env, kwargs) self.assertEqual(foo_dep.get_link_args(), [(p1 / 'libfoo.a').as_posix(), (p2 / 'libbar.a').as_posix()]) bar_dep = PkgConfigDependency('bar', env, kwargs) self.assertEqual(bar_dep.get_link_args(), [(p2 / 'libbar.a').as_posix()]) internal_dep = PkgConfigDependency('internal', env, kwargs) if compiler.get_argument_syntax() == 'msvc': self.assertEqual(internal_dep.get_link_args(), []) else: link_args = internal_dep.get_link_args() for link_arg in link_args: for lib in ('pthread', 'm', 'c', 'dl', 'rt'): self.assertNotIn('lib{}.a'.format(lib), link_arg, msg=link_args) finally: # Test ends PkgConfigDependency._call_pkgbin = old_call PkgConfigDependency.check_pkgconfig = old_check # Reset dependency class to ensure that in-process configure doesn't mess up PkgConfigDependency.pkgbin_cache = {} PkgConfigDependency.class_pkgbin = PerMachine(None, None) def test_version_compare(self): comparefunc = mesonbuild.mesonlib.version_compare_many for (a, b, result) in [ ('0.99.beta19', '>= 0.99.beta14', True), ]: self.assertEqual(comparefunc(a, b)[0], result) for (a, b, op) in [ ("1.0010", "1.9", operator.gt), ("1.05", "1.5", operator.eq), ("1.0", "1", operator.gt), ("2.50", "2.5", operator.gt), ("fc4", "fc.4", operator.eq), ("FC5", "fc4", operator.lt), ("2a", "2.0", operator.lt), ("1.0", "1.fc4", operator.gt), ("3.0.0_fc", "3.0.0.fc", operator.eq), ("1.0", "1.0", operator.eq), ("1.0", "2.0", operator.lt), ("2.0", "1.0", operator.gt), ("2.0.1", "2.0.1", operator.eq), ("2.0", "2.0.1", operator.lt), ("2.0.1", "2.0", operator.gt), ("2.0.1a", "2.0.1a", operator.eq), ("2.0.1a", "2.0.1", operator.gt), ("2.0.1", "2.0.1a", operator.lt), ("5.5p1", "5.5p1", operator.eq), ("5.5p1", "5.5p2", operator.lt), ("5.5p2", "5.5p1", operator.gt), ("5.5p10", "5.5p10", operator.eq), ("5.5p1", "5.5p10", operator.lt), ("5.5p10", "5.5p1", operator.gt), ("10xyz", "10.1xyz", operator.lt), ("10.1xyz", "10xyz", operator.gt), ("xyz10", "xyz10", operator.eq), ("xyz10", "xyz10.1", operator.lt), ("xyz10.1", "xyz10", operator.gt), ("xyz.4", "xyz.4", operator.eq), ("xyz.4", "8", operator.lt), ("8", "xyz.4", operator.gt), ("xyz.4", "2", operator.lt), ("2", "xyz.4", operator.gt), ("5.5p2", "5.6p1", operator.lt), ("5.6p1", "5.5p2", operator.gt), ("5.6p1", "6.5p1", operator.lt), ("6.5p1", "5.6p1", operator.gt), ("6.0.rc1", "6.0", operator.gt), ("6.0", "6.0.rc1", operator.lt), ("10b2", "10a1", operator.gt), ("10a2", "10b2", operator.lt), ("1.0aa", "1.0aa", operator.eq), ("1.0a", "1.0aa", operator.lt), ("1.0aa", "1.0a", operator.gt), ("10.0001", "10.0001", operator.eq), ("10.0001", "10.1", operator.eq), ("10.1", "10.0001", operator.eq), ("10.0001", "10.0039", operator.lt), ("10.0039", "10.0001", operator.gt), ("4.999.9", "5.0", operator.lt), ("5.0", "4.999.9", operator.gt), ("20101121", "20101121", operator.eq), ("20101121", "20101122", operator.lt), ("20101122", "20101121", operator.gt), ("2_0", "2_0", operator.eq), ("2.0", "2_0", operator.eq), ("2_0", "2.0", operator.eq), ("a", "a", operator.eq), ("a+", "a+", operator.eq), ("a+", "a_", operator.eq), ("a_", "a+", operator.eq), ("+a", "+a", operator.eq), ("+a", "_a", operator.eq), ("_a", "+a", operator.eq), ("+_", "+_", operator.eq), ("_+", "+_", operator.eq), ("_+", "_+", operator.eq), ("+", "_", operator.eq), ("_", "+", operator.eq), ('0.99.beta19', '0.99.beta14', operator.gt), ("1.0.0", "2.0.0", operator.lt), (".0.0", "2.0.0", operator.lt), ("alpha", "beta", operator.lt), ("1.0", "1.0.0", operator.lt), ("2.456", "2.1000", operator.lt), ("2.1000", "3.111", operator.lt), ("2.001", "2.1", operator.eq), ("2.34", "2.34", operator.eq), ("6.1.2", "6.3.8", operator.lt), ("1.7.3.0", "2.0.0", operator.lt), ("2.24.51", "2.25", operator.lt), ("2.1.5+20120813+gitdcbe778", "2.1.5", operator.gt), ("3.4.1", "3.4b1", operator.gt), ("041206", "200090325", operator.lt), ("0.6.2+git20130413", "0.6.2", operator.gt), ("2.6.0+bzr6602", "2.6.0", operator.gt), ("2.6.0", "2.6b2", operator.gt), ("2.6.0+bzr6602", "2.6b2x", operator.gt), ("0.6.7+20150214+git3a710f9", "0.6.7", operator.gt), ("15.8b", "15.8.0.1", operator.lt), ("1.2rc1", "1.2.0", operator.lt), ]: ver_a = Version(a) ver_b = Version(b) if op is operator.eq: for o, name in [(op, 'eq'), (operator.ge, 'ge'), (operator.le, 'le')]: self.assertTrue(o(ver_a, ver_b), '{} {} {}'.format(ver_a, name, ver_b)) if op is operator.lt: for o, name in [(op, 'lt'), (operator.le, 'le'), (operator.ne, 'ne')]: self.assertTrue(o(ver_a, ver_b), '{} {} {}'.format(ver_a, name, ver_b)) for o, name in [(operator.gt, 'gt'), (operator.ge, 'ge'), (operator.eq, 'eq')]: self.assertFalse(o(ver_a, ver_b), '{} {} {}'.format(ver_a, name, ver_b)) if op is operator.gt: for o, name in [(op, 'gt'), (operator.ge, 'ge'), (operator.ne, 'ne')]: self.assertTrue(o(ver_a, ver_b), '{} {} {}'.format(ver_a, name, ver_b)) for o, name in [(operator.lt, 'lt'), (operator.le, 'le'), (operator.eq, 'eq')]: self.assertFalse(o(ver_a, ver_b), '{} {} {}'.format(ver_a, name, ver_b)) def test_msvc_toolset_version(self): env = get_fake_env() cc = env.detect_c_compiler(MachineChoice.HOST) if cc.get_argument_syntax() != 'msvc': raise unittest.SkipTest('Test only applies to MSVC-like compilers') toolset_ver = cc.get_toolset_version() self.assertIsNotNone(toolset_ver) if cc.id == 'msvc' and int(''.join(cc.version.split('.')[0:2])) < 1910: return if 'VCToolsVersion' in os.environ: vctools_ver = os.environ['VCToolsVersion'] else: self.assertIn('VCINSTALLDIR', os.environ) # See https://devblogs.microsoft.com/cppblog/finding-the-visual-c-compiler-tools-in-visual-studio-2017/ vctools_ver = (Path(os.environ['VCINSTALLDIR']) / 'Auxiliary' / 'Build' / 'Microsoft.VCToolsVersion.default.txt').read_text() self.assertTrue(vctools_ver.startswith(toolset_ver), msg='{!r} does not start with {!r}'.format(vctools_ver, toolset_ver)) def test_split_args(self): split_args = mesonbuild.mesonlib.split_args join_args = mesonbuild.mesonlib.join_args if is_windows(): test_data = [ # examples from https://docs.microsoft.com/en-us/cpp/c-language/parsing-c-command-line-arguments (r'"a b c" d e', ['a b c', 'd', 'e'], True), (r'"ab\"c" "\\" d', ['ab"c', '\\', 'd'], False), (r'a\\\b d"e f"g h', [r'a\\\b', 'de fg', 'h'], False), (r'a\\\"b c d', [r'a\"b', 'c', 'd'], False), (r'a\\\\"b c" d e', [r'a\\b c', 'd', 'e'], False), # other basics (r'""', [''], True), (r'a b c d "" e', ['a', 'b', 'c', 'd', '', 'e'], True), (r"'a b c' d e", ["'a", 'b', "c'", 'd', 'e'], True), (r"'a&b&c' d e", ["'a&b&c'", 'd', 'e'], True), (r"a & b & c d e", ['a', '&', 'b', '&', 'c', 'd', 'e'], True), (r"'a & b & c d e'", ["'a", '&', 'b', '&', 'c', 'd', "e'"], True), ('a b\nc\rd \n\re', ['a', 'b', 'c', 'd', 'e'], False), # more illustrative tests (r'cl test.cpp /O1 /Fe:test.exe', ['cl', 'test.cpp', '/O1', '/Fe:test.exe'], True), (r'cl "test.cpp /O1 /Fe:test.exe"', ['cl', 'test.cpp /O1 /Fe:test.exe'], True), (r'cl /DNAME=\"Bob\" test.cpp', ['cl', '/DNAME="Bob"', 'test.cpp'], False), (r'cl "/DNAME=\"Bob\"" test.cpp', ['cl', '/DNAME="Bob"', 'test.cpp'], True), (r'cl /DNAME=\"Bob, Alice\" test.cpp', ['cl', '/DNAME="Bob,', 'Alice"', 'test.cpp'], False), (r'cl "/DNAME=\"Bob, Alice\"" test.cpp', ['cl', '/DNAME="Bob, Alice"', 'test.cpp'], True), (r'cl C:\path\with\backslashes.cpp', ['cl', r'C:\path\with\backslashes.cpp'], True), (r'cl C:\\path\\with\\double\\backslashes.cpp', ['cl', r'C:\\path\\with\\double\\backslashes.cpp'], True), (r'cl "C:\\path\\with\\double\\backslashes.cpp"', ['cl', r'C:\\path\\with\\double\\backslashes.cpp'], False), (r'cl C:\path with spaces\test.cpp', ['cl', r'C:\path', 'with', r'spaces\test.cpp'], False), (r'cl "C:\path with spaces\test.cpp"', ['cl', r'C:\path with spaces\test.cpp'], True), (r'cl /DPATH="C:\path\with\backslashes test.cpp', ['cl', r'/DPATH=C:\path\with\backslashes test.cpp'], False), (r'cl /DPATH=\"C:\\ends\\with\\backslashes\\\" test.cpp', ['cl', r'/DPATH="C:\\ends\\with\\backslashes\"', 'test.cpp'], False), (r'cl /DPATH="C:\\ends\\with\\backslashes\\" test.cpp', ['cl', '/DPATH=C:\\\\ends\\\\with\\\\backslashes\\', 'test.cpp'], False), (r'cl "/DNAME=\"C:\\ends\\with\\backslashes\\\"" test.cpp', ['cl', r'/DNAME="C:\\ends\\with\\backslashes\"', 'test.cpp'], True), (r'cl "/DNAME=\"C:\\ends\\with\\backslashes\\\\"" test.cpp', ['cl', r'/DNAME="C:\\ends\\with\\backslashes\\ test.cpp'], False), (r'cl "/DNAME=\"C:\\ends\\with\\backslashes\\\\\"" test.cpp', ['cl', r'/DNAME="C:\\ends\\with\\backslashes\\"', 'test.cpp'], True), ] else: test_data = [ (r"'a b c' d e", ['a b c', 'd', 'e'], True), (r"a/b/c d e", ['a/b/c', 'd', 'e'], True), (r"a\b\c d e", [r'abc', 'd', 'e'], False), (r"a\\b\\c d e", [r'a\b\c', 'd', 'e'], False), (r'"a b c" d e', ['a b c', 'd', 'e'], False), (r'"a\\b\\c\\" d e', ['a\\b\\c\\', 'd', 'e'], False), (r"'a\b\c\' d e", ['a\\b\\c\\', 'd', 'e'], True), (r"'a&b&c' d e", ['a&b&c', 'd', 'e'], True), (r"a & b & c d e", ['a', '&', 'b', '&', 'c', 'd', 'e'], False), (r"'a & b & c d e'", ['a & b & c d e'], True), (r"abd'e f'g h", [r'abde fg', 'h'], False), ('a b\nc\rd \n\re', ['a', 'b', 'c', 'd', 'e'], False), ('g++ -DNAME="Bob" test.cpp', ['g++', '-DNAME=Bob', 'test.cpp'], False), ("g++ '-DNAME=\"Bob\"' test.cpp", ['g++', '-DNAME="Bob"', 'test.cpp'], True), ('g++ -DNAME="Bob, Alice" test.cpp', ['g++', '-DNAME=Bob, Alice', 'test.cpp'], False), ("g++ '-DNAME=\"Bob, Alice\"' test.cpp", ['g++', '-DNAME="Bob, Alice"', 'test.cpp'], True), ] for (cmd, expected, roundtrip) in test_data: self.assertEqual(split_args(cmd), expected) if roundtrip: self.assertEqual(join_args(expected), cmd) def test_quote_arg(self): split_args = mesonbuild.mesonlib.split_args quote_arg = mesonbuild.mesonlib.quote_arg if is_windows(): test_data = [ ('', '""'), ('arg1', 'arg1'), ('/option1', '/option1'), ('/Ovalue', '/Ovalue'), ('/OBob&Alice', '/OBob&Alice'), ('/Ovalue with spaces', r'"/Ovalue with spaces"'), (r'/O"value with spaces"', r'"/O\"value with spaces\""'), (r'/OC:\path with spaces\test.exe', r'"/OC:\path with spaces\test.exe"'), ('/LIBPATH:C:\\path with spaces\\ends\\with\\backslashes\\', r'"/LIBPATH:C:\path with spaces\ends\with\backslashes\\"'), ('/LIBPATH:"C:\\path with spaces\\ends\\with\\backslashes\\\\"', r'"/LIBPATH:\"C:\path with spaces\ends\with\backslashes\\\\\""'), (r'/DMSG="Alice said: \"Let\'s go\""', r'"/DMSG=\"Alice said: \\\"Let\'s go\\\"\""'), ] else: test_data = [ ('arg1', 'arg1'), ('--option1', '--option1'), ('-O=value', '-O=value'), ('-O=Bob&Alice', "'-O=Bob&Alice'"), ('-O=value with spaces', "'-O=value with spaces'"), ('-O="value with spaces"', '\'-O=\"value with spaces\"\''), ('-O=/path with spaces/test', '\'-O=/path with spaces/test\''), ('-DMSG="Alice said: \\"Let\'s go\\""', "'-DMSG=\"Alice said: \\\"Let'\"'\"'s go\\\"\"'"), ] for (arg, expected) in test_data: self.assertEqual(quote_arg(arg), expected) self.assertEqual(split_args(expected)[0], arg) def test_depfile(self): for (f, target, expdeps) in [ # empty, unknown target ([''], 'unknown', set()), # simple target & deps (['meson/foo.o : foo.c foo.h'], 'meson/foo.o', set({'foo.c', 'foo.h'})), (['meson/foo.o: foo.c foo.h'], 'foo.c', set()), # get all deps (['meson/foo.o: foo.c foo.h', 'foo.c: gen.py'], 'meson/foo.o', set({'foo.c', 'foo.h', 'gen.py'})), (['meson/foo.o: foo.c foo.h', 'foo.c: gen.py'], 'foo.c', set({'gen.py'})), # linue continuation, multiple targets (['foo.o \\', 'foo.h: bar'], 'foo.h', set({'bar'})), (['foo.o \\', 'foo.h: bar'], 'foo.o', set({'bar'})), # \\ handling (['foo: Program\\ F\\iles\\\\X'], 'foo', set({'Program Files\\X'})), # $ handling (['f$o.o: c/b'], 'f$o.o', set({'c/b'})), (['f$$o.o: c/b'], 'f$o.o', set({'c/b'})), # cycles (['a: b', 'b: a'], 'a', set({'a', 'b'})), (['a: b', 'b: a'], 'b', set({'a', 'b'})), ]: d = mesonbuild.depfile.DepFile(f) deps = d.get_all_dependencies(target) self.assertEqual(sorted(deps), sorted(expdeps)) def test_log_once(self): f = io.StringIO() with mock.patch('mesonbuild.mlog.log_file', f), \ mock.patch('mesonbuild.mlog._logged_once', set()): mesonbuild.mlog.log_once('foo') mesonbuild.mlog.log_once('foo') actual = f.getvalue().strip() self.assertEqual(actual, 'foo', actual) def test_log_once_ansi(self): f = io.StringIO() with mock.patch('mesonbuild.mlog.log_file', f), \ mock.patch('mesonbuild.mlog._logged_once', set()): mesonbuild.mlog.log_once(mesonbuild.mlog.bold('foo')) mesonbuild.mlog.log_once(mesonbuild.mlog.bold('foo')) actual = f.getvalue().strip() self.assertEqual(actual.count('foo'), 1, actual) mesonbuild.mlog.log_once('foo') actual = f.getvalue().strip() self.assertEqual(actual.count('foo'), 1, actual) f.truncate() mesonbuild.mlog.warning('bar', once=True) mesonbuild.mlog.warning('bar', once=True) actual = f.getvalue().strip() self.assertEqual(actual.count('bar'), 1, actual) def test_sort_libpaths(self): sort_libpaths = mesonbuild.dependencies.base.sort_libpaths self.assertEqual(sort_libpaths( ['/home/mesonuser/.local/lib', '/usr/local/lib', '/usr/lib'], ['/home/mesonuser/.local/lib/pkgconfig', '/usr/local/lib/pkgconfig']), ['/home/mesonuser/.local/lib', '/usr/local/lib', '/usr/lib']) self.assertEqual(sort_libpaths( ['/usr/local/lib', '/home/mesonuser/.local/lib', '/usr/lib'], ['/home/mesonuser/.local/lib/pkgconfig', '/usr/local/lib/pkgconfig']), ['/home/mesonuser/.local/lib', '/usr/local/lib', '/usr/lib']) self.assertEqual(sort_libpaths( ['/usr/lib', '/usr/local/lib', '/home/mesonuser/.local/lib'], ['/home/mesonuser/.local/lib/pkgconfig', '/usr/local/lib/pkgconfig']), ['/home/mesonuser/.local/lib', '/usr/local/lib', '/usr/lib']) self.assertEqual(sort_libpaths( ['/usr/lib', '/usr/local/lib', '/home/mesonuser/.local/lib'], ['/home/mesonuser/.local/lib/pkgconfig', '/usr/local/libdata/pkgconfig']), ['/home/mesonuser/.local/lib', '/usr/local/lib', '/usr/lib']) def test_dependency_factory_order(self): b = mesonbuild.dependencies.base with tempfile.TemporaryDirectory() as tmpdir: with chdir(tmpdir): env = get_fake_env() env.scratch_dir = tmpdir f = b.DependencyFactory( 'test_dep', methods=[b.DependencyMethods.PKGCONFIG, b.DependencyMethods.CMAKE] ) actual = [m() for m in f(env, MachineChoice.HOST, {'required': False})] self.assertListEqual([m.type_name for m in actual], ['pkgconfig', 'cmake']) f = b.DependencyFactory( 'test_dep', methods=[b.DependencyMethods.CMAKE, b.DependencyMethods.PKGCONFIG] ) actual = [m() for m in f(env, MachineChoice.HOST, {'required': False})] self.assertListEqual([m.type_name for m in actual], ['cmake', 'pkgconfig']) def test_validate_json(self) -> None: try: from jsonschema import validate, ValidationError except ImportError: if is_ci(): raise raise unittest.SkipTest('Python jsonschema module not found.') with Path('data/test.schema.json').open() as f: schema = json.load(f) errors = [] # type: T.Tuple[str, Exception] for p in Path('test cases').glob('**/test.json'): with p.open() as f: try: validate(json.load(f), schema=schema) except ValidationError as e: errors.append((p.resolve(), e)) for f, e in errors: print('Failed to validate: "{}"'.format(f)) print(str(e)) self.assertFalse(errors) def test_typed_pos_args_types(self) -> None: @typed_pos_args('foo', str, int, bool) def _(obj, node, args: T.Tuple[str, int, bool], kwargs) -> None: self.assertIsInstance(args, tuple) self.assertIsInstance(args[0], str) self.assertIsInstance(args[1], int) self.assertIsInstance(args[2], bool) _(None, mock.Mock(), ['string', 1, False], None) def test_typed_pos_args_types_invalid(self) -> None: @typed_pos_args('foo', str, int, bool) def _(obj, node, args: T.Tuple[str, int, bool], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string', 1.0, False], None) self.assertEqual(str(cm.exception), 'foo argument 2 was of type "float" but should have been "int"') def test_typed_pos_args_types_wrong_number(self) -> None: @typed_pos_args('foo', str, int, bool) def _(obj, node, args: T.Tuple[str, int, bool], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string', 1], None) self.assertEqual(str(cm.exception), 'foo takes exactly 3 arguments, but got 2.') with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string', 1, True, True], None) self.assertEqual(str(cm.exception), 'foo takes exactly 3 arguments, but got 4.') def test_typed_pos_args_varargs(self) -> None: @typed_pos_args('foo', str, varargs=str) def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None: self.assertIsInstance(args, tuple) self.assertIsInstance(args[0], str) self.assertIsInstance(args[1], list) self.assertIsInstance(args[1][0], str) self.assertIsInstance(args[1][1], str) _(None, mock.Mock(), ['string', 'var', 'args'], None) def test_typed_pos_args_varargs_not_given(self) -> None: @typed_pos_args('foo', str, varargs=str) def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None: self.assertIsInstance(args, tuple) self.assertIsInstance(args[0], str) self.assertIsInstance(args[1], list) self.assertEqual(args[1], []) _(None, mock.Mock(), ['string'], None) def test_typed_pos_args_varargs_invalid(self) -> None: @typed_pos_args('foo', str, varargs=str) def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string', 'var', 'args', 0], None) self.assertEqual(str(cm.exception), 'foo argument 4 was of type "int" but should have been "str"') def test_typed_pos_args_varargs_invalid_mulitple_types(self) -> None: @typed_pos_args('foo', str, varargs=(str, list)) def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string', 'var', 'args', 0], None) self.assertEqual(str(cm.exception), 'foo argument 4 was of type "int" but should have been one of: "str", "list"') def test_typed_pos_args_max_varargs(self) -> None: @typed_pos_args('foo', str, varargs=str, max_varargs=5) def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None: self.assertIsInstance(args, tuple) self.assertIsInstance(args[0], str) self.assertIsInstance(args[1], list) self.assertIsInstance(args[1][0], str) self.assertIsInstance(args[1][1], str) _(None, mock.Mock(), ['string', 'var', 'args'], None) def test_typed_pos_args_max_varargs_exceeded(self) -> None: @typed_pos_args('foo', str, varargs=str, max_varargs=1) def _(obj, node, args: T.Tuple[str, T.Tuple[str, ...]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string', 'var', 'args'], None) self.assertEqual(str(cm.exception), 'foo takes between 1 and 2 arguments, but got 3.') def test_typed_pos_args_min_varargs(self) -> None: @typed_pos_args('foo', varargs=str, max_varargs=2, min_varargs=1) def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None: self.assertIsInstance(args, tuple) self.assertIsInstance(args[0], list) self.assertIsInstance(args[0][0], str) self.assertIsInstance(args[0][1], str) _(None, mock.Mock(), ['string', 'var'], None) def test_typed_pos_args_min_varargs_not_met(self) -> None: @typed_pos_args('foo', str, varargs=str, min_varargs=1) def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string'], None) self.assertEqual(str(cm.exception), 'foo takes at least 2 arguments, but got 1.') def test_typed_pos_args_min_and_max_varargs_exceeded(self) -> None: @typed_pos_args('foo', str, varargs=str, min_varargs=1, max_varargs=2) def _(obj, node, args: T.Tuple[str, T.Tuple[str, ...]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string', 'var', 'args', 'bar'], None) self.assertEqual(str(cm.exception), 'foo takes between 2 and 3 arguments, but got 4.') def test_typed_pos_args_min_and_max_varargs_not_met(self) -> None: @typed_pos_args('foo', str, varargs=str, min_varargs=1, max_varargs=2) def _(obj, node, args: T.Tuple[str, T.Tuple[str, ...]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string'], None) self.assertEqual(str(cm.exception), 'foo takes between 2 and 3 arguments, but got 1.') def test_typed_pos_args_variadic_and_optional(self) -> None: @typed_pos_args('foo', str, optargs=[str], varargs=str, min_varargs=0) def _(obj, node, args: T.Tuple[str, T.List[str]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(AssertionError) as cm: _(None, mock.Mock(), ['string'], None) self.assertEqual( str(cm.exception), 'varargs and optargs not supported together as this would be ambiguous') def test_typed_pos_args_min_optargs_not_met(self) -> None: @typed_pos_args('foo', str, str, optargs=[str]) def _(obj, node, args: T.Tuple[str, T.Optional[str]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string'], None) self.assertEqual(str(cm.exception), 'foo takes at least 2 arguments, but got 1.') def test_typed_pos_args_min_optargs_max_exceeded(self) -> None: @typed_pos_args('foo', str, optargs=[str]) def _(obj, node, args: T.Tuple[str, T.Optional[str]], kwargs) -> None: self.assertTrue(False) # should not be reachable with self.assertRaises(InvalidArguments) as cm: _(None, mock.Mock(), ['string', '1', '2'], None) self.assertEqual(str(cm.exception), 'foo takes at most 2 arguments, but got 3.') def test_typed_pos_args_optargs_not_given(self) -> None: @typed_pos_args('foo', str, optargs=[str]) def _(obj, node, args: T.Tuple[str, T.Optional[str]], kwargs) -> None: self.assertEqual(len(args), 2) self.assertIsInstance(args[0], str) self.assertEqual(args[0], 'string') self.assertIsNone(args[1]) _(None, mock.Mock(), ['string'], None) def test_typed_pos_args_optargs_some_given(self) -> None: @typed_pos_args('foo', str, optargs=[str, int]) def _(obj, node, args: T.Tuple[str, T.Optional[str], T.Optional[int]], kwargs) -> None: self.assertEqual(len(args), 3) self.assertIsInstance(args[0], str) self.assertEqual(args[0], 'string') self.assertIsInstance(args[1], str) self.assertEqual(args[1], '1') self.assertIsNone(args[2]) _(None, mock.Mock(), ['string', '1'], None) def test_typed_pos_args_optargs_all_given(self) -> None: @typed_pos_args('foo', str, optargs=[str]) def _(obj, node, args: T.Tuple[str, T.Optional[str]], kwargs) -> None: self.assertEqual(len(args), 2) self.assertIsInstance(args[0], str) self.assertEqual(args[0], 'string') self.assertIsInstance(args[1], str) _(None, mock.Mock(), ['string', '1'], None) @unittest.skipIf(is_tarball(), 'Skipping because this is a tarball release') class DataTests(unittest.TestCase): def test_snippets(self): hashcounter = re.compile('^ *( snippet_dir = Path('docs/markdown/snippets') self.assertTrue(snippet_dir.is_dir()) for f in snippet_dir.glob('*'): self.assertTrue(f.is_file()) if f.parts[-1].endswith('~'): continue if f.suffix == '.md': in_code_block = False with f.open() as snippet: for line in snippet: if line.startswith(' '): continue if line.startswith('```'): in_code_block = not in_code_block if in_code_block: continue m = re.match(hashcounter, line) if m: self.assertEqual(len(m.group(0)), 2, 'All headings in snippets must have two hash symbols: ' + f.name) self.assertFalse(in_code_block, 'Unclosed code block.') else: if f.name != 'add_release_note_snippets_here': self.assertTrue(False, 'A file without .md suffix in snippets dir: ' + f.name) def test_compiler_options_documented(self): md = None with open('docs/markdown/Builtin-options.md', encoding='utf-8') as f: md = f.read() self.assertIsNotNone(md) env = get_fake_env() # FIXME: Support other compilers cc = env.detect_c_compiler(MachineChoice.HOST) cpp = env.detect_cpp_compiler(MachineChoice.HOST) for comp in (cc, cpp): for opt in comp.get_options(): self.assertIn(str(opt), md) for opt in comp.base_options: self.assertIn(str(opt), md) self.assertNotIn('b_unknown', md) @staticmethod def _get_section_content(name, sections, md): for section in sections: if section and section.group(1) == name: try: next_section = next(sections) end = next_section.start() except StopIteration: end = len(md) # Extract the content for this section return md[section.end():end] raise RuntimeError('Could not find "{}" heading'.format(name)) def test_builtin_options_documented(self): from itertools import tee md = None with open('docs/markdown/Builtin-options.md', encoding='utf-8') as f: md = f.read() self.assertIsNotNone(md) found_entries = set() sections = re.finditer(r"^## (.+)$", md, re.MULTILINE) # Extract the content for this section content = self._get_section_content("Universal options", sections, md) subsections = tee(re.finditer(r"^### (.+)$", content, re.MULTILINE)) subcontent1 = self._get_section_content("Directories", subsections[0], content) subcontent2 = self._get_section_content("Core options", subsections[1], content) for subcontent in (subcontent1, subcontent2): # Find the option names options = set() # Match either a table row or a table heading separator: | ------ | rows = re.finditer(r"^\|(?: (\w+) .* | *-+ *)\|", subcontent, re.MULTILINE) # Skip the header of the first table next(rows) # Skip the heading separator of the first table next(rows) for m in rows: value = m.group(1) # End when the `buildtype` table starts if value is None: break options.add(value) self.assertEqual(len(found_entries & options), 0) found_entries |= options self.assertEqual(found_entries, set([ *[str(k) for k in mesonbuild.coredata.BUILTIN_OPTIONS], *[str(k) for k in mesonbuild.coredata.BUILTIN_OPTIONS_PER_MACHINE], ])) # Check that `buildtype` table inside `Core options` matches how # setting of builtin options behaves # # Find all tables inside this subsection tables = re.finditer(r"^\| (\w+) .* \|\n\| *[-|\s]+ *\|$", subcontent2, re.MULTILINE) # Get the table we want using the header of the first column table = self._get_section_content('buildtype', tables, subcontent2) # Get table row data rows = re.finditer(r"^\|(?: (\w+)\s+\| (\w+)\s+\| (\w+) .* | *-+ *)\|", table, re.MULTILINE) env = get_fake_env() for m in rows: buildtype, debug, opt = m.groups() if debug == 'true': debug = True elif debug == 'false': debug = False else: raise RuntimeError('Invalid debug value {!r} in row:\n{}'.format(debug, m.group())) env.coredata.set_option(OptionKey('buildtype'), buildtype) self.assertEqual(env.coredata.options[OptionKey('buildtype')].value, buildtype) self.assertEqual(env.coredata.options[OptionKey('optimization')].value, opt) self.assertEqual(env.coredata.options[OptionKey('debug')].value, debug) def test_cpu_families_documented(self): with open("docs/markdown/Reference-tables.md", encoding='utf-8') as f: md = f.read() self.assertIsNotNone(md) sections = re.finditer(r"^## (.+)$", md, re.MULTILINE) content = self._get_section_content("CPU families", sections, md) # Find the list entries arches = [m.group(1) for m in re.finditer(r"^\| (\w+) +\|", content, re.MULTILINE)] # Drop the header arches = set(arches[1:]) self.assertEqual(arches, set(mesonbuild.environment.known_cpu_families)) def test_markdown_files_in_sitemap(self): with open("docs/sitemap.txt", encoding='utf-8') as f: md = f.read() self.assertIsNotNone(md) toc = list(m.group(1) for m in re.finditer(r"^\s*(\w.*)$", md, re.MULTILINE)) markdownfiles = [f.name for f in Path("docs/markdown").iterdir() if f.is_file() and f.suffix == '.md'] exceptions = ['_Sidebar.md'] for f in markdownfiles: if f not in exceptions: self.assertIn(f, toc) def test_vim_syntax_highlighting(self): env = get_fake_env() interp = Interpreter(FakeBuild(env), mock=True) with open('data/syntax-highlighting/vim/syntax/meson.vim') as f: res = re.search(r'syn keyword mesonBuiltin(\s+\\\s\w+)+', f.read(), re.MULTILINE) defined = set([a.strip() for a in res.group().split('\\')][1:]) self.assertEqual(defined, set(chain(interp.funcs.keys(), interp.builtin.keys()))) def test_all_functions_defined_in_ast_interpreter(self): env = get_fake_env() interp = Interpreter(FakeBuild(env), mock=True) astint = AstInterpreter('.', '', '') self.assertEqual(set(interp.funcs.keys()), set(astint.funcs.keys())) def test_mesondata_is_up_to_date(self): from mesonbuild.mesondata import mesondata err_msg = textwrap.dedent(''' ########################################################### ### mesonbuild.mesondata is not up-to-date ### ### Please regenerate it by running tools/gen_data.py ### ########################################################### ''') root_dir = Path(__file__).resolve().parent mesonbuild_dir = root_dir / 'mesonbuild' data_dirs = mesonbuild_dir.glob('**/data') data_files = [] # type: T.List[T.Tuple(str, str)] for i in data_dirs: for p in i.iterdir(): data_files += [(p.relative_to(mesonbuild_dir).as_posix(), hashlib.sha256(p.read_bytes()).hexdigest())] current_files = set(mesondata.keys()) scanned_files = set([x[0] for x in data_files]) self.assertSetEqual(current_files, scanned_files, err_msg + 'Data files were added or removed\n') errors = [] for i in data_files: if mesondata[i[0]].sha256sum != i[1]: errors += [i[0]] self.assertListEqual(errors, [], err_msg + 'Files were changed') class BasePlatformTests(unittest.TestCase): prefix = '/usr' libdir = 'lib' def setUp(self): super().setUp() self.maxDiff = None src_root = os.path.dirname(__file__) src_root = os.path.join(os.getcwd(), src_root) self.src_root = src_root # Get the backend # FIXME: Extract this from argv? self.backend = getattr(Backend, os.environ.get('MESON_UNIT_TEST_BACKEND', 'ninja')) self.meson_args = ['--backend=' + self.backend.name] self.meson_native_file = None self.meson_cross_file = None self.meson_command = python_command + [get_meson_script()] self.setup_command = self.meson_command + self.meson_args self.mconf_command = self.meson_command + ['configure'] self.mintro_command = self.meson_command + ['introspect'] self.wrap_command = self.meson_command + ['wrap'] self.rewrite_command = self.meson_command + ['rewrite'] # Backend-specific build commands self.build_command, self.clean_command, self.test_command, self.install_command, \ self.uninstall_command = get_backend_commands(self.backend) # Test directories self.common_test_dir = os.path.join(src_root, 'test cases/common') self.vala_test_dir = os.path.join(src_root, 'test cases/vala') self.framework_test_dir = os.path.join(src_root, 'test cases/frameworks') self.unit_test_dir = os.path.join(src_root, 'test cases/unit') self.rewrite_test_dir = os.path.join(src_root, 'test cases/rewrite') self.linuxlike_test_dir = os.path.join(src_root, 'test cases/linuxlike') # Misc stuff self.orig_env = os.environ.copy() if self.backend is Backend.ninja: self.no_rebuild_stdout = ['ninja: no work to do.', 'samu: nothing to do'] else: # VS doesn't have a stable output when no changes are done self.no_rebuild_stdout = ['UNKNOWN BACKEND {!r}'.format(self.backend.name)] self.builddirs = [] self.new_builddir() def change_builddir(self, newdir): self.builddir = newdir self.privatedir = os.path.join(self.builddir, 'meson-private') self.logdir = os.path.join(self.builddir, 'meson-logs') self.installdir = os.path.join(self.builddir, 'install') self.distdir = os.path.join(self.builddir, 'meson-dist') self.mtest_command = self.meson_command + ['test', '-C', self.builddir] self.builddirs.append(self.builddir) def new_builddir(self): if not is_cygwin(): newdir = tempfile.mkdtemp(dir=os.getcwd()) else: # But not on Cygwin because that breaks the umask tests. See: # https://github.com/mesonbuild/meson/pull/5546#issuecomment-509666523 newdir = tempfile.mkdtemp() # In case the directory is inside a symlinked directory, find the real # path otherwise we might not find the srcdir from inside the builddir. newdir = os.path.realpath(newdir) self.change_builddir(newdir) def _print_meson_log(self): log = os.path.join(self.logdir, 'meson-log.txt') if not os.path.isfile(log): print("{!r} doesn't exist".format(log)) return with open(log, 'r', encoding='utf-8') as f: print(f.read()) def tearDown(self): for path in self.builddirs: try: windows_proof_rmtree(path) except FileNotFoundError: pass os.environ.clear() os.environ.update(self.orig_env) super().tearDown() def _run(self, command, *, workdir=None, override_envvars=None): if override_envvars is None: env = None else: env = os.environ.copy() env.update(override_envvars) p = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, encoding='utf-8', universal_newlines=True, cwd=workdir, timeout=60 * 5) print(p.stdout) if p.returncode != 0: if 'MESON_SKIP_TEST' in p.stdout: raise unittest.SkipTest('Project requested skipping.') raise subprocess.CalledProcessError(p.returncode, command, output=p.stdout) return p.stdout def init(self, srcdir, *, extra_args=None, default_args=True, inprocess=False, override_envvars=None, workdir=None): self.assertPathExists(srcdir) if extra_args is None: extra_args = [] if not isinstance(extra_args, list): extra_args = [extra_args] args = [srcdir, self.builddir] if default_args: args += ['--prefix', self.prefix] if self.libdir: args += ['--libdir', self.libdir] if self.meson_native_file: args += ['--native-file', self.meson_native_file] if self.meson_cross_file: args += ['--cross-file', self.meson_cross_file] self.privatedir = os.path.join(self.builddir, 'meson-private') if inprocess: try: (returncode, out, err) = run_configure_inprocess(self.meson_args + args + extra_args, override_envvars) if 'MESON_SKIP_TEST' in out: raise unittest.SkipTest('Project requested skipping.') if returncode != 0: self._print_meson_log() print('Stdout:\n') print(out) print('Stderr:\n') print(err) raise RuntimeError('Configure failed') except Exception: self._print_meson_log() raise finally: mesonbuild.mlog.shutdown() mesonbuild.mlog.log_dir = None mesonbuild.mlog.log_file = None else: try: out = self._run(self.setup_command + args + extra_args, override_envvars=override_envvars, workdir=workdir) except unittest.SkipTest: raise unittest.SkipTest('Project requested skipping: ' + srcdir) except Exception: self._print_meson_log() raise return out def build(self, target=None, *, extra_args=None, override_envvars=None): if extra_args is None: extra_args = [] args = get_builddir_target_args(self.backend, self.builddir, target) return self._run(self.build_command + args + extra_args, workdir=self.builddir, override_envvars=override_envvars) def clean(self, *, override_envvars=None): dir_args = get_builddir_target_args(self.backend, self.builddir, None) self._run(self.clean_command + dir_args, workdir=self.builddir, override_envvars=override_envvars) def run_tests(self, *, inprocess=False, override_envvars=None): if not inprocess: self._run(self.test_command, workdir=self.builddir, override_envvars=override_envvars) else: with mock.patch.dict(os.environ, override_envvars): run_mtest_inprocess(['-C', self.builddir]) def install(self, *, use_destdir=True, override_envvars=None): if self.backend is not Backend.ninja: raise unittest.SkipTest('{!r} backend can\'t install files'.format(self.backend.name)) if use_destdir: destdir = {'DESTDIR': self.installdir} if override_envvars is None: override_envvars = destdir else: override_envvars.update(destdir) self._run(self.install_command, workdir=self.builddir, override_envvars=override_envvars) def uninstall(self, *, override_envvars=None): self._run(self.uninstall_command, workdir=self.builddir, override_envvars=override_envvars) def run_target(self, target, *, override_envvars=None): return self.build(target=target, override_envvars=override_envvars) def setconf(self, arg, will_build=True): if not isinstance(arg, list): arg = [arg] if will_build: ensure_backend_detects_changes(self.backend) self._run(self.mconf_command + arg + [self.builddir]) def wipe(self): windows_proof_rmtree(self.builddir) def utime(self, f): ensure_backend_detects_changes(self.backend) os.utime(f) def get_compdb(self): if self.backend is not Backend.ninja: raise unittest.SkipTest('Compiler db not available with {} backend'.format(self.backend.name)) try: with open(os.path.join(self.builddir, 'compile_commands.json')) as ifile: contents = json.load(ifile) except FileNotFoundError: raise unittest.SkipTest('Compiler db not found') # If Ninja is using .rsp files, generate them, read their contents, and # replace it as the command for all compile commands in the parsed json. if len(contents) > 0 and contents[0]['command'].endswith('.rsp'): # Pretend to build so that the rsp files are generated self.build(extra_args=['-d', 'keeprsp', '-n']) for each in contents: # Extract the actual command from the rsp file compiler, rsp = each['command'].split(' @') rsp = os.path.join(self.builddir, rsp) # Replace the command with its contents with open(rsp, 'r', encoding='utf-8') as f: each['command'] = compiler + ' ' + f.read() return contents def get_meson_log(self): with open(os.path.join(self.builddir, 'meson-logs', 'meson-log.txt')) as f: return f.readlines() def get_meson_log_compiler_checks(self): log = self.get_meson_log() prefix = 'Command line:' cmds = [l[len(prefix):].split() for l in log if l.startswith(prefix)] return cmds def get_meson_log_sanitychecks(self): log = self.get_meson_log() prefix = 'Sanity check compiler command line:' cmds = [l[len(prefix):].split() for l in log if l.startswith(prefix)] return cmds def introspect(self, args): if isinstance(args, str): args = [args] out = subprocess.check_output(self.mintro_command + args + [self.builddir], universal_newlines=True) return json.loads(out) def introspect_directory(self, directory, args): if isinstance(args, str): args = [args] out = subprocess.check_output(self.mintro_command + args + [directory], universal_newlines=True) try: obj = json.loads(out) except Exception as e: print(out) raise e return obj def assertPathEqual(self, path1, path2): self.assertEqual(PurePath(path1), PurePath(path2)) def assertPathListEqual(self, pathlist1, pathlist2): self.assertEqual(len(pathlist1), len(pathlist2)) worklist = list(zip(pathlist1, pathlist2)) for i in worklist: if i[0] is None: self.assertEqual(i[0], i[1]) else: self.assertPathEqual(i[0], i[1]) def assertPathBasenameEqual(self, path, basename): msg = '{!r} does not end with {!r}'.format(path, basename) # We cannot use os.path.basename because it returns '' when the path # ends with '/' for some silly reason. This is not how the UNIX utility # `basename` works. path_basename = PurePath(path).parts[-1] self.assertEqual(PurePath(path_basename), PurePath(basename), msg) def assertReconfiguredBuildIsNoop(self): ret = self.build() self.assertIn('The Meson build system', ret) if self.backend is Backend.ninja: for line in ret.split('\n'): if line in self.no_rebuild_stdout: break else: raise AssertionError('build was reconfigured, but was not no-op') elif self.backend is Backend.vs: # Ensure that some target said that no rebuild was done # XXX: Note CustomBuild did indeed rebuild, because of the regen checker! self.assertIn('ClCompile:\n All outputs are up-to-date.', ret) self.assertIn('Link:\n All outputs are up-to-date.', ret) # Ensure that no targets were built self.assertNotRegex(ret, re.compile('ClCompile:\n [^\n]*cl', flags=re.IGNORECASE)) self.assertNotRegex(ret, re.compile('Link:\n [^\n]*link', flags=re.IGNORECASE)) elif self.backend is Backend.xcode: raise unittest.SkipTest('Please help us fix this test on the xcode backend') else: raise RuntimeError('Invalid backend: {!r}'.format(self.backend.name)) def assertBuildIsNoop(self): ret = self.build() if self.backend is Backend.ninja: self.assertIn(ret.split('\n')[-2], self.no_rebuild_stdout) elif self.backend is Backend.vs: # Ensure that some target of each type said that no rebuild was done # We always have at least one CustomBuild target for the regen checker self.assertIn('CustomBuild:\n All outputs are up-to-date.', ret) self.assertIn('ClCompile:\n All outputs are up-to-date.', ret) self.assertIn('Link:\n All outputs are up-to-date.', ret) # Ensure that no targets were built self.assertNotRegex(ret, re.compile('CustomBuild:\n [^\n]*cl', flags=re.IGNORECASE)) self.assertNotRegex(ret, re.compile('ClCompile:\n [^\n]*cl', flags=re.IGNORECASE)) self.assertNotRegex(ret, re.compile('Link:\n [^\n]*link', flags=re.IGNORECASE)) elif self.backend is Backend.xcode: raise unittest.SkipTest('Please help us fix this test on the xcode backend') else: raise RuntimeError('Invalid backend: {!r}'.format(self.backend.name)) def assertRebuiltTarget(self, target): ret = self.build() if self.backend is Backend.ninja: self.assertIn('Linking target {}'.format(target), ret) elif self.backend is Backend.vs: # Ensure that this target was rebuilt linkre = re.compile('Link:\n [^\n]*link[^\n]*' + target, flags=re.IGNORECASE) self.assertRegex(ret, linkre) elif self.backend is Backend.xcode: raise unittest.SkipTest('Please help us fix this test on the xcode backend') else: raise RuntimeError('Invalid backend: {!r}'.format(self.backend.name)) @staticmethod def get_target_from_filename(filename): base = os.path.splitext(filename)[0] if base.startswith(('lib', 'cyg')): return base[3:] return base def assertBuildRelinkedOnlyTarget(self, target): ret = self.build() if self.backend is Backend.ninja: linked_targets = [] for line in ret.split('\n'): if 'Linking target' in line: fname = line.rsplit('target ')[-1] linked_targets.append(self.get_target_from_filename(fname)) self.assertEqual(linked_targets, [target]) elif self.backend is Backend.vs: # Ensure that this target was rebuilt linkre = re.compile(r'Link:\n [^\n]*link.exe[^\n]*/OUT:".\\([^"]*)"', flags=re.IGNORECASE) matches = linkre.findall(ret) self.assertEqual(len(matches), 1, msg=matches) self.assertEqual(self.get_target_from_filename(matches[0]), target) elif self.backend is Backend.xcode: raise unittest.SkipTest('Please help us fix this test on the xcode backend') else: raise RuntimeError('Invalid backend: {!r}'.format(self.backend.name)) def assertPathExists(self, path): m = 'Path {!r} should exist'.format(path) self.assertTrue(os.path.exists(path), msg=m) def assertPathDoesNotExist(self, path): m = 'Path {!r} should not exist'.format(path) self.assertFalse(os.path.exists(path), msg=m) class AllPlatformTests(BasePlatformTests): def test_default_options_prefix(self): testdir = os.path.join(self.common_test_dir, '88 default options') self.init(testdir, default_args=False, inprocess=True) opts = self.introspect('--buildoptions') for opt in opts: if opt['name'] == 'prefix': prefix = opt['value'] break else: raise self.fail('Did not find option "prefix"') self.assertEqual(prefix, '/absoluteprefix') def test_do_conf_file_preserve_newlines(self): def conf_file(in_data, confdata): with temp_filename() as fin: with open(fin, 'wb') as fobj: fobj.write(in_data.encode('utf-8')) with temp_filename() as fout: mesonbuild.mesonlib.do_conf_file(fin, fout, confdata, 'meson') with open(fout, 'rb') as fobj: return fobj.read().decode('utf-8') confdata = {'VAR': ('foo', 'bar')} self.assertEqual(conf_file('@VAR@\n@VAR@\n', confdata), 'foo\nfoo\n') self.assertEqual(conf_file('@VAR@\r\n@VAR@\r\n', confdata), 'foo\r\nfoo\r\n') def test_do_conf_file_by_format(self): def conf_str(in_data, confdata, vformat): (result, missing_variables, confdata_useless) = mesonbuild.mesonlib.do_conf_str(in_data, confdata, variable_format = vformat) return '\n'.join(result) def check_formats(confdata, result): self.assertEqual(conf_str(['#mesondefine VAR'], confdata, 'meson'), result) self.assertEqual(conf_str(['#cmakedefine VAR ${VAR}'], confdata, 'cmake'), result) self.assertEqual(conf_str(['#cmakedefine VAR @VAR@'], confdata, 'cmake@'), result) confdata = ConfigurationData() # Key error as they do not exists check_formats(confdata, '/* #undef VAR */\n') # Check boolean confdata.values = {'VAR': (False, 'description')} check_formats(confdata, '#undef VAR\n') confdata.values = {'VAR': (True, 'description')} check_formats(confdata, '#define VAR\n') # Check string confdata.values = {'VAR': ('value', 'description')} check_formats(confdata, '#define VAR value\n') # Check integer confdata.values = {'VAR': (10, 'description')} check_formats(confdata, '#define VAR 10\n') # Check multiple string with cmake formats confdata.values = {'VAR': ('value', 'description')} self.assertEqual(conf_str(['#cmakedefine VAR xxx @VAR@ yyy @VAR@'], confdata, 'cmake@'), '#define VAR xxx value yyy value\n') self.assertEqual(conf_str(['#define VAR xxx @VAR@ yyy @VAR@'], confdata, 'cmake@'), '#define VAR xxx value yyy value') self.assertEqual(conf_str(['#cmakedefine VAR xxx ${VAR} yyy ${VAR}'], confdata, 'cmake'), '#define VAR xxx value yyy value\n') self.assertEqual(conf_str(['#define VAR xxx ${VAR} yyy ${VAR}'], confdata, 'cmake'), '#define VAR xxx value yyy value') # Handles meson format exceptions # Unknown format self.assertRaises(mesonbuild.mesonlib.MesonException, conf_str, ['#mesondefine VAR xxx'], confdata, 'unknown_format') # More than 2 params in mesondefine self.assertRaises(mesonbuild.mesonlib.MesonException, conf_str, ['#mesondefine VAR xxx'], confdata, 'meson') # Mismatched line with format self.assertRaises(mesonbuild.mesonlib.MesonException, conf_str, ['#cmakedefine VAR'], confdata, 'meson') self.assertRaises(mesonbuild.mesonlib.MesonException, conf_str, ['#mesondefine VAR'], confdata, 'cmake') self.assertRaises(mesonbuild.mesonlib.MesonException, conf_str, ['#mesondefine VAR'], confdata, 'cmake@') # Dict value in confdata confdata.values = {'VAR': (['value'], 'description')} self.assertRaises(mesonbuild.mesonlib.MesonException, conf_str, ['#mesondefine VAR'], confdata, 'meson') def test_absolute_prefix_libdir(self): testdir = os.path.join(self.common_test_dir, '88 default options') # on Windows, /someabs is *not* an absolute path prefix = 'x:/someabs' if is_windows() else '/someabs' libdir = 'libdir' extra_args = ['--prefix=' + prefix, # This can just be a relative path, but we want to test # that passing this as an absolute path also works '--libdir=' + prefix + '/' + libdir] self.init(testdir, extra_args=extra_args, default_args=False) opts = self.introspect('--buildoptions') for opt in opts: if opt['name'] == 'prefix': self.assertEqual(prefix, opt['value']) elif opt['name'] == 'libdir': self.assertEqual(libdir, opt['value']) def test_libdir_must_be_inside_prefix(self): testdir = os.path.join(self.common_test_dir, '1 trivial') # libdir being inside prefix is ok if is_windows(): args = ['--prefix', 'x:/opt', '--libdir', 'x:/opt/lib32'] else: args = ['--prefix', '/opt', '--libdir', '/opt/lib32'] self.init(testdir, extra_args=args) self.wipe() # libdir not being inside prefix is not ok if is_windows(): args = ['--prefix', 'x:/usr', '--libdir', 'x:/opt/lib32'] else: args = ['--prefix', '/usr', '--libdir', '/opt/lib32'] self.assertRaises(subprocess.CalledProcessError, self.init, testdir, extra_args=args) self.wipe() # libdir must be inside prefix even when set via mesonconf self.init(testdir) if is_windows(): self.assertRaises(subprocess.CalledProcessError, self.setconf, '-Dlibdir=x:/opt', False) else: self.assertRaises(subprocess.CalledProcessError, self.setconf, '-Dlibdir=/opt', False) def test_prefix_dependent_defaults(self): testdir = os.path.join(self.common_test_dir, '1 trivial') expected = { '/opt': {'prefix': '/opt', 'bindir': 'bin', 'datadir': 'share', 'includedir': 'include', 'infodir': 'share/info', 'libexecdir': 'libexec', 'localedir': 'share/locale', 'localstatedir': 'var', 'mandir': 'share/man', 'sbindir': 'sbin', 'sharedstatedir': 'com', 'sysconfdir': 'etc'}, '/usr': {'prefix': '/usr', 'bindir': 'bin', 'datadir': 'share', 'includedir': 'include', 'infodir': 'share/info', 'libexecdir': 'libexec', 'localedir': 'share/locale', 'localstatedir': '/var', 'mandir': 'share/man', 'sbindir': 'sbin', 'sharedstatedir': '/var/lib', 'sysconfdir': '/etc'}, '/usr/local': {'prefix': '/usr/local', 'bindir': 'bin', 'datadir': 'share', 'includedir': 'include', 'infodir': 'share/info', 'libexecdir': 'libexec', 'localedir': 'share/locale', 'localstatedir': '/var/local', 'mandir': 'share/man', 'sbindir': 'sbin', 'sharedstatedir': '/var/local/lib', 'sysconfdir': 'etc'}, # N.B. We don't check 'libdir' as it's platform dependent, see # default_libdir(): } if mesonbuild.mesonlib.default_prefix() == '/usr/local': expected[None] = expected['/usr/local'] for prefix in expected: args = [] if prefix: args += ['--prefix', prefix] self.init(testdir, extra_args=args, default_args=False) opts = self.introspect('--buildoptions') for opt in opts: name = opt['name'] value = opt['value'] if name in expected[prefix]: self.assertEqual(value, expected[prefix][name]) self.wipe() def test_default_options_prefix_dependent_defaults(self): testdir = os.path.join(self.common_test_dir, '164 default options prefix dependent defaults') expected = { '': {'prefix': '/usr', 'sysconfdir': '/etc', 'localstatedir': '/var', 'sharedstatedir': '/sharedstate'}, '--prefix=/usr': {'prefix': '/usr', 'sysconfdir': '/etc', 'localstatedir': '/var', 'sharedstatedir': '/sharedstate'}, '--sharedstatedir=/var/state': {'prefix': '/usr', 'sysconfdir': '/etc', 'localstatedir': '/var', 'sharedstatedir': '/var/state'}, '--sharedstatedir=/var/state --prefix=/usr --sysconfdir=sysconf': {'prefix': '/usr', 'sysconfdir': 'sysconf', 'localstatedir': '/var', 'sharedstatedir': '/var/state'}, } for args in expected: self.init(testdir, extra_args=args.split(), default_args=False) opts = self.introspect('--buildoptions') for opt in opts: name = opt['name'] value = opt['value'] if name in expected[args]: self.assertEqual(value, expected[args][name]) self.wipe() def test_clike_get_library_dirs(self): env = get_fake_env() cc = env.detect_c_compiler(MachineChoice.HOST) for d in cc.get_library_dirs(env): self.assertTrue(os.path.exists(d)) self.assertTrue(os.path.isdir(d)) self.assertTrue(os.path.isabs(d)) def test_static_library_overwrite(self): testdir = os.path.join(self.common_test_dir, '3 static') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) static_linker = env.detect_static_linker(cc) if is_windows(): raise unittest.SkipTest('https://github.com/mesonbuild/meson/issues/1526') if not isinstance(static_linker, mesonbuild.linkers.ArLinker): raise unittest.SkipTest('static linker is not `ar`') # Configure self.init(testdir) # Get name of static library targets = self.introspect('--targets') self.assertEqual(len(targets), 1) libname = targets[0]['filename'][0] # Build and get contents of static library self.build() before = self._run(['ar', 't', os.path.join(self.builddir, libname)]).split() # Filter out non-object-file contents before = [f for f in before if f.endswith(('.o', '.obj'))] # Static library should contain only one object self.assertEqual(len(before), 1, msg=before) # Change the source to be built into the static library self.setconf('-Dsource=libfile2.c') self.build() after = self._run(['ar', 't', os.path.join(self.builddir, libname)]).split() # Filter out non-object-file contents after = [f for f in after if f.endswith(('.o', '.obj'))] # Static library should contain only one object self.assertEqual(len(after), 1, msg=after) # and the object must have changed self.assertNotEqual(before, after) def test_static_compile_order(self): testdir = os.path.join(self.common_test_dir, '5 linkstatic') self.init(testdir) compdb = self.get_compdb() # Rules will get written out in this order self.assertTrue(compdb[0]['file'].endswith("libfile.c")) self.assertTrue(compdb[1]['file'].endswith("libfile2.c")) self.assertTrue(compdb[2]['file'].endswith("libfile3.c")) self.assertTrue(compdb[3]['file'].endswith("libfile4.c")) # FIXME: We don't have access to the linker command def test_run_target_files_path(self): testdir = os.path.join(self.common_test_dir, '52 run target') self.init(testdir) self.run_target('check_exists') self.run_target('check-env') self.run_target('check-env-ct') def test_install_introspection(self): if self.backend is not Backend.ninja: raise unittest.SkipTest('{!r} backend can\'t install files'.format(self.backend.name)) testdir = os.path.join(self.common_test_dir, '8 install') self.init(testdir) intro = self.introspect('--targets') if intro[0]['type'] == 'executable': intro = intro[::-1] self.assertPathListEqual(intro[0]['install_filename'], ['/usr/lib/libstat.a']) self.assertPathListEqual(intro[1]['install_filename'], ['/usr/bin/prog' + exe_suffix]) def test_install_subdir_introspection(self): testdir = os.path.join(self.common_test_dir, '60 install subdir') self.init(testdir) intro = self.introspect('--installed') expected = { 'sub2': 'share/sub2', 'subdir/sub1': 'share/sub1', 'subdir/sub_elided': 'share', 'sub1': 'share/sub1', 'sub/sub1': 'share/sub1', 'sub_elided': 'share', 'nested_elided/sub': 'share', 'new_directory': 'share/new_directory', } self.assertEqual(len(intro), len(expected)) # Convert expected to PurePath expected_converted = {PurePath(os.path.join(testdir, key)): PurePath(os.path.join(self.prefix, val)) for key, val in expected.items()} intro_converted = {PurePath(key): PurePath(val) for key, val in intro.items()} for src, dst in expected_converted.items(): self.assertIn(src, intro_converted) self.assertEqual(dst, intro_converted[src]) def test_install_introspection_multiple_outputs(self): if self.backend is not Backend.ninja: raise unittest.SkipTest('{!r} backend can\'t install files'.format(self.backend.name)) testdir = os.path.join(self.common_test_dir, '141 custom target multiple outputs') self.init(testdir) intro = self.introspect('--targets') if intro[0]['type'] == 'executable': intro = intro[::-1] self.assertPathListEqual(intro[0]['install_filename'], ['/usr/include/diff.h', '/usr/bin/diff.sh']) self.assertPathListEqual(intro[1]['install_filename'], ['/opt/same.h', '/opt/same.sh']) self.assertPathListEqual(intro[2]['install_filename'], ['/usr/include/first.h', None]) self.assertPathListEqual(intro[3]['install_filename'], [None, '/usr/bin/second.sh']) def test_install_log_content(self): testdir = os.path.join(self.common_test_dir, '60 install subdir') self.init(testdir) self.install() installpath = Path(self.installdir) # Find installed files and directories expected = {installpath: 0} for name in installpath.rglob('*'): expected[name] = 0 def read_logs(): # Find logged files and directories with Path(self.builddir, 'meson-logs', 'install-log.txt').open() as f: return list(map(lambda l: Path(l.strip()), filter(lambda l: not l.startswith('#'), f.readlines()))) logged = read_logs() for name in logged: self.assertTrue(name in expected, 'Log contains extra entry {}'.format(name)) expected[name] += 1 for name, count in expected.items(): self.assertGreater(count, 0, 'Log is missing entry for {}'.format(name)) self.assertLess(count, 2, 'Log has multiple entries for {}'.format(name)) # Verify that with --dry-run we obtain the same logs but with nothing # actually installed windows_proof_rmtree(self.installdir) self._run(self.meson_command + ['install', '--dry-run', '--destdir', self.installdir], workdir=self.builddir) self.assertEqual(logged, read_logs()) self.assertFalse(os.path.exists(self.installdir)) def test_uninstall(self): exename = os.path.join(self.installdir, 'usr/bin/prog' + exe_suffix) testdir = os.path.join(self.common_test_dir, '8 install') self.init(testdir) self.assertPathDoesNotExist(exename) self.install() self.assertPathExists(exename) self.uninstall() self.assertPathDoesNotExist(exename) def test_forcefallback(self): testdir = os.path.join(self.unit_test_dir, '31 forcefallback') self.init(testdir, extra_args=['--wrap-mode=forcefallback']) self.build() self.run_tests() def test_nopromote(self): testdir = os.path.join(self.common_test_dir, '99 subproject subdir') with self.assertRaises(subprocess.CalledProcessError) as cm: self.init(testdir, extra_args=['--wrap-mode=nopromote']) self.assertIn('Dependency "subsub" not found', cm.exception.stdout) def test_force_fallback_for(self): testdir = os.path.join(self.unit_test_dir, '31 forcefallback') self.init(testdir, extra_args=['--force-fallback-for=zlib,foo']) self.build() self.run_tests() def test_env_ops_dont_stack(self): testdir = os.path.join(self.unit_test_dir, '63 test env does not stack') out = self.init(testdir) self.assertRegex(out, r'WARNING: Overriding.*TEST_VAR_APPEND') self.assertRegex(out, r'WARNING: Overriding.*TEST_VAR_PREPEND') self.assertNotRegex(out, r'WARNING: Overriding.*TEST_VAR_SET') self.run_tests() def test_testsetups(self): if not shutil.which('valgrind'): raise unittest.SkipTest('Valgrind not installed.') testdir = os.path.join(self.unit_test_dir, '2 testsetups') self.init(testdir) self.build() # Run tests without setup self.run_tests() with open(os.path.join(self.logdir, 'testlog.txt'), encoding='utf-8') as f: basic_log = f.read() # Run buggy test with setup that has env that will make it fail self.assertRaises(subprocess.CalledProcessError, self._run, self.mtest_command + ['--setup=valgrind']) with open(os.path.join(self.logdir, 'testlog-valgrind.txt'), encoding='utf-8') as f: vg_log = f.read() self.assertFalse('TEST_ENV is set' in basic_log) self.assertFalse('Memcheck' in basic_log) self.assertTrue('TEST_ENV is set' in vg_log) self.assertTrue('Memcheck' in vg_log) # Run buggy test with setup without env that will pass self._run(self.mtest_command + ['--setup=wrapper']) # Setup with no properties works self._run(self.mtest_command + ['--setup=empty']) # Setup with only env works self._run(self.mtest_command + ['--setup=onlyenv']) self._run(self.mtest_command + ['--setup=onlyenv2']) self._run(self.mtest_command + ['--setup=onlyenv3']) # Setup with only a timeout works self._run(self.mtest_command + ['--setup=timeout']) # Setup that does not define a wrapper works with --wrapper self._run(self.mtest_command + ['--setup=timeout', '--wrapper', shutil.which('valgrind')]) # Setup that skips test works self._run(self.mtest_command + ['--setup=good']) with open(os.path.join(self.logdir, 'testlog-good.txt'), encoding='utf-8') as f: exclude_suites_log = f.read() self.assertFalse('buggy' in exclude_suites_log) # --suite overrides add_test_setup(xclude_suites) self._run(self.mtest_command + ['--setup=good', '--suite', 'buggy']) with open(os.path.join(self.logdir, 'testlog-good.txt'), encoding='utf-8') as f: include_suites_log = f.read() self.assertTrue('buggy' in include_suites_log) def test_testsetup_selection(self): testdir = os.path.join(self.unit_test_dir, '14 testsetup selection') self.init(testdir) self.build() # Run tests without setup self.run_tests() self.assertRaises(subprocess.CalledProcessError, self._run, self.mtest_command + ['--setup=missingfromfoo']) self._run(self.mtest_command + ['--setup=missingfromfoo', '--no-suite=foo:']) self._run(self.mtest_command + ['--setup=worksforall']) self._run(self.mtest_command + ['--setup=main:worksforall']) self.assertRaises(subprocess.CalledProcessError, self._run, self.mtest_command + ['--setup=onlyinbar']) self.assertRaises(subprocess.CalledProcessError, self._run, self.mtest_command + ['--setup=onlyinbar', '--no-suite=main:']) self._run(self.mtest_command + ['--setup=onlyinbar', '--no-suite=main:', '--no-suite=foo:']) self._run(self.mtest_command + ['--setup=bar:onlyinbar']) self.assertRaises(subprocess.CalledProcessError, self._run, self.mtest_command + ['--setup=foo:onlyinbar']) self.assertRaises(subprocess.CalledProcessError, self._run, self.mtest_command + ['--setup=main:onlyinbar']) def test_testsetup_default(self): testdir = os.path.join(self.unit_test_dir, '49 testsetup default') self.init(testdir) self.build() # Run tests without --setup will cause the default setup to be used self.run_tests() with open(os.path.join(self.logdir, 'testlog.txt'), encoding='utf-8') as f: default_log = f.read() # Run tests with explicitly using the same setup that is set as default self._run(self.mtest_command + ['--setup=mydefault']) with open(os.path.join(self.logdir, 'testlog-mydefault.txt'), encoding='utf-8') as f: mydefault_log = f.read() # Run tests with another setup self._run(self.mtest_command + ['--setup=other']) with open(os.path.join(self.logdir, 'testlog-other.txt'), encoding='utf-8') as f: other_log = f.read() self.assertTrue('ENV_A is 1' in default_log) self.assertTrue('ENV_B is 2' in default_log) self.assertTrue('ENV_C is 2' in default_log) self.assertTrue('ENV_A is 1' in mydefault_log) self.assertTrue('ENV_B is 2' in mydefault_log) self.assertTrue('ENV_C is 2' in mydefault_log) self.assertTrue('ENV_A is 1' in other_log) self.assertTrue('ENV_B is 3' in other_log) self.assertTrue('ENV_C is 2' in other_log) def assertFailedTestCount(self, failure_count, command): try: self._run(command) self.assertEqual(0, failure_count, 'Expected %d tests to fail.' % failure_count) except subprocess.CalledProcessError as e: self.assertEqual(e.returncode, failure_count) def test_suite_selection(self): testdir = os.path.join(self.unit_test_dir, '4 suite selection') self.init(testdir) self.build() self.assertFailedTestCount(4, self.mtest_command) self.assertFailedTestCount(0, self.mtest_command + ['--suite', ':success']) self.assertFailedTestCount(3, self.mtest_command + ['--suite', ':fail']) self.assertFailedTestCount(4, self.mtest_command + ['--no-suite', ':success']) self.assertFailedTestCount(1, self.mtest_command + ['--no-suite', ':fail']) self.assertFailedTestCount(1, self.mtest_command + ['--suite', 'mainprj']) self.assertFailedTestCount(0, self.mtest_command + ['--suite', 'subprjsucc']) self.assertFailedTestCount(1, self.mtest_command + ['--suite', 'subprjfail']) self.assertFailedTestCount(1, self.mtest_command + ['--suite', 'subprjmix']) self.assertFailedTestCount(3, self.mtest_command + ['--no-suite', 'mainprj']) self.assertFailedTestCount(4, self.mtest_command + ['--no-suite', 'subprjsucc']) self.assertFailedTestCount(3, self.mtest_command + ['--no-suite', 'subprjfail']) self.assertFailedTestCount(3, self.mtest_command + ['--no-suite', 'subprjmix']) self.assertFailedTestCount(1, self.mtest_command + ['--suite', 'mainprj:fail']) self.assertFailedTestCount(0, self.mtest_command + ['--suite', 'mainprj:success']) self.assertFailedTestCount(3, self.mtest_command + ['--no-suite', 'mainprj:fail']) self.assertFailedTestCount(4, self.mtest_command + ['--no-suite', 'mainprj:success']) self.assertFailedTestCount(1, self.mtest_command + ['--suite', 'subprjfail:fail']) self.assertFailedTestCount(0, self.mtest_command + ['--suite', 'subprjfail:success']) self.assertFailedTestCount(3, self.mtest_command + ['--no-suite', 'subprjfail:fail']) self.assertFailedTestCount(4, self.mtest_command + ['--no-suite', 'subprjfail:success']) self.assertFailedTestCount(0, self.mtest_command + ['--suite', 'subprjsucc:fail']) self.assertFailedTestCount(0, self.mtest_command + ['--suite', 'subprjsucc:success']) self.assertFailedTestCount(4, self.mtest_command + ['--no-suite', 'subprjsucc:fail']) self.assertFailedTestCount(4, self.mtest_command + ['--no-suite', 'subprjsucc:success']) self.assertFailedTestCount(1, self.mtest_command + ['--suite', 'subprjmix:fail']) self.assertFailedTestCount(0, self.mtest_command + ['--suite', 'subprjmix:success']) self.assertFailedTestCount(3, self.mtest_command + ['--no-suite', 'subprjmix:fail']) self.assertFailedTestCount(4, self.mtest_command + ['--no-suite', 'subprjmix:success']) self.assertFailedTestCount(2, self.mtest_command + ['--suite', 'subprjfail', '--suite', 'subprjmix:fail']) self.assertFailedTestCount(3, self.mtest_command + ['--suite', 'subprjfail', '--suite', 'subprjmix', '--suite', 'mainprj']) self.assertFailedTestCount(2, self.mtest_command + ['--suite', 'subprjfail', '--suite', 'subprjmix', '--suite', 'mainprj', '--no-suite', 'subprjmix:fail']) self.assertFailedTestCount(1, self.mtest_command + ['--suite', 'subprjfail', '--suite', 'subprjmix', '--suite', 'mainprj', '--no-suite', 'subprjmix:fail', 'mainprj-failing_test']) self.assertFailedTestCount(2, self.mtest_command + ['--no-suite', 'subprjfail:fail', '--no-suite', 'subprjmix:fail']) def test_build_by_default(self): testdir = os.path.join(self.common_test_dir, '130 build by default') self.init(testdir) self.build() genfile1 = os.path.join(self.builddir, 'generated1.dat') genfile2 = os.path.join(self.builddir, 'generated2.dat') exe1 = os.path.join(self.builddir, 'fooprog' + exe_suffix) exe2 = os.path.join(self.builddir, 'barprog' + exe_suffix) self.assertPathExists(genfile1) self.assertPathExists(genfile2) self.assertPathDoesNotExist(exe1) self.assertPathDoesNotExist(exe2) self.build(target=('fooprog' + exe_suffix)) self.assertPathExists(exe1) self.build(target=('barprog' + exe_suffix)) self.assertPathExists(exe2) def test_internal_include_order(self): if mesonbuild.environment.detect_msys2_arch() and ('MESON_RSP_THRESHOLD' in os.environ): raise unittest.SkipTest('Test does not yet support gcc rsp files on msys2') testdir = os.path.join(self.common_test_dir, '131 include order') self.init(testdir) execmd = fxecmd = None for cmd in self.get_compdb(): if 'someexe' in cmd['command']: execmd = cmd['command'] continue if 'somefxe' in cmd['command']: fxecmd = cmd['command'] continue if not execmd or not fxecmd: raise Exception('Could not find someexe and somfxe commands') # Check include order for 'someexe' incs = [a for a in split_args(execmd) if a.startswith("-I")] self.assertEqual(len(incs), 9) # Need to run the build so the private dir is created. self.build() pdirs = glob(os.path.join(self.builddir, 'sub4/someexe*.p')) self.assertEqual(len(pdirs), 1) privdir = pdirs[0][len(self.builddir)+1:] self.assertPathEqual(incs[0], "-I" + privdir) # target build subdir self.assertPathEqual(incs[1], "-Isub4") # target source subdir self.assertPathBasenameEqual(incs[2], 'sub4') # include paths added via per-target c_args: ['-I'...] self.assertPathBasenameEqual(incs[3], 'sub3') # target include_directories: build dir self.assertPathEqual(incs[4], "-Isub2") # target include_directories: source dir self.assertPathBasenameEqual(incs[5], 'sub2') # target internal dependency include_directories: build dir self.assertPathEqual(incs[6], "-Isub1") # target internal dependency include_directories: source dir self.assertPathBasenameEqual(incs[7], 'sub1') # custom target include dir self.assertPathEqual(incs[8], '-Ictsub') # Check include order for 'somefxe' incs = [a for a in split_args(fxecmd) if a.startswith('-I')] self.assertEqual(len(incs), 9) # target private dir pdirs = glob(os.path.join(self.builddir, 'somefxe*.p')) self.assertEqual(len(pdirs), 1) privdir = pdirs[0][len(self.builddir)+1:] self.assertPathEqual(incs[0], '-I' + privdir) # target build dir self.assertPathEqual(incs[1], '-I.') # target source dir self.assertPathBasenameEqual(incs[2], os.path.basename(testdir)) # target internal dependency correct include_directories: build dir self.assertPathEqual(incs[3], "-Isub4") # target internal dependency correct include_directories: source dir self.assertPathBasenameEqual(incs[4], 'sub4') # target internal dependency dep include_directories: build dir self.assertPathEqual(incs[5], "-Isub1") # target internal dependency dep include_directories: source dir self.assertPathBasenameEqual(incs[6], 'sub1') # target internal dependency wrong include_directories: build dir self.assertPathEqual(incs[7], "-Isub2") # target internal dependency wrong include_directories: source dir self.assertPathBasenameEqual(incs[8], 'sub2') def test_compiler_detection(self): gnu = mesonbuild.compilers.GnuCompiler clang = mesonbuild.compilers.ClangCompiler intel = mesonbuild.compilers.IntelGnuLikeCompiler msvc = (mesonbuild.compilers.VisualStudioCCompiler, mesonbuild.compilers.VisualStudioCPPCompiler) clangcl = (mesonbuild.compilers.ClangClCCompiler, mesonbuild.compilers.ClangClCPPCompiler) ar = mesonbuild.linkers.ArLinker lib = mesonbuild.linkers.VisualStudioLinker langs = [('c', 'CC'), ('cpp', 'CXX')] if not is_windows() and platform.machine().lower() != 'e2k': langs += [('objc', 'OBJC'), ('objcpp', 'OBJCXX')] testdir = os.path.join(self.unit_test_dir, '5 compiler detection') env = get_fake_env(testdir, self.builddir, self.prefix) for lang, evar in langs: # Detect with evar and do sanity checks on that if evar in os.environ: ecc = getattr(env, 'detect_{}_compiler'.format(lang))(MachineChoice.HOST) self.assertTrue(ecc.version) elinker = env.detect_static_linker(ecc) # Pop it so we don't use it for the next detection evalue = os.environ.pop(evar) # Very rough/strict heuristics. Would never work for actual # compiler detection, but should be ok for the tests. ebase = os.path.basename(evalue) if ebase.startswith('g') or ebase.endswith(('-gcc', '-g++')): self.assertIsInstance(ecc, gnu) self.assertIsInstance(elinker, ar) elif 'clang-cl' in ebase: self.assertIsInstance(ecc, clangcl) self.assertIsInstance(elinker, lib) elif 'clang' in ebase: self.assertIsInstance(ecc, clang) self.assertIsInstance(elinker, ar) elif ebase.startswith('ic'): self.assertIsInstance(ecc, intel) self.assertIsInstance(elinker, ar) elif ebase.startswith('cl'): self.assertIsInstance(ecc, msvc) self.assertIsInstance(elinker, lib) else: raise AssertionError('Unknown compiler {!r}'.format(evalue)) # Check that we actually used the evalue correctly as the compiler self.assertEqual(ecc.get_exelist(), split_args(evalue)) # Do auto-detection of compiler based on platform, PATH, etc. cc = getattr(env, 'detect_{}_compiler'.format(lang))(MachineChoice.HOST) self.assertTrue(cc.version) linker = env.detect_static_linker(cc) # Check compiler type if isinstance(cc, gnu): self.assertIsInstance(linker, ar) if is_osx(): self.assertIsInstance(cc.linker, mesonbuild.linkers.AppleDynamicLinker) elif is_sunos(): self.assertIsInstance(cc.linker, (mesonbuild.linkers.SolarisDynamicLinker, mesonbuild.linkers.GnuLikeDynamicLinkerMixin)) else: self.assertIsInstance(cc.linker, mesonbuild.linkers.GnuLikeDynamicLinkerMixin) if isinstance(cc, clangcl): self.assertIsInstance(linker, lib) self.assertIsInstance(cc.linker, mesonbuild.linkers.ClangClDynamicLinker) if isinstance(cc, clang): self.assertIsInstance(linker, ar) if is_osx(): self.assertIsInstance(cc.linker, mesonbuild.linkers.AppleDynamicLinker) elif is_windows(): # This is clang, not clang-cl. This can be either an # ld-like linker of link.exe-like linker (usually the # former for msys2, the latter otherwise) self.assertIsInstance(cc.linker, (mesonbuild.linkers.MSVCDynamicLinker, mesonbuild.linkers.GnuLikeDynamicLinkerMixin)) else: self.assertIsInstance(cc.linker, mesonbuild.linkers.GnuLikeDynamicLinkerMixin) if isinstance(cc, intel): self.assertIsInstance(linker, ar) if is_osx(): self.assertIsInstance(cc.linker, mesonbuild.linkers.AppleDynamicLinker) elif is_windows(): self.assertIsInstance(cc.linker, mesonbuild.linkers.XilinkDynamicLinker) else: self.assertIsInstance(cc.linker, mesonbuild.linkers.GnuDynamicLinker) if isinstance(cc, msvc): self.assertTrue(is_windows()) self.assertIsInstance(linker, lib) self.assertEqual(cc.id, 'msvc') self.assertTrue(hasattr(cc, 'is_64')) self.assertIsInstance(cc.linker, mesonbuild.linkers.MSVCDynamicLinker) # If we're on Windows CI, we know what the compiler will be if 'arch' in os.environ: if os.environ['arch'] == 'x64': self.assertTrue(cc.is_64) else: self.assertFalse(cc.is_64) # Set evar ourselves to a wrapper script that just calls the same # exelist + some argument. This is meant to test that setting # something like `ccache gcc -pipe` or `distcc ccache gcc` works. wrapper = os.path.join(testdir, 'compiler wrapper.py') wrappercc = python_command + [wrapper] + cc.get_exelist() + ['-DSOME_ARG'] os.environ[evar] = ' '.join(quote_arg(w) for w in wrappercc) # Check static linker too wrapperlinker = python_command + [wrapper] + linker.get_exelist() + linker.get_always_args() os.environ['AR'] = ' '.join(quote_arg(w) for w in wrapperlinker) # Need a new env to re-run environment loading env = get_fake_env(testdir, self.builddir, self.prefix) wcc = getattr(env, 'detect_{}_compiler'.format(lang))(MachineChoice.HOST) wlinker = env.detect_static_linker(wcc) # Pop it so we don't use it for the next detection evalue = os.environ.pop('AR') # Must be the same type since it's a wrapper around the same exelist self.assertIs(type(cc), type(wcc)) self.assertIs(type(linker), type(wlinker)) # Ensure that the exelist is correct self.assertEqual(wcc.get_exelist(), wrappercc) self.assertEqual(wlinker.get_exelist(), wrapperlinker) # Ensure that the version detection worked correctly self.assertEqual(cc.version, wcc.version) if hasattr(cc, 'is_64'): self.assertEqual(cc.is_64, wcc.is_64) def test_always_prefer_c_compiler_for_asm(self): testdir = os.path.join(self.common_test_dir, '134 c cpp and asm') # Skip if building with MSVC env = get_fake_env(testdir, self.builddir, self.prefix) if env.detect_c_compiler(MachineChoice.HOST).get_id() == 'msvc': raise unittest.SkipTest('MSVC can\'t compile assembly') self.init(testdir) commands = {'c-asm': {}, 'cpp-asm': {}, 'cpp-c-asm': {}, 'c-cpp-asm': {}} for cmd in self.get_compdb(): # Get compiler split = split_args(cmd['command']) if split[0] == 'ccache': compiler = split[1] else: compiler = split[0] # Classify commands if 'Ic-asm' in cmd['command']: if cmd['file'].endswith('.S'): commands['c-asm']['asm'] = compiler elif cmd['file'].endswith('.c'): commands['c-asm']['c'] = compiler else: raise AssertionError('{!r} found in cpp-asm?'.format(cmd['command'])) elif 'Icpp-asm' in cmd['command']: if cmd['file'].endswith('.S'): commands['cpp-asm']['asm'] = compiler elif cmd['file'].endswith('.cpp'): commands['cpp-asm']['cpp'] = compiler else: raise AssertionError('{!r} found in cpp-asm?'.format(cmd['command'])) elif 'Ic-cpp-asm' in cmd['command']: if cmd['file'].endswith('.S'): commands['c-cpp-asm']['asm'] = compiler elif cmd['file'].endswith('.c'): commands['c-cpp-asm']['c'] = compiler elif cmd['file'].endswith('.cpp'): commands['c-cpp-asm']['cpp'] = compiler else: raise AssertionError('{!r} found in c-cpp-asm?'.format(cmd['command'])) elif 'Icpp-c-asm' in cmd['command']: if cmd['file'].endswith('.S'): commands['cpp-c-asm']['asm'] = compiler elif cmd['file'].endswith('.c'): commands['cpp-c-asm']['c'] = compiler elif cmd['file'].endswith('.cpp'): commands['cpp-c-asm']['cpp'] = compiler else: raise AssertionError('{!r} found in cpp-c-asm?'.format(cmd['command'])) else: raise AssertionError('Unknown command {!r} found'.format(cmd['command'])) # Check that .S files are always built with the C compiler self.assertEqual(commands['c-asm']['asm'], commands['c-asm']['c']) self.assertEqual(commands['c-asm']['asm'], commands['cpp-asm']['asm']) self.assertEqual(commands['cpp-asm']['asm'], commands['c-cpp-asm']['c']) self.assertEqual(commands['c-cpp-asm']['asm'], commands['c-cpp-asm']['c']) self.assertEqual(commands['cpp-c-asm']['asm'], commands['cpp-c-asm']['c']) self.assertNotEqual(commands['cpp-asm']['asm'], commands['cpp-asm']['cpp']) self.assertNotEqual(commands['c-cpp-asm']['c'], commands['c-cpp-asm']['cpp']) self.assertNotEqual(commands['cpp-c-asm']['c'], commands['cpp-c-asm']['cpp']) # Check that the c-asm target is always linked with the C linker build_ninja = os.path.join(self.builddir, 'build.ninja') with open(build_ninja, 'r', encoding='utf-8') as f: contents = f.read() m = re.search('build c-asm.*: c_LINKER', contents) self.assertIsNotNone(m, msg=contents) def test_preprocessor_checks_CPPFLAGS(self): testdir = os.path.join(self.common_test_dir, '133 get define') define = 'MESON_TEST_DEFINE_VALUE' # NOTE: this list can't have \n, ' or " # \n is never substituted by the GNU pre-processor via a -D define # ' and " confuse split_args() even when they are escaped # % and # confuse the MSVC preprocessor # !, ^, *, and < confuse lcc preprocessor value = 'spaces and fun@$&()-=_+{}[]:;>?,./~`' for env_var in ['CPPFLAGS', 'CFLAGS']: env = {} env[env_var] = '-D{}="{}"'.format(define, value) env['LDFLAGS'] = '-DMESON_FAIL_VALUE=cflags-read' self.init(testdir, extra_args=['-D{}={}'.format(define, value)], override_envvars=env) def test_custom_target_exe_data_deterministic(self): testdir = os.path.join(self.common_test_dir, '110 custom target capture') self.init(testdir) meson_exe_dat1 = glob(os.path.join(self.privatedir, 'meson_exe*.dat')) self.wipe() self.init(testdir) meson_exe_dat2 = glob(os.path.join(self.privatedir, 'meson_exe*.dat')) self.assertListEqual(meson_exe_dat1, meson_exe_dat2) def test_noop_changes_cause_no_rebuilds(self): testdir = os.path.join(self.common_test_dir, '6 linkshared') self.init(testdir) self.build() # Immediately rebuilding should not do anything self.assertBuildIsNoop() # Changing mtime of meson.build should not rebuild anything self.utime(os.path.join(testdir, 'meson.build')) self.assertReconfiguredBuildIsNoop() # Changing mtime of libefile.c should rebuild the library, but not relink the executable self.utime(os.path.join(testdir, 'libfile.c')) self.assertBuildRelinkedOnlyTarget('mylib') def test_source_changes_cause_rebuild(self): testdir = os.path.join(self.common_test_dir, '20 header in file list') self.init(testdir) self.build() # Immediately rebuilding should not do anything self.assertBuildIsNoop() # Changing mtime of header.h should rebuild everything self.utime(os.path.join(testdir, 'header.h')) self.assertBuildRelinkedOnlyTarget('prog') def test_custom_target_changes_cause_rebuild(self): testdir = os.path.join(self.common_test_dir, '58 custom header generator') self.init(testdir) self.build() # Immediately rebuilding should not do anything self.assertBuildIsNoop() # Changing mtime of these should rebuild everything for f in ('input.def', 'makeheader.py', 'somefile.txt'): self.utime(os.path.join(testdir, f)) self.assertBuildRelinkedOnlyTarget('prog') def test_source_generator_program_cause_rebuild(self): testdir = os.path.join(self.common_test_dir, '91 gen extra') self.init(testdir) self.build() # Immediately rebuilding should not do anything self.assertBuildIsNoop() # Changing mtime of generator should rebuild the executable self.utime(os.path.join(testdir, 'srcgen.py')) self.assertRebuiltTarget('basic') def test_static_library_lto(self): testdir = os.path.join(self.common_test_dir, '5 linkstatic') env = get_fake_env(testdir, self.builddir, self.prefix) if env.detect_c_compiler(MachineChoice.HOST).get_id() == 'clang' and is_windows(): raise unittest.SkipTest('LTO not (yet) supported by windows clang') self.init(testdir, extra_args='-Db_lto=true') self.build() self.run_tests() @skip_if_not_base_option('b_lto_threads') def test_lto_threads(self): if is_cygwin(): raise unittest.SkipTest('LTO is broken on Cygwin.') testdir = os.path.join(self.common_test_dir, '6 linkshared') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) extra_args: T.List[str] = [] if cc.get_id() == 'clang': if is_windows(): raise unittest.SkipTest('LTO not (yet) supported by windows clang') else: extra_args.append('-D_cargs=-Werror=unused-command-line-argument') self.init(testdir, extra_args=['-Db_lto=true', '-Db_lto_threads=8'] + extra_args) self.build() self.run_tests() expected = set(cc.get_lto_compile_args(threads=8)) targets = self.introspect('--targets') # This assumes all of the targets support lto for t in targets: for s in t['target_sources']: for e in expected: self.assertIn(e, s['parameters']) @skip_if_not_base_option('b_lto_mode') @skip_if_not_base_option('b_lto_threads') def test_lto_mode(self): testdir = os.path.join(self.common_test_dir, '6 linkshared') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) if cc.get_id() != 'clang': raise unittest.SkipTest('Only clang currently supports thinLTO') if cc.linker.id not in {'ld.lld', 'ld.gold', 'ld64', 'lld-link'}: raise unittest.SkipTest('thinLTO requires ld.lld, ld.gold, ld64, or lld-link') elif is_windows(): raise unittest.SkipTest('LTO not (yet) supported by windows clang') self.init(testdir, extra_args=['-Db_lto=true', '-Db_lto_mode=thin', '-Db_lto_threads=8', '-Dc_args=-Werror=unused-command-line-argument']) self.build() self.run_tests() expected = set(cc.get_lto_compile_args(threads=8, mode='thin')) targets = self.introspect('--targets') # This assumes all of the targets support lto for t in targets: for s in t['target_sources']: self.assertTrue(expected.issubset(set(s['parameters'])), f'Incorrect values for {t["name"]}') def test_dist_git(self): if not shutil.which('git'): raise unittest.SkipTest('Git not found') if self.backend is not Backend.ninja: raise unittest.SkipTest('Dist is only supported with Ninja') try: self.dist_impl(_git_init, _git_add_all) except PermissionError: # When run under Windows CI, something (virus scanner?) # holds on to the git files so cleaning up the dir # fails sometimes. pass def has_working_hg(self): if not shutil.which('hg'): return False try: # This check should not be necessary, but # CI under macOS passes the above test even # though Mercurial is not installed. if subprocess.call(['hg', '--version'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) != 0: return False return True except FileNotFoundError: return False def test_dist_hg(self): if not self.has_working_hg(): raise unittest.SkipTest('Mercurial not found or broken.') if self.backend is not Backend.ninja: raise unittest.SkipTest('Dist is only supported with Ninja') def hg_init(project_dir): subprocess.check_call(['hg', 'init'], cwd=project_dir) with open(os.path.join(project_dir, '.hg', 'hgrc'), 'w') as f: print('[ui]', file=f) print('username=Author Person <teh_coderz@example.com>', file=f) subprocess.check_call(['hg', 'add', 'meson.build', 'distexe.c'], cwd=project_dir) subprocess.check_call(['hg', 'commit', '-m', 'I am a project'], cwd=project_dir) try: self.dist_impl(hg_init, include_subprojects=False) except PermissionError: # When run under Windows CI, something (virus scanner?) # holds on to the hg files so cleaning up the dir # fails sometimes. pass def test_dist_git_script(self): if not shutil.which('git'): raise unittest.SkipTest('Git not found') if self.backend is not Backend.ninja: raise unittest.SkipTest('Dist is only supported with Ninja') try: with tempfile.TemporaryDirectory() as tmpdir: project_dir = os.path.join(tmpdir, 'a') shutil.copytree(os.path.join(self.unit_test_dir, '35 dist script'), project_dir) _git_init(project_dir) self.init(project_dir) self.build('dist') except PermissionError: # When run under Windows CI, something (virus scanner?) # holds on to the git files so cleaning up the dir # fails sometimes. pass def create_dummy_subproject(self, project_dir, name): path = os.path.join(project_dir, 'subprojects', name) os.makedirs(path) with open(os.path.join(path, 'meson.build'), 'w') as ofile: ofile.write("project('{}', version: '1.0')".format(name)) return path def dist_impl(self, vcs_init, vcs_add_all=None, include_subprojects=True): # Create this on the fly because having rogue .git directories inside # the source tree leads to all kinds of trouble. with tempfile.TemporaryDirectory() as project_dir: with open(os.path.join(project_dir, 'meson.build'), 'w') as ofile: ofile.write(textwrap.dedent('''\ project('disttest', 'c', version : '1.4.3') e = executable('distexe', 'distexe.c') test('dist test', e) subproject('vcssub', required : false) subproject('tarballsub', required : false) subproject('samerepo', required : false) ''')) with open(os.path.join(project_dir, 'distexe.c'), 'w') as ofile: ofile.write(textwrap.dedent('''\ #include<stdio.h> int main(int argc, char **argv) { printf("I am a distribution test.\\n"); return 0; } ''')) xz_distfile = os.path.join(self.distdir, 'disttest-1.4.3.tar.xz') xz_checksumfile = xz_distfile + '.sha256sum' zip_distfile = os.path.join(self.distdir, 'disttest-1.4.3.zip') zip_checksumfile = zip_distfile + '.sha256sum' vcs_init(project_dir) if include_subprojects: vcs_init(self.create_dummy_subproject(project_dir, 'vcssub')) self.create_dummy_subproject(project_dir, 'tarballsub') self.create_dummy_subproject(project_dir, 'unusedsub') if vcs_add_all: vcs_add_all(self.create_dummy_subproject(project_dir, 'samerepo')) self.init(project_dir) self.build('dist') self.assertPathExists(xz_distfile) self.assertPathExists(xz_checksumfile) self.assertPathDoesNotExist(zip_distfile) self.assertPathDoesNotExist(zip_checksumfile) self._run(self.meson_command + ['dist', '--formats', 'zip'], workdir=self.builddir) self.assertPathExists(zip_distfile) self.assertPathExists(zip_checksumfile) if include_subprojects: # Verify that without --include-subprojects we have files from # the main project and also files from subprojects part of the # main vcs repository. z = zipfile.ZipFile(zip_distfile) expected = ['disttest-1.4.3/', 'disttest-1.4.3/meson.build', 'disttest-1.4.3/distexe.c'] if vcs_add_all: expected += ['disttest-1.4.3/subprojects/', 'disttest-1.4.3/subprojects/samerepo/', 'disttest-1.4.3/subprojects/samerepo/meson.build'] self.assertEqual(sorted(expected), sorted(z.namelist())) # Verify that with --include-subprojects we now also have files # from tarball and separate vcs subprojects. But not files from # unused subprojects. self._run(self.meson_command + ['dist', '--formats', 'zip', '--include-subprojects'], workdir=self.builddir) z = zipfile.ZipFile(zip_distfile) expected += ['disttest-1.4.3/subprojects/tarballsub/', 'disttest-1.4.3/subprojects/tarballsub/meson.build', 'disttest-1.4.3/subprojects/vcssub/', 'disttest-1.4.3/subprojects/vcssub/meson.build'] self.assertEqual(sorted(expected), sorted(z.namelist())) if vcs_add_all: # Verify we can distribute separately subprojects in the same vcs # repository as the main project. subproject_dir = os.path.join(project_dir, 'subprojects', 'samerepo') self.new_builddir() self.init(subproject_dir) self.build('dist') xz_distfile = os.path.join(self.distdir, 'samerepo-1.0.tar.xz') xz_checksumfile = xz_distfile + '.sha256sum' self.assertPathExists(xz_distfile) self.assertPathExists(xz_checksumfile) tar = tarfile.open(xz_distfile, "r:xz") self.assertEqual(sorted(['samerepo-1.0', 'samerepo-1.0/meson.build']), sorted([i.name for i in tar])) def test_rpath_uses_ORIGIN(self): if is_windows() or is_cygwin(): raise unittest.SkipTest('Windows PE/COFF binaries do not use RPATH') testdir = os.path.join(self.common_test_dir, '40 library chain') self.init(testdir) self.build() for each in ('prog', 'subdir/liblib1.so', ): rpath = get_rpath(os.path.join(self.builddir, each)) self.assertTrue(rpath, 'Rpath could not be determined for {}.'.format(each)) if is_dragonflybsd(): # DragonflyBSD will prepend /usr/lib/gccVERSION to the rpath, # so ignore that. self.assertTrue(rpath.startswith('/usr/lib/gcc')) rpaths = rpath.split(':')[1:] else: rpaths = rpath.split(':') for path in rpaths: self.assertTrue(path.startswith('$ORIGIN'), msg=(each, path)) # These two don't link to anything else, so they do not need an rpath entry. for each in ('subdir/subdir2/liblib2.so', 'subdir/subdir3/liblib3.so'): rpath = get_rpath(os.path.join(self.builddir, each)) if is_dragonflybsd(): # The rpath should be equal to /usr/lib/gccVERSION self.assertTrue(rpath.startswith('/usr/lib/gcc')) self.assertEqual(len(rpath.split(':')), 1) else: self.assertTrue(rpath is None) def test_dash_d_dedup(self): testdir = os.path.join(self.unit_test_dir, '9 d dedup') self.init(testdir) cmd = self.get_compdb()[0]['command'] self.assertTrue('-D FOO -D BAR' in cmd or '"-D" "FOO" "-D" "BAR"' in cmd or '/D FOO /D BAR' in cmd or '"/D" "FOO" "/D" "BAR"' in cmd) def test_all_forbidden_targets_tested(self): testdir = os.path.join(self.common_test_dir, '151 reserved targets') targets = mesonbuild.coredata.FORBIDDEN_TARGET_NAMES # We don't actually define a target with this name targets.pop('build.ninja') # Remove this to avoid multiple entries with the same name # but different case. targets.pop('PHONY') for i in targets: self.assertPathExists(os.path.join(testdir, i)) def detect_prebuild_env(self): env = get_fake_env() cc = env.detect_c_compiler(MachineChoice.HOST) stlinker = env.detect_static_linker(cc) if mesonbuild.mesonlib.is_windows(): object_suffix = 'obj' shared_suffix = 'dll' elif mesonbuild.mesonlib.is_cygwin(): object_suffix = 'o' shared_suffix = 'dll' elif mesonbuild.mesonlib.is_osx(): object_suffix = 'o' shared_suffix = 'dylib' else: object_suffix = 'o' shared_suffix = 'so' return (cc, stlinker, object_suffix, shared_suffix) def pbcompile(self, compiler, source, objectfile, extra_args=None): cmd = compiler.get_exelist() extra_args = extra_args or [] if compiler.get_argument_syntax() == 'msvc': cmd += ['/nologo', '/Fo' + objectfile, '/c', source] + extra_args else: cmd += ['-c', source, '-o', objectfile] + extra_args subprocess.check_call(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) def test_prebuilt_object(self): (compiler, _, object_suffix, _) = self.detect_prebuild_env() tdir = os.path.join(self.unit_test_dir, '15 prebuilt object') source = os.path.join(tdir, 'source.c') objectfile = os.path.join(tdir, 'prebuilt.' + object_suffix) self.pbcompile(compiler, source, objectfile) try: self.init(tdir) self.build() self.run_tests() finally: os.unlink(objectfile) def build_static_lib(self, compiler, linker, source, objectfile, outfile, extra_args=None): if extra_args is None: extra_args = [] if compiler.get_argument_syntax() == 'msvc': link_cmd = ['lib', '/NOLOGO', '/OUT:' + outfile, objectfile] else: link_cmd = ['ar', 'csr', outfile, objectfile] link_cmd = linker.get_exelist() link_cmd += linker.get_always_args() link_cmd += linker.get_std_link_args() link_cmd += linker.get_output_args(outfile) link_cmd += [objectfile] self.pbcompile(compiler, source, objectfile, extra_args=extra_args) try: subprocess.check_call(link_cmd) finally: os.unlink(objectfile) def test_prebuilt_static_lib(self): (cc, stlinker, object_suffix, _) = self.detect_prebuild_env() tdir = os.path.join(self.unit_test_dir, '16 prebuilt static') source = os.path.join(tdir, 'libdir/best.c') objectfile = os.path.join(tdir, 'libdir/best.' + object_suffix) stlibfile = os.path.join(tdir, 'libdir/libbest.a') self.build_static_lib(cc, stlinker, source, objectfile, stlibfile) # Run the test try: self.init(tdir) self.build() self.run_tests() finally: os.unlink(stlibfile) def build_shared_lib(self, compiler, source, objectfile, outfile, impfile, extra_args=None): if extra_args is None: extra_args = [] if compiler.get_argument_syntax() == 'msvc': link_cmd = compiler.get_linker_exelist() + [ '/NOLOGO', '/DLL', '/DEBUG', '/IMPLIB:' + impfile, '/OUT:' + outfile, objectfile] else: if not (compiler.info.is_windows() or compiler.info.is_cygwin() or compiler.info.is_darwin()): extra_args += ['-fPIC'] link_cmd = compiler.get_exelist() + ['-shared', '-o', outfile, objectfile] if not mesonbuild.mesonlib.is_osx(): link_cmd += ['-Wl,-soname=' + os.path.basename(outfile)] self.pbcompile(compiler, source, objectfile, extra_args=extra_args) try: subprocess.check_call(link_cmd) finally: os.unlink(objectfile) def test_prebuilt_shared_lib(self): (cc, _, object_suffix, shared_suffix) = self.detect_prebuild_env() tdir = os.path.join(self.unit_test_dir, '17 prebuilt shared') source = os.path.join(tdir, 'alexandria.c') objectfile = os.path.join(tdir, 'alexandria.' + object_suffix) impfile = os.path.join(tdir, 'alexandria.lib') if cc.get_argument_syntax() == 'msvc': shlibfile = os.path.join(tdir, 'alexandria.' + shared_suffix) elif is_cygwin(): shlibfile = os.path.join(tdir, 'cygalexandria.' + shared_suffix) else: shlibfile = os.path.join(tdir, 'libalexandria.' + shared_suffix) self.build_shared_lib(cc, source, objectfile, shlibfile, impfile) # Run the test try: self.init(tdir) self.build() self.run_tests() finally: os.unlink(shlibfile) if mesonbuild.mesonlib.is_windows(): # Clean up all the garbage MSVC writes in the # source tree. for fname in glob(os.path.join(tdir, 'alexandria.*')): if os.path.splitext(fname)[1] not in ['.c', '.h']: os.unlink(fname) @skipIfNoPkgconfig def test_pkgconfig_static(self): (cc, stlinker, objext, shext) = self.detect_prebuild_env() testdir = os.path.join(self.unit_test_dir, '18 pkgconfig static') source = os.path.join(testdir, 'foo.c') objectfile = os.path.join(testdir, 'foo.' + objext) stlibfile = os.path.join(testdir, 'libfoo.a') impfile = os.path.join(testdir, 'foo.lib') if cc.get_argument_syntax() == 'msvc': shlibfile = os.path.join(testdir, 'foo.' + shext) elif is_cygwin(): shlibfile = os.path.join(testdir, 'cygfoo.' + shext) else: shlibfile = os.path.join(testdir, 'libfoo.' + shext) # Build libs self.build_static_lib(cc, stlinker, source, objectfile, stlibfile, extra_args=['-DFOO_STATIC']) self.build_shared_lib(cc, source, objectfile, shlibfile, impfile) # Run test try: self.init(testdir, override_envvars={'PKG_CONFIG_LIBDIR': self.builddir}) self.build() self.run_tests() finally: os.unlink(stlibfile) os.unlink(shlibfile) if mesonbuild.mesonlib.is_windows(): # Clean up all the garbage MSVC writes in the # source tree. for fname in glob(os.path.join(testdir, 'foo.*')): if os.path.splitext(fname)[1] not in ['.c', '.h', '.in']: os.unlink(fname) @skipIfNoPkgconfig @mock.patch.dict(os.environ) def test_pkgconfig_gen_escaping(self): testdir = os.path.join(self.common_test_dir, '45 pkgconfig-gen') prefix = '/usr/with spaces' libdir = 'lib' self.init(testdir, extra_args=['--prefix=' + prefix, '--libdir=' + libdir]) # Find foo dependency os.environ['PKG_CONFIG_LIBDIR'] = self.privatedir env = get_fake_env(testdir, self.builddir, self.prefix) kwargs = {'required': True, 'silent': True} foo_dep = PkgConfigDependency('libfoo', env, kwargs) # Ensure link_args are properly quoted libdir = PurePath(prefix) / PurePath(libdir) link_args = ['-L' + libdir.as_posix(), '-lfoo'] self.assertEqual(foo_dep.get_link_args(), link_args) # Ensure include args are properly quoted incdir = PurePath(prefix) / PurePath('include') cargs = ['-I' + incdir.as_posix(), '-DLIBFOO'] # pkg-config and pkgconf does not respect the same order self.assertEqual(sorted(foo_dep.get_compile_args()), sorted(cargs)) def test_array_option_change(self): def get_opt(): opts = self.introspect('--buildoptions') for x in opts: if x.get('name') == 'list': return x raise Exception(opts) expected = { 'name': 'list', 'description': 'list', 'section': 'user', 'type': 'array', 'value': ['foo', 'bar'], 'machine': 'any', } tdir = os.path.join(self.unit_test_dir, '19 array option') self.init(tdir) original = get_opt() self.assertDictEqual(original, expected) expected['value'] = ['oink', 'boink'] self.setconf('-Dlist=oink,boink') changed = get_opt() self.assertEqual(changed, expected) def test_array_option_bad_change(self): def get_opt(): opts = self.introspect('--buildoptions') for x in opts: if x.get('name') == 'list': return x raise Exception(opts) expected = { 'name': 'list', 'description': 'list', 'section': 'user', 'type': 'array', 'value': ['foo', 'bar'], 'machine': 'any', } tdir = os.path.join(self.unit_test_dir, '19 array option') self.init(tdir) original = get_opt() self.assertDictEqual(original, expected) with self.assertRaises(subprocess.CalledProcessError): self.setconf('-Dlist=bad') changed = get_opt() self.assertDictEqual(changed, expected) def test_array_option_empty_equivalents(self): def get_opt(): opts = self.introspect('--buildoptions') for x in opts: if x.get('name') == 'list': return x raise Exception(opts) expected = { 'name': 'list', 'description': 'list', 'section': 'user', 'type': 'array', 'value': [], 'machine': 'any', } tdir = os.path.join(self.unit_test_dir, '19 array option') self.init(tdir, extra_args='-Dlist=') original = get_opt() self.assertDictEqual(original, expected) def opt_has(self, name, value): res = self.introspect('--buildoptions') found = False for i in res: if i['name'] == name: self.assertEqual(i['value'], value) found = True break self.assertTrue(found, "Array option not found in introspect data.") def test_free_stringarray_setting(self): testdir = os.path.join(self.common_test_dir, '41 options') self.init(testdir) self.opt_has('free_array_opt', []) self.setconf('-Dfree_array_opt=foo,bar', will_build=False) self.opt_has('free_array_opt', ['foo', 'bar']) self.setconf("-Dfree_array_opt=['a,b', 'c,d']", will_build=False) self.opt_has('free_array_opt', ['a,b', 'c,d']) # When running under Travis Mac CI, the file updates seem to happen # too fast so the timestamps do not get properly updated. # Call this method before file operations in appropriate places # to make things work. def mac_ci_delay(self): if is_osx() and is_ci(): import time time.sleep(1) def test_options_with_choices_changing(self) -> None: testdir = Path(os.path.join(self.unit_test_dir, '85 change option choices')) options1 = str(testdir / 'meson_options.1.txt') options2 = str(testdir / 'meson_options.2.txt') # Test that old options are changed to the new defaults if they are not valid real_options = str(testdir / 'meson_options.txt') self.addCleanup(os.unlink, real_options) shutil.copy(options1, real_options) self.init(str(testdir)) self.mac_ci_delay() shutil.copy(options2, real_options) self.build() opts = self.introspect('--buildoptions') for item in opts: if item['name'] == 'combo': self.assertEqual(item['value'], 'b') self.assertEqual(item['choices'], ['b', 'c', 'd']) elif item['name'] == 'arr': self.assertEqual(item['value'], ['b']) self.assertEqual(item['choices'], ['b', 'c', 'd']) self.wipe() self.mac_ci_delay() # When the old options are valid they should remain shutil.copy(options1, real_options) self.init(str(testdir), extra_args=['-Dcombo=c', '-Darray=b,c']) self.mac_ci_delay() shutil.copy(options2, real_options) self.build() opts = self.introspect('--buildoptions') for item in opts: if item['name'] == 'combo': self.assertEqual(item['value'], 'c') self.assertEqual(item['choices'], ['b', 'c', 'd']) elif item['name'] == 'arr': self.assertEqual(item['value'], ['b', 'c']) self.assertEqual(item['choices'], ['b', 'c', 'd']) def test_subproject_promotion(self): testdir = os.path.join(self.unit_test_dir, '12 promote') workdir = os.path.join(self.builddir, 'work') shutil.copytree(testdir, workdir) spdir = os.path.join(workdir, 'subprojects') s3dir = os.path.join(spdir, 's3') scommondir = os.path.join(spdir, 'scommon') self.assertFalse(os.path.isdir(s3dir)) subprocess.check_call(self.wrap_command + ['promote', 's3'], cwd=workdir, stdout=subprocess.DEVNULL) self.assertTrue(os.path.isdir(s3dir)) self.assertFalse(os.path.isdir(scommondir)) self.assertNotEqual(subprocess.call(self.wrap_command + ['promote', 'scommon'], cwd=workdir, stderr=subprocess.DEVNULL), 0) self.assertNotEqual(subprocess.call(self.wrap_command + ['promote', 'invalid/path/to/scommon'], cwd=workdir, stderr=subprocess.DEVNULL), 0) self.assertFalse(os.path.isdir(scommondir)) subprocess.check_call(self.wrap_command + ['promote', 'subprojects/s2/subprojects/scommon'], cwd=workdir) self.assertTrue(os.path.isdir(scommondir)) promoted_wrap = os.path.join(spdir, 'athing.wrap') self.assertFalse(os.path.isfile(promoted_wrap)) subprocess.check_call(self.wrap_command + ['promote', 'athing'], cwd=workdir) self.assertTrue(os.path.isfile(promoted_wrap)) self.init(workdir) self.build() def test_subproject_promotion_wrap(self): testdir = os.path.join(self.unit_test_dir, '44 promote wrap') workdir = os.path.join(self.builddir, 'work') shutil.copytree(testdir, workdir) spdir = os.path.join(workdir, 'subprojects') ambiguous_wrap = os.path.join(spdir, 'ambiguous.wrap') self.assertNotEqual(subprocess.call(self.wrap_command + ['promote', 'ambiguous'], cwd=workdir, stderr=subprocess.DEVNULL), 0) self.assertFalse(os.path.isfile(ambiguous_wrap)) subprocess.check_call(self.wrap_command + ['promote', 'subprojects/s2/subprojects/ambiguous.wrap'], cwd=workdir) self.assertTrue(os.path.isfile(ambiguous_wrap)) def test_warning_location(self): tdir = os.path.join(self.unit_test_dir, '22 warning location') out = self.init(tdir) for expected in [ r'meson.build:4: WARNING: Keyword argument "link_with" defined multiple times.', r'sub' + os.path.sep + r'meson.build:3: WARNING: Keyword argument "link_with" defined multiple times.', r'meson.build:6: WARNING: a warning of some sort', r'sub' + os.path.sep + r'meson.build:4: WARNING: subdir warning', r'meson.build:7: WARNING: Module unstable-simd has no backwards or forwards compatibility and might not exist in future releases.', r"meson.build:11: WARNING: The variable(s) 'MISSING' in the input file 'conf.in' are not present in the given configuration data.", r'meson.build:1: WARNING: Passed invalid keyword argument "invalid".', ]: self.assertRegex(out, re.escape(expected)) for wd in [ self.src_root, self.builddir, os.getcwd(), ]: self.new_builddir() out = self.init(tdir, workdir=wd) expected = os.path.join(relpath(tdir, self.src_root), 'meson.build') relwd = relpath(self.src_root, wd) if relwd != '.': expected = os.path.join(relwd, expected) expected = '\n' + expected + ':' self.assertIn(expected, out) def test_error_location_path(self): # this list contains errors from all the different steps in the # lexer/parser/interpreter we have tests for. for (t, f) in [ ('10 out of bounds', 'meson.build'), ('18 wrong plusassign', 'meson.build'), ('61 bad option argument', 'meson_options.txt'), ('102 subdir parse error', os.path.join('subdir', 'meson.build')), ('103 invalid option file', 'meson_options.txt'), ]: tdir = os.path.join(self.src_root, 'test cases', 'failing', t) for wd in [ self.src_root, self.builddir, os.getcwd(), ]: try: self.init(tdir, workdir=wd) except subprocess.CalledProcessError as e: expected = os.path.join('test cases', 'failing', t, f) relwd = relpath(self.src_root, wd) if relwd != '.': expected = os.path.join(relwd, expected) expected = '\n' + expected + ':' self.assertIn(expected, e.output) else: self.fail('configure unexpectedly succeeded') def test_permitted_method_kwargs(self): tdir = os.path.join(self.unit_test_dir, '25 non-permitted kwargs') out = self.init(tdir) for expected in [ r'WARNING: Passed invalid keyword argument "prefixxx".', r'WARNING: Passed invalid keyword argument "argsxx".', r'WARNING: Passed invalid keyword argument "invalidxx".', ]: self.assertRegex(out, re.escape(expected)) def test_templates(self): ninja = detect_ninja() if ninja is None: raise unittest.SkipTest('This test currently requires ninja. Fix this once "meson build" works.') langs = ['c'] env = get_fake_env() for l in ['cpp', 'cs', 'd', 'java', 'cuda', 'fortran', 'objc', 'objcpp', 'rust']: try: comp = env.detect_compiler_for(l, MachineChoice.HOST) with tempfile.TemporaryDirectory() as d: comp.sanity_check(d, env) langs.append(l) except EnvironmentException: pass for lang in langs: for target_type in ('executable', 'library'): # test empty directory with tempfile.TemporaryDirectory() as tmpdir: self._run(self.meson_command + ['init', '--language', lang, '--type', target_type], workdir=tmpdir) self._run(self.setup_command + ['--backend=ninja', 'builddir'], workdir=tmpdir) self._run(ninja, workdir=os.path.join(tmpdir, 'builddir')) # test directory with existing code file if lang in {'c', 'cpp', 'd'}: with tempfile.TemporaryDirectory() as tmpdir: with open(os.path.join(tmpdir, 'foo.' + lang), 'w') as f: f.write('int main(void) {}') self._run(self.meson_command + ['init', '-b'], workdir=tmpdir) elif lang in {'java'}: with tempfile.TemporaryDirectory() as tmpdir: with open(os.path.join(tmpdir, 'Foo.' + lang), 'w') as f: f.write('public class Foo { public static void main() {} }') self._run(self.meson_command + ['init', '-b'], workdir=tmpdir) def test_compiler_run_command(self): testdir = os.path.join(self.unit_test_dir, '24 compiler run_command') self.init(testdir) def test_identical_target_name_in_subproject_flat_layout(self): testdir = os.path.join(self.common_test_dir, '173 identical target name in subproject flat layout') self.init(testdir, extra_args=['--layout=flat']) self.build() def test_identical_target_name_in_subdir_flat_layout(self): testdir = os.path.join(self.common_test_dir, '182 same target name flat layout') self.init(testdir, extra_args=['--layout=flat']) self.build() def test_flock(self): exception_raised = False with tempfile.TemporaryDirectory() as tdir: os.mkdir(os.path.join(tdir, 'meson-private')) with BuildDirLock(tdir): try: with BuildDirLock(tdir): pass except MesonException: exception_raised = True self.assertTrue(exception_raised, 'Double locking did not raise exception.') @unittest.skipIf(is_osx(), 'Test not applicable to OSX') def test_check_module_linking(self): tdir = os.path.join(self.unit_test_dir, '30 shared_mod linking') out = self.init(tdir) msg = ('WARNING: target links against shared modules. This is not ' 'recommended as it is not supported on some platforms') self.assertIn(msg, out) def test_ndebug_if_release_disabled(self): testdir = os.path.join(self.unit_test_dir, '28 ndebug if-release') self.init(testdir, extra_args=['--buildtype=release', '-Db_ndebug=if-release']) self.build() exe = os.path.join(self.builddir, 'main') self.assertEqual(b'NDEBUG=1', subprocess.check_output(exe).strip()) def test_ndebug_if_release_enabled(self): testdir = os.path.join(self.unit_test_dir, '28 ndebug if-release') self.init(testdir, extra_args=['--buildtype=debugoptimized', '-Db_ndebug=if-release']) self.build() exe = os.path.join(self.builddir, 'main') self.assertEqual(b'NDEBUG=0', subprocess.check_output(exe).strip()) def test_guessed_linker_dependencies(self): testdirbase = os.path.join(self.unit_test_dir, '29 guessed linker dependencies') testdirlib = os.path.join(testdirbase, 'lib') extra_args = None libdir_flags = ['-L'] env = get_fake_env(testdirlib, self.builddir, self.prefix) if env.detect_c_compiler(MachineChoice.HOST).get_id() in {'msvc', 'clang-cl', 'intel-cl'}: # msvc-like compiler, also test it with msvc-specific flags libdir_flags += ['/LIBPATH:', '-LIBPATH:'] else: # static libraries are not linkable with -l with msvc because meson installs them # as .a files which unix_args_to_native will not know as it expects libraries to use # .lib as extension. For a DLL the import library is installed as .lib. Thus for msvc # this tests needs to use shared libraries to test the path resolving logic in the # dependency generation code path. extra_args = ['--default-library', 'static'] initial_builddir = self.builddir initial_installdir = self.installdir for libdir_flag in libdir_flags: # build library self.new_builddir() self.init(testdirlib, extra_args=extra_args) self.build() self.install() libbuilddir = self.builddir installdir = self.installdir libdir = os.path.join(self.installdir, self.prefix.lstrip('/').lstrip('\\'), 'lib') # build user of library self.new_builddir() # replace is needed because meson mangles platform paths passed via LDFLAGS self.init(os.path.join(testdirbase, 'exe'), override_envvars={"LDFLAGS": '{}{}'.format(libdir_flag, libdir.replace('\\', '/'))}) self.build() self.assertBuildIsNoop() # rebuild library exebuilddir = self.builddir self.installdir = installdir self.builddir = libbuilddir # Microsoft's compiler is quite smart about touching import libs on changes, # so ensure that there is actually a change in symbols. self.setconf('-Dmore_exports=true') self.build() self.install() # no ensure_backend_detects_changes needed because self.setconf did that already # assert user of library will be rebuild self.builddir = exebuilddir self.assertRebuiltTarget('app') # restore dirs for the next test case self.installdir = initial_builddir self.builddir = initial_installdir def test_conflicting_d_dash_option(self): testdir = os.path.join(self.unit_test_dir, '37 mixed command line args') with self.assertRaises((subprocess.CalledProcessError, RuntimeError)) as e: self.init(testdir, extra_args=['-Dbindir=foo', '--bindir=bar']) # Just to ensure that we caught the correct error self.assertIn('as both', e.stderr) def _test_same_option_twice(self, arg, args): testdir = os.path.join(self.unit_test_dir, '37 mixed command line args') self.init(testdir, extra_args=args) opts = self.introspect('--buildoptions') for item in opts: if item['name'] == arg: self.assertEqual(item['value'], 'bar') return raise Exception('Missing {} value?'.format(arg)) def test_same_dash_option_twice(self): self._test_same_option_twice('bindir', ['--bindir=foo', '--bindir=bar']) def test_same_d_option_twice(self): self._test_same_option_twice('bindir', ['-Dbindir=foo', '-Dbindir=bar']) def test_same_project_d_option_twice(self): self._test_same_option_twice('one', ['-Done=foo', '-Done=bar']) def _test_same_option_twice_configure(self, arg, args): testdir = os.path.join(self.unit_test_dir, '37 mixed command line args') self.init(testdir) self.setconf(args) opts = self.introspect('--buildoptions') for item in opts: if item['name'] == arg: self.assertEqual(item['value'], 'bar') return raise Exception('Missing {} value?'.format(arg)) def test_same_dash_option_twice_configure(self): self._test_same_option_twice_configure( 'bindir', ['--bindir=foo', '--bindir=bar']) def test_same_d_option_twice_configure(self): self._test_same_option_twice_configure( 'bindir', ['-Dbindir=foo', '-Dbindir=bar']) def test_same_project_d_option_twice_configure(self): self._test_same_option_twice_configure( 'one', ['-Done=foo', '-Done=bar']) def test_command_line(self): testdir = os.path.join(self.unit_test_dir, '34 command line') # Verify default values when passing no args that affect the # configuration, and as a bonus, test that --profile-self works. self.init(testdir, extra_args=['--profile-self', '--fatal-meson-warnings']) obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('default_library')].value, 'static') self.assertEqual(obj.options[OptionKey('warning_level')].value, '1') self.assertEqual(obj.options[OptionKey('set_sub_opt')].value, True) self.assertEqual(obj.options[OptionKey('subp_opt', 'subp')].value, 'default3') self.wipe() # warning_level is special, it's --warnlevel instead of --warning-level # for historical reasons self.init(testdir, extra_args=['--warnlevel=2', '--fatal-meson-warnings']) obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('warning_level')].value, '2') self.setconf('--warnlevel=3') obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('warning_level')].value, '3') self.wipe() # But when using -D syntax, it should be 'warning_level' self.init(testdir, extra_args=['-Dwarning_level=2', '--fatal-meson-warnings']) obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('warning_level')].value, '2') self.setconf('-Dwarning_level=3') obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('warning_level')].value, '3') self.wipe() # Mixing --option and -Doption is forbidden with self.assertRaises((subprocess.CalledProcessError, RuntimeError)) as cm: self.init(testdir, extra_args=['--warnlevel=1', '-Dwarning_level=3']) if isinstance(cm.exception, subprocess.CalledProcessError): self.assertNotEqual(0, cm.exception.returncode) self.assertIn('as both', cm.exception.output) else: self.assertIn('as both', str(cm.exception)) self.init(testdir) with self.assertRaises((subprocess.CalledProcessError, RuntimeError)) as cm: self.setconf(['--warnlevel=1', '-Dwarning_level=3']) if isinstance(cm.exception, subprocess.CalledProcessError): self.assertNotEqual(0, cm.exception.returncode) self.assertIn('as both', cm.exception.output) else: self.assertIn('as both', str(cm.exception)) self.wipe() # --default-library should override default value from project() self.init(testdir, extra_args=['--default-library=both', '--fatal-meson-warnings']) obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('default_library')].value, 'both') self.setconf('--default-library=shared') obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('default_library')].value, 'shared') if self.backend is Backend.ninja: # reconfigure target works only with ninja backend self.build('reconfigure') obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('default_library')].value, 'shared') self.wipe() # Should warn on unknown options out = self.init(testdir, extra_args=['-Dbad=1', '-Dfoo=2', '-Dwrong_link_args=foo']) self.assertIn('Unknown options: "bad, foo, wrong_link_args"', out) self.wipe() # Should fail on malformed option msg = "Option 'foo' must have a value separated by equals sign." with self.assertRaises((subprocess.CalledProcessError, RuntimeError)) as cm: self.init(testdir, extra_args=['-Dfoo']) if isinstance(cm.exception, subprocess.CalledProcessError): self.assertNotEqual(0, cm.exception.returncode) self.assertIn(msg, cm.exception.output) else: self.assertIn(msg, str(cm.exception)) self.init(testdir) with self.assertRaises((subprocess.CalledProcessError, RuntimeError)) as cm: self.setconf('-Dfoo') if isinstance(cm.exception, subprocess.CalledProcessError): self.assertNotEqual(0, cm.exception.returncode) self.assertIn(msg, cm.exception.output) else: self.assertIn(msg, str(cm.exception)) self.wipe() # It is not an error to set wrong option for unknown subprojects or # language because we don't have control on which one will be selected. self.init(testdir, extra_args=['-Dc_wrong=1', '-Dwrong:bad=1', '-Db_wrong=1']) self.wipe() # Test we can set subproject option self.init(testdir, extra_args=['-Dsubp:subp_opt=foo', '--fatal-meson-warnings']) obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('subp_opt', 'subp')].value, 'foo') self.wipe() # c_args value should be parsed with split_args self.init(testdir, extra_args=['-Dc_args=-Dfoo -Dbar "-Dthird=one two"', '--fatal-meson-warnings']) obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('args', lang='c')].value, ['-Dfoo', '-Dbar', '-Dthird=one two']) self.setconf('-Dc_args="foo bar" one two') obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('args', lang='c')].value, ['foo bar', 'one', 'two']) self.wipe() self.init(testdir, extra_args=['-Dset_percent_opt=myoption%', '--fatal-meson-warnings']) obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('set_percent_opt')].value, 'myoption%') self.wipe() # Setting a 2nd time the same option should override the first value try: self.init(testdir, extra_args=['--bindir=foo', '--bindir=bar', '-Dbuildtype=plain', '-Dbuildtype=release', '-Db_sanitize=address', '-Db_sanitize=thread', '-Dc_args=-Dfoo', '-Dc_args=-Dbar', '-Db_lundef=false', '--fatal-meson-warnings']) obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('bindir')].value, 'bar') self.assertEqual(obj.options[OptionKey('buildtype')].value, 'release') self.assertEqual(obj.options[OptionKey('b_sanitize')].value, 'thread') self.assertEqual(obj.options[OptionKey('args', lang='c')].value, ['-Dbar']) self.setconf(['--bindir=bar', '--bindir=foo', '-Dbuildtype=release', '-Dbuildtype=plain', '-Db_sanitize=thread', '-Db_sanitize=address', '-Dc_args=-Dbar', '-Dc_args=-Dfoo']) obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('bindir')].value, 'foo') self.assertEqual(obj.options[OptionKey('buildtype')].value, 'plain') self.assertEqual(obj.options[OptionKey('b_sanitize')].value, 'address') self.assertEqual(obj.options[OptionKey('args', lang='c')].value, ['-Dfoo']) self.wipe() except KeyError: # Ignore KeyError, it happens on CI for compilers that does not # support b_sanitize. We have to test with a base option because # they used to fail this test with Meson 0.46 an earlier versions. pass def test_warning_level_0(self): testdir = os.path.join(self.common_test_dir, '208 warning level 0') # Verify default values when passing no args self.init(testdir) obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('warning_level')].value, '0') self.wipe() # verify we can override w/ --warnlevel self.init(testdir, extra_args=['--warnlevel=1']) obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('warning_level')].value, '1') self.setconf('--warnlevel=0') obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('warning_level')].value, '0') self.wipe() # verify we can override w/ -Dwarning_level self.init(testdir, extra_args=['-Dwarning_level=1']) obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('warning_level')].value, '1') self.setconf('-Dwarning_level=0') obj = mesonbuild.coredata.load(self.builddir) self.assertEqual(obj.options[OptionKey('warning_level')].value, '0') self.wipe() def test_feature_check_usage_subprojects(self): testdir = os.path.join(self.unit_test_dir, '41 featurenew subprojects') out = self.init(testdir) # Parent project warns correctly self.assertRegex(out, "WARNING: Project targeting '>=0.45'.*'0.47.0': dict") # Subprojects warn correctly self.assertRegex(out, r"\|WARNING: Project targeting '>=0.40'.*'0.44.0': disabler") self.assertRegex(out, r"\|WARNING: Project targeting '!=0.40'.*'0.44.0': disabler") # Subproject has a new-enough meson_version, no warning self.assertNotRegex(out, "WARNING: Project targeting.*Python") # Ensure a summary is printed in the subproject and the outer project self.assertRegex(out, r"\|WARNING: Project specifies a minimum meson_version '>=0.40'") self.assertRegex(out, r"\| \* 0.44.0: {'disabler'}") self.assertRegex(out, "WARNING: Project specifies a minimum meson_version '>=0.45'") self.assertRegex(out, " * 0.47.0: {'dict'}") def test_configure_file_warnings(self): testdir = os.path.join(self.common_test_dir, "14 configure file") out = self.init(testdir) self.assertRegex(out, "WARNING:.*'empty'.*config.h.in.*not present.*") self.assertRegex(out, "WARNING:.*'FOO_BAR'.*nosubst-nocopy2.txt.in.*not present.*") self.assertRegex(out, "WARNING:.*'empty'.*config.h.in.*not present.*") self.assertRegex(out, "WARNING:.*empty configuration_data.*test.py.in") # Warnings for configuration files that are overwritten. self.assertRegex(out, "WARNING:.*\"double_output.txt\".*overwrites") self.assertRegex(out, "WARNING:.*\"subdir.double_output2.txt\".*overwrites") self.assertNotRegex(out, "WARNING:.*no_write_conflict.txt.*overwrites") self.assertNotRegex(out, "WARNING:.*@BASENAME@.*overwrites") self.assertRegex(out, "WARNING:.*\"sameafterbasename\".*overwrites") # No warnings about empty configuration data objects passed to files with substitutions self.assertNotRegex(out, "WARNING:.*empty configuration_data.*nosubst-nocopy1.txt.in") self.assertNotRegex(out, "WARNING:.*empty configuration_data.*nosubst-nocopy2.txt.in") with open(os.path.join(self.builddir, 'nosubst-nocopy1.txt'), 'rb') as f: self.assertEqual(f.read().strip(), b'/* #undef FOO_BAR */') with open(os.path.join(self.builddir, 'nosubst-nocopy2.txt'), 'rb') as f: self.assertEqual(f.read().strip(), b'') self.assertRegex(out, r"DEPRECATION:.*\['array'\] is invalid.*dict") def test_dirs(self): with tempfile.TemporaryDirectory() as containing: with tempfile.TemporaryDirectory(dir=containing) as srcdir: mfile = os.path.join(srcdir, 'meson.build') of = open(mfile, 'w') of.write("project('foobar', 'c')\n") of.close() pc = subprocess.run(self.setup_command, cwd=srcdir, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL) self.assertIn(b'Must specify at least one directory name', pc.stdout) with tempfile.TemporaryDirectory(dir=srcdir) as builddir: subprocess.run(self.setup_command, check=True, cwd=builddir, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) def get_opts_as_dict(self): result = {} for i in self.introspect('--buildoptions'): result[i['name']] = i['value'] return result def test_buildtype_setting(self): testdir = os.path.join(self.common_test_dir, '1 trivial') self.init(testdir) opts = self.get_opts_as_dict() self.assertEqual(opts['buildtype'], 'debug') self.assertEqual(opts['debug'], True) self.setconf('-Ddebug=false') opts = self.get_opts_as_dict() self.assertEqual(opts['debug'], False) self.assertEqual(opts['buildtype'], 'debug') self.assertEqual(opts['optimization'], '0') self.setconf('-Doptimization=g') opts = self.get_opts_as_dict() self.assertEqual(opts['debug'], False) self.assertEqual(opts['buildtype'], 'debug') self.assertEqual(opts['optimization'], 'g') @skipIfNoPkgconfig @unittest.skipIf(is_windows(), 'Help needed with fixing this test on windows') def test_native_dep_pkgconfig(self): testdir = os.path.join(self.unit_test_dir, '46 native dep pkgconfig var') with tempfile.NamedTemporaryFile(mode='w', delete=False) as crossfile: crossfile.write(textwrap.dedent( '''[binaries] pkgconfig = '{0}' [properties] [host_machine] system = 'linux' cpu_family = 'arm' cpu = 'armv7' endian = 'little' '''.format(os.path.join(testdir, 'cross_pkgconfig.py')))) crossfile.flush() self.meson_cross_file = crossfile.name env = {'PKG_CONFIG_LIBDIR': os.path.join(testdir, 'native_pkgconfig')} self.init(testdir, extra_args=['-Dstart_native=false'], override_envvars=env) self.wipe() self.init(testdir, extra_args=['-Dstart_native=true'], override_envvars=env) @skipIfNoPkgconfig @unittest.skipIf(is_windows(), 'Help needed with fixing this test on windows') def test_pkg_config_libdir(self): testdir = os.path.join(self.unit_test_dir, '46 native dep pkgconfig var') with tempfile.NamedTemporaryFile(mode='w', delete=False) as crossfile: crossfile.write(textwrap.dedent( '''[binaries] pkgconfig = 'pkg-config' [properties] pkg_config_libdir = ['{0}'] [host_machine] system = 'linux' cpu_family = 'arm' cpu = 'armv7' endian = 'little' '''.format(os.path.join(testdir, 'cross_pkgconfig')))) crossfile.flush() self.meson_cross_file = crossfile.name env = {'PKG_CONFIG_LIBDIR': os.path.join(testdir, 'native_pkgconfig')} self.init(testdir, extra_args=['-Dstart_native=false'], override_envvars=env) self.wipe() self.init(testdir, extra_args=['-Dstart_native=true'], override_envvars=env) def __reconfigure(self, change_minor=False): # Set an older version to force a reconfigure from scratch filename = os.path.join(self.privatedir, 'coredata.dat') with open(filename, 'rb') as f: obj = pickle.load(f) if change_minor: v = mesonbuild.coredata.version.split('.') obj.version = '.'.join(v[0:2] + [str(int(v[2]) + 1)]) else: obj.version = '0.47.0' with open(filename, 'wb') as f: pickle.dump(obj, f) def test_reconfigure(self): testdir = os.path.join(self.unit_test_dir, '48 reconfigure') self.init(testdir, extra_args=['-Dopt1=val1']) self.setconf('-Dopt2=val2') self.__reconfigure() out = self.init(testdir, extra_args=['--reconfigure', '-Dopt3=val3']) self.assertRegex(out, 'Regenerating configuration from scratch') self.assertRegex(out, 'opt1 val1') self.assertRegex(out, 'opt2 val2') self.assertRegex(out, 'opt3 val3') self.assertRegex(out, 'opt4 default4') self.build() self.run_tests() # Create a file in builddir and verify wipe command removes it filename = os.path.join(self.builddir, 'something') open(filename, 'w').close() self.assertTrue(os.path.exists(filename)) out = self.init(testdir, extra_args=['--wipe', '-Dopt4=val4']) self.assertFalse(os.path.exists(filename)) self.assertRegex(out, 'opt1 val1') self.assertRegex(out, 'opt2 val2') self.assertRegex(out, 'opt3 val3') self.assertRegex(out, 'opt4 val4') self.build() self.run_tests() def test_wipe_from_builddir(self): testdir = os.path.join(self.common_test_dir, '158 custom target subdir depend files') self.init(testdir) self.__reconfigure() with Path(self.builddir): self.init(testdir, extra_args=['--wipe']) def test_minor_version_does_not_reconfigure_wipe(self): testdir = os.path.join(self.unit_test_dir, '48 reconfigure') self.init(testdir, extra_args=['-Dopt1=val1']) self.setconf('-Dopt2=val2') self.__reconfigure(change_minor=True) out = self.init(testdir, extra_args=['--reconfigure', '-Dopt3=val3']) self.assertNotRegex(out, 'Regenerating configuration from scratch') self.assertRegex(out, 'opt1 val1') self.assertRegex(out, 'opt2 val2') self.assertRegex(out, 'opt3 val3') self.assertRegex(out, 'opt4 default4') self.build() self.run_tests() def test_target_construct_id_from_path(self): # This id is stable but not guessable. # The test is supposed to prevent unintentional # changes of target ID generation. target_id = Target.construct_id_from_path('some/obscure/subdir', 'target-id', '@suffix') self.assertEqual('5e002d3@@target-id@suffix', target_id) target_id = Target.construct_id_from_path('subproject/foo/subdir/bar', 'target2-id', '@other') self.assertEqual('81d46d1@@target2-id@other', target_id) def test_introspect_projectinfo_without_configured_build(self): testfile = os.path.join(self.common_test_dir, '34 run program', 'meson.build') res = self.introspect_directory(testfile, '--projectinfo') self.assertEqual(set(res['buildsystem_files']), set(['meson.build'])) self.assertEqual(res['version'], 'undefined') self.assertEqual(res['descriptive_name'], 'run command') self.assertEqual(res['subprojects'], []) testfile = os.path.join(self.common_test_dir, '41 options', 'meson.build') res = self.introspect_directory(testfile, '--projectinfo') self.assertEqual(set(res['buildsystem_files']), set(['meson_options.txt', 'meson.build'])) self.assertEqual(res['version'], 'undefined') self.assertEqual(res['descriptive_name'], 'options') self.assertEqual(res['subprojects'], []) testfile = os.path.join(self.common_test_dir, '44 subproject options', 'meson.build') res = self.introspect_directory(testfile, '--projectinfo') self.assertEqual(set(res['buildsystem_files']), set(['meson_options.txt', 'meson.build'])) self.assertEqual(res['version'], 'undefined') self.assertEqual(res['descriptive_name'], 'suboptions') self.assertEqual(len(res['subprojects']), 1) subproject_files = set(f.replace('\\', '/') for f in res['subprojects'][0]['buildsystem_files']) self.assertEqual(subproject_files, set(['subprojects/subproject/meson_options.txt', 'subprojects/subproject/meson.build'])) self.assertEqual(res['subprojects'][0]['name'], 'subproject') self.assertEqual(res['subprojects'][0]['version'], 'undefined') self.assertEqual(res['subprojects'][0]['descriptive_name'], 'subproject') def test_introspect_projectinfo_subprojects(self): testdir = os.path.join(self.common_test_dir, '99 subproject subdir') self.init(testdir) res = self.introspect('--projectinfo') expected = { 'descriptive_name': 'proj', 'version': 'undefined', 'subproject_dir': 'subprojects', 'subprojects': [ { 'descriptive_name': 'sub', 'name': 'sub', 'version': '1.0' }, { 'descriptive_name': 'sub_implicit', 'name': 'sub_implicit', 'version': '1.0', }, { 'descriptive_name': 'sub-novar', 'name': 'sub_novar', 'version': '1.0', }, { 'descriptive_name': 'subsub', 'name': 'subsub', 'version': 'undefined' }, { 'descriptive_name': 'subsubsub', 'name': 'subsubsub', 'version': 'undefined' }, ] } res['subprojects'] = sorted(res['subprojects'], key=lambda i: i['name']) self.assertDictEqual(expected, res) def test_introspection_target_subproject(self): testdir = os.path.join(self.common_test_dir, '43 subproject') self.init(testdir) res = self.introspect('--targets') expected = { 'sublib': 'sublib', 'simpletest': 'sublib', 'user': None } for entry in res: name = entry['name'] self.assertEqual(entry['subproject'], expected[name]) def test_introspect_projectinfo_subproject_dir(self): testdir = os.path.join(self.common_test_dir, '76 custom subproject dir') self.init(testdir) res = self.introspect('--projectinfo') self.assertEqual(res['subproject_dir'], 'custom_subproject_dir') def test_introspect_projectinfo_subproject_dir_from_source(self): testfile = os.path.join(self.common_test_dir, '76 custom subproject dir', 'meson.build') res = self.introspect_directory(testfile, '--projectinfo') self.assertEqual(res['subproject_dir'], 'custom_subproject_dir') @skipIfNoExecutable('clang-format') def test_clang_format(self): if self.backend is not Backend.ninja: raise unittest.SkipTest('Clang-format is for now only supported on Ninja, not {}'.format(self.backend.name)) testdir = os.path.join(self.unit_test_dir, '54 clang-format') testfile = os.path.join(testdir, 'prog.c') badfile = os.path.join(testdir, 'prog_orig_c') goodfile = os.path.join(testdir, 'prog_expected_c') testheader = os.path.join(testdir, 'header.h') badheader = os.path.join(testdir, 'header_orig_h') goodheader = os.path.join(testdir, 'header_expected_h') try: shutil.copyfile(badfile, testfile) shutil.copyfile(badheader, testheader) self.init(testdir) self.assertNotEqual(Path(testfile).read_text(), Path(goodfile).read_text()) self.assertNotEqual(Path(testheader).read_text(), Path(goodheader).read_text()) self.run_target('clang-format') self.assertEqual(Path(testheader).read_text(), Path(goodheader).read_text()) finally: if os.path.exists(testfile): os.unlink(testfile) if os.path.exists(testheader): os.unlink(testheader) @skipIfNoExecutable('clang-tidy') def test_clang_tidy(self): if self.backend is not Backend.ninja: raise unittest.SkipTest('Clang-tidy is for now only supported on Ninja, not {}'.format(self.backend.name)) if shutil.which('c++') is None: raise unittest.SkipTest('Clang-tidy breaks when ccache is used and "c++" not in path.') if is_osx(): raise unittest.SkipTest('Apple ships a broken clang-tidy that chokes on -pipe.') testdir = os.path.join(self.unit_test_dir, '70 clang-tidy') dummydir = os.path.join(testdir, 'dummydir.h') self.init(testdir, override_envvars={'CXX': 'c++'}) out = self.run_target('clang-tidy') self.assertIn('cttest.cpp:4:20', out) self.assertNotIn(dummydir, out) def test_identity_cross(self): testdir = os.path.join(self.unit_test_dir, '71 cross') # Do a build to generate a cross file where the host is this target self.init(testdir, extra_args=['-Dgenerate=true']) self.meson_cross_file = os.path.join(self.builddir, "crossfile") self.assertTrue(os.path.exists(self.meson_cross_file)) # Now verify that this is detected as cross self.new_builddir() self.init(testdir) def test_introspect_buildoptions_without_configured_build(self): testdir = os.path.join(self.unit_test_dir, '59 introspect buildoptions') testfile = os.path.join(testdir, 'meson.build') res_nb = self.introspect_directory(testfile, ['--buildoptions'] + self.meson_args) self.init(testdir, default_args=False) res_wb = self.introspect('--buildoptions') self.maxDiff = None # XXX: These now generate in a different order, is that okay? self.assertListEqual(sorted(res_nb, key=lambda x: x['name']), sorted(res_wb, key=lambda x: x['name'])) def test_meson_configure_from_source_does_not_crash(self): testdir = os.path.join(self.unit_test_dir, '59 introspect buildoptions') self._run(self.mconf_command + [testdir]) def test_introspect_buildoptions_cross_only(self): testdir = os.path.join(self.unit_test_dir, '84 cross only introspect') testfile = os.path.join(testdir, 'meson.build') res = self.introspect_directory(testfile, ['--buildoptions'] + self.meson_args) optnames = [o['name'] for o in res] self.assertIn('c_args', optnames) self.assertNotIn('build.c_args', optnames) def test_introspect_json_dump(self): testdir = os.path.join(self.unit_test_dir, '57 introspection') self.init(testdir) infodir = os.path.join(self.builddir, 'meson-info') self.assertPathExists(infodir) def assertKeyTypes(key_type_list, obj, strict: bool = True): for i in key_type_list: if isinstance(i[1], (list, tuple)) and None in i[1]: i = (i[0], tuple([x for x in i[1] if x is not None])) if i[0] not in obj or obj[i[0]] is None: continue self.assertIn(i[0], obj) self.assertIsInstance(obj[i[0]], i[1]) if strict: for k in obj.keys(): found = False for i in key_type_list: if k == i[0]: found = True break self.assertTrue(found, 'Key "{}" not in expected list'.format(k)) root_keylist = [ ('benchmarks', list), ('buildoptions', list), ('buildsystem_files', list), ('dependencies', list), ('installed', dict), ('projectinfo', dict), ('targets', list), ('tests', list), ] test_keylist = [ ('cmd', list), ('env', dict), ('name', str), ('timeout', int), ('suite', list), ('is_parallel', bool), ('protocol', str), ('depends', list), ('workdir', (str, None)), ('priority', int), ] buildoptions_keylist = [ ('name', str), ('section', str), ('type', str), ('description', str), ('machine', str), ('choices', (list, None)), ('value', (str, int, bool, list)), ] buildoptions_typelist = [ ('combo', str, [('choices', list)]), ('string', str, []), ('boolean', bool, []), ('integer', int, []), ('array', list, []), ] buildoptions_sections = ['core', 'backend', 'base', 'compiler', 'directory', 'user', 'test'] buildoptions_machines = ['any', 'build', 'host'] dependencies_typelist = [ ('name', str), ('version', str), ('compile_args', list), ('link_args', list), ] targets_typelist = [ ('name', str), ('id', str), ('type', str), ('defined_in', str), ('filename', list), ('build_by_default', bool), ('target_sources', list), ('extra_files', list), ('subproject', (str, None)), ('install_filename', (list, None)), ('installed', bool), ] targets_sources_typelist = [ ('language', str), ('compiler', list), ('parameters', list), ('sources', list), ('generated_sources', list), ] # First load all files res = {} for i in root_keylist: curr = os.path.join(infodir, 'intro-{}.json'.format(i[0])) self.assertPathExists(curr) with open(curr, 'r') as fp: res[i[0]] = json.load(fp) assertKeyTypes(root_keylist, res) # Match target ids to input and output files for ease of reference src_to_id = {} out_to_id = {} for i in res['targets']: print(json.dump(i, sys.stdout)) out_to_id.update({os.path.relpath(out, self.builddir): i['id'] for out in i['filename']}) for group in i['target_sources']: src_to_id.update({os.path.relpath(src, testdir): i['id'] for src in group['sources']}) # Check Tests and benchmarks tests_to_find = ['test case 1', 'test case 2', 'benchmark 1'] deps_to_find = {'test case 1': [src_to_id['t1.cpp']], 'test case 2': [src_to_id['t2.cpp'], src_to_id['t3.cpp']], 'benchmark 1': [out_to_id['file2'], src_to_id['t3.cpp']]} for i in res['benchmarks'] + res['tests']: assertKeyTypes(test_keylist, i) if i['name'] in tests_to_find: tests_to_find.remove(i['name']) self.assertEqual(sorted(i['depends']), sorted(deps_to_find[i['name']])) self.assertListEqual(tests_to_find, []) # Check buildoptions buildopts_to_find = {'cpp_std': 'c++11'} for i in res['buildoptions']: assertKeyTypes(buildoptions_keylist, i) valid_type = False for j in buildoptions_typelist: if i['type'] == j[0]: self.assertIsInstance(i['value'], j[1]) assertKeyTypes(j[2], i, strict=False) valid_type = True break self.assertIn(i['section'], buildoptions_sections) self.assertIn(i['machine'], buildoptions_machines) self.assertTrue(valid_type) if i['name'] in buildopts_to_find: self.assertEqual(i['value'], buildopts_to_find[i['name']]) buildopts_to_find.pop(i['name'], None) self.assertDictEqual(buildopts_to_find, {}) # Check buildsystem_files bs_files = ['meson.build', 'meson_options.txt', 'sharedlib/meson.build', 'staticlib/meson.build'] bs_files = [os.path.join(testdir, x) for x in bs_files] self.assertPathListEqual(list(sorted(res['buildsystem_files'])), list(sorted(bs_files))) # Check dependencies dependencies_to_find = ['threads'] for i in res['dependencies']: assertKeyTypes(dependencies_typelist, i) if i['name'] in dependencies_to_find: dependencies_to_find.remove(i['name']) self.assertListEqual(dependencies_to_find, []) # Check projectinfo self.assertDictEqual(res['projectinfo'], {'version': '1.2.3', 'descriptive_name': 'introspection', 'subproject_dir': 'subprojects', 'subprojects': []}) # Check targets targets_to_find = { 'sharedTestLib': ('shared library', True, False, 'sharedlib/meson.build'), 'staticTestLib': ('static library', True, False, 'staticlib/meson.build'), 'test1': ('executable', True, True, 'meson.build'), 'test2': ('executable', True, False, 'meson.build'), 'test3': ('executable', True, False, 'meson.build'), } for i in res['targets']: assertKeyTypes(targets_typelist, i) if i['name'] in targets_to_find: tgt = targets_to_find[i['name']] self.assertEqual(i['type'], tgt[0]) self.assertEqual(i['build_by_default'], tgt[1]) self.assertEqual(i['installed'], tgt[2]) self.assertPathEqual(i['defined_in'], os.path.join(testdir, tgt[3])) targets_to_find.pop(i['name'], None) for j in i['target_sources']: assertKeyTypes(targets_sources_typelist, j) self.assertDictEqual(targets_to_find, {}) def test_introspect_file_dump_equals_all(self): testdir = os.path.join(self.unit_test_dir, '57 introspection') self.init(testdir) res_all = self.introspect('--all') res_file = {} root_keylist = [ 'benchmarks', 'buildoptions', 'buildsystem_files', 'dependencies', 'installed', 'projectinfo', 'targets', 'tests', ] infodir = os.path.join(self.builddir, 'meson-info') self.assertPathExists(infodir) for i in root_keylist: curr = os.path.join(infodir, 'intro-{}.json'.format(i)) self.assertPathExists(curr) with open(curr, 'r') as fp: res_file[i] = json.load(fp) self.assertEqual(res_all, res_file) def test_introspect_meson_info(self): testdir = os.path.join(self.unit_test_dir, '57 introspection') introfile = os.path.join(self.builddir, 'meson-info', 'meson-info.json') self.init(testdir) self.assertPathExists(introfile) with open(introfile, 'r') as fp: res1 = json.load(fp) for i in ['meson_version', 'directories', 'introspection', 'build_files_updated', 'error']: self.assertIn(i, res1) self.assertEqual(res1['error'], False) self.assertEqual(res1['build_files_updated'], True) def test_introspect_config_update(self): testdir = os.path.join(self.unit_test_dir, '57 introspection') introfile = os.path.join(self.builddir, 'meson-info', 'intro-buildoptions.json') self.init(testdir) self.assertPathExists(introfile) with open(introfile, 'r') as fp: res1 = json.load(fp) for i in res1: if i['name'] == 'cpp_std': i['value'] = 'c++14' if i['name'] == 'build.cpp_std': i['value'] = 'c++14' if i['name'] == 'buildtype': i['value'] = 'release' if i['name'] == 'optimization': i['value'] = '3' if i['name'] == 'debug': i['value'] = False self.setconf('-Dcpp_std=c++14') self.setconf('-Dbuildtype=release') with open(introfile, 'r') as fp: res2 = json.load(fp) self.assertListEqual(res1, res2) def test_introspect_targets_from_source(self): testdir = os.path.join(self.unit_test_dir, '57 introspection') testfile = os.path.join(testdir, 'meson.build') introfile = os.path.join(self.builddir, 'meson-info', 'intro-targets.json') self.init(testdir) self.assertPathExists(introfile) with open(introfile, 'r') as fp: res_wb = json.load(fp) res_nb = self.introspect_directory(testfile, ['--targets'] + self.meson_args) # Account for differences in output res_wb = [i for i in res_wb if i['type'] != 'custom'] for i in res_wb: i['filename'] = [os.path.relpath(x, self.builddir) for x in i['filename']] if 'install_filename' in i: del i['install_filename'] sources = [] for j in i['target_sources']: sources += j['sources'] i['target_sources'] = [{ 'language': 'unknown', 'compiler': [], 'parameters': [], 'sources': sources, 'generated_sources': [] }] self.maxDiff = None self.assertListEqual(res_nb, res_wb) def test_introspect_ast_source(self): testdir = os.path.join(self.unit_test_dir, '57 introspection') testfile = os.path.join(testdir, 'meson.build') res_nb = self.introspect_directory(testfile, ['--ast'] + self.meson_args) node_counter = {} def accept_node(json_node): self.assertIsInstance(json_node, dict) for i in ['lineno', 'colno', 'end_lineno', 'end_colno']: self.assertIn(i, json_node) self.assertIsInstance(json_node[i], int) self.assertIn('node', json_node) n = json_node['node'] self.assertIsInstance(n, str) self.assertIn(n, nodes) if n not in node_counter: node_counter[n] = 0 node_counter[n] = node_counter[n] + 1 for nodeDesc in nodes[n]: key = nodeDesc[0] func = nodeDesc[1] self.assertIn(key, json_node) if func is None: tp = nodeDesc[2] self.assertIsInstance(json_node[key], tp) continue func(json_node[key]) def accept_node_list(node_list): self.assertIsInstance(node_list, list) for i in node_list: accept_node(i) def accept_kwargs(kwargs): self.assertIsInstance(kwargs, list) for i in kwargs: self.assertIn('key', i) self.assertIn('val', i) accept_node(i['key']) accept_node(i['val']) nodes = { 'BooleanNode': [('value', None, bool)], 'IdNode': [('value', None, str)], 'NumberNode': [('value', None, int)], 'StringNode': [('value', None, str)], 'ContinueNode': [], 'BreakNode': [], 'ArgumentNode': [('positional', accept_node_list), ('kwargs', accept_kwargs)], 'ArrayNode': [('args', accept_node)], 'DictNode': [('args', accept_node)], 'EmptyNode': [], 'OrNode': [('left', accept_node), ('right', accept_node)], 'AndNode': [('left', accept_node), ('right', accept_node)], 'ComparisonNode': [('left', accept_node), ('right', accept_node), ('ctype', None, str)], 'ArithmeticNode': [('left', accept_node), ('right', accept_node), ('op', None, str)], 'NotNode': [('right', accept_node)], 'CodeBlockNode': [('lines', accept_node_list)], 'IndexNode': [('object', accept_node), ('index', accept_node)], 'MethodNode': [('object', accept_node), ('args', accept_node), ('name', None, str)], 'FunctionNode': [('args', accept_node), ('name', None, str)], 'AssignmentNode': [('value', accept_node), ('var_name', None, str)], 'PlusAssignmentNode': [('value', accept_node), ('var_name', None, str)], 'ForeachClauseNode': [('items', accept_node), ('block', accept_node), ('varnames', None, list)], 'IfClauseNode': [('ifs', accept_node_list), ('else', accept_node)], 'IfNode': [('condition', accept_node), ('block', accept_node)], 'UMinusNode': [('right', accept_node)], 'TernaryNode': [('condition', accept_node), ('true', accept_node), ('false', accept_node)], } accept_node(res_nb) for n, c in [('ContinueNode', 2), ('BreakNode', 1), ('NotNode', 3)]: self.assertIn(n, node_counter) self.assertEqual(node_counter[n], c) def test_introspect_dependencies_from_source(self): testdir = os.path.join(self.unit_test_dir, '57 introspection') testfile = os.path.join(testdir, 'meson.build') res_nb = self.introspect_directory(testfile, ['--scan-dependencies'] + self.meson_args) expected = [ { 'name': 'threads', 'required': True, 'version': [], 'has_fallback': False, 'conditional': False }, { 'name': 'zlib', 'required': False, 'version': [], 'has_fallback': False, 'conditional': False }, { 'name': 'bugDep1', 'required': True, 'version': [], 'has_fallback': False, 'conditional': False }, { 'name': 'somethingthatdoesnotexist', 'required': True, 'version': ['>=1.2.3'], 'has_fallback': False, 'conditional': True }, { 'name': 'look_i_have_a_fallback', 'required': True, 'version': ['>=1.0.0', '<=99.9.9'], 'has_fallback': True, 'conditional': True } ] self.maxDiff = None self.assertListEqual(res_nb, expected) def test_unstable_coredata(self): testdir = os.path.join(self.common_test_dir, '1 trivial') self.init(testdir) # just test that the command does not fail (e.g. because it throws an exception) self._run([*self.meson_command, 'unstable-coredata', self.builddir]) @skip_if_no_cmake def test_cmake_prefix_path(self): testdir = os.path.join(self.unit_test_dir, '64 cmake_prefix_path') self.init(testdir, extra_args=['-Dcmake_prefix_path=' + os.path.join(testdir, 'prefix')]) @skip_if_no_cmake def test_cmake_parser(self): testdir = os.path.join(self.unit_test_dir, '65 cmake parser') self.init(testdir, extra_args=['-Dcmake_prefix_path=' + os.path.join(testdir, 'prefix')]) def test_alias_target(self): if self.backend is Backend.vs: # FIXME: This unit test is broken with vs backend, needs investigation raise unittest.SkipTest('Skipping alias_target test with {} backend'.format(self.backend.name)) testdir = os.path.join(self.unit_test_dir, '66 alias target') self.init(testdir) self.build() self.assertPathDoesNotExist(os.path.join(self.builddir, 'prog' + exe_suffix)) self.assertPathDoesNotExist(os.path.join(self.builddir, 'hello.txt')) self.run_target('build-all') self.assertPathExists(os.path.join(self.builddir, 'prog' + exe_suffix)) self.assertPathExists(os.path.join(self.builddir, 'hello.txt')) def test_configure(self): testdir = os.path.join(self.common_test_dir, '2 cpp') self.init(testdir) self._run(self.mconf_command + [self.builddir]) def test_summary(self): testdir = os.path.join(self.unit_test_dir, '73 summary') out = self.init(testdir) expected = textwrap.dedent(r''' Some Subproject 2.0 string : bar integer: 1 boolean: True My Project 1.0 Configuration Some boolean : False Another boolean: True Some string : Hello World A list : string 1 True empty list : enabled_opt : enabled A number : 1 yes : YES no : NO coma list : a, b, c Stuff missing prog : NO existing prog : ''' + sys.executable + ''' missing dep : NO internal dep : YES Plugins long coma list : alpha, alphacolor, apetag, audiofx, audioparsers, auparse, autodetect, avi Subprojects sub : YES sub2 : NO Problem encountered: This subproject failed ''') expected_lines = expected.split('\n')[1:] out_start = out.find(expected_lines[0]) out_lines = out[out_start:].split('\n')[:len(expected_lines)] if sys.version_info < (3, 7, 0): # Dictionary order is not stable in Python <3.7, so sort the lines # while comparing self.assertEqual(sorted(expected_lines), sorted(out_lines)) else: self.assertEqual(expected_lines, out_lines) def test_meson_compile(self): def get_exe_name(basename: str) -> str: if is_windows(): return '{}.exe'.format(basename) else: return basename def get_shared_lib_name(basename: str) -> str: if mesonbuild.environment.detect_msys2_arch(): return 'lib{}.dll'.format(basename) elif is_windows(): return '{}.dll'.format(basename) elif is_cygwin(): return 'cyg{}.dll'.format(basename) elif is_osx(): return 'lib{}.dylib'.format(basename) else: return 'lib{}.so'.format(basename) def get_static_lib_name(basename: str) -> str: return 'lib{}.a'.format(basename) # Base case (no targets or additional arguments) testdir = os.path.join(self.common_test_dir, '1 trivial') self.init(testdir) self._run([*self.meson_command, 'compile', '-C', self.builddir]) self.assertPathExists(os.path.join(self.builddir, get_exe_name('trivialprog'))) # `--clean` self._run([*self.meson_command, 'compile', '-C', self.builddir, '--clean']) self.assertPathDoesNotExist(os.path.join(self.builddir, get_exe_name('trivialprog'))) # Target specified in a project with unique names testdir = os.path.join(self.common_test_dir, '6 linkshared') self.init(testdir, extra_args=['--wipe']) # Multiple targets and target type specified self._run([*self.meson_command, 'compile', '-C', self.builddir, 'mylib', 'mycpplib:shared_library']) # Check that we have a shared lib, but not an executable, i.e. check that target actually worked self.assertPathExists(os.path.join(self.builddir, get_shared_lib_name('mylib'))) self.assertPathDoesNotExist(os.path.join(self.builddir, get_exe_name('prog'))) self.assertPathExists(os.path.join(self.builddir, get_shared_lib_name('mycpplib'))) self.assertPathDoesNotExist(os.path.join(self.builddir, get_exe_name('cppprog'))) # Target specified in a project with non unique names testdir = os.path.join(self.common_test_dir, '186 same target name') self.init(testdir, extra_args=['--wipe']) self._run([*self.meson_command, 'compile', '-C', self.builddir, './foo']) self.assertPathExists(os.path.join(self.builddir, get_static_lib_name('foo'))) self._run([*self.meson_command, 'compile', '-C', self.builddir, 'sub/foo']) self.assertPathExists(os.path.join(self.builddir, 'sub', get_static_lib_name('foo'))) # run_target testdir = os.path.join(self.common_test_dir, '52 run target') self.init(testdir, extra_args=['--wipe']) out = self._run([*self.meson_command, 'compile', '-C', self.builddir, 'py3hi']) self.assertIn('I am Python3.', out) # `--$BACKEND-args` testdir = os.path.join(self.common_test_dir, '1 trivial') if self.backend is Backend.ninja: self.init(testdir, extra_args=['--wipe']) # Dry run - should not create a program self._run([*self.meson_command, 'compile', '-C', self.builddir, '--ninja-args=-n']) self.assertPathDoesNotExist(os.path.join(self.builddir, get_exe_name('trivialprog'))) elif self.backend is Backend.vs: self.init(testdir, extra_args=['--wipe']) self._run([*self.meson_command, 'compile', '-C', self.builddir]) # Explicitly clean the target through msbuild interface self._run([*self.meson_command, 'compile', '-C', self.builddir, '--vs-args=-t:{}:Clean'.format(re.sub(r'[\%\$\@\;\.\(\)\']', '_', get_exe_name('trivialprog')))]) self.assertPathDoesNotExist(os.path.join(self.builddir, get_exe_name('trivialprog'))) def test_spurious_reconfigure_built_dep_file(self): testdir = os.path.join(self.unit_test_dir, '75 dep files') # Regression test: Spurious reconfigure was happening when build # directory is inside source directory. # See https://gitlab.freedesktop.org/gstreamer/gst-build/-/issues/85. srcdir = os.path.join(self.builddir, 'srctree') shutil.copytree(testdir, srcdir) builddir = os.path.join(srcdir, '_build') self.change_builddir(builddir) self.init(srcdir) self.build() # During first configure the file did not exist so no dependency should # have been set. A rebuild should not trigger a reconfigure. self.clean() out = self.build() self.assertNotIn('Project configured', out) self.init(srcdir, extra_args=['--reconfigure']) # During the reconfigure the file did exist, but is inside build # directory, so no dependency should have been set. A rebuild should not # trigger a reconfigure. self.clean() out = self.build() self.assertNotIn('Project configured', out) def _test_junit(self, case: str) -> None: try: import lxml.etree as et except ImportError: raise unittest.SkipTest('lxml required, but not found.') schema = et.XMLSchema(et.parse(str(Path(__file__).parent / 'data' / 'schema.xsd'))) self.init(case) self.run_tests() junit = et.parse(str(Path(self.builddir) / 'meson-logs' / 'testlog.junit.xml')) try: schema.assertValid(junit) except et.DocumentInvalid as e: self.fail(e.error_log) def test_junit_valid_tap(self): self._test_junit(os.path.join(self.common_test_dir, '207 tap tests')) def test_junit_valid_exitcode(self): self._test_junit(os.path.join(self.common_test_dir, '42 test args')) def test_junit_valid_gtest(self): self._test_junit(os.path.join(self.framework_test_dir, '2 gtest')) def test_link_language_linker(self): # TODO: there should be some way to query how we're linking things # without resorting to reading the ninja.build file if self.backend is not Backend.ninja: raise unittest.SkipTest('This test reads the ninja file') testdir = os.path.join(self.common_test_dir, '226 link language') self.init(testdir) build_ninja = os.path.join(self.builddir, 'build.ninja') with open(build_ninja, 'r', encoding='utf-8') as f: contents = f.read() self.assertRegex(contents, r'build main(\.exe)?.*: c_LINKER') self.assertRegex(contents, r'build (lib|cyg)?mylib.*: c_LINKER') def test_commands_documented(self): # The docs directory is not in release tarballs. if not os.path.isdir('docs'): raise unittest.SkipTest('Doc directory does not exist.') doc_path = 'docs/markdown/Commands.md' md = None with open(doc_path, encoding='utf-8') as f: md = f.read() self.assertIsNotNone(md) ## Get command sections section_pattern = re.compile(r'^### (.+)$', re.MULTILINE) md_command_section_matches = [i for i in section_pattern.finditer(md)] md_command_sections = dict() for i, s in enumerate(md_command_section_matches): section_end = len(md) if i == len(md_command_section_matches) - 1 else md_command_section_matches[i + 1].start() md_command_sections[s.group(1)] = (s.start(), section_end) ## Validate commands md_commands = set(k for k,v in md_command_sections.items()) help_output = self._run(self.meson_command + ['--help']) help_commands = set(c.strip() for c in re.findall(r'usage:(?:.+)?{((?:[a-z]+,*)+?)}', help_output, re.MULTILINE|re.DOTALL)[0].split(',')) self.assertEqual(md_commands | {'help'}, help_commands, 'Doc file: `{}`'.format(doc_path)) ## Validate that each section has proper placeholders def get_data_pattern(command): return re.compile( r'{{ ' + command + r'_usage.inc }}[\r\n]' r'.*?' r'{{ ' + command + r'_arguments.inc }}[\r\n]', flags = re.MULTILINE|re.DOTALL) for command in md_commands: m = get_data_pattern(command).search(md, pos=md_command_sections[command][0], endpos=md_command_sections[command][1]) self.assertIsNotNone(m, 'Command `{}` is missing placeholders for dynamic data. Doc file: `{}`'.format(command, doc_path)) def _check_coverage_files(self, types=('text', 'xml', 'html')): covdir = Path(self.builddir) / 'meson-logs' files = [] if 'text' in types: files.append('coverage.txt') if 'xml' in types: files.append('coverage.xml') if 'html' in types: files.append('coveragereport/index.html') for f in files: self.assertTrue((covdir / f).is_file(), msg='{} is not a file'.format(f)) def test_coverage(self): if mesonbuild.environment.detect_msys2_arch(): raise unittest.SkipTest('Skipped due to problems with coverage on MSYS2') gcovr_exe, gcovr_new_rootdir = mesonbuild.environment.detect_gcovr() if not gcovr_exe: raise unittest.SkipTest('gcovr not found, or too old') testdir = os.path.join(self.common_test_dir, '1 trivial') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) if cc.get_id() == 'clang': if not mesonbuild.environment.detect_llvm_cov(): raise unittest.SkipTest('llvm-cov not found') if cc.get_id() == 'msvc': raise unittest.SkipTest('Test only applies to non-MSVC compilers') self.init(testdir, extra_args=['-Db_coverage=true']) self.build() self.run_tests() self.run_target('coverage') self._check_coverage_files() def test_coverage_complex(self): if mesonbuild.environment.detect_msys2_arch(): raise unittest.SkipTest('Skipped due to problems with coverage on MSYS2') gcovr_exe, gcovr_new_rootdir = mesonbuild.environment.detect_gcovr() if not gcovr_exe: raise unittest.SkipTest('gcovr not found, or too old') testdir = os.path.join(self.common_test_dir, '106 generatorcustom') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) if cc.get_id() == 'clang': if not mesonbuild.environment.detect_llvm_cov(): raise unittest.SkipTest('llvm-cov not found') if cc.get_id() == 'msvc': raise unittest.SkipTest('Test only applies to non-MSVC compilers') self.init(testdir, extra_args=['-Db_coverage=true']) self.build() self.run_tests() self.run_target('coverage') self._check_coverage_files() def test_coverage_html(self): if mesonbuild.environment.detect_msys2_arch(): raise unittest.SkipTest('Skipped due to problems with coverage on MSYS2') gcovr_exe, gcovr_new_rootdir = mesonbuild.environment.detect_gcovr() if not gcovr_exe: raise unittest.SkipTest('gcovr not found, or too old') testdir = os.path.join(self.common_test_dir, '1 trivial') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) if cc.get_id() == 'clang': if not mesonbuild.environment.detect_llvm_cov(): raise unittest.SkipTest('llvm-cov not found') if cc.get_id() == 'msvc': raise unittest.SkipTest('Test only applies to non-MSVC compilers') self.init(testdir, extra_args=['-Db_coverage=true']) self.build() self.run_tests() self.run_target('coverage-html') self._check_coverage_files(['html']) def test_coverage_text(self): if mesonbuild.environment.detect_msys2_arch(): raise unittest.SkipTest('Skipped due to problems with coverage on MSYS2') gcovr_exe, gcovr_new_rootdir = mesonbuild.environment.detect_gcovr() if not gcovr_exe: raise unittest.SkipTest('gcovr not found, or too old') testdir = os.path.join(self.common_test_dir, '1 trivial') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) if cc.get_id() == 'clang': if not mesonbuild.environment.detect_llvm_cov(): raise unittest.SkipTest('llvm-cov not found') if cc.get_id() == 'msvc': raise unittest.SkipTest('Test only applies to non-MSVC compilers') self.init(testdir, extra_args=['-Db_coverage=true']) self.build() self.run_tests() self.run_target('coverage-text') self._check_coverage_files(['text']) def test_coverage_xml(self): if mesonbuild.environment.detect_msys2_arch(): raise unittest.SkipTest('Skipped due to problems with coverage on MSYS2') gcovr_exe, gcovr_new_rootdir = mesonbuild.environment.detect_gcovr() if not gcovr_exe: raise unittest.SkipTest('gcovr not found, or too old') testdir = os.path.join(self.common_test_dir, '1 trivial') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) if cc.get_id() == 'clang': if not mesonbuild.environment.detect_llvm_cov(): raise unittest.SkipTest('llvm-cov not found') if cc.get_id() == 'msvc': raise unittest.SkipTest('Test only applies to non-MSVC compilers') self.init(testdir, extra_args=['-Db_coverage=true']) self.build() self.run_tests() self.run_target('coverage-xml') self._check_coverage_files(['xml']) def test_cross_file_constants(self): with temp_filename() as crossfile1, temp_filename() as crossfile2: with open(crossfile1, 'w') as f: f.write(textwrap.dedent( ''' [constants] compiler = 'gcc' ''')) with open(crossfile2, 'w') as f: f.write(textwrap.dedent( ''' [constants] toolchain = '/toolchain/' common_flags = ['--sysroot=' + toolchain / 'sysroot'] [properties] c_args = common_flags + ['-DSOMETHING'] cpp_args = c_args + ['-DSOMETHING_ELSE'] [binaries] c = toolchain / compiler ''')) values = mesonbuild.coredata.parse_machine_files([crossfile1, crossfile2]) self.assertEqual(values['binaries']['c'], '/toolchain/gcc') self.assertEqual(values['properties']['c_args'], ['--sysroot=/toolchain/sysroot', '-DSOMETHING']) self.assertEqual(values['properties']['cpp_args'], ['--sysroot=/toolchain/sysroot', '-DSOMETHING', '-DSOMETHING_ELSE']) @unittest.skipIf(is_windows(), 'Directory cleanup fails for some reason') def test_wrap_git(self): with tempfile.TemporaryDirectory() as tmpdir: srcdir = os.path.join(tmpdir, 'src') shutil.copytree(os.path.join(self.unit_test_dir, '82 wrap-git'), srcdir) upstream = os.path.join(srcdir, 'subprojects', 'wrap_git_upstream') upstream_uri = Path(upstream).as_uri() _git_init(upstream) with open(os.path.join(srcdir, 'subprojects', 'wrap_git.wrap'), 'w') as f: f.write(textwrap.dedent(''' [wrap-git] url = {} patch_directory = wrap_git_builddef revision = master '''.format(upstream_uri))) self.init(srcdir) self.build() self.run_tests() def test_multi_output_custom_target_no_warning(self): testdir = os.path.join(self.common_test_dir, '229 custom_target source') out = self.init(testdir) self.assertNotRegex(out, 'WARNING:.*Using the first one.') self.build() self.run_tests() @unittest.skipUnless(is_linux() and (re.search('^i.86$|^x86$|^x64$|^x86_64$|^amd64$', platform.processor()) is not None), 'Requires ASM compiler for x86 or x86_64 platform currently only available on Linux CI runners') def test_nostdlib(self): testdir = os.path.join(self.unit_test_dir, '79 nostdlib') machinefile = os.path.join(self.builddir, 'machine.txt') with open(machinefile, 'w') as f: f.write(textwrap.dedent(''' [properties] c_stdlib = 'mylibc' ''')) # Test native C stdlib self.meson_native_file = machinefile self.init(testdir) self.build() # Test cross C stdlib self.new_builddir() self.meson_native_file = None self.meson_cross_file = machinefile self.init(testdir) self.build() def test_meson_version_compare(self): testdir = os.path.join(self.unit_test_dir, '83 meson version compare') out = self.init(testdir) self.assertNotRegex(out, r'WARNING') def test_wrap_redirect(self): redirect_wrap = os.path.join(self.builddir, 'redirect.wrap') real_wrap = os.path.join(self.builddir, 'foo/subprojects/real.wrap') os.makedirs(os.path.dirname(real_wrap)) # Invalid redirect, filename must have .wrap extension with open(redirect_wrap, 'w') as f: f.write(textwrap.dedent(''' [wrap-redirect] filename = foo/subprojects/real.wrapper ''')) with self.assertRaisesRegex(WrapException, 'wrap-redirect filename must be a .wrap file'): PackageDefinition(redirect_wrap) # Invalid redirect, filename cannot be in parent directory with open(redirect_wrap, 'w') as f: f.write(textwrap.dedent(''' [wrap-redirect] filename = ../real.wrap ''')) with self.assertRaisesRegex(WrapException, 'wrap-redirect filename cannot contain ".."'): PackageDefinition(redirect_wrap) # Invalid redirect, filename must be in foo/subprojects/real.wrap with open(redirect_wrap, 'w') as f: f.write(textwrap.dedent(''' [wrap-redirect] filename = foo/real.wrap ''')) with self.assertRaisesRegex(WrapException, 'wrap-redirect filename must be in the form foo/subprojects/bar.wrap'): wrap = PackageDefinition(redirect_wrap) # Correct redirect with open(redirect_wrap, 'w') as f: f.write(textwrap.dedent(''' [wrap-redirect] filename = foo/subprojects/real.wrap ''')) with open(real_wrap, 'w') as f: f.write(textwrap.dedent(''' [wrap-git] url = http://invalid ''')) wrap = PackageDefinition(redirect_wrap) self.assertEqual(wrap.get('url'), 'http://invalid') @skip_if_no_cmake def test_nested_cmake_rebuild(self) -> None: # This checks a bug where if a non-meson project is used as a third # level (or deeper) subproject it doesn't cause a rebuild if the build # files for that project are changed testdir = os.path.join(self.unit_test_dir, '86 nested subproject regenerate depends') cmakefile = Path(testdir) / 'subprojects' / 'sub2' / 'CMakeLists.txt' self.init(testdir) self.build() with cmakefile.open('a') as f: os.utime(str(cmakefile)) self.assertReconfiguredBuildIsNoop() def test_version_file(self): srcdir = os.path.join(self.common_test_dir, '2 cpp') self.init(srcdir) projinfo = self.introspect('--projectinfo') self.assertEqual(projinfo['version'], '1.0.0') def test_cflags_cppflags(self): envs = {'CPPFLAGS': '-DCPPFLAG', 'CFLAGS': '-DCFLAG', 'CXXFLAGS': '-DCXXFLAG'} srcdir = os.path.join(self.unit_test_dir, '90 multiple envvars') self.init(srcdir, override_envvars=envs) self.build() def test_build_b_options(self) -> None: # Currently (0.57) these do nothing, but they've always been allowed srcdir = os.path.join(self.common_test_dir, '2 cpp') self.init(srcdir, extra_args=['-Dbuild.b_lto=true']) def test_install_skip_subprojects(self): testdir = os.path.join(self.unit_test_dir, '91 install skip subprojects') self.init(testdir) self.build() main_expected = [ '', 'share', 'include', 'foo', 'bin', 'share/foo', 'share/foo/foo.dat', 'include/foo.h', 'foo/foofile', 'bin/foo' + exe_suffix, ] bar_expected = [ 'bar', 'share/foo/bar.dat', 'include/bar.h', 'bin/bar' + exe_suffix, 'bar/barfile' ] env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) if cc.get_argument_syntax() == 'msvc': main_expected.append('bin/foo.pdb') bar_expected.append('bin/bar.pdb') prefix = destdir_join(self.installdir, self.prefix) main_expected = [Path(prefix, p) for p in main_expected] bar_expected = [Path(prefix, p) for p in bar_expected] all_expected = main_expected + bar_expected def check_installed_files(extra_args, expected): args = ['install', '--destdir', self.installdir] + extra_args self._run(self.meson_command + args, workdir=self.builddir) all_files = [p for p in Path(self.installdir).rglob('*')] self.assertEqual(sorted(expected), sorted(all_files)) windows_proof_rmtree(self.installdir) check_installed_files([], all_expected) check_installed_files(['--skip-subprojects'], main_expected) check_installed_files(['--skip-subprojects', 'bar'], main_expected) check_installed_files(['--skip-subprojects', 'another'], all_expected) class FailureTests(BasePlatformTests): dnf = "[Dd]ependency.*not found(:.*)?" nopkg = '[Pp]kg-config.*not found' def setUp(self): super().setUp() self.srcdir = os.path.realpath(tempfile.mkdtemp()) self.mbuild = os.path.join(self.srcdir, 'meson.build') self.moptions = os.path.join(self.srcdir, 'meson_options.txt') def tearDown(self): super().tearDown() windows_proof_rmtree(self.srcdir) def assertMesonRaises(self, contents, match, *, extra_args=None, langs=None, meson_version=None, options=None, override_envvars=None): if langs is None: langs = [] with open(self.mbuild, 'w') as f: f.write("project('failure test', 'c', 'cpp'") if meson_version: f.write(", meson_version: '{}'".format(meson_version)) f.write(")\n") for lang in langs: f.write("add_languages('{}', required : false)\n".format(lang)) f.write(contents) if options is not None: with open(self.moptions, 'w') as f: f.write(options) o = {'MESON_FORCE_BACKTRACE': '1'} if override_envvars is None: override_envvars = o else: override_envvars.update(o) # Force tracebacks so we can detect them properly with self.assertRaisesRegex(MesonException, match, msg=contents): # Must run in-process or we'll get a generic CalledProcessError self.init(self.srcdir, extra_args=extra_args, inprocess=True, override_envvars = override_envvars) def obtainMesonOutput(self, contents, match, extra_args, langs, meson_version=None): if langs is None: langs = [] with open(self.mbuild, 'w') as f: f.write("project('output test', 'c', 'cpp'") if meson_version: f.write(", meson_version: '{}'".format(meson_version)) f.write(")\n") for lang in langs: f.write("add_languages('{}', required : false)\n".format(lang)) f.write(contents) # Run in-process for speed and consistency with assertMesonRaises return self.init(self.srcdir, extra_args=extra_args, inprocess=True) def assertMesonOutputs(self, contents, match, extra_args=None, langs=None, meson_version=None): out = self.obtainMesonOutput(contents, match, extra_args, langs, meson_version) self.assertRegex(out, match) def assertMesonDoesNotOutput(self, contents, match, extra_args=None, langs=None, meson_version=None): out = self.obtainMesonOutput(contents, match, extra_args, langs, meson_version) self.assertNotRegex(out, match) @skipIfNoPkgconfig def test_dependency(self): if subprocess.call(['pkg-config', '--exists', 'zlib']) != 0: raise unittest.SkipTest('zlib not found with pkg-config') a = (("dependency('zlib', method : 'fail')", "'fail' is invalid"), ("dependency('zlib', static : '1')", "[Ss]tatic.*boolean"), ("dependency('zlib', version : 1)", "Item must be a list or one of <class 'str'>"), ("dependency('zlib', required : 1)", "[Rr]equired.*boolean"), ("dependency('zlib', method : 1)", "[Mm]ethod.*string"), ("dependency('zlibfail')", self.dnf),) for contents, match in a: self.assertMesonRaises(contents, match) def test_apple_frameworks_dependency(self): if not is_osx(): raise unittest.SkipTest('only run on macOS') self.assertMesonRaises("dependency('appleframeworks')", "requires at least one module") def test_extraframework_dependency_method(self): code = "dependency('python', method : 'extraframework')" if not is_osx(): self.assertMesonRaises(code, self.dnf) else: # Python2 framework is always available on macOS self.assertMesonOutputs(code, '[Dd]ependency.*python.*found.*YES') def test_sdl2_notfound_dependency(self): # Want to test failure, so skip if available if shutil.which('sdl2-config'): raise unittest.SkipTest('sdl2-config found') self.assertMesonRaises("dependency('sdl2', method : 'sdlconfig')", self.dnf) if shutil.which('pkg-config'): self.assertMesonRaises("dependency('sdl2', method : 'pkg-config')", self.dnf) with no_pkgconfig(): # Look for pkg-config, cache it, then # Use cached pkg-config without erroring out, then # Use cached pkg-config to error out code = "dependency('foobarrr', method : 'pkg-config', required : false)\n" \ "dependency('foobarrr2', method : 'pkg-config', required : false)\n" \ "dependency('sdl2', method : 'pkg-config')" self.assertMesonRaises(code, self.nopkg) def test_gnustep_notfound_dependency(self): # Want to test failure, so skip if available if shutil.which('gnustep-config'): raise unittest.SkipTest('gnustep-config found') self.assertMesonRaises("dependency('gnustep')", "(requires a Objc compiler|{})".format(self.dnf), langs = ['objc']) def test_wx_notfound_dependency(self): # Want to test failure, so skip if available if shutil.which('wx-config-3.0') or shutil.which('wx-config') or shutil.which('wx-config-gtk3'): raise unittest.SkipTest('wx-config, wx-config-3.0 or wx-config-gtk3 found') self.assertMesonRaises("dependency('wxwidgets')", self.dnf) self.assertMesonOutputs("dependency('wxwidgets', required : false)", "Run-time dependency .*WxWidgets.* found: .*NO.*") def test_wx_dependency(self): if not shutil.which('wx-config-3.0') and not shutil.which('wx-config') and not shutil.which('wx-config-gtk3'): raise unittest.SkipTest('Neither wx-config, wx-config-3.0 nor wx-config-gtk3 found') self.assertMesonRaises("dependency('wxwidgets', modules : 1)", "module argument is not a string") def test_llvm_dependency(self): self.assertMesonRaises("dependency('llvm', modules : 'fail')", "(required.*fail|{})".format(self.dnf)) def test_boost_notfound_dependency(self): # Can be run even if Boost is found or not self.assertMesonRaises("dependency('boost', modules : 1)", "module.*not a string") self.assertMesonRaises("dependency('boost', modules : 'fail')", "(fail.*not found|{})".format(self.dnf)) def test_boost_BOOST_ROOT_dependency(self): # Test BOOST_ROOT; can be run even if Boost is found or not self.assertMesonRaises("dependency('boost')", "(boost_root.*absolute|{})".format(self.dnf), override_envvars = {'BOOST_ROOT': 'relative/path'}) def test_dependency_invalid_method(self): code = '''zlib_dep = dependency('zlib', required : false) zlib_dep.get_configtool_variable('foo') ''' self.assertMesonRaises(code, ".* is not a config-tool dependency") code = '''zlib_dep = dependency('zlib', required : false) dep = declare_dependency(dependencies : zlib_dep) dep.get_pkgconfig_variable('foo') ''' self.assertMesonRaises(code, "Method.*pkgconfig.*is invalid.*internal") code = '''zlib_dep = dependency('zlib', required : false) dep = declare_dependency(dependencies : zlib_dep) dep.get_configtool_variable('foo') ''' self.assertMesonRaises(code, "Method.*configtool.*is invalid.*internal") def test_objc_cpp_detection(self): env = get_fake_env() try: env.detect_objc_compiler(MachineChoice.HOST) env.detect_objcpp_compiler(MachineChoice.HOST) except EnvironmentException: code = "add_languages('objc')\nadd_languages('objcpp')" self.assertMesonRaises(code, "Unknown compiler") return raise unittest.SkipTest("objc and objcpp found, can't test detection failure") def test_subproject_variables(self): tdir = os.path.join(self.unit_test_dir, '20 subproj dep variables') out = self.init(tdir, inprocess=True) self.assertRegex(out, r"Neither a subproject directory nor a .*nosubproj.wrap.* file was found") self.assertRegex(out, r'Function does not take positional arguments.') self.assertRegex(out, r'Dependency .*somenotfounddep.* from subproject .*subprojects/somesubproj.* found: .*NO.*') self.assertRegex(out, r'Dependency .*zlibproxy.* from subproject .*subprojects.*somesubproj.* found: .*YES.*') self.assertRegex(out, r'Missing key .*source_filename.* in subsubproject.wrap') def test_exception_exit_status(self): tdir = os.path.join(self.unit_test_dir, '21 exit status') with self.assertRaises(subprocess.CalledProcessError) as cm: self.init(tdir, inprocess=False, override_envvars = {'MESON_UNIT_TEST': '1'}) self.assertEqual(cm.exception.returncode, 2) self.wipe() def test_dict_requires_key_value_pairs(self): self.assertMesonRaises("dict = {3, 'foo': 'bar'}", 'Only key:value pairs are valid in dict construction.') self.assertMesonRaises("{'foo': 'bar', 3}", 'Only key:value pairs are valid in dict construction.') def test_dict_forbids_duplicate_keys(self): self.assertMesonRaises("dict = {'a': 41, 'a': 42}", 'Duplicate dictionary key: a.*') def test_dict_forbids_integer_key(self): self.assertMesonRaises("dict = {3: 'foo'}", 'Key must be a string.*') def test_using_too_recent_feature(self): # Here we use a dict, which was introduced in 0.47.0 self.assertMesonOutputs("dict = {}", ".*WARNING.*Project targeting.*but.*", meson_version='>= 0.46.0') def test_using_recent_feature(self): # Same as above, except the meson version is now appropriate self.assertMesonDoesNotOutput("dict = {}", ".*WARNING.*Project targeting.*but.*", meson_version='>= 0.47') def test_using_too_recent_feature_dependency(self): self.assertMesonOutputs("dependency('pcap', required: false)", ".*WARNING.*Project targeting.*but.*", meson_version='>= 0.41.0') def test_vcs_tag_featurenew_build_always_stale(self): vcs_tag = '''version_data = configuration_data() version_data.set('PROJVER', '@VCS_TAG@') vf = configure_file(output : 'version.h.in', configuration: version_data) f = vcs_tag(input : vf, output : 'version.h') ''' msg = '.*WARNING:.*feature.*build_always_stale.*custom_target.*' self.assertMesonDoesNotOutput(vcs_tag, msg, meson_version='>=0.43') def test_missing_subproject_not_required_and_required(self): self.assertMesonRaises("sub1 = subproject('not-found-subproject', required: false)\n" + "sub2 = subproject('not-found-subproject', required: true)", """.*Subproject "subprojects/not-found-subproject" required but not found.*""") def test_get_variable_on_not_found_project(self): self.assertMesonRaises("sub1 = subproject('not-found-subproject', required: false)\n" + "sub1.get_variable('naaa')", """Subproject "subprojects/not-found-subproject" disabled can't get_variable on it.""") def test_version_checked_before_parsing_options(self): options = "option('some-option', type: 'foo', value: '')" match = 'Meson version is.*but project requires >=2000' self.assertMesonRaises("", match, meson_version='>=2000', options=options) def test_assert_default_message(self): self.assertMesonRaises("k1 = 'a'\n" + "assert({\n" + " k1: 1,\n" + "}['a'] == 2)\n", r"Assert failed: {k1 : 1}\['a'\] == 2") def test_wrap_nofallback(self): self.assertMesonRaises("dependency('notfound', fallback : ['foo', 'foo_dep'])", r"Dependency \'notfound\' not found and fallback is disabled", extra_args=['--wrap-mode=nofallback']) def test_message(self): self.assertMesonOutputs("message('Array:', ['a', 'b'])", r"Message:.* Array: \['a', 'b'\]") def test_warning(self): self.assertMesonOutputs("warning('Array:', ['a', 'b'])", r"WARNING:.* Array: \['a', 'b'\]") def test_override_dependency_twice(self): self.assertMesonRaises("meson.override_dependency('foo', declare_dependency())\n" + "meson.override_dependency('foo', declare_dependency())", """Tried to override dependency 'foo' which has already been resolved or overridden""") @unittest.skipIf(is_windows(), 'zlib is not available on Windows') def test_override_resolved_dependency(self): self.assertMesonRaises("dependency('zlib')\n" + "meson.override_dependency('zlib', declare_dependency())", """Tried to override dependency 'zlib' which has already been resolved or overridden""") def test_error_func(self): self.assertMesonRaises("error('a', 'b', ['c', ['d', {'e': 'f'}]], 'g')", "Problem encountered: a b \['c', \['d', {'e' : 'f'}\]\] g") @unittest.skipUnless(is_windows() or is_cygwin(), "requires Windows (or Windows via Cygwin)") class WindowsTests(BasePlatformTests): def setUp(self): super().setUp() self.platform_test_dir = os.path.join(self.src_root, 'test cases/windows') @unittest.skipIf(is_cygwin(), 'Test only applicable to Windows') @mock.patch.dict(os.environ) def test_find_program(self): testdir = os.path.join(self.platform_test_dir, '8 find program') # Find `cmd` and `cmd.exe` prog1 = ExternalProgram('cmd') self.assertTrue(prog1.found(), msg='cmd not found') prog2 = ExternalProgram('cmd.exe') self.assertTrue(prog2.found(), msg='cmd.exe not found') self.assertPathEqual(prog1.get_path(), prog2.get_path()) # Find cmd.exe with args without searching prog = ExternalProgram('cmd', command=['cmd', '/C']) self.assertTrue(prog.found(), msg='cmd not found with args') self.assertPathEqual(prog.get_command()[0], 'cmd') # Find cmd with an absolute path that's missing the extension cmd_path = prog2.get_path()[:-4] prog = ExternalProgram(cmd_path) self.assertTrue(prog.found(), msg='{!r} not found'.format(cmd_path)) # Finding a script with no extension inside a directory works prog = ExternalProgram(os.path.join(testdir, 'test-script')) self.assertTrue(prog.found(), msg='test-script not found') # Finding a script with an extension inside a directory works prog = ExternalProgram(os.path.join(testdir, 'test-script-ext.py')) self.assertTrue(prog.found(), msg='test-script-ext.py not found') # Finding a script in PATH os.environ['PATH'] += os.pathsep + testdir # If `.PY` is in PATHEXT, scripts can be found as programs if '.PY' in [ext.upper() for ext in os.environ['PATHEXT'].split(';')]: # Finding a script in PATH w/o extension works and adds the interpreter prog = ExternalProgram('test-script-ext') self.assertTrue(prog.found(), msg='test-script-ext not found in PATH') self.assertPathEqual(prog.get_command()[0], python_command[0]) self.assertPathBasenameEqual(prog.get_path(), 'test-script-ext.py') # Finding a script in PATH with extension works and adds the interpreter prog = ExternalProgram('test-script-ext.py') self.assertTrue(prog.found(), msg='test-script-ext.py not found in PATH') self.assertPathEqual(prog.get_command()[0], python_command[0]) self.assertPathBasenameEqual(prog.get_path(), 'test-script-ext.py') # Using a script with an extension directly via command= works and adds the interpreter prog = ExternalProgram('test-script-ext.py', command=[os.path.join(testdir, 'test-script-ext.py'), '--help']) self.assertTrue(prog.found(), msg='test-script-ext.py with full path not picked up via command=') self.assertPathEqual(prog.get_command()[0], python_command[0]) self.assertPathEqual(prog.get_command()[2], '--help') self.assertPathBasenameEqual(prog.get_path(), 'test-script-ext.py') # Using a script without an extension directly via command= works and adds the interpreter prog = ExternalProgram('test-script', command=[os.path.join(testdir, 'test-script'), '--help']) self.assertTrue(prog.found(), msg='test-script with full path not picked up via command=') self.assertPathEqual(prog.get_command()[0], python_command[0]) self.assertPathEqual(prog.get_command()[2], '--help') self.assertPathBasenameEqual(prog.get_path(), 'test-script') # Ensure that WindowsApps gets removed from PATH path = os.environ['PATH'] if 'WindowsApps' not in path: username = os.environ['USERNAME'] appstore_dir = r'C:\Users\{}\AppData\Local\Microsoft\WindowsApps'.format(username) path = os.pathsep + appstore_dir path = ExternalProgram._windows_sanitize_path(path) self.assertNotIn('WindowsApps', path) def test_ignore_libs(self): testdir = os.path.join(self.platform_test_dir, '1 basic') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) if cc.get_argument_syntax() != 'msvc': raise unittest.SkipTest('Not using MSVC') # To force people to update this test, and also test self.assertEqual(set(cc.ignore_libs), {'c', 'm', 'pthread', 'dl', 'rt', 'execinfo'}) for l in cc.ignore_libs: self.assertEqual(cc.find_library(l, env, []), []) def test_rc_depends_files(self): testdir = os.path.join(self.platform_test_dir, '5 resources') # resource compiler depfile generation is not yet implemented for msvc env = get_fake_env(testdir, self.builddir, self.prefix) depfile_works = env.detect_c_compiler(MachineChoice.HOST).get_id() not in {'msvc', 'clang-cl', 'intel-cl'} self.init(testdir) self.build() # Immediately rebuilding should not do anything self.assertBuildIsNoop() # Test compile_resources(depend_file:) # Changing mtime of sample.ico should rebuild prog self.utime(os.path.join(testdir, 'res', 'sample.ico')) self.assertRebuiltTarget('prog') # Test depfile generation by compile_resources # Changing mtime of resource.h should rebuild myres.rc and then prog if depfile_works: self.utime(os.path.join(testdir, 'inc', 'resource', 'resource.h')) self.assertRebuiltTarget('prog') self.wipe() if depfile_works: testdir = os.path.join(self.platform_test_dir, '12 resources with custom targets') self.init(testdir) self.build() # Immediately rebuilding should not do anything self.assertBuildIsNoop() # Changing mtime of resource.h should rebuild myres_1.rc and then prog_1 self.utime(os.path.join(testdir, 'res', 'resource.h')) self.assertRebuiltTarget('prog_1') def test_msvc_cpp17(self): testdir = os.path.join(self.unit_test_dir, '45 vscpp17') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) if cc.get_argument_syntax() != 'msvc': raise unittest.SkipTest('Test only applies to MSVC-like compilers') try: self.init(testdir) except subprocess.CalledProcessError: # According to Python docs, output is only stored when # using check_output. We don't use it, so we can't check # that the output is correct (i.e. that it failed due # to the right reason). return self.build() def test_install_pdb_introspection(self): testdir = os.path.join(self.platform_test_dir, '1 basic') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) if cc.get_argument_syntax() != 'msvc': raise unittest.SkipTest('Test only applies to MSVC-like compilers') self.init(testdir) installed = self.introspect('--installed') files = [os.path.basename(path) for path in installed.values()] self.assertTrue('prog.pdb' in files) def _check_ld(self, name: str, lang: str, expected: str) -> None: if not shutil.which(name): raise unittest.SkipTest('Could not find {}.'.format(name)) envvars = [mesonbuild.envconfig.ENV_VAR_PROG_MAP['{}_ld'.format(lang)]] # Also test a deprecated variable if there is one. if f'{lang}_ld' in mesonbuild.envconfig.DEPRECATED_ENV_PROG_MAP: envvars.append( mesonbuild.envconfig.DEPRECATED_ENV_PROG_MAP[f'{lang}_ld']) for envvar in envvars: with mock.patch.dict(os.environ, {envvar: name}): env = get_fake_env() try: comp = getattr(env, 'detect_{}_compiler'.format(lang))(MachineChoice.HOST) except EnvironmentException: raise unittest.SkipTest('Could not find a compiler for {}'.format(lang)) self.assertEqual(comp.linker.id, expected) def test_link_environment_variable_lld_link(self): env = get_fake_env() comp = getattr(env, 'detect_c_compiler')(MachineChoice.HOST) if isinstance(comp, mesonbuild.compilers.GnuLikeCompiler): raise unittest.SkipTest('GCC cannot be used with link compatible linkers.') self._check_ld('lld-link', 'c', 'lld-link') def test_link_environment_variable_link(self): env = get_fake_env() comp = getattr(env, 'detect_c_compiler')(MachineChoice.HOST) if isinstance(comp, mesonbuild.compilers.GnuLikeCompiler): raise unittest.SkipTest('GCC cannot be used with link compatible linkers.') self._check_ld('link', 'c', 'link') def test_link_environment_variable_optlink(self): env = get_fake_env() comp = getattr(env, 'detect_c_compiler')(MachineChoice.HOST) if isinstance(comp, mesonbuild.compilers.GnuLikeCompiler): raise unittest.SkipTest('GCC cannot be used with link compatible linkers.') self._check_ld('optlink', 'c', 'optlink') @skip_if_not_language('rust') def test_link_environment_variable_rust(self): self._check_ld('link', 'rust', 'link') @skip_if_not_language('d') def test_link_environment_variable_d(self): env = get_fake_env() comp = getattr(env, 'detect_d_compiler')(MachineChoice.HOST) if comp.id == 'dmd': raise unittest.SkipTest('meson cannot reliably make DMD use a different linker.') self._check_ld('lld-link', 'd', 'lld-link') def test_pefile_checksum(self): try: import pefile except ImportError: if is_ci(): raise raise unittest.SkipTest('pefile module not found') testdir = os.path.join(self.common_test_dir, '6 linkshared') self.init(testdir, extra_args=['--buildtype=release']) self.build() # Test that binaries have a non-zero checksum env = get_fake_env() cc = env.detect_c_compiler(MachineChoice.HOST) cc_id = cc.get_id() ld_id = cc.get_linker_id() dll = glob(os.path.join(self.builddir, '*mycpplib.dll'))[0] exe = os.path.join(self.builddir, 'cppprog.exe') for f in (dll, exe): pe = pefile.PE(f) msg = 'PE file: {!r}, compiler: {!r}, linker: {!r}'.format(f, cc_id, ld_id) if cc_id == 'clang-cl': # Latest clang-cl tested (7.0) does not write checksums out self.assertFalse(pe.verify_checksum(), msg=msg) else: # Verify that a valid checksum was written by all other compilers self.assertTrue(pe.verify_checksum(), msg=msg) def test_qt5dependency_vscrt(self): # Verify that the `b_vscrt` option is available env = get_fake_env() cc = env.detect_c_compiler(MachineChoice.HOST) if OptionKey('b_vscrt') not in cc.base_options: raise unittest.SkipTest('Compiler does not support setting the VS CRT') # Verify that qmake is for Qt5 if not shutil.which('qmake-qt5'): if not shutil.which('qmake') and not is_ci(): raise unittest.SkipTest('QMake not found') output = subprocess.getoutput('qmake --version') if 'Qt version 5' not in output and not is_ci(): raise unittest.SkipTest('Qmake found, but it is not for Qt 5.') # Setup with /MDd testdir = os.path.join(self.framework_test_dir, '4 qt') self.init(testdir, extra_args=['-Db_vscrt=mdd']) # Verify that we're linking to the debug versions of Qt DLLs build_ninja = os.path.join(self.builddir, 'build.ninja') with open(build_ninja, 'r', encoding='utf-8') as f: contents = f.read() m = re.search('build qt5core.exe: cpp_LINKER.*Qt5Cored.lib', contents) self.assertIsNotNone(m, msg=contents) def test_compiler_checks_vscrt(self): # Verify that the `b_vscrt` option is available env = get_fake_env() cc = env.detect_c_compiler(MachineChoice.HOST) if OptionKey('b_vscrt') not in cc.base_options: raise unittest.SkipTest('Compiler does not support setting the VS CRT') def sanitycheck_vscrt(vscrt): checks = self.get_meson_log_sanitychecks() self.assertTrue(len(checks) > 0) for check in checks: self.assertIn(vscrt, check) testdir = os.path.join(self.common_test_dir, '1 trivial') self.init(testdir) sanitycheck_vscrt('/MDd') self.new_builddir() self.init(testdir, extra_args=['-Dbuildtype=debugoptimized']) sanitycheck_vscrt('/MD') self.new_builddir() self.init(testdir, extra_args=['-Dbuildtype=release']) sanitycheck_vscrt('/MD') self.new_builddir() self.init(testdir, extra_args=['-Db_vscrt=md']) sanitycheck_vscrt('/MD') self.new_builddir() self.init(testdir, extra_args=['-Db_vscrt=mdd']) sanitycheck_vscrt('/MDd') self.new_builddir() self.init(testdir, extra_args=['-Db_vscrt=mt']) sanitycheck_vscrt('/MT') self.new_builddir() self.init(testdir, extra_args=['-Db_vscrt=mtd']) sanitycheck_vscrt('/MTd') def test_modules(self): if self.backend is not Backend.ninja: raise unittest.SkipTest('C++ modules only work with the Ninja backend (not {}).'.format(self.backend.name)) if 'VSCMD_VER' not in os.environ: raise unittest.SkipTest('C++ modules is only supported with Visual Studio.') if version_compare(os.environ['VSCMD_VER'], '<16.9.0'): raise unittest.SkipTest('C++ modules are only supported with VS 2019 Preview or newer.') self.init(os.path.join(self.unit_test_dir, '87 cpp modules')) self.build() @unittest.skipUnless(is_osx(), "requires Darwin") class DarwinTests(BasePlatformTests): def setUp(self): super().setUp() self.platform_test_dir = os.path.join(self.src_root, 'test cases/osx') def test_apple_bitcode(self): testdir = os.path.join(self.platform_test_dir, '7 bitcode') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) if cc.id != 'clang': raise unittest.SkipTest('Not using Clang on OSX') # Try with bitcode enabled out = self.init(testdir, extra_args='-Db_bitcode=true') # Warning was printed self.assertRegex(out, 'WARNING:.*b_bitcode') # Compiler options were added for compdb in self.get_compdb(): if 'module' in compdb['file']: self.assertNotIn('-fembed-bitcode', compdb['command']) else: self.assertIn('-fembed-bitcode', compdb['command']) build_ninja = os.path.join(self.builddir, 'build.ninja') # Linker options were added with open(build_ninja, 'r', encoding='utf-8') as f: contents = f.read() m = re.search('LINK_ARGS =.*-bitcode_bundle', contents) self.assertIsNotNone(m, msg=contents) # Try with bitcode disabled self.setconf('-Db_bitcode=false') # Regenerate build self.build() for compdb in self.get_compdb(): self.assertNotIn('-fembed-bitcode', compdb['command']) build_ninja = os.path.join(self.builddir, 'build.ninja') with open(build_ninja, 'r', encoding='utf-8') as f: contents = f.read() m = re.search('LINK_ARGS =.*-bitcode_bundle', contents) self.assertIsNone(m, msg=contents) def test_apple_bitcode_modules(self): testdir = os.path.join(self.common_test_dir, '149 shared module resolving symbol in executable') # Ensure that it builds even with bitcode enabled self.init(testdir, extra_args='-Db_bitcode=true') self.build() self.run_tests() def _get_darwin_versions(self, fname): fname = os.path.join(self.builddir, fname) out = subprocess.check_output(['otool', '-L', fname], universal_newlines=True) m = re.match(r'.*version (.*), current version (.*)\)', out.split('\n')[1]) self.assertIsNotNone(m, msg=out) return m.groups() @skipIfNoPkgconfig def test_library_versioning(self): testdir = os.path.join(self.platform_test_dir, '2 library versions') self.init(testdir) self.build() targets = {} for t in self.introspect('--targets'): targets[t['name']] = t['filename'][0] if isinstance(t['filename'], list) else t['filename'] self.assertEqual(self._get_darwin_versions(targets['some']), ('7.0.0', '7.0.0')) self.assertEqual(self._get_darwin_versions(targets['noversion']), ('0.0.0', '0.0.0')) self.assertEqual(self._get_darwin_versions(targets['onlyversion']), ('1.0.0', '1.0.0')) self.assertEqual(self._get_darwin_versions(targets['onlysoversion']), ('5.0.0', '5.0.0')) self.assertEqual(self._get_darwin_versions(targets['intver']), ('2.0.0', '2.0.0')) self.assertEqual(self._get_darwin_versions(targets['stringver']), ('2.3.0', '2.3.0')) self.assertEqual(self._get_darwin_versions(targets['stringlistver']), ('2.4.0', '2.4.0')) self.assertEqual(self._get_darwin_versions(targets['intstringver']), ('1111.0.0', '2.5.0')) self.assertEqual(self._get_darwin_versions(targets['stringlistvers']), ('2.6.0', '2.6.1')) def test_duplicate_rpath(self): testdir = os.path.join(self.unit_test_dir, '10 build_rpath') # We purposely pass a duplicate rpath to Meson, in order # to ascertain that Meson does not call install_name_tool # with duplicate -delete_rpath arguments, which would # lead to erroring out on installation env = {"LDFLAGS": "-Wl,-rpath,/foo/bar"} self.init(testdir, override_envvars=env) self.build() self.install() def test_removing_unused_linker_args(self): testdir = os.path.join(self.common_test_dir, '105 has arg') env = {'CFLAGS': '-L/tmp -L /var/tmp -headerpad_max_install_names -Wl,-export_dynamic -framework Foundation'} self.init(testdir, override_envvars=env) @unittest.skipUnless(not is_windows(), "requires something Unix-like") class LinuxlikeTests(BasePlatformTests): def test_basic_soname(self): testdir = os.path.join(self.common_test_dir, '4 shared') self.init(testdir) self.build() lib1 = os.path.join(self.builddir, 'libmylib.so') soname = get_soname(lib1) self.assertEqual(soname, 'libmylib.so') def test_custom_soname(self): testdir = os.path.join(self.common_test_dir, '25 library versions') self.init(testdir) self.build() lib1 = os.path.join(self.builddir, 'prefixsomelib.suffix') soname = get_soname(lib1) self.assertEqual(soname, 'prefixsomelib.suffix') def test_pic(self): if is_windows() or is_cygwin() or is_osx(): raise unittest.SkipTest('PIC not relevant') testdir = os.path.join(self.common_test_dir, '3 static') self.init(testdir) compdb = self.get_compdb() self.assertIn('-fPIC', compdb[0]['command']) self.setconf('-Db_staticpic=false') # Regenerate build self.build() compdb = self.get_compdb() self.assertNotIn('-fPIC', compdb[0]['command']) @mock.patch.dict(os.environ) def test_pkgconfig_gen(self): testdir = os.path.join(self.common_test_dir, '45 pkgconfig-gen') self.init(testdir) env = get_fake_env(testdir, self.builddir, self.prefix) kwargs = {'required': True, 'silent': True} os.environ['PKG_CONFIG_LIBDIR'] = self.privatedir foo_dep = PkgConfigDependency('libfoo', env, kwargs) self.assertTrue(foo_dep.found()) self.assertEqual(foo_dep.get_version(), '1.0') self.assertIn('-lfoo', foo_dep.get_link_args()) self.assertEqual(foo_dep.get_pkgconfig_variable('foo', {}), 'bar') self.assertPathEqual(foo_dep.get_pkgconfig_variable('datadir', {}), '/usr/data') libhello_nolib = PkgConfigDependency('libhello_nolib', env, kwargs) self.assertTrue(libhello_nolib.found()) self.assertEqual(libhello_nolib.get_link_args(), []) self.assertEqual(libhello_nolib.get_compile_args(), []) self.assertEqual(libhello_nolib.get_pkgconfig_variable('foo', {}), 'bar') def test_pkgconfig_gen_deps(self): testdir = os.path.join(self.common_test_dir, '45 pkgconfig-gen') self.init(testdir) privatedir1 = self.privatedir self.new_builddir() testdir = os.path.join(self.common_test_dir, '45 pkgconfig-gen', 'dependencies') self.init(testdir, override_envvars={'PKG_CONFIG_LIBDIR': privatedir1}) privatedir2 = self.privatedir env = { 'PKG_CONFIG_LIBDIR': os.pathsep.join([privatedir1, privatedir2]), 'PKG_CONFIG_SYSTEM_LIBRARY_PATH': '/usr/lib', } self._run(['pkg-config', 'dependency-test', '--validate'], override_envvars=env) # pkg-config strips some duplicated flags so we have to parse the # generated file ourself. expected = { 'Requires': 'libexposed', 'Requires.private': 'libfoo >= 1.0', 'Libs': '-L${libdir} -llibmain -pthread -lcustom', 'Libs.private': '-lcustom2 -L${libdir} -llibinternal', 'Cflags': '-I${includedir} -pthread -DCUSTOM', } if is_osx() or is_haiku(): expected['Cflags'] = expected['Cflags'].replace('-pthread ', '') with open(os.path.join(privatedir2, 'dependency-test.pc')) as f: matched_lines = 0 for line in f: parts = line.split(':', 1) if parts[0] in expected: key = parts[0] val = parts[1].strip() expected_val = expected[key] self.assertEqual(expected_val, val) matched_lines += 1 self.assertEqual(len(expected), matched_lines) cmd = ['pkg-config', 'requires-test'] out = self._run(cmd + ['--print-requires'], override_envvars=env).strip().split('\n') if not is_openbsd(): self.assertEqual(sorted(out), sorted(['libexposed', 'libfoo >= 1.0', 'libhello'])) else: self.assertEqual(sorted(out), sorted(['libexposed', 'libfoo>=1.0', 'libhello'])) cmd = ['pkg-config', 'requires-private-test'] out = self._run(cmd + ['--print-requires-private'], override_envvars=env).strip().split('\n') if not is_openbsd(): self.assertEqual(sorted(out), sorted(['libexposed', 'libfoo >= 1.0', 'libhello'])) else: self.assertEqual(sorted(out), sorted(['libexposed', 'libfoo>=1.0', 'libhello'])) cmd = ['pkg-config', 'pub-lib-order'] out = self._run(cmd + ['--libs'], override_envvars=env).strip().split() self.assertEqual(out, ['-llibmain2', '-llibinternal']) # See common/45 pkgconfig-gen/meson.build for description of the case this test with open(os.path.join(privatedir1, 'simple2.pc')) as f: content = f.read() self.assertIn('Libs: -L${libdir} -lsimple2 -lsimple1', content) self.assertIn('Libs.private: -lz', content) with open(os.path.join(privatedir1, 'simple3.pc')) as f: content = f.read() self.assertEqual(1, content.count('-lsimple3')) with open(os.path.join(privatedir1, 'simple5.pc')) as f: content = f.read() self.assertNotIn('-lstat2', content) @mock.patch.dict(os.environ) def test_pkgconfig_uninstalled(self): testdir = os.path.join(self.common_test_dir, '45 pkgconfig-gen') self.init(testdir) self.build() os.environ['PKG_CONFIG_LIBDIR'] = os.path.join(self.builddir, 'meson-uninstalled') if is_cygwin(): os.environ['PATH'] += os.pathsep + self.builddir self.new_builddir() testdir = os.path.join(self.common_test_dir, '45 pkgconfig-gen', 'dependencies') self.init(testdir) self.build() self.run_tests() def test_pkg_unfound(self): testdir = os.path.join(self.unit_test_dir, '23 unfound pkgconfig') self.init(testdir) with open(os.path.join(self.privatedir, 'somename.pc')) as f: pcfile = f.read() self.assertFalse('blub_blob_blib' in pcfile) def test_vala_c_warnings(self): if not shutil.which('valac'): raise unittest.SkipTest('valac not installed.') testdir = os.path.join(self.vala_test_dir, '5 target glib') self.init(testdir) compdb = self.get_compdb() vala_command = None c_command = None for each in compdb: if each['file'].endswith('GLib.Thread.c'): vala_command = each['command'] elif each['file'].endswith('GLib.Thread.vala'): continue elif each['file'].endswith('retcode.c'): c_command = each['command'] else: m = 'Unknown file {!r} in vala_c_warnings test'.format(each['file']) raise AssertionError(m) self.assertIsNotNone(vala_command) self.assertIsNotNone(c_command) # -w suppresses all warnings, should be there in Vala but not in C self.assertIn(" -w ", vala_command) self.assertNotIn(" -w ", c_command) # -Wall enables all warnings, should be there in C but not in Vala self.assertNotIn(" -Wall ", vala_command) self.assertIn(" -Wall ", c_command) # -Werror converts warnings to errors, should always be there since it's # injected by an unrelated piece of code and the project has werror=true self.assertIn(" -Werror ", vala_command) self.assertIn(" -Werror ", c_command) @skipIfNoPkgconfig def test_qtdependency_pkgconfig_detection(self): # Verify Qt4 or Qt5 can be found with pkg-config qt4 = subprocess.call(['pkg-config', '--exists', 'QtCore']) qt5 = subprocess.call(['pkg-config', '--exists', 'Qt5Core']) testdir = os.path.join(self.framework_test_dir, '4 qt') self.init(testdir, extra_args=['-Dmethod=pkg-config']) # Confirm that the dependency was found with pkg-config mesonlog = self.get_meson_log() if qt4 == 0: self.assertRegex('\n'.join(mesonlog), r'Run-time dependency qt4 \(modules: Core\) found: YES 4.* \(pkg-config\)\n') if qt5 == 0: self.assertRegex('\n'.join(mesonlog), r'Run-time dependency qt5 \(modules: Core\) found: YES 5.* \(pkg-config\)\n') @skip_if_not_base_option('b_sanitize') def test_generate_gir_with_address_sanitizer(self): if is_cygwin(): raise unittest.SkipTest('asan not available on Cygwin') if is_openbsd(): raise unittest.SkipTest('-fsanitize=address is not supported on OpenBSD') testdir = os.path.join(self.framework_test_dir, '7 gnome') self.init(testdir, extra_args=['-Db_sanitize=address', '-Db_lundef=false']) self.build() def test_qt5dependency_qmake_detection(self): # Verify that qmake is for Qt5 if not shutil.which('qmake-qt5'): if not shutil.which('qmake'): raise unittest.SkipTest('QMake not found') output = subprocess.getoutput('qmake --version') if 'Qt version 5' not in output: raise unittest.SkipTest('Qmake found, but it is not for Qt 5.') # Disable pkg-config codepath and force searching with qmake/qmake-qt5 testdir = os.path.join(self.framework_test_dir, '4 qt') self.init(testdir, extra_args=['-Dmethod=qmake']) # Confirm that the dependency was found with qmake mesonlog = self.get_meson_log() self.assertRegex('\n'.join(mesonlog), r'Run-time dependency qt5 \(modules: Core\) found: YES .* \((qmake|qmake-qt5)\)\n') def test_qt6dependency_qmake_detection(self): # Verify that qmake is for Qt5 if not shutil.which('qmake-qt6'): if not shutil.which('qmake'): raise unittest.SkipTest('QMake not found') output = subprocess.getoutput('qmake --version') if 'Qt version 6' not in output: raise unittest.SkipTest('Qmake found, but it is not for Qt 6.') # Disable pkg-config codepath and force searching with qmake/qmake-qt6 testdir = os.path.join(self.framework_test_dir, '4 qt') self.init(testdir, extra_args=['-Dmethod=qmake']) # Confirm that the dependency was found with qmake mesonlog = self.get_meson_log() self.assertRegex('\n'.join(mesonlog), r'Run-time dependency qt6 \(modules: Core\) found: YES .* \((qmake|qmake-qt6)\)\n') def glob_sofiles_without_privdir(self, g): files = glob(g) return [f for f in files if not f.endswith('.p')] def _test_soname_impl(self, libpath, install): if is_cygwin() or is_osx(): raise unittest.SkipTest('Test only applicable to ELF and linuxlike sonames') testdir = os.path.join(self.unit_test_dir, '1 soname') self.init(testdir) self.build() if install: self.install() # File without aliases set. nover = os.path.join(libpath, 'libnover.so') self.assertPathExists(nover) self.assertFalse(os.path.islink(nover)) self.assertEqual(get_soname(nover), 'libnover.so') self.assertEqual(len(self.glob_sofiles_without_privdir(nover[:-3] + '*')), 1) # File with version set verset = os.path.join(libpath, 'libverset.so') self.assertPathExists(verset + '.4.5.6') self.assertEqual(os.readlink(verset), 'libverset.so.4') self.assertEqual(get_soname(verset), 'libverset.so.4') self.assertEqual(len(self.glob_sofiles_without_privdir(verset[:-3] + '*')), 3) # File with soversion set soverset = os.path.join(libpath, 'libsoverset.so') self.assertPathExists(soverset + '.1.2.3') self.assertEqual(os.readlink(soverset), 'libsoverset.so.1.2.3') self.assertEqual(get_soname(soverset), 'libsoverset.so.1.2.3') self.assertEqual(len(self.glob_sofiles_without_privdir(soverset[:-3] + '*')), 2) # File with version and soversion set to same values settosame = os.path.join(libpath, 'libsettosame.so') self.assertPathExists(settosame + '.7.8.9') self.assertEqual(os.readlink(settosame), 'libsettosame.so.7.8.9') self.assertEqual(get_soname(settosame), 'libsettosame.so.7.8.9') self.assertEqual(len(self.glob_sofiles_without_privdir(settosame[:-3] + '*')), 2) # File with version and soversion set to different values bothset = os.path.join(libpath, 'libbothset.so') self.assertPathExists(bothset + '.1.2.3') self.assertEqual(os.readlink(bothset), 'libbothset.so.1.2.3') self.assertEqual(os.readlink(bothset + '.1.2.3'), 'libbothset.so.4.5.6') self.assertEqual(get_soname(bothset), 'libbothset.so.1.2.3') self.assertEqual(len(self.glob_sofiles_without_privdir(bothset[:-3] + '*')), 3) def test_soname(self): self._test_soname_impl(self.builddir, False) def test_installed_soname(self): libdir = self.installdir + os.path.join(self.prefix, self.libdir) self._test_soname_impl(libdir, True) def test_compiler_check_flags_order(self): testdir = os.path.join(self.common_test_dir, '37 has function') env = get_fake_env(testdir, self.builddir, self.prefix) cpp = env.detect_cpp_compiler(MachineChoice.HOST) Oflag = '-O3' OflagCPP = Oflag if cpp.get_id() in ('clang', 'gcc'): # prevent developers from adding "int main(int argc, char **argv)" # to small Meson checks unless these parameters are actually used OflagCPP += ' -Werror=unused-parameter' env = {'CFLAGS': Oflag, 'CXXFLAGS': OflagCPP} self.init(testdir, override_envvars=env) cmds = self.get_meson_log_compiler_checks() for cmd in cmds: if cmd[0] == 'ccache': cmd = cmd[1:] # Verify that -I flags from the `args` kwarg are first # This is set in the '37 has function' test case self.assertEqual(cmd[1], '-I/tmp') # Verify that -O3 set via the environment is overridden by -O0 Oargs = [arg for arg in cmd if arg.startswith('-O')] self.assertEqual(Oargs, [Oflag, '-O0']) def _test_stds_impl(self, testdir: str, compiler: 'Compiler') -> None: has_cpp17 = (compiler.get_id() not in {'clang', 'gcc'} or compiler.get_id() == 'clang' and _clang_at_least(compiler, '>=5.0.0', '>=9.1') or compiler.get_id() == 'gcc' and version_compare(compiler.version, '>=5.0.0')) has_cpp2a_c17 = (compiler.get_id() not in {'clang', 'gcc'} or compiler.get_id() == 'clang' and _clang_at_least(compiler, '>=6.0.0', '>=10.0') or compiler.get_id() == 'gcc' and version_compare(compiler.version, '>=8.0.0')) has_cpp20 = (compiler.get_id() not in {'clang', 'gcc'} or compiler.get_id() == 'clang' and _clang_at_least(compiler, '>=10.0.0', None) or compiler.get_id() == 'gcc' and version_compare(compiler.version, '>=10.0.0')) has_c18 = (compiler.get_id() not in {'clang', 'gcc'} or compiler.get_id() == 'clang' and _clang_at_least(compiler, '>=8.0.0', '>=11.0') or compiler.get_id() == 'gcc' and version_compare(compiler.version, '>=8.0.0')) # Check that all the listed -std=xxx options for this compiler work just fine when used # https://en.wikipedia.org/wiki/Xcode#Latest_versions # https://www.gnu.org/software/gcc/projects/cxx-status.html key = OptionKey('std', lang=compiler.language) for v in compiler.get_options()[key].choices: # we do it like this to handle gnu++17,c++17 and gnu17,c17 cleanly # thus, C++ first if '++17' in v and not has_cpp17: continue elif '++2a' in v and not has_cpp2a_c17: # https://en.cppreference.com/w/cpp/compiler_support continue elif '++20' in v and not has_cpp20: continue # now C elif '17' in v and not has_cpp2a_c17: continue elif '18' in v and not has_c18: continue self.init(testdir, extra_args=[f'-D{key!s}={v}']) cmd = self.get_compdb()[0]['command'] # c++03 and gnu++03 are not understood by ICC, don't try to look for them skiplist = frozenset([ ('intel', 'c++03'), ('intel', 'gnu++03')]) if v != 'none' and not (compiler.get_id(), v) in skiplist: cmd_std = " -std={} ".format(v) self.assertIn(cmd_std, cmd) try: self.build() except Exception: print(f'{key!s} was {v!r}') raise self.wipe() # Check that an invalid std option in CFLAGS/CPPFLAGS fails # Needed because by default ICC ignores invalid options cmd_std = '-std=FAIL' if compiler.language == 'c': env_flag_name = 'CFLAGS' elif compiler.language == 'cpp': env_flag_name = 'CXXFLAGS' else: raise NotImplementedError('Language {} not defined.'.format(compiler.language)) env = {} env[env_flag_name] = cmd_std with self.assertRaises((subprocess.CalledProcessError, mesonbuild.mesonlib.EnvironmentException), msg='C compiler should have failed with -std=FAIL'): self.init(testdir, override_envvars = env) # ICC won't fail in the above because additional flags are needed to # make unknown -std=... options errors. self.build() def test_compiler_c_stds(self): testdir = os.path.join(self.common_test_dir, '1 trivial') env = get_fake_env(testdir, self.builddir, self.prefix) cc = env.detect_c_compiler(MachineChoice.HOST) self._test_stds_impl(testdir, cc) def test_compiler_cpp_stds(self): testdir = os.path.join(self.common_test_dir, '2 cpp') env = get_fake_env(testdir, self.builddir, self.prefix) cpp = env.detect_cpp_compiler(MachineChoice.HOST) self._test_stds_impl(testdir, cpp) def test_unity_subproj(self): testdir = os.path.join(self.common_test_dir, '43 subproject') self.init(testdir, extra_args='--unity=subprojects') pdirs = glob(os.path.join(self.builddir, 'subprojects/sublib/simpletest*.p')) self.assertEqual(len(pdirs), 1) self.assertPathExists(os.path.join(pdirs[0], 'simpletest-unity0.c')) sdirs = glob(os.path.join(self.builddir, 'subprojects/sublib/*sublib*.p')) self.assertEqual(len(sdirs), 1) self.assertPathExists(os.path.join(sdirs[0], 'sublib-unity0.c')) self.assertPathDoesNotExist(os.path.join(self.builddir, 'user@exe/user-unity.c')) self.build() def test_installed_modes(self): # Test file modes testdir = os.path.join(self.common_test_dir, '12 data') self.init(testdir) self.install() f = os.path.join(self.installdir, 'etc', 'etcfile.dat') found_mode = stat.filemode(os.stat(f).st_mode) want_mode = 'rw------T' self.assertEqual(want_mode, found_mode[1:]) f = os.path.join(self.installdir, 'usr', 'bin', 'runscript.sh') statf = os.stat(f) found_mode = stat.filemode(statf.st_mode) want_mode = 'rwxr-sr-x' self.assertEqual(want_mode, found_mode[1:]) if os.getuid() == 0: # The chown failed nonfatally if we're not root self.assertEqual(0, statf.st_uid) self.assertEqual(0, statf.st_gid) f = os.path.join(self.installdir, 'usr', 'share', 'progname', 'fileobject_datafile.dat') orig = os.path.join(testdir, 'fileobject_datafile.dat') statf = os.stat(f) statorig = os.stat(orig) found_mode = stat.filemode(statf.st_mode) orig_mode = stat.filemode(statorig.st_mode) self.assertEqual(orig_mode[1:], found_mode[1:]) self.assertEqual(os.getuid(), statf.st_uid) if os.getuid() == 0: # The chown failed nonfatally if we're not root self.assertEqual(0, statf.st_gid) self.wipe() # Test directory modes testdir = os.path.join(self.common_test_dir, '60 install subdir') self.init(testdir) self.install() f = os.path.join(self.installdir, 'usr', 'share', 'sub1', 'second.dat') statf = os.stat(f) found_mode = stat.filemode(statf.st_mode) want_mode = 'rwxr-x--t' self.assertEqual(want_mode, found_mode[1:]) if os.getuid() == 0: # The chown failed nonfatally if we're not root self.assertEqual(0, statf.st_uid) def test_installed_modes_extended(self): testdir = os.path.join(self.common_test_dir, '191 install_mode') self.init(testdir) self.build() self.install() for fsobj, want_mode in [ ('bin', 'drwxr-x---'), ('bin/runscript.sh', '-rwxr-sr-x'), ('bin/trivialprog', '-rwxr-sr-x'), ('include', 'drwxr-x---'), ('include/config.h', '-rw-rwSr--'), ('include/rootdir.h', '-r--r--r-T'), ('lib', 'drwxr-x---'), ('lib/libstat.a', '-rw---Sr--'), ('share', 'drwxr-x---'), ('share/man', 'drwxr-x---'), ('share/man/man1', 'drwxr-x---'), ('share/man/man1/foo.1', '-r--r--r-T'), ('share/sub1', 'drwxr-x---'), ('share/sub1/second.dat', '-rwxr-x--t'), ('subdir', 'drwxr-x---'), ('subdir/data.dat', '-rw-rwSr--'), ]: f = os.path.join(self.installdir, 'usr', *fsobj.split('/')) found_mode = stat.filemode(os.stat(f).st_mode) self.assertEqual(want_mode, found_mode, msg=('Expected file %s to have mode %s but found %s instead.' % (fsobj, want_mode, found_mode))) # Ensure that introspect --installed works on all types of files # FIXME: also verify the files list self.introspect('--installed') def test_install_umask(self): # Copy source tree to a temporary directory and change permissions # there to simulate a checkout with umask 002. orig_testdir = os.path.join(self.unit_test_dir, '26 install umask') # Create a new testdir under tmpdir. tmpdir = os.path.realpath(tempfile.mkdtemp()) self.addCleanup(windows_proof_rmtree, tmpdir) testdir = os.path.join(tmpdir, '26 install umask') # Copy the tree using shutil.copyfile, which will use the current umask # instead of preserving permissions of the old tree. save_umask = os.umask(0o002) self.addCleanup(os.umask, save_umask) shutil.copytree(orig_testdir, testdir, copy_function=shutil.copyfile) # Preserve the executable status of subdir/sayhello though. os.chmod(os.path.join(testdir, 'subdir', 'sayhello'), 0o775) self.init(testdir) # Run the build under a 027 umask now. os.umask(0o027) self.build() # And keep umask 027 for the install step too. self.install() for executable in [ 'bin/prog', 'share/subdir/sayhello', ]: f = os.path.join(self.installdir, 'usr', *executable.split('/')) found_mode = stat.filemode(os.stat(f).st_mode) want_mode = '-rwxr-xr-x' self.assertEqual(want_mode, found_mode, msg=('Expected file %s to have mode %s but found %s instead.' % (executable, want_mode, found_mode))) for directory in [ 'usr', 'usr/bin', 'usr/include', 'usr/share', 'usr/share/man', 'usr/share/man/man1', 'usr/share/subdir', ]: f = os.path.join(self.installdir, *directory.split('/')) found_mode = stat.filemode(os.stat(f).st_mode) want_mode = 'drwxr-xr-x' self.assertEqual(want_mode, found_mode, msg=('Expected directory %s to have mode %s but found %s instead.' % (directory, want_mode, found_mode))) for datafile in [ 'include/sample.h', 'share/datafile.cat', 'share/file.dat', 'share/man/man1/prog.1', 'share/subdir/datafile.dog', ]: f = os.path.join(self.installdir, 'usr', *datafile.split('/')) found_mode = stat.filemode(os.stat(f).st_mode) want_mode = '-rw-r--r--' self.assertEqual(want_mode, found_mode, msg=('Expected file %s to have mode %s but found %s instead.' % (datafile, want_mode, found_mode))) def test_cpp_std_override(self): testdir = os.path.join(self.unit_test_dir, '6 std override') self.init(testdir) compdb = self.get_compdb() # Don't try to use -std=c++03 as a check for the # presence of a compiler flag, as ICC does not # support it. for i in compdb: if 'prog98' in i['file']: c98_comp = i['command'] if 'prog11' in i['file']: c11_comp = i['command'] if 'progp' in i['file']: plain_comp = i['command'] self.assertNotEqual(len(plain_comp), 0) self.assertIn('-std=c++98', c98_comp) self.assertNotIn('-std=c++11', c98_comp) self.assertIn('-std=c++11', c11_comp) self.assertNotIn('-std=c++98', c11_comp) self.assertNotIn('-std=c++98', plain_comp) self.assertNotIn('-std=c++11', plain_comp) # Now werror self.assertIn('-Werror', plain_comp) self.assertNotIn('-Werror', c98_comp) def test_run_installed(self): if is_cygwin() or is_osx(): raise unittest.SkipTest('LD_LIBRARY_PATH and RPATH not applicable') testdir = os.path.join(self.unit_test_dir, '7 run installed') self.init(testdir) self.build() self.install() installed_exe = os.path.join(self.installdir, 'usr/bin/prog') installed_libdir = os.path.join(self.installdir, 'usr/foo') installed_lib = os.path.join(installed_libdir, 'libfoo.so') self.assertTrue(os.path.isfile(installed_exe)) self.assertTrue(os.path.isdir(installed_libdir)) self.assertTrue(os.path.isfile(installed_lib)) # Must fail when run without LD_LIBRARY_PATH to ensure that # rpath has been properly stripped rather than pointing to the builddir. self.assertNotEqual(subprocess.call(installed_exe, stderr=subprocess.DEVNULL), 0) # When LD_LIBRARY_PATH is set it should start working. # For some reason setting LD_LIBRARY_PATH in os.environ fails # when all tests are run (but works when only this test is run), # but doing this explicitly works. env = os.environ.copy() env['LD_LIBRARY_PATH'] = ':'.join([installed_libdir, env.get('LD_LIBRARY_PATH', '')]) self.assertEqual(subprocess.call(installed_exe, env=env), 0) # Ensure that introspect --installed works installed = self.introspect('--installed') for v in installed.values(): self.assertTrue('prog' in v or 'foo' in v) @skipIfNoPkgconfig def test_order_of_l_arguments(self): testdir = os.path.join(self.unit_test_dir, '8 -L -l order') self.init(testdir, override_envvars={'PKG_CONFIG_PATH': testdir}) # NOTE: .pc file has -Lfoo -lfoo -Lbar -lbar but pkg-config reorders # the flags before returning them to -Lfoo -Lbar -lfoo -lbar # but pkgconf seems to not do that. Sigh. Support both. expected_order = [('-L/me/first', '-lfoo1'), ('-L/me/second', '-lfoo2'), ('-L/me/first', '-L/me/second'), ('-lfoo1', '-lfoo2'), ('-L/me/second', '-L/me/third'), ('-L/me/third', '-L/me/fourth',), ('-L/me/third', '-lfoo3'), ('-L/me/fourth', '-lfoo4'), ('-lfoo3', '-lfoo4'), ] with open(os.path.join(self.builddir, 'build.ninja')) as ifile: for line in ifile: if expected_order[0][0] in line: for first, second in expected_order: self.assertLess(line.index(first), line.index(second)) return raise RuntimeError('Linker entries not found in the Ninja file.') def test_introspect_dependencies(self): testdir = os.path.join(self.framework_test_dir, '7 gnome') self.init(testdir) glib_found = False gobject_found = False deps = self.introspect('--dependencies') self.assertIsInstance(deps, list) for dep in deps: self.assertIsInstance(dep, dict) self.assertIn('name', dep) self.assertIn('compile_args', dep) self.assertIn('link_args', dep) if dep['name'] == 'glib-2.0': glib_found = True elif dep['name'] == 'gobject-2.0': gobject_found = True self.assertTrue(glib_found) self.assertTrue(gobject_found) if subprocess.call(['pkg-config', '--exists', 'glib-2.0 >= 2.56.2']) != 0: raise unittest.SkipTest('glib >= 2.56.2 needed for the rest') targets = self.introspect('--targets') docbook_target = None for t in targets: if t['name'] == 'generated-gdbus-docbook': docbook_target = t break self.assertIsInstance(docbook_target, dict) self.assertEqual(os.path.basename(t['filename'][0]), 'generated-gdbus-doc-' + os.path.basename(t['target_sources'][0]['sources'][0])) def test_introspect_installed(self): testdir = os.path.join(self.linuxlike_test_dir, '7 library versions') self.init(testdir) install = self.introspect('--installed') install = {os.path.basename(k): v for k, v in install.items()} print(install) if is_osx(): the_truth = { 'libmodule.dylib': '/usr/lib/libmodule.dylib', 'libnoversion.dylib': '/usr/lib/libnoversion.dylib', 'libonlysoversion.5.dylib': '/usr/lib/libonlysoversion.5.dylib', 'libonlysoversion.dylib': '/usr/lib/libonlysoversion.dylib', 'libonlyversion.1.dylib': '/usr/lib/libonlyversion.1.dylib', 'libonlyversion.dylib': '/usr/lib/libonlyversion.dylib', 'libsome.0.dylib': '/usr/lib/libsome.0.dylib', 'libsome.dylib': '/usr/lib/libsome.dylib', } the_truth_2 = {'/usr/lib/libsome.dylib', '/usr/lib/libsome.0.dylib', } else: the_truth = { 'libmodule.so': '/usr/lib/libmodule.so', 'libnoversion.so': '/usr/lib/libnoversion.so', 'libonlysoversion.so': '/usr/lib/libonlysoversion.so', 'libonlysoversion.so.5': '/usr/lib/libonlysoversion.so.5', 'libonlyversion.so': '/usr/lib/libonlyversion.so', 'libonlyversion.so.1': '/usr/lib/libonlyversion.so.1', 'libonlyversion.so.1.4.5': '/usr/lib/libonlyversion.so.1.4.5', 'libsome.so': '/usr/lib/libsome.so', 'libsome.so.0': '/usr/lib/libsome.so.0', 'libsome.so.1.2.3': '/usr/lib/libsome.so.1.2.3', } the_truth_2 = {'/usr/lib/libsome.so', '/usr/lib/libsome.so.0', '/usr/lib/libsome.so.1.2.3'} self.assertDictEqual(install, the_truth) targets = self.introspect('--targets') for t in targets: if t['name'] != 'some': continue self.assertSetEqual(the_truth_2, set(t['install_filename'])) def test_build_rpath(self): if is_cygwin(): raise unittest.SkipTest('Windows PE/COFF binaries do not use RPATH') testdir = os.path.join(self.unit_test_dir, '10 build_rpath') self.init(testdir) self.build() build_rpath = get_rpath(os.path.join(self.builddir, 'prog')) self.assertEqual(build_rpath, '$ORIGIN/sub:/foo/bar') build_rpath = get_rpath(os.path.join(self.builddir, 'progcxx')) self.assertEqual(build_rpath, '$ORIGIN/sub:/foo/bar') self.install() install_rpath = get_rpath(os.path.join(self.installdir, 'usr/bin/prog')) self.assertEqual(install_rpath, '/baz') install_rpath = get_rpath(os.path.join(self.installdir, 'usr/bin/progcxx')) self.assertEqual(install_rpath, 'baz') @skipIfNoPkgconfig def test_build_rpath_pkgconfig(self): if is_cygwin(): raise unittest.SkipTest('Windows PE/COFF binaries do not use RPATH') testdir = os.path.join(self.unit_test_dir, '90 pkgconfig build rpath order') self.init(testdir, override_envvars={'PKG_CONFIG_PATH': testdir}) self.build() build_rpath = get_rpath(os.path.join(self.builddir, 'prog')) self.assertEqual(build_rpath, '$ORIGIN/sub:/foo/bar:/foo/dummy') build_rpath = get_rpath(os.path.join(self.builddir, 'progcxx')) self.assertEqual(build_rpath, '$ORIGIN/sub:/foo/bar:/foo/dummy') self.install() install_rpath = get_rpath(os.path.join(self.installdir, 'usr/bin/prog')) self.assertEqual(install_rpath, '/baz:/foo/dummy') install_rpath = get_rpath(os.path.join(self.installdir, 'usr/bin/progcxx')) self.assertEqual(install_rpath, 'baz:/foo/dummy') def test_global_rpath(self): if is_cygwin(): raise unittest.SkipTest('Windows PE/COFF binaries do not use RPATH') if is_osx(): raise unittest.SkipTest('Global RPATHs via LDFLAGS not yet supported on MacOS (does anybody need it?)') testdir = os.path.join(self.unit_test_dir, '81 global-rpath') oldinstalldir = self.installdir # Build and install an external library without DESTDIR. # The external library generates a .pc file without an rpath. yonder_dir = os.path.join(testdir, 'yonder') yonder_prefix = os.path.join(oldinstalldir, 'yonder') yonder_libdir = os.path.join(yonder_prefix, self.libdir) self.prefix = yonder_prefix self.installdir = yonder_prefix self.init(yonder_dir) self.build() self.install(use_destdir=False) # Since rpath has multiple valid formats we need to # test that they are all properly used. rpath_formats = [ ('-Wl,-rpath=', False), ('-Wl,-rpath,', False), ('-Wl,--just-symbols=', True), ('-Wl,--just-symbols,', True), ('-Wl,-R', False), ('-Wl,-R,', False) ] for rpath_format, exception in rpath_formats: # Build an app that uses that installed library. # Supply the rpath to the installed library via LDFLAGS # (as systems like buildroot and guix are wont to do) # and verify install preserves that rpath. self.new_builddir() env = {'LDFLAGS': rpath_format + yonder_libdir, 'PKG_CONFIG_PATH': os.path.join(yonder_libdir, 'pkgconfig')} if exception: with self.assertRaises(subprocess.CalledProcessError): self.init(testdir, override_envvars=env) continue self.init(testdir, override_envvars=env) self.build() self.install(use_destdir=False) got_rpath = get_rpath(os.path.join(yonder_prefix, 'bin/rpathified')) self.assertEqual(got_rpath, yonder_libdir, rpath_format) @skip_if_not_base_option('b_sanitize') def test_pch_with_address_sanitizer(self): if is_cygwin(): raise unittest.SkipTest('asan not available on Cygwin') if is_openbsd(): raise unittest.SkipTest('-fsanitize=address is not supported on OpenBSD') testdir = os.path.join(self.common_test_dir, '13 pch') self.init(testdir, extra_args=['-Db_sanitize=address', '-Db_lundef=false']) self.build() compdb = self.get_compdb() for i in compdb: self.assertIn("-fsanitize=address", i["command"]) def test_cross_find_program(self): testdir = os.path.join(self.unit_test_dir, '11 cross prog') crossfile = tempfile.NamedTemporaryFile(mode='w') print(os.path.join(testdir, 'some_cross_tool.py')) tool_path = os.path.join(testdir, 'some_cross_tool.py') crossfile.write(textwrap.dedent(f'''\ [binaries] c = '{shutil.which('gcc' if is_sunos() else 'cc')}' ar = '{shutil.which('ar')}' strip = '{shutil.which('strip')}' sometool.py = ['{tool_path}'] someothertool.py = '{tool_path}' [properties] [host_machine] system = 'linux' cpu_family = 'arm' cpu = 'armv7' # Not sure if correct. endian = 'little' ''')) crossfile.flush() self.meson_cross_file = crossfile.name self.init(testdir) def test_reconfigure(self): testdir = os.path.join(self.unit_test_dir, '13 reconfigure') self.init(testdir, extra_args=['-Db_coverage=true'], default_args=False) self.build('reconfigure') def test_vala_generated_source_buildir_inside_source_tree(self): if not shutil.which('valac'): raise unittest.SkipTest('valac not installed.') testdir = os.path.join(self.vala_test_dir, '8 generated sources') newdir = os.path.join(self.builddir, 'srctree') shutil.copytree(testdir, newdir) testdir = newdir # New builddir builddir = os.path.join(testdir, 'subdir/_build') os.makedirs(builddir, exist_ok=True) self.change_builddir(builddir) self.init(testdir) self.build() def test_old_gnome_module_codepaths(self): testdir = os.path.join(self.framework_test_dir, '7 gnome') mesonbuild.modules.gnome.native_glib_version = '2.20' env = {'MESON_UNIT_TEST_PRETEND_GLIB_OLD': "1"} try: self.init(testdir, inprocess=True, override_envvars=env) self.build(override_envvars=env) finally: mesonbuild.modules.gnome.native_glib_version = None @skipIfNoPkgconfig def test_pkgconfig_usage(self): testdir1 = os.path.join(self.unit_test_dir, '27 pkgconfig usage/dependency') testdir2 = os.path.join(self.unit_test_dir, '27 pkgconfig usage/dependee') if subprocess.call(['pkg-config', '--cflags', 'glib-2.0'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) != 0: raise unittest.SkipTest('Glib 2.0 dependency not available.') with tempfile.TemporaryDirectory() as tempdirname: self.init(testdir1, extra_args=['--prefix=' + tempdirname, '--libdir=lib'], default_args=False) self.install(use_destdir=False) shutil.rmtree(self.builddir) os.mkdir(self.builddir) pkg_dir = os.path.join(tempdirname, 'lib/pkgconfig') self.assertTrue(os.path.exists(os.path.join(pkg_dir, 'libpkgdep.pc'))) lib_dir = os.path.join(tempdirname, 'lib') myenv = os.environ.copy() myenv['PKG_CONFIG_PATH'] = pkg_dir # Private internal libraries must not leak out. pkg_out = subprocess.check_output(['pkg-config', '--static', '--libs', 'libpkgdep'], env=myenv) self.assertFalse(b'libpkgdep-int' in pkg_out, 'Internal library leaked out.') # Dependencies must not leak to cflags when building only a shared library. pkg_out = subprocess.check_output(['pkg-config', '--cflags', 'libpkgdep'], env=myenv) self.assertFalse(b'glib' in pkg_out, 'Internal dependency leaked to headers.') # Test that the result is usable. self.init(testdir2, override_envvars=myenv) self.build(override_envvars=myenv) myenv = os.environ.copy() myenv['LD_LIBRARY_PATH'] = ':'.join([lib_dir, myenv.get('LD_LIBRARY_PATH', '')]) if is_cygwin(): bin_dir = os.path.join(tempdirname, 'bin') myenv['PATH'] = bin_dir + os.pathsep + myenv['PATH'] self.assertTrue(os.path.isdir(lib_dir)) test_exe = os.path.join(self.builddir, 'pkguser') self.assertTrue(os.path.isfile(test_exe)) subprocess.check_call(test_exe, env=myenv) @skipIfNoPkgconfig def test_pkgconfig_relative_paths(self): testdir = os.path.join(self.unit_test_dir, '62 pkgconfig relative paths') pkg_dir = os.path.join(testdir, 'pkgconfig') self.assertTrue(os.path.exists(os.path.join(pkg_dir, 'librelativepath.pc'))) env = get_fake_env(testdir, self.builddir, self.prefix) env.coredata.set_options({OptionKey('pkg_config_path'): pkg_dir}, subproject='') kwargs = {'required': True, 'silent': True} relative_path_dep = PkgConfigDependency('librelativepath', env, kwargs) self.assertTrue(relative_path_dep.found()) # Ensure link_args are properly quoted libpath = Path(self.builddir) / '../relativepath/lib' link_args = ['-L' + libpath.as_posix(), '-lrelativepath'] self.assertEqual(relative_path_dep.get_link_args(), link_args) @skipIfNoPkgconfig def test_pkgconfig_internal_libraries(self): with tempfile.TemporaryDirectory() as tempdirname: # build library testdirbase = os.path.join(self.unit_test_dir, '32 pkgconfig use libraries') testdirlib = os.path.join(testdirbase, 'lib') self.init(testdirlib, extra_args=['--prefix=' + tempdirname, '--libdir=lib', '--default-library=static'], default_args=False) self.build() self.install(use_destdir=False) # build user of library pkg_dir = os.path.join(tempdirname, 'lib/pkgconfig') self.new_builddir() self.init(os.path.join(testdirbase, 'app'), override_envvars={'PKG_CONFIG_PATH': pkg_dir}) self.build() @skipIfNoPkgconfig def test_static_archive_stripping(self): with tempfile.TemporaryDirectory() as tempdirname: testdirbase = os.path.join(self.unit_test_dir, '67 static archive stripping') # build lib self.new_builddir() testdirlib = os.path.join(testdirbase, 'lib') testlibprefix = os.path.join(tempdirname, 'libprefix') self.init(testdirlib, extra_args=['--prefix=' + testlibprefix, '--libdir=lib', '--default-library=static', '--buildtype=debug', '--strip'], default_args=False) self.build() self.install(use_destdir=False) # build executable (uses lib, fails if static archive has been stripped incorrectly) pkg_dir = os.path.join(testlibprefix, 'lib/pkgconfig') self.new_builddir() self.init(os.path.join(testdirbase, 'app'), override_envvars={'PKG_CONFIG_PATH': pkg_dir}) self.build() @skipIfNoPkgconfig def test_pkgconfig_formatting(self): testdir = os.path.join(self.unit_test_dir, '38 pkgconfig format') self.init(testdir) myenv = os.environ.copy() myenv['PKG_CONFIG_PATH'] = self.privatedir stdo = subprocess.check_output(['pkg-config', '--libs-only-l', 'libsomething'], env=myenv) deps = [b'-lgobject-2.0', b'-lgio-2.0', b'-lglib-2.0', b'-lsomething'] if is_windows() or is_cygwin() or is_osx() or is_openbsd(): # On Windows, libintl is a separate library deps.append(b'-lintl') self.assertEqual(set(deps), set(stdo.split())) @skipIfNoPkgconfig @skip_if_not_language('cs') def test_pkgconfig_csharp_library(self): testdir = os.path.join(self.unit_test_dir, '50 pkgconfig csharp library') self.init(testdir) myenv = os.environ.copy() myenv['PKG_CONFIG_PATH'] = self.privatedir stdo = subprocess.check_output(['pkg-config', '--libs', 'libsomething'], env=myenv) self.assertEqual("-r/usr/lib/libsomething.dll", str(stdo.decode('ascii')).strip()) @skipIfNoPkgconfig def test_pkgconfig_link_order(self): testdir = os.path.join(self.unit_test_dir, '53 pkgconfig static link order') self.init(testdir) myenv = os.environ.copy() myenv['PKG_CONFIG_PATH'] = self.privatedir stdo = subprocess.check_output(['pkg-config', '--libs', 'libsomething'], env=myenv) deps = stdo.split() self.assertTrue(deps.index(b'-lsomething') < deps.index(b'-ldependency')) def test_deterministic_dep_order(self): testdir = os.path.join(self.unit_test_dir, '43 dep order') self.init(testdir) with open(os.path.join(self.builddir, 'build.ninja')) as bfile: for line in bfile: if 'build myexe:' in line or 'build myexe.exe:' in line: self.assertIn('liblib1.a liblib2.a', line) return raise RuntimeError('Could not find the build rule') def test_deterministic_rpath_order(self): if is_cygwin(): raise unittest.SkipTest('rpath are not used on Cygwin') testdir = os.path.join(self.unit_test_dir, '42 rpath order') self.init(testdir) if is_osx(): rpathre = re.compile(r'-rpath,.*/subprojects/sub1.*-rpath,.*/subprojects/sub2') else: rpathre = re.compile(r'-rpath,\$\$ORIGIN/subprojects/sub1:\$\$ORIGIN/subprojects/sub2') with open(os.path.join(self.builddir, 'build.ninja')) as bfile: for line in bfile: if '-rpath' in line: self.assertRegex(line, rpathre) return raise RuntimeError('Could not find the rpath') def test_override_with_exe_dep(self): testdir = os.path.join(self.src_root, 'test cases', 'native', '9 override with exe') self.init(testdir) with open(os.path.join(self.builddir, 'build.ninja')) as bfile: for line in bfile: if 'main1.c:' in line or 'main2.c:' in line: self.assertIn('| subprojects/sub/foobar', line) @skipIfNoPkgconfig def test_usage_external_library(self): oldprefix = self.prefix # Install external library so we can find it testdir = os.path.join(self.unit_test_dir, '40 external, internal library rpath', 'external library') # install into installdir without using DESTDIR installdir = self.installdir self.prefix = installdir self.init(testdir) self.prefix = oldprefix self.build() self.install(use_destdir=False) ## New builddir for the consumer self.new_builddir() env = {'LIBRARY_PATH': os.path.join(installdir, self.libdir), 'PKG_CONFIG_PATH': os.path.join(installdir, self.libdir, 'pkgconfig')} testdir = os.path.join(self.unit_test_dir, '40 external, internal library rpath', 'built library') # install into installdir without using DESTDIR self.prefix = self.installdir self.init(testdir, override_envvars=env) self.prefix = oldprefix self.build(override_envvars=env) # test uninstalled self.run_tests(override_envvars=env) if not (is_osx() or is_linux()): return # test running after installation self.install(use_destdir=False) prog = os.path.join(self.installdir, 'bin', 'prog') self._run([prog]) if not is_osx(): # Rest of the workflow only works on macOS return out = self._run(['otool', '-L', prog]) self.assertNotIn('@rpath', out) ## New builddir for testing that DESTDIR is not added to install_name self.new_builddir() # install into installdir with DESTDIR self.init(testdir, override_envvars=env) self.build(override_envvars=env) # test running after installation self.install(override_envvars=env) prog = self.installdir + os.path.join(self.prefix, 'bin', 'prog') lib = self.installdir + os.path.join(self.prefix, 'lib', 'libbar_built.dylib') for f in prog, lib: out = self._run(['otool', '-L', f]) # Ensure that the otool output does not contain self.installdir self.assertNotRegex(out, self.installdir + '.*dylib ') @skipIfNoPkgconfig def test_usage_pkgconfig_prefixes(self): oldinstalldir = self.installdir # Build and install both external libraries without DESTDIR val1dir = os.path.join(self.unit_test_dir, '76 pkgconfig prefixes', 'val1') val1prefix = os.path.join(oldinstalldir, 'val1') self.prefix = val1prefix self.installdir = val1prefix self.init(val1dir) self.build() self.install(use_destdir=False) self.new_builddir() env1 = {} env1['PKG_CONFIG_PATH'] = os.path.join(val1prefix, self.libdir, 'pkgconfig') val2dir = os.path.join(self.unit_test_dir, '76 pkgconfig prefixes', 'val2') val2prefix = os.path.join(oldinstalldir, 'val2') self.prefix = val2prefix self.installdir = val2prefix self.init(val2dir, override_envvars=env1) self.build() self.install(use_destdir=False) self.new_builddir() # Build, install, and run the client program env2 = {} env2['PKG_CONFIG_PATH'] = os.path.join(val2prefix, self.libdir, 'pkgconfig') testdir = os.path.join(self.unit_test_dir, '76 pkgconfig prefixes', 'client') testprefix = os.path.join(oldinstalldir, 'client') self.prefix = testprefix self.installdir = testprefix self.init(testdir, override_envvars=env2) self.build() self.install(use_destdir=False) prog = os.path.join(self.installdir, 'bin', 'client') env3 = {} if is_cygwin(): env3['PATH'] = os.path.join(val1prefix, 'bin') + \ os.pathsep + \ os.path.join(val2prefix, 'bin') + \ os.pathsep + os.environ['PATH'] out = self._run([prog], override_envvars=env3).strip() # Expected output is val1 + val2 = 3 self.assertEqual(out, '3') def install_subdir_invalid_symlinks(self, testdir, subdir_path): testdir = os.path.join(self.common_test_dir, testdir) subdir = os.path.join(testdir, subdir_path) with chdir(subdir): # Can't distribute broken symlinks in the source tree because it breaks # the creation of zipapps. Create it dynamically and run the test by # hand. src = '../../nonexistent.txt' os.symlink(src, 'invalid-symlink.txt') try: self.init(testdir) self.build() self.install() install_path = subdir_path.split(os.path.sep)[-1] link = os.path.join(self.installdir, 'usr', 'share', install_path, 'invalid-symlink.txt') self.assertTrue(os.path.islink(link), msg=link) self.assertEqual(src, os.readlink(link)) self.assertFalse(os.path.isfile(link), msg=link) finally: os.remove(os.path.join(subdir, 'invalid-symlink.txt')) def test_install_subdir_symlinks(self): self.install_subdir_invalid_symlinks('60 install subdir', os.path.join('sub', 'sub1')) def test_install_subdir_symlinks_with_default_umask(self): self.install_subdir_invalid_symlinks('191 install_mode', 'sub2') def test_install_subdir_symlinks_with_default_umask_and_mode(self): self.install_subdir_invalid_symlinks('191 install_mode', 'sub1') @skipIfNoPkgconfigDep('gmodule-2.0') def test_ldflag_dedup(self): testdir = os.path.join(self.unit_test_dir, '52 ldflagdedup') if is_cygwin() or is_osx(): raise unittest.SkipTest('Not applicable on Cygwin or OSX.') env = get_fake_env() cc = env.detect_c_compiler(MachineChoice.HOST) linker = cc.linker if not linker.export_dynamic_args(env): raise unittest.SkipTest('Not applicable for linkers without --export-dynamic') self.init(testdir) build_ninja = os.path.join(self.builddir, 'build.ninja') max_count = 0 search_term = '-Wl,--export-dynamic' with open(build_ninja, 'r', encoding='utf-8') as f: for line in f: max_count = max(max_count, line.count(search_term)) self.assertEqual(max_count, 1, 'Export dynamic incorrectly deduplicated.') def test_compiler_libs_static_dedup(self): testdir = os.path.join(self.unit_test_dir, '56 dedup compiler libs') self.init(testdir) build_ninja = os.path.join(self.builddir, 'build.ninja') with open(build_ninja, 'r', encoding='utf-8') as f: lines = f.readlines() for lib in ('-ldl', '-lm', '-lc', '-lrt'): for line in lines: if lib not in line: continue # Assert that self.assertEqual(len(line.split(lib)), 2, msg=(lib, line)) @skipIfNoPkgconfig def test_noncross_options(self): # C_std defined in project options must be in effect also when native compiling. testdir = os.path.join(self.unit_test_dir, '51 noncross options') self.init(testdir, extra_args=['-Dpkg_config_path=' + testdir]) compdb = self.get_compdb() self.assertEqual(len(compdb), 2) self.assertRegex(compdb[0]['command'], '-std=c99') self.assertRegex(compdb[1]['command'], '-std=c99') self.build() def test_identity_cross(self): testdir = os.path.join(self.unit_test_dir, '61 identity cross') nativefile = tempfile.NamedTemporaryFile(mode='w') nativefile.write(textwrap.dedent('''\ [binaries] c = ['{0}'] '''.format(os.path.join(testdir, 'build_wrapper.py')))) nativefile.flush() self.meson_native_file = nativefile.name crossfile = tempfile.NamedTemporaryFile(mode='w') crossfile.write(textwrap.dedent('''\ [binaries] c = ['{0}'] '''.format(os.path.join(testdir, 'host_wrapper.py')))) crossfile.flush() self.meson_cross_file = crossfile.name # TODO should someday be explicit about build platform only here self.init(testdir) def test_identity_cross_env(self): testdir = os.path.join(self.unit_test_dir, '61 identity cross') env = { 'CC_FOR_BUILD': '"' + os.path.join(testdir, 'build_wrapper.py') + '"', } crossfile = tempfile.NamedTemporaryFile(mode='w') crossfile.write(textwrap.dedent('''\ [binaries] c = ['{0}'] '''.format(os.path.join(testdir, 'host_wrapper.py')))) crossfile.flush() self.meson_cross_file = crossfile.name # TODO should someday be explicit about build platform only here self.init(testdir, override_envvars=env) @skipIfNoPkgconfig def test_static_link(self): if is_cygwin(): raise unittest.SkipTest("Cygwin doesn't support LD_LIBRARY_PATH.") # Build some libraries and install them testdir = os.path.join(self.unit_test_dir, '68 static link/lib') libdir = os.path.join(self.installdir, self.libdir) oldprefix = self.prefix self.prefix = self.installdir self.init(testdir) self.install(use_destdir=False) # Test that installed libraries works self.new_builddir() self.prefix = oldprefix meson_args = ['-Dc_link_args=-L{}'.format(libdir), '--fatal-meson-warnings'] testdir = os.path.join(self.unit_test_dir, '68 static link') env = {'PKG_CONFIG_LIBDIR': os.path.join(libdir, 'pkgconfig')} self.init(testdir, extra_args=meson_args, override_envvars=env) self.build() self.run_tests() def _check_ld(self, check: str, name: str, lang: str, expected: str) -> None: if is_sunos(): raise unittest.SkipTest('Solaris currently cannot override the linker.') if not shutil.which(check): raise unittest.SkipTest('Could not find {}.'.format(check)) envvars = [mesonbuild.envconfig.ENV_VAR_PROG_MAP['{}_ld'.format(lang)]] # Also test a deprecated variable if there is one. if f'{lang}_ld' in mesonbuild.envconfig.DEPRECATED_ENV_PROG_MAP: envvars.append( mesonbuild.envconfig.DEPRECATED_ENV_PROG_MAP[f'{lang}_ld']) for envvar in envvars: with mock.patch.dict(os.environ, {envvar: name}): env = get_fake_env() comp = getattr(env, 'detect_{}_compiler'.format(lang))(MachineChoice.HOST) if isinstance(comp, (mesonbuild.compilers.AppleClangCCompiler, mesonbuild.compilers.AppleClangCPPCompiler, mesonbuild.compilers.AppleClangObjCCompiler, mesonbuild.compilers.AppleClangObjCPPCompiler)): raise unittest.SkipTest('AppleClang is currently only supported with ld64') if lang != 'rust' and comp.use_linker_args('bfd') == []: raise unittest.SkipTest( 'Compiler {} does not support using alternative linkers'.format(comp.id)) self.assertEqual(comp.linker.id, expected) def test_ld_environment_variable_bfd(self): self._check_ld('ld.bfd', 'bfd', 'c', 'ld.bfd') def test_ld_environment_variable_gold(self): self._check_ld('ld.gold', 'gold', 'c', 'ld.gold') def test_ld_environment_variable_lld(self): self._check_ld('ld.lld', 'lld', 'c', 'ld.lld') @skip_if_not_language('rust') @skipIfNoExecutable('ld.gold') # need an additional check here because _check_ld checks for gcc def test_ld_environment_variable_rust(self): self._check_ld('gcc', 'gcc -fuse-ld=gold', 'rust', 'ld.gold') def test_ld_environment_variable_cpp(self): self._check_ld('ld.gold', 'gold', 'cpp', 'ld.gold') @skip_if_not_language('objc') def test_ld_environment_variable_objc(self): self._check_ld('ld.gold', 'gold', 'objc', 'ld.gold') @skip_if_not_language('objcpp') def test_ld_environment_variable_objcpp(self): self._check_ld('ld.gold', 'gold', 'objcpp', 'ld.gold') @skip_if_not_language('fortran') def test_ld_environment_variable_fortran(self): self._check_ld('ld.gold', 'gold', 'fortran', 'ld.gold') @skip_if_not_language('d') def test_ld_environment_variable_d(self): # At least for me, ldc defaults to gold, and gdc defaults to bfd, so # let's pick lld, which isn't the default for either (currently) self._check_ld('ld.lld', 'lld', 'd', 'ld.lld') def compute_sha256(self, filename): with open(filename, 'rb') as f: return hashlib.sha256(f.read()).hexdigest() def test_wrap_with_file_url(self): testdir = os.path.join(self.unit_test_dir, '74 wrap file url') source_filename = os.path.join(testdir, 'subprojects', 'foo.tar.xz') patch_filename = os.path.join(testdir, 'subprojects', 'foo-patch.tar.xz') wrap_filename = os.path.join(testdir, 'subprojects', 'foo.wrap') source_hash = self.compute_sha256(source_filename) patch_hash = self.compute_sha256(patch_filename) wrap = textwrap.dedent("""\ [wrap-file] directory = foo source_url = http://server.invalid/foo source_fallback_url = file://{} source_filename = foo.tar.xz source_hash = {} patch_url = http://server.invalid/foo patch_fallback_url = file://{} patch_filename = foo-patch.tar.xz patch_hash = {} """.format(source_filename, source_hash, patch_filename, patch_hash)) with open(wrap_filename, 'w') as f: f.write(wrap) self.init(testdir) self.build() self.run_tests() windows_proof_rmtree(os.path.join(testdir, 'subprojects', 'packagecache')) windows_proof_rmtree(os.path.join(testdir, 'subprojects', 'foo')) os.unlink(wrap_filename) def test_no_rpath_for_static(self): testdir = os.path.join(self.common_test_dir, '5 linkstatic') self.init(testdir) self.build() build_rpath = get_rpath(os.path.join(self.builddir, 'prog')) self.assertIsNone(build_rpath) def test_lookup_system_after_broken_fallback(self): # Just to generate libfoo.pc so we can test system dependency lookup. testdir = os.path.join(self.common_test_dir, '45 pkgconfig-gen') self.init(testdir) privatedir = self.privatedir # Write test project where the first dependency() returns not-found # because 'broken' subproject does not exit, but that should not prevent # the 2nd dependency() to lookup on system. self.new_builddir() with tempfile.TemporaryDirectory() as d: with open(os.path.join(d, 'meson.build'), 'w') as f: f.write(textwrap.dedent('''\ project('test') dependency('notfound', fallback: 'broken', required: false) dependency('libfoo', fallback: 'broken', required: true) ''')) self.init(d, override_envvars={'PKG_CONFIG_LIBDIR': privatedir}) def test_as_link_whole(self): testdir = os.path.join(self.unit_test_dir, '78 as link whole') self.init(testdir) with open(os.path.join(self.privatedir, 'bar1.pc')) as f: content = f.read() self.assertIn('-lfoo', content) with open(os.path.join(self.privatedir, 'bar2.pc')) as f: content = f.read() self.assertNotIn('-lfoo', content) def test_prelinking(self): # Prelinking currently only works on recently new GNU toolchains. # Skip everything else. When support for other toolchains is added, # remove limitations as necessary. if is_osx(): raise unittest.SkipTest('Prelinking not supported on Darwin.') if 'clang' in os.environ.get('CC', 'dummy'): raise unittest.SkipTest('Prelinking not supported with Clang.') gccver = subprocess.check_output(['cc', '--version']) if b'7.5.0' in gccver: raise unittest.SkipTest('GCC on Bionic is too old to be supported.') testdir = os.path.join(self.unit_test_dir, '88 prelinking') self.init(testdir) self.build() outlib = os.path.join(self.builddir, 'libprelinked.a') ar = shutil.which('ar') self.assertTrue(os.path.exists(outlib)) self.assertTrue(ar is not None) p = subprocess.run([ar, 't', outlib], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, universal_newlines=True, timeout=1) obj_files = p.stdout.strip().split('\n') self.assertEqual(len(obj_files), 1) self.assertTrue(obj_files[0].endswith('-prelink.o')) class BaseLinuxCrossTests(BasePlatformTests): # Don't pass --libdir when cross-compiling. We have tests that # check whether meson auto-detects it correctly. libdir = None def should_run_cross_arm_tests(): return shutil.which('arm-linux-gnueabihf-gcc') and not platform.machine().lower().startswith('arm') @unittest.skipUnless(not is_windows() and should_run_cross_arm_tests(), "requires ability to cross compile to ARM") class LinuxCrossArmTests(BaseLinuxCrossTests): def setUp(self): super().setUp() src_root = os.path.dirname(__file__) self.meson_cross_file = os.path.join(src_root, 'cross', 'ubuntu-armhf.txt') def test_cflags_cross_environment_pollution(self): testdir = os.path.join(self.common_test_dir, '3 static') self.init(testdir, override_envvars={'CFLAGS': '-DBUILD_ENVIRONMENT_ONLY'}) compdb = self.get_compdb() self.assertNotIn('-DBUILD_ENVIRONMENT_ONLY', compdb[0]['command']) def test_cross_file_overrides_always_args(self): testdir = os.path.join(self.unit_test_dir, '33 cross file overrides always args') self.meson_cross_file = os.path.join(testdir, 'ubuntu-armhf-overrides.txt') self.init(testdir) compdb = self.get_compdb() self.assertRegex(compdb[0]['command'], '-D_FILE_OFFSET_BITS=64.*-U_FILE_OFFSET_BITS') self.build() def test_cross_libdir(self): # When cross compiling "libdir" should default to "lib" # rather than "lib/x86_64-linux-gnu" or something like that. testdir = os.path.join(self.common_test_dir, '1 trivial') self.init(testdir) for i in self.introspect('--buildoptions'): if i['name'] == 'libdir': self.assertEqual(i['value'], 'lib') return self.assertTrue(False, 'Option libdir not in introspect data.') def test_cross_libdir_subproject(self): # Guard against a regression where calling "subproject" # would reset the value of libdir to its default value. testdir = os.path.join(self.unit_test_dir, '77 subdir libdir') self.init(testdir, extra_args=['--libdir=fuf']) for i in self.introspect('--buildoptions'): if i['name'] == 'libdir': self.assertEqual(i['value'], 'fuf') return self.assertTrue(False, 'Libdir specified on command line gets reset.') def test_std_remains(self): # C_std defined in project options must be in effect also when cross compiling. testdir = os.path.join(self.unit_test_dir, '51 noncross options') self.init(testdir) compdb = self.get_compdb() self.assertRegex(compdb[0]['command'], '-std=c99') self.build() @skipIfNoPkgconfig def test_pkg_config_option(self): if not shutil.which('arm-linux-gnueabihf-pkg-config'): raise unittest.SkipTest('Cross-pkgconfig not found.') testdir = os.path.join(self.unit_test_dir, '58 pkg_config_path option') self.init(testdir, extra_args=[ '-Dbuild.pkg_config_path=' + os.path.join(testdir, 'build_extra_path'), '-Dpkg_config_path=' + os.path.join(testdir, 'host_extra_path'), ]) def test_run_native_test(self): testdir = os.path.join(self.unit_test_dir, '89 run native test') stamp_file = os.path.join(self.builddir, 'native_test_has_run.stamp') self.init(testdir) self.build() self.assertPathDoesNotExist(stamp_file) self.run_tests() self.assertPathExists(stamp_file) def should_run_cross_mingw_tests(): return shutil.which('x86_64-w64-mingw32-gcc') and not (is_windows() or is_cygwin()) @unittest.skipUnless(not is_windows() and should_run_cross_mingw_tests(), "requires ability to cross compile with MinGW") class LinuxCrossMingwTests(BaseLinuxCrossTests): def setUp(self): super().setUp() src_root = os.path.dirname(__file__) self.meson_cross_file = os.path.join(src_root, 'cross', 'linux-mingw-w64-64bit.txt') def test_exe_wrapper_behaviour(self): testdir = os.path.join(self.unit_test_dir, '36 exe_wrapper behaviour') # Configures, builds, and tests fine by default self.init(testdir) self.build() self.run_tests() self.wipe() os.mkdir(self.builddir) # Change cross file to use a non-existing exe_wrapper and it should fail self.meson_cross_file = os.path.join(testdir, 'broken-cross.txt') # Force tracebacks so we can detect them properly env = {'MESON_FORCE_BACKTRACE': '1'} error_message = "An exe_wrapper is needed but was not found. Please define one in cross file and check the command and/or add it to PATH." with self.assertRaises(MesonException) as cm: # Must run in-process or we'll get a generic CalledProcessError self.init(testdir, extra_args='-Drun-target=false', inprocess=True, override_envvars=env) self.assertEqual(str(cm.exception), error_message) with self.assertRaises(MesonException) as cm: # Must run in-process or we'll get a generic CalledProcessError self.init(testdir, extra_args='-Dcustom-target=false', inprocess=True, override_envvars=env) self.assertEqual(str(cm.exception), error_message) self.init(testdir, extra_args=['-Dcustom-target=false', '-Drun-target=false'], override_envvars=env) self.build() with self.assertRaises(MesonException) as cm: # Must run in-process or we'll get a generic CalledProcessError self.run_tests(inprocess=True, override_envvars=env) self.assertEqual(str(cm.exception), "The exe_wrapper defined in the cross file 'broken' was not found. Please check the command and/or add it to PATH.") @skipIfNoPkgconfig def test_cross_pkg_config_option(self): testdir = os.path.join(self.unit_test_dir, '58 pkg_config_path option') self.init(testdir, extra_args=[ '-Dbuild.pkg_config_path=' + os.path.join(testdir, 'build_extra_path'), '-Dpkg_config_path=' + os.path.join(testdir, 'host_extra_path'), ]) class PythonTests(BasePlatformTests): def test_versions(self): if self.backend is not Backend.ninja: raise unittest.SkipTest('Skipping python tests with {} backend'.format(self.backend.name)) testdir = os.path.join(self.src_root, 'test cases', 'unit', '39 python extmodule') # No python version specified, this will use meson's python self.init(testdir) self.build() self.run_tests() self.wipe() # When specifying a known name, (python2 / python3) the module # will also try 'python' as a fallback and use it if the major # version matches try: self.init(testdir, extra_args=['-Dpython=python2']) self.build() self.run_tests() except unittest.SkipTest: # python2 is not necessarily installed on the test machine, # if it is not, or the python headers can't be found, the test # will raise MESON_SKIP_TEST, we could check beforehand what version # of python is available, but it's a bit of a chicken and egg situation, # as that is the job of the module, so we just ask for forgiveness rather # than permission. pass self.wipe() for py in ('pypy', 'pypy3'): try: self.init(testdir, extra_args=['-Dpython=%s' % py]) except unittest.SkipTest: # Same as above, pypy2 and pypy3 are not expected to be present # on the test system, the test project only raises in these cases continue # We have a pypy, this is expected to work self.build() self.run_tests() self.wipe() # The test is configured to error out with MESON_SKIP_TEST # in case it could not find python with self.assertRaises(unittest.SkipTest): self.init(testdir, extra_args=['-Dpython=not-python']) self.wipe() # While dir is an external command on both Windows and Linux, # it certainly isn't python with self.assertRaises(unittest.SkipTest): self.init(testdir, extra_args=['-Dpython=dir']) self.wipe() class RewriterTests(BasePlatformTests): def setUp(self): super().setUp() self.maxDiff = None def prime(self, dirname): copy_tree(os.path.join(self.rewrite_test_dir, dirname), self.builddir) def rewrite_raw(self, directory, args): if isinstance(args, str): args = [args] command = self.rewrite_command + ['--verbose', '--skip', '--sourcedir', directory] + args p = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, timeout=60) print('STDOUT:') print(p.stdout) print('STDERR:') print(p.stderr) if p.returncode != 0: if 'MESON_SKIP_TEST' in p.stdout: raise unittest.SkipTest('Project requested skipping.') raise subprocess.CalledProcessError(p.returncode, command, output=p.stdout) if not p.stderr: return {} return json.loads(p.stderr) def rewrite(self, directory, args): if isinstance(args, str): args = [args] return self.rewrite_raw(directory, ['command'] + args) def test_target_source_list(self): self.prime('1 basic') out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = { 'target': { 'trivialprog0@exe': {'name': 'trivialprog0', 'sources': ['main.cpp', 'fileA.cpp', 'fileB.cpp', 'fileC.cpp']}, 'trivialprog1@exe': {'name': 'trivialprog1', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog2@exe': {'name': 'trivialprog2', 'sources': ['fileB.cpp', 'fileC.cpp']}, 'trivialprog3@exe': {'name': 'trivialprog3', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog4@exe': {'name': 'trivialprog4', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog5@exe': {'name': 'trivialprog5', 'sources': ['main.cpp', 'fileB.cpp', 'fileC.cpp']}, 'trivialprog6@exe': {'name': 'trivialprog6', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog7@exe': {'name': 'trivialprog7', 'sources': ['fileB.cpp', 'fileC.cpp', 'main.cpp', 'fileA.cpp']}, 'trivialprog8@exe': {'name': 'trivialprog8', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog9@exe': {'name': 'trivialprog9', 'sources': ['main.cpp', 'fileA.cpp']}, } } self.assertDictEqual(out, expected) def test_target_add_sources(self): self.prime('1 basic') out = self.rewrite(self.builddir, os.path.join(self.builddir, 'addSrc.json')) expected = { 'target': { 'trivialprog0@exe': {'name': 'trivialprog0', 'sources': ['a1.cpp', 'a2.cpp', 'a6.cpp', 'fileA.cpp', 'main.cpp', 'a7.cpp', 'fileB.cpp', 'fileC.cpp']}, 'trivialprog1@exe': {'name': 'trivialprog1', 'sources': ['a1.cpp', 'a2.cpp', 'a6.cpp', 'fileA.cpp', 'main.cpp']}, 'trivialprog2@exe': {'name': 'trivialprog2', 'sources': ['a7.cpp', 'fileB.cpp', 'fileC.cpp']}, 'trivialprog3@exe': {'name': 'trivialprog3', 'sources': ['a5.cpp', 'fileA.cpp', 'main.cpp']}, 'trivialprog4@exe': {'name': 'trivialprog4', 'sources': ['a5.cpp', 'main.cpp', 'fileA.cpp']}, 'trivialprog5@exe': {'name': 'trivialprog5', 'sources': ['a3.cpp', 'main.cpp', 'a7.cpp', 'fileB.cpp', 'fileC.cpp']}, 'trivialprog6@exe': {'name': 'trivialprog6', 'sources': ['main.cpp', 'fileA.cpp', 'a4.cpp']}, 'trivialprog7@exe': {'name': 'trivialprog7', 'sources': ['fileB.cpp', 'fileC.cpp', 'a1.cpp', 'a2.cpp', 'a6.cpp', 'fileA.cpp', 'main.cpp']}, 'trivialprog8@exe': {'name': 'trivialprog8', 'sources': ['a1.cpp', 'a2.cpp', 'a6.cpp', 'fileA.cpp', 'main.cpp']}, 'trivialprog9@exe': {'name': 'trivialprog9', 'sources': ['a1.cpp', 'a2.cpp', 'a6.cpp', 'fileA.cpp', 'main.cpp']}, } } self.assertDictEqual(out, expected) # Check the written file out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) self.assertDictEqual(out, expected) def test_target_add_sources_abs(self): self.prime('1 basic') abs_src = [os.path.join(self.builddir, x) for x in ['a1.cpp', 'a2.cpp', 'a6.cpp']] add = json.dumps([{"type": "target", "target": "trivialprog1", "operation": "src_add", "sources": abs_src}]) inf = json.dumps([{"type": "target", "target": "trivialprog1", "operation": "info"}]) self.rewrite(self.builddir, add) out = self.rewrite(self.builddir, inf) expected = {'target': {'trivialprog1@exe': {'name': 'trivialprog1', 'sources': ['a1.cpp', 'a2.cpp', 'a6.cpp', 'fileA.cpp', 'main.cpp']}}} self.assertDictEqual(out, expected) def test_target_remove_sources(self): self.prime('1 basic') out = self.rewrite(self.builddir, os.path.join(self.builddir, 'rmSrc.json')) expected = { 'target': { 'trivialprog0@exe': {'name': 'trivialprog0', 'sources': ['main.cpp', 'fileC.cpp']}, 'trivialprog1@exe': {'name': 'trivialprog1', 'sources': ['main.cpp']}, 'trivialprog2@exe': {'name': 'trivialprog2', 'sources': ['fileC.cpp']}, 'trivialprog3@exe': {'name': 'trivialprog3', 'sources': ['main.cpp']}, 'trivialprog4@exe': {'name': 'trivialprog4', 'sources': ['main.cpp']}, 'trivialprog5@exe': {'name': 'trivialprog5', 'sources': ['main.cpp', 'fileC.cpp']}, 'trivialprog6@exe': {'name': 'trivialprog6', 'sources': ['main.cpp']}, 'trivialprog7@exe': {'name': 'trivialprog7', 'sources': ['fileC.cpp', 'main.cpp']}, 'trivialprog8@exe': {'name': 'trivialprog8', 'sources': ['main.cpp']}, 'trivialprog9@exe': {'name': 'trivialprog9', 'sources': ['main.cpp']}, } } self.assertDictEqual(out, expected) # Check the written file out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) self.assertDictEqual(out, expected) def test_target_subdir(self): self.prime('2 subdirs') out = self.rewrite(self.builddir, os.path.join(self.builddir, 'addSrc.json')) expected = {'name': 'something', 'sources': ['first.c', 'second.c', 'third.c']} self.assertDictEqual(list(out['target'].values())[0], expected) # Check the written file out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) self.assertDictEqual(list(out['target'].values())[0], expected) def test_target_remove(self): self.prime('1 basic') self.rewrite(self.builddir, os.path.join(self.builddir, 'rmTgt.json')) out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = { 'target': { 'trivialprog2@exe': {'name': 'trivialprog2', 'sources': ['fileB.cpp', 'fileC.cpp']}, 'trivialprog3@exe': {'name': 'trivialprog3', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog4@exe': {'name': 'trivialprog4', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog5@exe': {'name': 'trivialprog5', 'sources': ['main.cpp', 'fileB.cpp', 'fileC.cpp']}, 'trivialprog6@exe': {'name': 'trivialprog6', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog7@exe': {'name': 'trivialprog7', 'sources': ['fileB.cpp', 'fileC.cpp', 'main.cpp', 'fileA.cpp']}, 'trivialprog8@exe': {'name': 'trivialprog8', 'sources': ['main.cpp', 'fileA.cpp']}, } } self.assertDictEqual(out, expected) def test_tatrget_add(self): self.prime('1 basic') self.rewrite(self.builddir, os.path.join(self.builddir, 'addTgt.json')) out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = { 'target': { 'trivialprog0@exe': {'name': 'trivialprog0', 'sources': ['main.cpp', 'fileA.cpp', 'fileB.cpp', 'fileC.cpp']}, 'trivialprog1@exe': {'name': 'trivialprog1', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog2@exe': {'name': 'trivialprog2', 'sources': ['fileB.cpp', 'fileC.cpp']}, 'trivialprog3@exe': {'name': 'trivialprog3', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog4@exe': {'name': 'trivialprog4', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog5@exe': {'name': 'trivialprog5', 'sources': ['main.cpp', 'fileB.cpp', 'fileC.cpp']}, 'trivialprog6@exe': {'name': 'trivialprog6', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog7@exe': {'name': 'trivialprog7', 'sources': ['fileB.cpp', 'fileC.cpp', 'main.cpp', 'fileA.cpp']}, 'trivialprog8@exe': {'name': 'trivialprog8', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog9@exe': {'name': 'trivialprog9', 'sources': ['main.cpp', 'fileA.cpp']}, 'trivialprog10@sha': {'name': 'trivialprog10', 'sources': ['new1.cpp', 'new2.cpp']}, } } self.assertDictEqual(out, expected) def test_target_remove_subdir(self): self.prime('2 subdirs') self.rewrite(self.builddir, os.path.join(self.builddir, 'rmTgt.json')) out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) self.assertDictEqual(out, {}) def test_target_add_subdir(self): self.prime('2 subdirs') self.rewrite(self.builddir, os.path.join(self.builddir, 'addTgt.json')) out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = {'name': 'something', 'sources': ['first.c', 'second.c']} self.assertDictEqual(out['target']['94b671c@@something@exe'], expected) def test_target_source_sorting(self): self.prime('5 sorting') add_json = json.dumps([{'type': 'target', 'target': 'exe1', 'operation': 'src_add', 'sources': ['a666.c']}]) inf_json = json.dumps([{'type': 'target', 'target': 'exe1', 'operation': 'info'}]) out = self.rewrite(self.builddir, add_json) out = self.rewrite(self.builddir, inf_json) expected = { 'target': { 'exe1@exe': { 'name': 'exe1', 'sources': [ 'aaa/a/a1.c', 'aaa/b/b1.c', 'aaa/b/b2.c', 'aaa/f1.c', 'aaa/f2.c', 'aaa/f3.c', 'bbb/a/b1.c', 'bbb/b/b2.c', 'bbb/c1/b5.c', 'bbb/c2/b7.c', 'bbb/c10/b6.c', 'bbb/a4.c', 'bbb/b3.c', 'bbb/b4.c', 'bbb/b5.c', 'a1.c', 'a2.c', 'a3.c', 'a10.c', 'a20.c', 'a30.c', 'a100.c', 'a101.c', 'a110.c', 'a210.c', 'a666.c', 'b1.c', 'c2.c' ] } } } self.assertDictEqual(out, expected) def test_target_same_name_skip(self): self.prime('4 same name targets') out = self.rewrite(self.builddir, os.path.join(self.builddir, 'addSrc.json')) out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = {'name': 'myExe', 'sources': ['main.cpp']} self.assertEqual(len(out['target']), 2) for val in out['target'].values(): self.assertDictEqual(expected, val) def test_kwargs_info(self): self.prime('3 kwargs') out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = { 'kwargs': { 'project#/': {'version': '0.0.1'}, 'target#tgt1': {'build_by_default': True}, 'dependency#dep1': {'required': False} } } self.assertDictEqual(out, expected) def test_kwargs_set(self): self.prime('3 kwargs') self.rewrite(self.builddir, os.path.join(self.builddir, 'set.json')) out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = { 'kwargs': { 'project#/': {'version': '0.0.2', 'meson_version': '0.50.0', 'license': ['GPL', 'MIT']}, 'target#tgt1': {'build_by_default': False, 'build_rpath': '/usr/local', 'dependencies': 'dep1'}, 'dependency#dep1': {'required': True, 'method': 'cmake'} } } self.assertDictEqual(out, expected) def test_kwargs_add(self): self.prime('3 kwargs') self.rewrite(self.builddir, os.path.join(self.builddir, 'add.json')) out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = { 'kwargs': { 'project#/': {'version': '0.0.1', 'license': ['GPL', 'MIT', 'BSD', 'Boost']}, 'target#tgt1': {'build_by_default': True}, 'dependency#dep1': {'required': False} } } self.assertDictEqual(out, expected) def test_kwargs_remove(self): self.prime('3 kwargs') self.rewrite(self.builddir, os.path.join(self.builddir, 'remove.json')) out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = { 'kwargs': { 'project#/': {'version': '0.0.1', 'license': 'GPL'}, 'target#tgt1': {'build_by_default': True}, 'dependency#dep1': {'required': False} } } self.assertDictEqual(out, expected) def test_kwargs_remove_regex(self): self.prime('3 kwargs') self.rewrite(self.builddir, os.path.join(self.builddir, 'remove_regex.json')) out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = { 'kwargs': { 'project#/': {'version': '0.0.1', 'default_options': 'debug=true'}, 'target#tgt1': {'build_by_default': True}, 'dependency#dep1': {'required': False} } } self.assertDictEqual(out, expected) def test_kwargs_delete(self): self.prime('3 kwargs') self.rewrite(self.builddir, os.path.join(self.builddir, 'delete.json')) out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = { 'kwargs': { 'project#/': {}, 'target#tgt1': {}, 'dependency#dep1': {'required': False} } } self.assertDictEqual(out, expected) def test_default_options_set(self): self.prime('3 kwargs') self.rewrite(self.builddir, os.path.join(self.builddir, 'defopts_set.json')) out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = { 'kwargs': { 'project#/': {'version': '0.0.1', 'default_options': ['buildtype=release', 'debug=True', 'cpp_std=c++11']}, 'target#tgt1': {'build_by_default': True}, 'dependency#dep1': {'required': False} } } self.assertDictEqual(out, expected) def test_default_options_delete(self): self.prime('3 kwargs') self.rewrite(self.builddir, os.path.join(self.builddir, 'defopts_delete.json')) out = self.rewrite(self.builddir, os.path.join(self.builddir, 'info.json')) expected = { 'kwargs': { 'project#/': {'version': '0.0.1', 'default_options': ['cpp_std=c++14', 'debug=true']}, 'target#tgt1': {'build_by_default': True}, 'dependency#dep1': {'required': False} } } self.assertDictEqual(out, expected) class NativeFileTests(BasePlatformTests): def setUp(self): super().setUp() self.testcase = os.path.join(self.unit_test_dir, '47 native file binary') self.current_config = 0 self.current_wrapper = 0 def helper_create_native_file(self, values): filename = os.path.join(self.builddir, 'generated{}.config'.format(self.current_config)) self.current_config += 1 with open(filename, 'wt') as f: for section, entries in values.items(): f.write('[{}]\n'.format(section)) for k, v in entries.items(): if isinstance(v, (bool, int, float)): f.write("{}={}\n".format(k, v)) elif isinstance(v, list): f.write("{}=[{}]\n".format(k, ', '.join(["'{}'".format(w) for w in v]))) else: f.write("{}='{}'\n".format(k, v)) return filename def helper_create_binary_wrapper(self, binary, dir_=None, extra_args=None, **kwargs): filename = os.path.join(dir_ or self.builddir, 'binary_wrapper{}.py'.format(self.current_wrapper)) extra_args = extra_args or {} self.current_wrapper += 1 if is_haiku(): chbang = '#!/bin/env python3' else: chbang = '#!/usr/bin/env python3' with open(filename, 'wt') as f: f.write(textwrap.dedent('''\ {} import argparse import subprocess import sys def main(): parser = argparse.ArgumentParser() '''.format(chbang))) for name in chain(extra_args, kwargs): f.write(' parser.add_argument("-{0}", "--{0}", action="store_true")\n'.format(name)) f.write(' args, extra_args = parser.parse_known_args()\n') for name, value in chain(extra_args.items(), kwargs.items()): f.write(' if args.{}:\n'.format(name)) f.write(' print("{}", file=sys.{})\n'.format(value, kwargs.get('outfile', 'stdout'))) f.write(' sys.exit(0)\n') f.write(textwrap.dedent(''' ret = subprocess.run( ["{}"] + extra_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) print(ret.stdout.decode('utf-8')) print(ret.stderr.decode('utf-8'), file=sys.stderr) sys.exit(ret.returncode) if __name__ == '__main__': main() '''.format(binary))) if not is_windows(): os.chmod(filename, 0o755) return filename # On windows we need yet another level of indirection, as cmd cannot # invoke python files itself, so instead we generate a .bat file, which # invokes our python wrapper batfile = os.path.join(self.builddir, 'binary_wrapper{}.bat'.format(self.current_wrapper)) with open(batfile, 'wt') as f: f.write(r'@{} {} %*'.format(sys.executable, filename)) return batfile def helper_for_compiler(self, lang, cb, for_machine = MachineChoice.HOST): env = get_fake_env() getter = getattr(env, 'detect_{}_compiler'.format(lang)) getter = functools.partial(getter, for_machine) cc = getter() binary, newid = cb(cc) env.binaries[for_machine].binaries[lang] = binary compiler = getter() self.assertEqual(compiler.id, newid) def test_multiple_native_files_override(self): wrapper = self.helper_create_binary_wrapper('bash', version='foo') config = self.helper_create_native_file({'binaries': {'bash': wrapper}}) wrapper = self.helper_create_binary_wrapper('bash', version='12345') config2 = self.helper_create_native_file({'binaries': {'bash': wrapper}}) self.init(self.testcase, extra_args=[ '--native-file', config, '--native-file', config2, '-Dcase=find_program']) # This test hangs on cygwin. @unittest.skipIf(os.name != 'posix' or is_cygwin(), 'Uses fifos, which are not available on non Unix OSes.') def test_native_file_is_pipe(self): fifo = os.path.join(self.builddir, 'native.file') os.mkfifo(fifo) with tempfile.TemporaryDirectory() as d: wrapper = self.helper_create_binary_wrapper('bash', d, version='12345') def filler(): with open(fifo, 'w') as f: f.write('[binaries]\n') f.write("bash = '{}'\n".format(wrapper)) thread = threading.Thread(target=filler) thread.start() self.init(self.testcase, extra_args=['--native-file', fifo, '-Dcase=find_program']) thread.join() os.unlink(fifo) self.init(self.testcase, extra_args=['--wipe']) def test_multiple_native_files(self): wrapper = self.helper_create_binary_wrapper('bash', version='12345') config = self.helper_create_native_file({'binaries': {'bash': wrapper}}) wrapper = self.helper_create_binary_wrapper('python') config2 = self.helper_create_native_file({'binaries': {'python': wrapper}}) self.init(self.testcase, extra_args=[ '--native-file', config, '--native-file', config2, '-Dcase=find_program']) def _simple_test(self, case, binary, entry=None): wrapper = self.helper_create_binary_wrapper(binary, version='12345') config = self.helper_create_native_file({'binaries': {entry or binary: wrapper}}) self.init(self.testcase, extra_args=['--native-file', config, '-Dcase={}'.format(case)]) def test_find_program(self): self._simple_test('find_program', 'bash') def test_config_tool_dep(self): # Do the skip at this level to avoid screwing up the cache if mesonbuild.environment.detect_msys2_arch(): raise unittest.SkipTest('Skipped due to problems with LLVM on MSYS2') if not shutil.which('llvm-config'): raise unittest.SkipTest('No llvm-installed, cannot test') self._simple_test('config_dep', 'llvm-config') def test_python3_module(self): self._simple_test('python3', 'python3') def test_python_module(self): if is_windows(): # Bat adds extra crap to stdout, so the version check logic in the # python module breaks. This is fine on other OSes because they # don't need the extra indirection. raise unittest.SkipTest('bat indirection breaks internal sanity checks.') elif is_osx(): binary = 'python' else: binary = 'python2' # We not have python2, check for it for v in ['2', '2.7', '-2.7']: rc = subprocess.call(['pkg-config', '--cflags', 'python{}'.format(v)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) if rc == 0: break else: raise unittest.SkipTest('Not running Python 2 tests because dev packages not installed.') self._simple_test('python', binary, entry='python') @unittest.skipIf(is_windows(), 'Setting up multiple compilers on windows is hard') @skip_if_env_set('CC') def test_c_compiler(self): def cb(comp): if comp.id == 'gcc': if not shutil.which('clang'): raise unittest.SkipTest('Only one compiler found, cannot test.') return 'clang', 'clang' if not is_real_gnu_compiler(shutil.which('gcc')): raise unittest.SkipTest('Only one compiler found, cannot test.') return 'gcc', 'gcc' self.helper_for_compiler('c', cb) @unittest.skipIf(is_windows(), 'Setting up multiple compilers on windows is hard') @skip_if_env_set('CXX') def test_cpp_compiler(self): def cb(comp): if comp.id == 'gcc': if not shutil.which('clang++'): raise unittest.SkipTest('Only one compiler found, cannot test.') return 'clang++', 'clang' if not is_real_gnu_compiler(shutil.which('g++')): raise unittest.SkipTest('Only one compiler found, cannot test.') return 'g++', 'gcc' self.helper_for_compiler('cpp', cb) @skip_if_not_language('objc') @skip_if_env_set('OBJC') def test_objc_compiler(self): def cb(comp): if comp.id == 'gcc': if not shutil.which('clang'): raise unittest.SkipTest('Only one compiler found, cannot test.') return 'clang', 'clang' if not is_real_gnu_compiler(shutil.which('gcc')): raise unittest.SkipTest('Only one compiler found, cannot test.') return 'gcc', 'gcc' self.helper_for_compiler('objc', cb) @skip_if_not_language('objcpp') @skip_if_env_set('OBJCXX') def test_objcpp_compiler(self): def cb(comp): if comp.id == 'gcc': if not shutil.which('clang++'): raise unittest.SkipTest('Only one compiler found, cannot test.') return 'clang++', 'clang' if not is_real_gnu_compiler(shutil.which('g++')): raise unittest.SkipTest('Only one compiler found, cannot test.') return 'g++', 'gcc' self.helper_for_compiler('objcpp', cb) @skip_if_not_language('d') @skip_if_env_set('DC') def test_d_compiler(self): def cb(comp): if comp.id == 'dmd': if shutil.which('ldc'): return 'ldc', 'ldc' elif shutil.which('gdc'): return 'gdc', 'gdc' else: raise unittest.SkipTest('No alternative dlang compiler found.') if shutil.which('dmd'): return 'dmd', 'dmd' raise unittest.SkipTest('No alternative dlang compiler found.') self.helper_for_compiler('d', cb) @skip_if_not_language('cs') @skip_if_env_set('CSC') def test_cs_compiler(self): def cb(comp): if comp.id == 'csc': if not shutil.which('mcs'): raise unittest.SkipTest('No alternate C# implementation.') return 'mcs', 'mcs' if not shutil.which('csc'): raise unittest.SkipTest('No alternate C# implementation.') return 'csc', 'csc' self.helper_for_compiler('cs', cb) @skip_if_not_language('fortran') @skip_if_env_set('FC') def test_fortran_compiler(self): def cb(comp): if comp.id == 'lcc': if shutil.which('lfortran'): return 'lfortran', 'lcc' raise unittest.SkipTest('No alternate Fortran implementation.') elif comp.id == 'gcc': if shutil.which('ifort'): # There is an ICC for windows (windows build, linux host), # but we don't support that ATM so lets not worry about it. if is_windows(): return 'ifort', 'intel-cl' return 'ifort', 'intel' elif shutil.which('flang'): return 'flang', 'flang' elif shutil.which('pgfortran'): return 'pgfortran', 'pgi' # XXX: there are several other fortran compilers meson # supports, but I don't have any of them to test with raise unittest.SkipTest('No alternate Fortran implementation.') if not shutil.which('gfortran'): raise unittest.SkipTest('No alternate Fortran implementation.') return 'gfortran', 'gcc' self.helper_for_compiler('fortran', cb) def _single_implementation_compiler(self, lang: str, binary: str, version_str: str, version: str) -> None: wrapper = self.helper_create_binary_wrapper(binary, version=version_str) env = get_fake_env() getter = getattr(env, 'detect_{}_compiler'.format(lang)) getter = functools.partial(getter, MachineChoice.HOST) env.binaries.host.binaries[lang] = [wrapper] compiler = getter() self.assertEqual(compiler.version, version) @skip_if_not_language('vala') @skip_if_env_set('VALAC') def test_vala_compiler(self): self._single_implementation_compiler( 'vala', 'valac', 'Vala 1.2345', '1.2345') @skip_if_not_language('rust') @skip_if_env_set('RUSTC') def test_rust_compiler(self): self._single_implementation_compiler( 'rust', 'rustc', 'rustc 1.2345', '1.2345') @skip_if_not_language('java') def test_java_compiler(self): self._single_implementation_compiler( 'java', 'javac', 'javac 9.99.77', '9.99.77') @skip_if_not_language('swift') def test_swift_compiler(self): wrapper = self.helper_create_binary_wrapper( 'swiftc', version='Swift 1.2345', outfile='stderr', extra_args={'Xlinker': 'macosx_version. PROJECT:ld - 1.2.3'}) env = get_fake_env() env.binaries.host.binaries['swift'] = [wrapper] compiler = env.detect_swift_compiler(MachineChoice.HOST) self.assertEqual(compiler.version, '1.2345') def test_native_file_dirs(self): testcase = os.path.join(self.unit_test_dir, '60 native file override') self.init(testcase, default_args=False, extra_args=['--native-file', os.path.join(testcase, 'nativefile')]) def test_native_file_dirs_overridden(self): testcase = os.path.join(self.unit_test_dir, '60 native file override') self.init(testcase, default_args=False, extra_args=['--native-file', os.path.join(testcase, 'nativefile'), '-Ddef_libdir=liblib', '-Dlibdir=liblib']) def test_compile_sys_path(self): testcase = os.path.join(self.common_test_dir, '1 trivial') # It really doesn't matter what's in the native file, just that it exists config = self.helper_create_native_file({'binaries': {'bash': 'false'}}) self.init(testcase, extra_args=['--native-file', config]) self.build() def test_user_options(self): testcase = os.path.join(self.common_test_dir, '41 options') for opt, value in [('testoption', 'some other val'), ('other_one', True), ('combo_opt', 'one'), ('array_opt', ['two']), ('integer_opt', 0), ('CaseSenSiTivE', 'SOME other Value'), ('CASESENSITIVE', 'some other Value')]: config = self.helper_create_native_file({'project options': {opt: value}}) with self.assertRaises(subprocess.CalledProcessError) as cm: self.init(testcase, extra_args=['--native-file', config]) self.assertRegex(cm.exception.stdout, r'Incorrect value to [a-z]+ option') def test_user_options_command_line_overrides(self): testcase = os.path.join(self.common_test_dir, '41 options') config = self.helper_create_native_file({'project options': {'other_one': True}}) self.init(testcase, extra_args=['--native-file', config, '-Dother_one=false']) def test_user_options_subproject(self): testcase = os.path.join(self.unit_test_dir, '80 user options for subproject') s = os.path.join(testcase, 'subprojects') if not os.path.exists(s): os.mkdir(s) s = os.path.join(s, 'sub') if not os.path.exists(s): sub = os.path.join(self.common_test_dir, '41 options') shutil.copytree(sub, s) for opt, value in [('testoption', 'some other val'), ('other_one', True), ('combo_opt', 'one'), ('array_opt', ['two']), ('integer_opt', 0)]: config = self.helper_create_native_file({'sub:project options': {opt: value}}) with self.assertRaises(subprocess.CalledProcessError) as cm: self.init(testcase, extra_args=['--native-file', config]) self.assertRegex(cm.exception.stdout, r'Incorrect value to [a-z]+ option') def test_option_bool(self): # Bools are allowed to be unquoted testcase = os.path.join(self.common_test_dir, '1 trivial') config = self.helper_create_native_file({'built-in options': {'werror': True}}) self.init(testcase, extra_args=['--native-file', config]) configuration = self.introspect('--buildoptions') for each in configuration: # Test that no-per subproject options are inherited from the parent if 'werror' in each['name']: self.assertEqual(each['value'], True) break else: self.fail('Did not find werror in build options?') def test_option_integer(self): # Bools are allowed to be unquoted testcase = os.path.join(self.common_test_dir, '1 trivial') config = self.helper_create_native_file({'built-in options': {'unity_size': 100}}) self.init(testcase, extra_args=['--native-file', config]) configuration = self.introspect('--buildoptions') for each in configuration: # Test that no-per subproject options are inherited from the parent if 'unity_size' in each['name']: self.assertEqual(each['value'], 100) break else: self.fail('Did not find unity_size in build options?') def test_builtin_options(self): testcase = os.path.join(self.common_test_dir, '2 cpp') config = self.helper_create_native_file({'built-in options': {'cpp_std': 'c++14'}}) self.init(testcase, extra_args=['--native-file', config]) configuration = self.introspect('--buildoptions') for each in configuration: if each['name'] == 'cpp_std': self.assertEqual(each['value'], 'c++14') break else: self.fail('Did not find werror in build options?') def test_builtin_options_conf_overrides_env(self): testcase = os.path.join(self.common_test_dir, '2 cpp') config = self.helper_create_native_file({'built-in options': {'pkg_config_path': '/foo'}}) self.init(testcase, extra_args=['--native-file', config], override_envvars={'PKG_CONFIG_PATH': '/bar'}) configuration = self.introspect('--buildoptions') for each in configuration: if each['name'] == 'pkg_config_path': self.assertEqual(each['value'], ['/foo']) break else: self.fail('Did not find pkg_config_path in build options?') def test_builtin_options_subprojects(self): testcase = os.path.join(self.common_test_dir, '99 subproject subdir') config = self.helper_create_native_file({'built-in options': {'default_library': 'both', 'c_args': ['-Dfoo']}, 'sub:built-in options': {'default_library': 'static'}}) self.init(testcase, extra_args=['--native-file', config]) configuration = self.introspect('--buildoptions') found = 0 for each in configuration: # Test that no-per subproject options are inherited from the parent if 'c_args' in each['name']: # This path will be hit twice, once for build and once for host, self.assertEqual(each['value'], ['-Dfoo']) found += 1 elif each['name'] == 'default_library': self.assertEqual(each['value'], 'both') found += 1 elif each['name'] == 'sub:default_library': self.assertEqual(each['value'], 'static') found += 1 self.assertEqual(found, 4, 'Did not find all three sections') def test_builtin_options_subprojects_overrides_buildfiles(self): # If the buildfile says subproject(... default_library: shared), ensure that's overwritten testcase = os.path.join(self.common_test_dir, '224 persubproject options') config = self.helper_create_native_file({'sub2:built-in options': {'default_library': 'shared'}}) with self.assertRaises((RuntimeError, subprocess.CalledProcessError)) as cm: self.init(testcase, extra_args=['--native-file', config]) if isinstance(cm, RuntimeError): check = str(cm.exception) else: check = cm.exception.stdout self.assertIn(check, 'Parent should override default_library') def test_builtin_options_subprojects_dont_inherits_parent_override(self): # If the buildfile says subproject(... default_library: shared), ensure that's overwritten testcase = os.path.join(self.common_test_dir, '224 persubproject options') config = self.helper_create_native_file({'built-in options': {'default_library': 'both'}}) self.init(testcase, extra_args=['--native-file', config]) def test_builtin_options_compiler_properties(self): # the properties section can have lang_args, and those need to be # overwritten by the built-in options testcase = os.path.join(self.common_test_dir, '1 trivial') config = self.helper_create_native_file({ 'built-in options': {'c_args': ['-DFOO']}, 'properties': {'c_args': ['-DBAR']}, }) self.init(testcase, extra_args=['--native-file', config]) configuration = self.introspect('--buildoptions') for each in configuration: if each['name'] == 'c_args': self.assertEqual(each['value'], ['-DFOO']) break else: self.fail('Did not find c_args in build options?') def test_builtin_options_compiler_properties_legacy(self): # The legacy placement in properties is still valid if a 'built-in # options' setting is present, but doesn't have the lang_args testcase = os.path.join(self.common_test_dir, '1 trivial') config = self.helper_create_native_file({ 'built-in options': {'default_library': 'static'}, 'properties': {'c_args': ['-DBAR']}, }) self.init(testcase, extra_args=['--native-file', config]) configuration = self.introspect('--buildoptions') for each in configuration: if each['name'] == 'c_args': self.assertEqual(each['value'], ['-DBAR']) break else: self.fail('Did not find c_args in build options?') def test_builtin_options_paths(self): # the properties section can have lang_args, and those need to be # overwritten by the built-in options testcase = os.path.join(self.common_test_dir, '1 trivial') config = self.helper_create_native_file({ 'built-in options': {'bindir': 'foo'}, 'paths': {'bindir': 'bar'}, }) self.init(testcase, extra_args=['--native-file', config]) configuration = self.introspect('--buildoptions') for each in configuration: if each['name'] == 'bindir': self.assertEqual(each['value'], 'foo') break else: self.fail('Did not find bindir in build options?') def test_builtin_options_paths_legacy(self): testcase = os.path.join(self.common_test_dir, '1 trivial') config = self.helper_create_native_file({ 'built-in options': {'default_library': 'static'}, 'paths': {'bindir': 'bar'}, }) self.init(testcase, extra_args=['--native-file', config]) configuration = self.introspect('--buildoptions') for each in configuration: if each['name'] == 'bindir': self.assertEqual(each['value'], 'bar') break else: self.fail('Did not find bindir in build options?') class CrossFileTests(BasePlatformTests): def setUp(self): super().setUp() self.current_config = 0 self.current_wrapper = 0 def _cross_file_generator(self, *, needs_exe_wrapper: bool = False, exe_wrapper: T.Optional[T.List[str]] = None) -> str: if is_windows(): raise unittest.SkipTest('Cannot run this test on non-mingw/non-cygwin windows') return textwrap.dedent(f"""\ [binaries] c = '{shutil.which('gcc' if is_sunos() else 'cc')}' ar = '{shutil.which('ar')}' strip = '{shutil.which('strip')}' exe_wrapper = {str(exe_wrapper) if exe_wrapper is not None else '[]'} [properties] needs_exe_wrapper = {needs_exe_wrapper} [host_machine] system = 'linux' cpu_family = 'x86' cpu = 'i686' endian = 'little' """) def _stub_exe_wrapper(self) -> str: return textwrap.dedent('''\ #!/usr/bin/env python3 import subprocess import sys sys.exit(subprocess.run(sys.argv[1:]).returncode) ''') def test_needs_exe_wrapper_true(self): testdir = os.path.join(self.unit_test_dir, '72 cross test passed') with tempfile.TemporaryDirectory() as d: p = Path(d) / 'crossfile' with p.open('wt') as f: f.write(self._cross_file_generator(needs_exe_wrapper=True)) self.init(testdir, extra_args=['--cross-file=' + str(p)]) out = self.run_target('test') self.assertRegex(out, r'Skipped:\s*1\s*\n') def test_needs_exe_wrapper_false(self): testdir = os.path.join(self.unit_test_dir, '72 cross test passed') with tempfile.TemporaryDirectory() as d: p = Path(d) / 'crossfile' with p.open('wt') as f: f.write(self._cross_file_generator(needs_exe_wrapper=False)) self.init(testdir, extra_args=['--cross-file=' + str(p)]) out = self.run_target('test') self.assertNotRegex(out, r'Skipped:\s*1\n') def test_needs_exe_wrapper_true_wrapper(self): testdir = os.path.join(self.unit_test_dir, '72 cross test passed') with tempfile.TemporaryDirectory() as d: s = Path(d) / 'wrapper.py' with s.open('wt') as f: f.write(self._stub_exe_wrapper()) s.chmod(0o774) p = Path(d) / 'crossfile' with p.open('wt') as f: f.write(self._cross_file_generator( needs_exe_wrapper=True, exe_wrapper=[str(s)])) self.init(testdir, extra_args=['--cross-file=' + str(p), '-Dexpect=true']) out = self.run_target('test') self.assertRegex(out, r'Ok:\s*3\s*\n') def test_cross_exe_passed_no_wrapper(self): testdir = os.path.join(self.unit_test_dir, '72 cross test passed') with tempfile.TemporaryDirectory() as d: p = Path(d) / 'crossfile' with p.open('wt') as f: f.write(self._cross_file_generator(needs_exe_wrapper=True)) self.init(testdir, extra_args=['--cross-file=' + str(p)]) self.build() out = self.run_target('test') self.assertRegex(out, r'Skipped:\s*1\s*\n') # The test uses mocking and thus requires that the current process is the # one to run the Meson steps. If we are using an external test executable # (most commonly in Debian autopkgtests) then the mocking won't work. @unittest.skipIf('MESON_EXE' in os.environ, 'MESON_EXE is defined, can not use mocking.') def test_cross_file_system_paths(self): if is_windows(): raise unittest.SkipTest('system crossfile paths not defined for Windows (yet)') testdir = os.path.join(self.common_test_dir, '1 trivial') cross_content = self._cross_file_generator() with tempfile.TemporaryDirectory() as d: dir_ = os.path.join(d, 'meson', 'cross') os.makedirs(dir_) with tempfile.NamedTemporaryFile('w', dir=dir_, delete=False) as f: f.write(cross_content) name = os.path.basename(f.name) with mock.patch.dict(os.environ, {'XDG_DATA_HOME': d}): self.init(testdir, extra_args=['--cross-file=' + name], inprocess=True) self.wipe() with mock.patch.dict(os.environ, {'XDG_DATA_DIRS': d}): os.environ.pop('XDG_DATA_HOME', None) self.init(testdir, extra_args=['--cross-file=' + name], inprocess=True) self.wipe() with tempfile.TemporaryDirectory() as d: dir_ = os.path.join(d, '.local', 'share', 'meson', 'cross') os.makedirs(dir_) with tempfile.NamedTemporaryFile('w', dir=dir_, delete=False) as f: f.write(cross_content) name = os.path.basename(f.name) # If XDG_DATA_HOME is set in the environment running the # tests this test will fail, os mock the environment, pop # it, then test with mock.patch.dict(os.environ): os.environ.pop('XDG_DATA_HOME', None) with mock.patch('mesonbuild.coredata.os.path.expanduser', lambda x: x.replace('~', d)): self.init(testdir, extra_args=['--cross-file=' + name], inprocess=True) self.wipe() def helper_create_cross_file(self, values): filename = os.path.join(self.builddir, 'generated{}.config'.format(self.current_config)) self.current_config += 1 with open(filename, 'wt') as f: for section, entries in values.items(): f.write('[{}]\n'.format(section)) for k, v in entries.items(): f.write("{}='{}'\n".format(k, v)) return filename def test_cross_file_dirs(self): testcase = os.path.join(self.unit_test_dir, '60 native file override') self.init(testcase, default_args=False, extra_args=['--native-file', os.path.join(testcase, 'nativefile'), '--cross-file', os.path.join(testcase, 'crossfile'), '-Ddef_bindir=binbar', '-Ddef_datadir=databar', '-Ddef_includedir=includebar', '-Ddef_infodir=infobar', '-Ddef_libdir=libbar', '-Ddef_libexecdir=libexecbar', '-Ddef_localedir=localebar', '-Ddef_localstatedir=localstatebar', '-Ddef_mandir=manbar', '-Ddef_sbindir=sbinbar', '-Ddef_sharedstatedir=sharedstatebar', '-Ddef_sysconfdir=sysconfbar']) def test_cross_file_dirs_overridden(self): testcase = os.path.join(self.unit_test_dir, '60 native file override') self.init(testcase, default_args=False, extra_args=['--native-file', os.path.join(testcase, 'nativefile'), '--cross-file', os.path.join(testcase, 'crossfile'), '-Ddef_libdir=liblib', '-Dlibdir=liblib', '-Ddef_bindir=binbar', '-Ddef_datadir=databar', '-Ddef_includedir=includebar', '-Ddef_infodir=infobar', '-Ddef_libexecdir=libexecbar', '-Ddef_localedir=localebar', '-Ddef_localstatedir=localstatebar', '-Ddef_mandir=manbar', '-Ddef_sbindir=sbinbar', '-Ddef_sharedstatedir=sharedstatebar', '-Ddef_sysconfdir=sysconfbar']) def test_cross_file_dirs_chain(self): # crossfile2 overrides crossfile overrides nativefile testcase = os.path.join(self.unit_test_dir, '60 native file override') self.init(testcase, default_args=False, extra_args=['--native-file', os.path.join(testcase, 'nativefile'), '--cross-file', os.path.join(testcase, 'crossfile'), '--cross-file', os.path.join(testcase, 'crossfile2'), '-Ddef_bindir=binbar2', '-Ddef_datadir=databar', '-Ddef_includedir=includebar', '-Ddef_infodir=infobar', '-Ddef_libdir=libbar', '-Ddef_libexecdir=libexecbar', '-Ddef_localedir=localebar', '-Ddef_localstatedir=localstatebar', '-Ddef_mandir=manbar', '-Ddef_sbindir=sbinbar', '-Ddef_sharedstatedir=sharedstatebar', '-Ddef_sysconfdir=sysconfbar']) def test_user_options(self): # This is just a touch test for cross file, since the implementation # shares code after loading from the files testcase = os.path.join(self.common_test_dir, '41 options') config = self.helper_create_cross_file({'project options': {'testoption': 'some other value'}}) with self.assertRaises(subprocess.CalledProcessError) as cm: self.init(testcase, extra_args=['--cross-file', config]) self.assertRegex(cm.exception.stdout, r'Incorrect value to [a-z]+ option') def test_builtin_options(self): testcase = os.path.join(self.common_test_dir, '2 cpp') config = self.helper_create_cross_file({'built-in options': {'cpp_std': 'c++14'}}) self.init(testcase, extra_args=['--cross-file', config]) configuration = self.introspect('--buildoptions') for each in configuration: if each['name'] == 'cpp_std': self.assertEqual(each['value'], 'c++14') break else: self.fail('No c++ standard set?') def test_builtin_options_per_machine(self): testcase = os.path.join(self.common_test_dir, '2 cpp') cross = self.helper_create_cross_file({'built-in options': {'pkg_config_path': '/cross/path', 'cpp_std': 'c++17'}}) native = self.helper_create_cross_file({'built-in options': {'pkg_config_path': '/native/path', 'cpp_std': 'c++14'}}) # Ensure that PKG_CONFIG_PATH is not set in the environment with mock.patch.dict('os.environ'): for k in ['PKG_CONFIG_PATH', 'PKG_CONFIG_PATH_FOR_BUILD']: try: del os.environ[k] except KeyError: pass self.init(testcase, extra_args=['--cross-file', cross, '--native-file', native]) configuration = self.introspect('--buildoptions') found = 0 for each in configuration: if each['name'] == 'pkg_config_path': self.assertEqual(each['value'], ['/cross/path']) found += 1 elif each['name'] == 'cpp_std': self.assertEqual(each['value'], 'c++17') found += 1 elif each['name'] == 'build.pkg_config_path': self.assertEqual(each['value'], ['/native/path']) found += 1 elif each['name'] == 'build.cpp_std': self.assertEqual(each['value'], 'c++14') found += 1 if found == 4: break self.assertEqual(found, 4, 'Did not find all sections.') def test_builtin_options_conf_overrides_env(self): testcase = os.path.join(self.common_test_dir, '2 cpp') config = self.helper_create_cross_file({'built-in options': {'pkg_config_path': '/native'}}) cross = self.helper_create_cross_file({'built-in options': {'pkg_config_path': '/cross'}}) self.init(testcase, extra_args=['--native-file', config, '--cross-file', cross], override_envvars={'PKG_CONFIG_PATH': '/bar', 'PKG_CONFIG_PATH_FOR_BUILD': '/dir'}) configuration = self.introspect('--buildoptions') found = 0 for each in configuration: if each['name'] == 'pkg_config_path': self.assertEqual(each['value'], ['/cross']) found += 1 elif each['name'] == 'build.pkg_config_path': self.assertEqual(each['value'], ['/native']) found += 1 if found == 2: break self.assertEqual(found, 2, 'Did not find all sections.') class TAPParserTests(unittest.TestCase): def assert_test(self, events, **kwargs): if 'explanation' not in kwargs: kwargs['explanation'] = None self.assertEqual(next(events), TAPParser.Test(**kwargs)) def assert_plan(self, events, **kwargs): if 'skipped' not in kwargs: kwargs['skipped'] = False if 'explanation' not in kwargs: kwargs['explanation'] = None self.assertEqual(next(events), TAPParser.Plan(**kwargs)) def assert_version(self, events, **kwargs): self.assertEqual(next(events), TAPParser.Version(**kwargs)) def assert_error(self, events): self.assertEqual(type(next(events)), TAPParser.Error) def assert_bailout(self, events, **kwargs): self.assertEqual(next(events), TAPParser.Bailout(**kwargs)) def assert_last(self, events): with self.assertRaises(StopIteration): next(events) def parse_tap(self, s): parser = TAPParser() return iter(parser.parse(io.StringIO(s))) def parse_tap_v13(self, s): events = self.parse_tap('TAP version 13\n' + s) self.assert_version(events, version=13) return events def test_empty(self): events = self.parse_tap('') self.assert_last(events) def test_empty_plan(self): events = self.parse_tap('1..0') self.assert_plan(events, num_tests=0, late=False, skipped=True) self.assert_last(events) def test_plan_directive(self): events = self.parse_tap('1..0 # skipped for some reason') self.assert_plan(events, num_tests=0, late=False, skipped=True, explanation='for some reason') self.assert_last(events) events = self.parse_tap('1..1 # skipped for some reason\nok 1') self.assert_error(events) self.assert_plan(events, num_tests=1, late=False, skipped=True, explanation='for some reason') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_last(events) events = self.parse_tap('1..1 # todo not supported here\nok 1') self.assert_error(events) self.assert_plan(events, num_tests=1, late=False, skipped=False, explanation='not supported here') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_last(events) def test_one_test_ok(self): events = self.parse_tap('ok') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_last(events) def test_one_test_with_number(self): events = self.parse_tap('ok 1') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_last(events) def test_one_test_with_name(self): events = self.parse_tap('ok 1 abc') self.assert_test(events, number=1, name='abc', result=TestResult.OK) self.assert_last(events) def test_one_test_not_ok(self): events = self.parse_tap('not ok') self.assert_test(events, number=1, name='', result=TestResult.FAIL) self.assert_last(events) def test_one_test_todo(self): events = self.parse_tap('not ok 1 abc # TODO') self.assert_test(events, number=1, name='abc', result=TestResult.EXPECTEDFAIL) self.assert_last(events) events = self.parse_tap('ok 1 abc # TODO') self.assert_test(events, number=1, name='abc', result=TestResult.UNEXPECTEDPASS) self.assert_last(events) def test_one_test_skip(self): events = self.parse_tap('ok 1 abc # SKIP') self.assert_test(events, number=1, name='abc', result=TestResult.SKIP) self.assert_last(events) def test_one_test_skip_failure(self): events = self.parse_tap('not ok 1 abc # SKIP') self.assert_test(events, number=1, name='abc', result=TestResult.FAIL) self.assert_last(events) def test_many_early_plan(self): events = self.parse_tap('1..4\nok 1\nnot ok 2\nok 3\nnot ok 4') self.assert_plan(events, num_tests=4, late=False) self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_test(events, number=2, name='', result=TestResult.FAIL) self.assert_test(events, number=3, name='', result=TestResult.OK) self.assert_test(events, number=4, name='', result=TestResult.FAIL) self.assert_last(events) def test_many_late_plan(self): events = self.parse_tap('ok 1\nnot ok 2\nok 3\nnot ok 4\n1..4') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_test(events, number=2, name='', result=TestResult.FAIL) self.assert_test(events, number=3, name='', result=TestResult.OK) self.assert_test(events, number=4, name='', result=TestResult.FAIL) self.assert_plan(events, num_tests=4, late=True) self.assert_last(events) def test_directive_case(self): events = self.parse_tap('ok 1 abc # skip') self.assert_test(events, number=1, name='abc', result=TestResult.SKIP) self.assert_last(events) events = self.parse_tap('ok 1 abc # ToDo') self.assert_test(events, number=1, name='abc', result=TestResult.UNEXPECTEDPASS) self.assert_last(events) def test_directive_explanation(self): events = self.parse_tap('ok 1 abc # skip why') self.assert_test(events, number=1, name='abc', result=TestResult.SKIP, explanation='why') self.assert_last(events) events = self.parse_tap('ok 1 abc # ToDo Because') self.assert_test(events, number=1, name='abc', result=TestResult.UNEXPECTEDPASS, explanation='Because') self.assert_last(events) def test_one_test_early_plan(self): events = self.parse_tap('1..1\nok') self.assert_plan(events, num_tests=1, late=False) self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_last(events) def test_one_test_late_plan(self): events = self.parse_tap('ok\n1..1') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_plan(events, num_tests=1, late=True) self.assert_last(events) def test_out_of_order(self): events = self.parse_tap('ok 2') self.assert_error(events) self.assert_test(events, number=2, name='', result=TestResult.OK) self.assert_last(events) def test_middle_plan(self): events = self.parse_tap('ok 1\n1..2\nok 2') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_plan(events, num_tests=2, late=True) self.assert_error(events) self.assert_test(events, number=2, name='', result=TestResult.OK) self.assert_last(events) def test_too_many_plans(self): events = self.parse_tap('1..1\n1..2\nok 1') self.assert_plan(events, num_tests=1, late=False) self.assert_error(events) self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_last(events) def test_too_many(self): events = self.parse_tap('ok 1\nnot ok 2\n1..1') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_test(events, number=2, name='', result=TestResult.FAIL) self.assert_plan(events, num_tests=1, late=True) self.assert_error(events) self.assert_last(events) events = self.parse_tap('1..1\nok 1\nnot ok 2') self.assert_plan(events, num_tests=1, late=False) self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_test(events, number=2, name='', result=TestResult.FAIL) self.assert_error(events) self.assert_last(events) def test_too_few(self): events = self.parse_tap('ok 1\nnot ok 2\n1..3') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_test(events, number=2, name='', result=TestResult.FAIL) self.assert_plan(events, num_tests=3, late=True) self.assert_error(events) self.assert_last(events) events = self.parse_tap('1..3\nok 1\nnot ok 2') self.assert_plan(events, num_tests=3, late=False) self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_test(events, number=2, name='', result=TestResult.FAIL) self.assert_error(events) self.assert_last(events) def test_too_few_bailout(self): events = self.parse_tap('1..3\nok 1\nnot ok 2\nBail out! no third test') self.assert_plan(events, num_tests=3, late=False) self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_test(events, number=2, name='', result=TestResult.FAIL) self.assert_bailout(events, message='no third test') self.assert_last(events) def test_diagnostics(self): events = self.parse_tap('1..1\n# ignored\nok 1') self.assert_plan(events, num_tests=1, late=False) self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_last(events) events = self.parse_tap('# ignored\n1..1\nok 1\n# ignored too') self.assert_plan(events, num_tests=1, late=False) self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_last(events) events = self.parse_tap('# ignored\nok 1\n1..1\n# ignored too') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_plan(events, num_tests=1, late=True) self.assert_last(events) def test_empty_line(self): events = self.parse_tap('1..1\n\nok 1') self.assert_plan(events, num_tests=1, late=False) self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_last(events) def test_unexpected(self): events = self.parse_tap('1..1\ninvalid\nok 1') self.assert_plan(events, num_tests=1, late=False) self.assert_error(events) self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_last(events) def test_version(self): events = self.parse_tap('TAP version 13\n') self.assert_version(events, version=13) self.assert_last(events) events = self.parse_tap('TAP version 12\n') self.assert_error(events) self.assert_last(events) events = self.parse_tap('1..0\nTAP version 13\n') self.assert_plan(events, num_tests=0, late=False, skipped=True) self.assert_error(events) self.assert_last(events) def test_yaml(self): events = self.parse_tap_v13('ok\n ---\n foo: abc\n bar: def\n ...\nok 2') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_test(events, number=2, name='', result=TestResult.OK) self.assert_last(events) events = self.parse_tap_v13('ok\n ---\n foo: abc\n bar: def') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_error(events) self.assert_last(events) events = self.parse_tap_v13('ok 1\n ---\n foo: abc\n bar: def\nnot ok 2') self.assert_test(events, number=1, name='', result=TestResult.OK) self.assert_error(events) self.assert_test(events, number=2, name='', result=TestResult.FAIL) self.assert_last(events) class SubprojectsCommandTests(BasePlatformTests): def setUp(self): super().setUp() self.root_dir = Path(self.builddir) self.project_dir = self.root_dir / 'src' self._create_project(self.project_dir) self.subprojects_dir = self.project_dir / 'subprojects' os.makedirs(str(self.subprojects_dir)) def _create_project(self, path, project_name='dummy'): os.makedirs(str(path), exist_ok=True) with open(str(path / 'meson.build'), 'w') as f: f.write("project('{}')".format(project_name)) def _git(self, cmd, workdir): return git(cmd, str(workdir), check=True)[1].strip() def _git_config(self, workdir): self._git(['config', 'user.name', 'Meson Test'], workdir) self._git(['config', 'user.email', 'meson.test@example.com'], workdir) def _git_remote(self, cmd, name): return self._git(cmd, self.root_dir / name) def _git_local(self, cmd, name): return self._git(cmd, self.subprojects_dir / name) def _git_local_branch(self, name): # Same as `git branch --show-current` but compatible with older git version branch = self._git_local(['rev-parse', '--abbrev-ref', 'HEAD'], name) return branch if branch != 'HEAD' else '' def _git_local_commit(self, name, ref='HEAD'): return self._git_local(['rev-parse', ref], name) def _git_remote_commit(self, name, ref='HEAD'): return self._git_remote(['rev-parse', ref], name) def _git_create_repo(self, path): # If a user has git configuration init.defaultBranch set we want to override that with tempfile.TemporaryDirectory() as d: out = git(['--version'], str(d))[1] if version_compare(mesonbuild.environment.search_version(out), '>= 2.28'): extra_cmd = ['--initial-branch', 'master'] else: extra_cmd = [] self._create_project(path) self._git(['init'] + extra_cmd, path) self._git_config(path) self._git(['add', '.'], path) self._git(['commit', '-m', 'Initial commit'], path) def _git_create_remote_repo(self, name): self._git_create_repo(self.root_dir / name) def _git_create_local_repo(self, name): self._git_create_repo(self.subprojects_dir / name) def _git_create_remote_commit(self, name, branch): self._git_remote(['checkout', branch], name) self._git_remote(['commit', '--allow-empty', '-m', 'initial {} commit'.format(branch)], name) def _git_create_remote_branch(self, name, branch): self._git_remote(['checkout', '-b', branch], name) self._git_remote(['commit', '--allow-empty', '-m', 'initial {} commit'.format(branch)], name) def _git_create_remote_tag(self, name, tag): self._git_remote(['commit', '--allow-empty', '-m', 'tag {} commit'.format(tag)], name) self._git_remote(['tag', tag], name) def _wrap_create_git(self, name, revision='master'): path = self.root_dir / name with open(str((self.subprojects_dir / name).with_suffix('.wrap')), 'w') as f: f.write(textwrap.dedent( ''' [wrap-git] url={} revision={} '''.format(os.path.abspath(str(path)), revision))) def _wrap_create_file(self, name, tarball='dummy.tar.gz'): path = self.root_dir / tarball with open(str((self.subprojects_dir / name).with_suffix('.wrap')), 'w') as f: f.write(textwrap.dedent( ''' [wrap-file] source_url={} '''.format(os.path.abspath(str(path))))) def _subprojects_cmd(self, args): return self._run(self.meson_command + ['subprojects'] + args, workdir=str(self.project_dir)) def test_git_update(self): subp_name = 'sub1' # Create a fake remote git repository and a wrap file. Checks that # "meson subprojects download" works. self._git_create_remote_repo(subp_name) self._wrap_create_git(subp_name) self._subprojects_cmd(['download']) self.assertPathExists(str(self.subprojects_dir / subp_name)) self._git_config(self.subprojects_dir / subp_name) # Create a new remote branch and update the wrap file. Checks that # "meson subprojects update --reset" checkout the new branch. self._git_create_remote_branch(subp_name, 'newbranch') self._wrap_create_git(subp_name, 'newbranch') self._subprojects_cmd(['update', '--reset']) self.assertEqual(self._git_local_branch(subp_name), 'newbranch') self.assertEqual(self._git_local_commit(subp_name), self._git_remote_commit(subp_name, 'newbranch')) # Update remote newbranch. Checks the new commit is pulled into existing # local newbranch. Make sure it does not print spurious 'git stash' message. self._git_create_remote_commit(subp_name, 'newbranch') out = self._subprojects_cmd(['update', '--reset']) self.assertNotIn('No local changes to save', out) self.assertEqual(self._git_local_branch(subp_name), 'newbranch') self.assertEqual(self._git_local_commit(subp_name), self._git_remote_commit(subp_name, 'newbranch')) # Update remote newbranch and switch to another branch. Checks that it # switch current branch to newbranch and pull latest commit. self._git_local(['checkout', 'master'], subp_name) self._git_create_remote_commit(subp_name, 'newbranch') self._subprojects_cmd(['update', '--reset']) self.assertEqual(self._git_local_branch(subp_name), 'newbranch') self.assertEqual(self._git_local_commit(subp_name), self._git_remote_commit(subp_name, 'newbranch')) # Stage some local changes then update. Checks that local changes got # stashed. self._create_project(self.subprojects_dir / subp_name, 'new_project_name') self._git_local(['add', '.'], subp_name) self._git_create_remote_commit(subp_name, 'newbranch') self._subprojects_cmd(['update', '--reset']) self.assertEqual(self._git_local_branch(subp_name), 'newbranch') self.assertEqual(self._git_local_commit(subp_name), self._git_remote_commit(subp_name, 'newbranch')) self.assertTrue(self._git_local(['stash', 'list'], subp_name)) # Create a new remote tag and update the wrap file. Checks that # "meson subprojects update --reset" checkout the new tag in detached mode. self._git_create_remote_tag(subp_name, 'newtag') self._wrap_create_git(subp_name, 'newtag') self._subprojects_cmd(['update', '--reset']) self.assertEqual(self._git_local_branch(subp_name), '') self.assertEqual(self._git_local_commit(subp_name), self._git_remote_commit(subp_name, 'newtag')) # Create a new remote commit and update the wrap file with the commit id. # Checks that "meson subprojects update --reset" checkout the new commit # in detached mode. self._git_local(['checkout', 'master'], subp_name) self._git_create_remote_commit(subp_name, 'newbranch') new_commit = self._git_remote(['rev-parse', 'HEAD'], subp_name) self._wrap_create_git(subp_name, new_commit) self._subprojects_cmd(['update', '--reset']) self.assertEqual(self._git_local_branch(subp_name), '') self.assertEqual(self._git_local_commit(subp_name), new_commit) # Create a local project not in a git repository, then update it with # a git wrap. Without --reset it should print error message and return # failure. With --reset it should delete existing project and clone the # new project. subp_name = 'sub2' self._create_project(self.subprojects_dir / subp_name) self._git_create_remote_repo(subp_name) self._wrap_create_git(subp_name) with self.assertRaises(subprocess.CalledProcessError) as cm: self._subprojects_cmd(['update']) self.assertIn('Not a git repository', cm.exception.output) self._subprojects_cmd(['update', '--reset']) self.assertEqual(self._git_local_commit(subp_name), self._git_remote_commit(subp_name)) @skipIfNoExecutable('true') def test_foreach(self): self._create_project(self.subprojects_dir / 'sub_file') self._wrap_create_file('sub_file') self._git_create_local_repo('sub_git') self._wrap_create_git('sub_git') self._git_create_local_repo('sub_git_no_wrap') def ran_in(s): ret = [] prefix = 'Executing command in ' for l in s.splitlines(): if l.startswith(prefix): ret.append(l[len(prefix):]) return sorted(ret) dummy_cmd = ['true'] out = self._subprojects_cmd(['foreach'] + dummy_cmd) self.assertEqual(ran_in(out), sorted(['subprojects/sub_file', 'subprojects/sub_git', 'subprojects/sub_git_no_wrap'])) out = self._subprojects_cmd(['foreach', '--types', 'git,file'] + dummy_cmd) self.assertEqual(ran_in(out), sorted(['subprojects/sub_file', 'subprojects/sub_git'])) out = self._subprojects_cmd(['foreach', '--types', 'file'] + dummy_cmd) self.assertEqual(ran_in(out), ['subprojects/sub_file']) out = self._subprojects_cmd(['foreach', '--types', 'git'] + dummy_cmd) self.assertEqual(ran_in(out), ['subprojects/sub_git']) def _clang_at_least(compiler: 'Compiler', minver: str, apple_minver: T.Optional[str]) -> bool: if isinstance(compiler, (mesonbuild.compilers.AppleClangCCompiler, mesonbuild.compilers.AppleClangCPPCompiler)): if apple_minver is None: return False return version_compare(compiler.version, apple_minver) return version_compare(compiler.version, minver) def unset_envs(): # For unit tests we must fully control all command lines # so that there are no unexpected changes coming from the # environment, for example when doing a package build. varnames = ['CPPFLAGS', 'LDFLAGS'] + list(mesonbuild.compilers.compilers.CFLAGS_MAPPING.values()) for v in varnames: if v in os.environ: del os.environ[v] def convert_args(argv): # If we got passed a list of tests, pass it on pytest_args = ['-v'] if '-v' in argv else [] test_list = [] for arg in argv: if arg.startswith('-'): if arg in ('-f', '--failfast'): arg = '--exitfirst' pytest_args.append(arg) continue # ClassName.test_name => 'ClassName and test_name' if '.' in arg: arg = ' and '.join(arg.split('.')) test_list.append(arg) if test_list: pytest_args += ['-k', ' or '.join(test_list)] return pytest_args def running_single_tests(argv, cases): got_test_arg = False for arg in argv: if arg.startswith('-'): continue for case in cases: if not arg.startswith(case): continue if '.' not in arg: # Got a testcase, done return False got_test_arg = True return got_test_arg def main(): unset_envs() cases = ['InternalTests', 'DataTests', 'AllPlatformTests', 'FailureTests', 'PythonTests', 'NativeFileTests', 'RewriterTests', 'CrossFileTests', 'TAPParserTests', 'SubprojectsCommandTests', 'LinuxlikeTests', 'LinuxCrossArmTests', 'LinuxCrossMingwTests', 'WindowsTests', 'DarwinTests'] try: import pytest # noqa: F401 # Need pytest-xdist for `-n` arg import xdist # noqa: F401 pytest_args = [] # Don't use pytest-xdist when running single unit tests since it wastes # time spawning a lot of processes to distribute tests to in that case. if not running_single_tests(sys.argv, cases): pytest_args += ['-n', 'auto'] pytest_args += ['./run_unittests.py'] pytest_args += convert_args(sys.argv[1:]) return subprocess.run(python_command + ['-m', 'pytest'] + pytest_args).returncode except ImportError: print('pytest-xdist not found, using unittest instead') # Fallback to plain unittest. return unittest.main(defaultTest=cases, buffer=True) if __name__ == '__main__': print('Meson build system', mesonbuild.coredata.version, 'Unit Tests') start = time.monotonic() try: raise SystemExit(main()) finally: print('Total time: {:.3f} seconds'.format(time.monotonic() - start))
true
true
f7f9fd75438250a3f49a7fedc87cc5c32d64ee2d
124
py
Python
knowledge_share/apps.py
vintasoftware/django-knowledge-share
2278a1ee0b47d4c8f3f4e7730558a989247e6b60
[ "MIT" ]
37
2017-02-19T12:40:30.000Z
2021-11-30T06:56:02.000Z
knowledge_share/apps.py
vintasoftware/django-knowledge-share
2278a1ee0b47d4c8f3f4e7730558a989247e6b60
[ "MIT" ]
21
2017-02-15T19:42:38.000Z
2021-05-13T16:52:31.000Z
knowledge_share/apps.py
vintasoftware/django-knowledge-share
2278a1ee0b47d4c8f3f4e7730558a989247e6b60
[ "MIT" ]
4
2017-03-02T13:11:35.000Z
2020-10-23T02:10:26.000Z
# -*- coding: utf-8 from django.apps import AppConfig class KnowledgeShareConfig(AppConfig): name = 'knowledge_share'
17.714286
38
0.741935
from django.apps import AppConfig class KnowledgeShareConfig(AppConfig): name = 'knowledge_share'
true
true
f7f9fda8a2fc91f384b62d3ab46059335846c12e
1,323
py
Python
fabfile/testbeds/testbed_sanity_a6s32_ubuntu_grizzly_multicfgm.py
GaryGaryWU/contrail_fabric_util
70b944afe801593cd2664ae46e87363534085bcc
[ "Apache-2.0" ]
null
null
null
fabfile/testbeds/testbed_sanity_a6s32_ubuntu_grizzly_multicfgm.py
GaryGaryWU/contrail_fabric_util
70b944afe801593cd2664ae46e87363534085bcc
[ "Apache-2.0" ]
null
null
null
fabfile/testbeds/testbed_sanity_a6s32_ubuntu_grizzly_multicfgm.py
GaryGaryWU/contrail_fabric_util
70b944afe801593cd2664ae46e87363534085bcc
[ "Apache-2.0" ]
null
null
null
from fabric.api import env host1 = 'root@10.84.13.32' host2 = 'root@10.84.13.33' host3 = 'root@10.84.13.38' host4 = 'root@10.84.13.19' host5 = 'root@10.84.13.22' ext_routers = [] router_asn = 64512 public_vn_rtgt = 10003 public_vn_subnet = "10.204.219.32/29" host_build = 'stack@10.84.24.64' env.roledefs = { 'all': [host1, host2, host3, host4, host5], 'cfgm': [host1, host2], 'openstack': [host3], 'control': [host1, host2], 'compute': [host4, host5], 'collector': [host1], 'webui': [host1], 'database': [host1, host2, host3], 'build': [host_build], } env.hostnames = { 'all': ['a6s32', 'a6s33', 'a6s38', 'a6s19', 'a6s22'] } env.password = 'c0ntrail123' env.passwords = { host1: 'c0ntrail123', host2: 'c0ntrail123', host3: 'c0ntrail123', host4: 'c0ntrail123', host5: 'c0ntrail123', host_build: 'contrail123', } env.ostypes = { host1:'ubuntu', host2:'ubuntu', host3:'ubuntu', host4:'ubuntu', host5:'ubuntu', } env.test_repo_dir="/home/stack/ubuntu_sanity/contrail-test" env.mail_from='vjoshi@juniper.net' env.mail_to='dl-contrail-sw@juniper.net' multi_tenancy=True env.encap_priority="'MPLSoUDP','MPLSoGRE','VXLAN'" env.mail_server='10.84.24.64' env.mail_port='4000' env.log_scenario='Ubuntu-Grizzly Five-Node Sanity[Multi CFGM]'
22.423729
62
0.650038
from fabric.api import env host1 = 'root@10.84.13.32' host2 = 'root@10.84.13.33' host3 = 'root@10.84.13.38' host4 = 'root@10.84.13.19' host5 = 'root@10.84.13.22' ext_routers = [] router_asn = 64512 public_vn_rtgt = 10003 public_vn_subnet = "10.204.219.32/29" host_build = 'stack@10.84.24.64' env.roledefs = { 'all': [host1, host2, host3, host4, host5], 'cfgm': [host1, host2], 'openstack': [host3], 'control': [host1, host2], 'compute': [host4, host5], 'collector': [host1], 'webui': [host1], 'database': [host1, host2, host3], 'build': [host_build], } env.hostnames = { 'all': ['a6s32', 'a6s33', 'a6s38', 'a6s19', 'a6s22'] } env.password = 'c0ntrail123' env.passwords = { host1: 'c0ntrail123', host2: 'c0ntrail123', host3: 'c0ntrail123', host4: 'c0ntrail123', host5: 'c0ntrail123', host_build: 'contrail123', } env.ostypes = { host1:'ubuntu', host2:'ubuntu', host3:'ubuntu', host4:'ubuntu', host5:'ubuntu', } env.test_repo_dir="/home/stack/ubuntu_sanity/contrail-test" env.mail_from='vjoshi@juniper.net' env.mail_to='dl-contrail-sw@juniper.net' multi_tenancy=True env.encap_priority="'MPLSoUDP','MPLSoGRE','VXLAN'" env.mail_server='10.84.24.64' env.mail_port='4000' env.log_scenario='Ubuntu-Grizzly Five-Node Sanity[Multi CFGM]'
true
true
f7f9ff010b2b4f8a00cbf81e975bdca3180081db
7,005
py
Python
ingestion/src/metadata/ingestion/source/mlflow.py
troyel/OpenMetadata
4577f12bfde471afd8655ce4ee949fcca3d7fd95
[ "Apache-2.0" ]
1
2022-03-17T08:55:30.000Z
2022-03-17T08:55:30.000Z
ingestion/src/metadata/ingestion/source/mlflow.py
troyel/OpenMetadata
4577f12bfde471afd8655ce4ee949fcca3d7fd95
[ "Apache-2.0" ]
null
null
null
ingestion/src/metadata/ingestion/source/mlflow.py
troyel/OpenMetadata
4577f12bfde471afd8655ce4ee949fcca3d7fd95
[ "Apache-2.0" ]
null
null
null
# Copyright 2021 Collate # 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. """ml flow source module""" import ast import logging from dataclasses import dataclass, field from typing import Iterable, List, Optional from mlflow.entities import RunData from mlflow.entities.model_registry import ModelVersion from mlflow.tracking import MlflowClient from metadata.generated.schema.api.data.createMlModel import CreateMlModelRequest from metadata.generated.schema.entity.data.mlmodel import ( FeatureType, MlFeature, MlHyperParameter, MlStore, ) from metadata.ingestion.api.common import ConfigModel, WorkflowContext from metadata.ingestion.api.source import Source, SourceStatus logger: logging.Logger = logging.getLogger(__name__) @dataclass class MlFlowStatus(SourceStatus): """ ML Model specific Status """ success: List[str] = field(default_factory=list) failures: List[str] = field(default_factory=list) warnings: List[str] = field(default_factory=list) def scanned(self, record: str) -> None: """ Log successful ML Model scans """ self.success.append(record) logger.info("ML Model scanned: %s", record) def failed(self, model_name: str, reason: str) -> None: """ Log failed ML Model scans """ self.failures.append(model_name) logger.error("ML Model failed: %s - %s", model_name, reason) def warned(self, model_name: str, reason: str) -> None: """ Log Ml Model with warnings """ self.warnings.append(model_name) logger.warning("ML Model warning: %s - %s", model_name, reason) class MlFlowConnectionConfig(ConfigModel): """ Required information to extract data from MLFlow """ tracking_uri: str registry_uri: Optional[str] class MlflowSource(Source[CreateMlModelRequest]): """ Source implementation to ingest MLFlow data. We will iterate on the registered ML Models and prepare an iterator of CreateMlModelRequest """ def __init__(self, config: MlFlowConnectionConfig, ctx: WorkflowContext): super().__init__(ctx) self.client = MlflowClient( tracking_uri=config.tracking_uri, registry_uri=config.registry_uri if config.registry_uri else None, ) self.status = MlFlowStatus() def prepare(self): pass @classmethod def create( cls, config_dict: dict, metadata_config_dict: dict, ctx: WorkflowContext ): config = MlFlowConnectionConfig.parse_obj(config_dict) return cls(config, ctx) def next_record(self) -> Iterable[CreateMlModelRequest]: """ Fetch all registered models from MlFlow. We are setting the `algorithm` to a constant as there is not a non-trivial generic approach for retrieving the algorithm from the registry. """ for model in self.client.list_registered_models(): # Get the latest version latest_version: Optional[ModelVersion] = next( ( ver for ver in model.latest_versions if ver.last_updated_timestamp == model.last_updated_timestamp ), None, ) if not latest_version: self.status.failed(model.name, reason="Invalid version") continue run = self.client.get_run(latest_version.run_id) self.status.scanned(model.name) yield CreateMlModelRequest( name=model.name, description=model.description, algorithm="mlflow", # Setting this to a constant mlHyperParameters=self._get_hyper_params(run.data), mlFeatures=self._get_ml_features( run.data, latest_version.run_id, model.name ), mlStore=self._get_ml_store(latest_version), ) @staticmethod def _get_hyper_params(data: RunData) -> Optional[List[MlHyperParameter]]: """ Get the hyper parameters from the parameters logged in the run data object. """ if data.params: return [ MlHyperParameter(name=param[0], value=param[1]) for param in data.params.items() ] return None @staticmethod def _get_ml_store(version: ModelVersion) -> Optional[MlStore]: """ Get the Ml Store from the model version object """ if version.source: return MlStore(storage=version.source) return None def _get_ml_features( self, data: RunData, run_id: str, model_name: str ) -> Optional[List[MlFeature]]: """ The RunData object comes with stringified `tags`. Let's transform those and try to extract the `signature` information """ if data.tags: try: props = ast.literal_eval(data.tags["mlflow.log-model.history"]) latest_props = next( (prop for prop in props if prop["run_id"] == run_id), None ) if not latest_props: reason = f"Cannot find the run ID properties for {run_id}" logging.warning(reason) self.status.warned(model_name, reason) return None if latest_props.get("signature") and latest_props["signature"].get( "inputs" ): features = ast.literal_eval(latest_props["signature"]["inputs"]) return [ MlFeature( name=feature["name"], dataType=FeatureType.categorical if feature["type"] == "string" else FeatureType.numerical, ) for feature in features ] # pylint: disable=broad-except) except Exception as exc: reason = f"Cannot extract properties from RunData {exc}" logging.warning(reason) self.status.warned(model_name, reason) return None def get_status(self) -> SourceStatus: return self.status def close(self) -> None: """ Don't need to close the client """
32.733645
84
0.601856
import ast import logging from dataclasses import dataclass, field from typing import Iterable, List, Optional from mlflow.entities import RunData from mlflow.entities.model_registry import ModelVersion from mlflow.tracking import MlflowClient from metadata.generated.schema.api.data.createMlModel import CreateMlModelRequest from metadata.generated.schema.entity.data.mlmodel import ( FeatureType, MlFeature, MlHyperParameter, MlStore, ) from metadata.ingestion.api.common import ConfigModel, WorkflowContext from metadata.ingestion.api.source import Source, SourceStatus logger: logging.Logger = logging.getLogger(__name__) @dataclass class MlFlowStatus(SourceStatus): success: List[str] = field(default_factory=list) failures: List[str] = field(default_factory=list) warnings: List[str] = field(default_factory=list) def scanned(self, record: str) -> None: self.success.append(record) logger.info("ML Model scanned: %s", record) def failed(self, model_name: str, reason: str) -> None: self.failures.append(model_name) logger.error("ML Model failed: %s - %s", model_name, reason) def warned(self, model_name: str, reason: str) -> None: self.warnings.append(model_name) logger.warning("ML Model warning: %s - %s", model_name, reason) class MlFlowConnectionConfig(ConfigModel): tracking_uri: str registry_uri: Optional[str] class MlflowSource(Source[CreateMlModelRequest]): def __init__(self, config: MlFlowConnectionConfig, ctx: WorkflowContext): super().__init__(ctx) self.client = MlflowClient( tracking_uri=config.tracking_uri, registry_uri=config.registry_uri if config.registry_uri else None, ) self.status = MlFlowStatus() def prepare(self): pass @classmethod def create( cls, config_dict: dict, metadata_config_dict: dict, ctx: WorkflowContext ): config = MlFlowConnectionConfig.parse_obj(config_dict) return cls(config, ctx) def next_record(self) -> Iterable[CreateMlModelRequest]: for model in self.client.list_registered_models(): latest_version: Optional[ModelVersion] = next( ( ver for ver in model.latest_versions if ver.last_updated_timestamp == model.last_updated_timestamp ), None, ) if not latest_version: self.status.failed(model.name, reason="Invalid version") continue run = self.client.get_run(latest_version.run_id) self.status.scanned(model.name) yield CreateMlModelRequest( name=model.name, description=model.description, algorithm="mlflow", mlHyperParameters=self._get_hyper_params(run.data), mlFeatures=self._get_ml_features( run.data, latest_version.run_id, model.name ), mlStore=self._get_ml_store(latest_version), ) @staticmethod def _get_hyper_params(data: RunData) -> Optional[List[MlHyperParameter]]: if data.params: return [ MlHyperParameter(name=param[0], value=param[1]) for param in data.params.items() ] return None @staticmethod def _get_ml_store(version: ModelVersion) -> Optional[MlStore]: if version.source: return MlStore(storage=version.source) return None def _get_ml_features( self, data: RunData, run_id: str, model_name: str ) -> Optional[List[MlFeature]]: if data.tags: try: props = ast.literal_eval(data.tags["mlflow.log-model.history"]) latest_props = next( (prop for prop in props if prop["run_id"] == run_id), None ) if not latest_props: reason = f"Cannot find the run ID properties for {run_id}" logging.warning(reason) self.status.warned(model_name, reason) return None if latest_props.get("signature") and latest_props["signature"].get( "inputs" ): features = ast.literal_eval(latest_props["signature"]["inputs"]) return [ MlFeature( name=feature["name"], dataType=FeatureType.categorical if feature["type"] == "string" else FeatureType.numerical, ) for feature in features ] except Exception as exc: reason = f"Cannot extract properties from RunData {exc}" logging.warning(reason) self.status.warned(model_name, reason) return None def get_status(self) -> SourceStatus: return self.status def close(self) -> None:
true
true
f7f9ff7db5f76a1eb3cfc7aa630a3bbd4a2f2502
2,642
py
Python
src/python/murder_in_the_dark_v1/prototype_junk/test.py
paul-felt/nerf-boom
72bbece49a187ae0896b51f01388a8a3d5cdaec8
[ "Apache-2.0" ]
null
null
null
src/python/murder_in_the_dark_v1/prototype_junk/test.py
paul-felt/nerf-boom
72bbece49a187ae0896b51f01388a8a3d5cdaec8
[ "Apache-2.0" ]
null
null
null
src/python/murder_in_the_dark_v1/prototype_junk/test.py
paul-felt/nerf-boom
72bbece49a187ae0896b51f01388a8a3d5cdaec8
[ "Apache-2.0" ]
null
null
null
from time import sleep import board import busio from digitalio import Direction, Pull from RPi import GPIO from adafruit_mcp230xx.mcp23017 import MCP23017 # Initialize the I2C bus: i2c = busio.I2C(board.SCL, board.SDA) # Initialize the MCP23017 chip on the bonnet mcp = MCP23017(i2c) # Optionally change the address of the device if you set any of the A0, A1, A2 # pins. Specify the new address with a keyword parameter: #mcp = MCP23017(i2c, address=0x21) # MCP23017 w/ A0 set # Make a list of all the pins (a.k.a 0-16) pins = [] for pin in range(0, 16): pins.append(mcp.get_pin(pin)) # Set all the pins to input for pin in pins: pin.direction = Direction.INPUT pin.pull = Pull.UP # Set up to check all the port B pins (pins 8-15) w/interrupts! mcp.interrupt_enable = 0xFFFF # Enable Interrupts in all pins # If intcon is set to 0's we will get interrupts on # both button presses and button releases mcp.interrupt_configuration = 0x0000 # interrupt on any change mcp.io_control = 0x44 # Interrupt as open drain and mirrored mcp.clear_ints() # Interrupts need to be cleared initially # Or, we can ask to be notified CONTINUOUSLY if a pin goes LOW (button press) # we won't get an IRQ pulse when the pin is HIGH! #mcp.interrupt_configuration = 0xFFFF # notify pin value #mcp.default_value = 0xFFFF # default value is 'high' so notify whenever 'low' def print_interrupt(port): '''Callback function to be called when an Interrupt occurs.''' for pin_flag in mcp.int_flag: print("Interrupt connected to Pin: {}".format(port)) print("Pin number: {} changed to: {}".format(pin_flag, pins[pin_flag].value)) mcp.clear_ints() # connect either interrupt pin to the Raspberry pi's pin 17. # They were previously configured as mirrored. GPIO.setmode(GPIO.BCM) interrupt = 17 GPIO.setup(interrupt, GPIO.IN, GPIO.PUD_UP) # Set up Pi's pin as input, pull up # The add_event_detect fuction will call our print_interrupt callback function # every time an interrupt gets triggered. GPIO.add_event_detect(interrupt, GPIO.FALLING, callback=print_interrupt, bouncetime=10) # The following lines are so the program runs for at least 60 seconds, # during that time it will detect any pin interrupt and print out the pin number # that changed state and its current state. # The program can be terminated using Ctrl+C. It doesn't matter how it # terminates it will always run GPIO.cleanup(). try: print("When button is pressed you'll see a message") sleep(60) # You could run your main while loop here. print("Time's up. Finished!") finally: GPIO.cleanup()
37.742857
87
0.732021
from time import sleep import board import busio from digitalio import Direction, Pull from RPi import GPIO from adafruit_mcp230xx.mcp23017 import MCP23017 i2c = busio.I2C(board.SCL, board.SDA) mcp = MCP23017(i2c) in range(0, 16): pins.append(mcp.get_pin(pin)) for pin in pins: pin.direction = Direction.INPUT pin.pull = Pull.UP mcp.interrupt_enable = 0xFFFF # both button presses and button releases mcp.interrupt_configuration = 0x0000 # interrupt on any change mcp.io_control = 0x44 # Interrupt as open drain and mirrored mcp.clear_ints() # Interrupts need to be cleared initially # Or, we can ask to be notified CONTINUOUSLY if a pin goes LOW (button press) # we won't get an IRQ pulse when the pin is HIGH! print("Interrupt connected to Pin: {}".format(port)) print("Pin number: {} changed to: {}".format(pin_flag, pins[pin_flag].value)) mcp.clear_ints() # They were previously configured as mirrored. GPIO.setmode(GPIO.BCM) interrupt = 17 GPIO.setup(interrupt, GPIO.IN, GPIO.PUD_UP) # Set up Pi's pin as input, pull up GPIO.add_event_detect(interrupt, GPIO.FALLING, callback=print_interrupt, bouncetime=10) # terminates it will always run GPIO.cleanup(). try: print("When button is pressed you'll see a message") sleep(60) print("Time's up. Finished!") finally: GPIO.cleanup()
true
true
f7f9ffa08a1c44479e50127445802d03fde50686
4,439
py
Python
components/collector/src/source_collectors/axe_core/accessibility.py
ICTU/quality-time
88d80ea30e35bd5f0bf5cce7cb43dc9f439e91f5
[ "Apache-2.0" ]
33
2016-01-20T07:35:48.000Z
2022-03-14T09:20:51.000Z
components/collector/src/source_collectors/axe_core/accessibility.py
ICTU/quality-time
88d80ea30e35bd5f0bf5cce7cb43dc9f439e91f5
[ "Apache-2.0" ]
2,410
2016-01-22T18:13:01.000Z
2022-03-31T16:57:34.000Z
components/collector/src/source_collectors/axe_core/accessibility.py
ICTU/quality-time
88d80ea30e35bd5f0bf5cce7cb43dc9f439e91f5
[ "Apache-2.0" ]
21
2016-01-16T11:49:23.000Z
2022-01-14T21:53:22.000Z
"""Axe-core accessibility analysis collectors.""" from collections.abc import Collection from typing import Any from base_collectors import JSONFileSourceCollector, SourceCollector from collector_utilities.functions import md5_hash, match_string_or_regular_expression from collector_utilities.type import JSON from model import Entities, Entity class AxeAccessibilityCollector(SourceCollector): """Collector base class for getting accessibility violations from Axe.""" def _include_violation(self, impact: str, tags: Collection[str]) -> bool: """Return whether to include the violation.""" if impact and impact not in self._parameter("impact"): return False if tags_to_include := self._parameter("tags_to_include"): for tag in tags: if match_string_or_regular_expression(tag, tags_to_include): break else: return False if tags_to_ignore := self._parameter("tags_to_ignore"): for tag in tags: if match_string_or_regular_expression(tag, tags_to_ignore): return False return True class AxeCoreAccessibility(JSONFileSourceCollector, AxeAccessibilityCollector): """Collector class to get accessibility violations from Axe-core JSON output.""" def _parse_json(self, json: JSON, filename: str) -> Entities: """Override to parse the violations.""" entity_attributes = [] for test_result in self.__parse_test_results(json): violations = {result_type: test_result.get(result_type) for result_type in self._parameter("result_types")} url = test_result.get("url", "") entity_attributes.extend(self.__parse_violations(violations, url)) return Entities(Entity(key=self.__create_key(attributes), **attributes) for attributes in entity_attributes) def __parse_test_results(self, json): """Yield dicts with test result (applicable/incomplete/violations/passes) as key and rules as values.""" if isinstance(json, list): if json and "tags" in json[0]: yield dict(violations=json) # The items in the list are violated rules else: for item in json: yield from self.__parse_test_results(item) # Recursively parse the nested JSON else: yield json # JSON is a dict with result types as keys and rules as values def __parse_violations(self, violations: dict[str, list[dict[str, list]]], url: str) -> list[dict[str, Any]]: """Parse the violations.""" entity_attributes = [] for result_type, violations_by_result_type in violations.items(): for violation in violations_by_result_type: entity_attributes.extend(self.__parse_violation(violation, result_type, url)) return entity_attributes def __parse_violation(self, violation: dict[str, list], result_type: str, url: str) -> list[dict[str, Any]]: """Parse a violation.""" entity_attributes = [] tags = violation.get("tags", []) for node in violation.get("nodes", []) or [violation]: # Use the violation as node if it has no nodes impact = node.get("impact") if self._include_violation(impact, tags): entity_attributes.append( dict( description=violation.get("description"), element=node.get("html"), help=violation.get("helpUrl"), impact=impact, page=url, url=url, result_type=result_type, tags=", ".join(sorted(tags)), violation_type=violation.get("id"), ) ) return entity_attributes @staticmethod def __create_key(attributes) -> str: """Create a key for the entity based on the attributes.""" # We ignore tags for two reasons: 1) If the violation is the same, so should the tags be. 2) Tags were added to # the entities later and including them in the key would change the key for existing entities. Nr 2) also # applies to the result type. return md5_hash(",".join(str(value) for key, value in attributes.items() if key not in {"tags", "result_type"}))
48.25
120
0.631674
from collections.abc import Collection from typing import Any from base_collectors import JSONFileSourceCollector, SourceCollector from collector_utilities.functions import md5_hash, match_string_or_regular_expression from collector_utilities.type import JSON from model import Entities, Entity class AxeAccessibilityCollector(SourceCollector): def _include_violation(self, impact: str, tags: Collection[str]) -> bool: if impact and impact not in self._parameter("impact"): return False if tags_to_include := self._parameter("tags_to_include"): for tag in tags: if match_string_or_regular_expression(tag, tags_to_include): break else: return False if tags_to_ignore := self._parameter("tags_to_ignore"): for tag in tags: if match_string_or_regular_expression(tag, tags_to_ignore): return False return True class AxeCoreAccessibility(JSONFileSourceCollector, AxeAccessibilityCollector): def _parse_json(self, json: JSON, filename: str) -> Entities: entity_attributes = [] for test_result in self.__parse_test_results(json): violations = {result_type: test_result.get(result_type) for result_type in self._parameter("result_types")} url = test_result.get("url", "") entity_attributes.extend(self.__parse_violations(violations, url)) return Entities(Entity(key=self.__create_key(attributes), **attributes) for attributes in entity_attributes) def __parse_test_results(self, json): if isinstance(json, list): if json and "tags" in json[0]: yield dict(violations=json) else: for item in json: yield from self.__parse_test_results(item) else: yield json def __parse_violations(self, violations: dict[str, list[dict[str, list]]], url: str) -> list[dict[str, Any]]: entity_attributes = [] for result_type, violations_by_result_type in violations.items(): for violation in violations_by_result_type: entity_attributes.extend(self.__parse_violation(violation, result_type, url)) return entity_attributes def __parse_violation(self, violation: dict[str, list], result_type: str, url: str) -> list[dict[str, Any]]: entity_attributes = [] tags = violation.get("tags", []) for node in violation.get("nodes", []) or [violation]: impact = node.get("impact") if self._include_violation(impact, tags): entity_attributes.append( dict( description=violation.get("description"), element=node.get("html"), help=violation.get("helpUrl"), impact=impact, page=url, url=url, result_type=result_type, tags=", ".join(sorted(tags)), violation_type=violation.get("id"), ) ) return entity_attributes @staticmethod def __create_key(attributes) -> str: return md5_hash(",".join(str(value) for key, value in attributes.items() if key not in {"tags", "result_type"}))
true
true
f7fa003616bdcd4a64292a7f8efb93d22a4db39a
8,565
py
Python
mythril/laser/ethereum/state/calldata.py
kalloc/mythril
eeee4d7c459189d278ac82a38c5fb778ddd58cdc
[ "MIT" ]
1,887
2018-01-07T10:16:08.000Z
2022-03-31T16:07:26.000Z
mythril/laser/ethereum/state/calldata.py
kalloc/mythril
eeee4d7c459189d278ac82a38c5fb778ddd58cdc
[ "MIT" ]
746
2018-01-09T07:14:01.000Z
2022-03-31T08:12:44.000Z
mythril/laser/ethereum/state/calldata.py
kalloc/mythril
eeee4d7c459189d278ac82a38c5fb778ddd58cdc
[ "MIT" ]
431
2018-01-08T07:47:59.000Z
2022-03-31T13:00:51.000Z
"""This module declares classes to represent call data.""" from typing import cast, Union, Tuple, List from enum import Enum from typing import Any, Union from z3 import Model from z3.z3types import Z3Exception from mythril.laser.ethereum.util import get_concrete_int from mythril.laser.smt import ( Array, BitVec, Bool, Concat, Expression, If, K, simplify, symbol_factory, ) class BaseCalldata: """Base calldata class This represents the calldata provided when sending a transaction to a contract.""" def __init__(self, tx_id: str) -> None: """ :param tx_id: """ self.tx_id = tx_id @property def calldatasize(self) -> BitVec: """ :return: Calldata size for this calldata object """ result = self.size if isinstance(result, int): return symbol_factory.BitVecVal(result, 256) return result def get_word_at(self, offset: int) -> Expression: """Gets word at offset. :param offset: :return: """ parts = self[offset : offset + 32] return simplify(Concat(parts)) def __getitem__(self, item: Union[int, slice, BitVec]) -> Any: """ :param item: :return: """ if isinstance(item, int) or isinstance(item, Expression): return self._load(item) if isinstance(item, slice): start = 0 if item.start is None else item.start step = 1 if item.step is None else item.step stop = self.size if item.stop is None else item.stop try: current_index = ( start if isinstance(start, BitVec) else symbol_factory.BitVecVal(start, 256) ) parts = [] while simplify(current_index != stop): element = self._load(current_index) if not isinstance(element, Expression): element = symbol_factory.BitVecVal(element, 8) parts.append(element) current_index = simplify(current_index + step) except Z3Exception: raise IndexError("Invalid Calldata Slice") return parts raise ValueError def _load(self, item: Union[int, BitVec]) -> Any: """ :param item: """ raise NotImplementedError() @property def size(self) -> Union[BitVec, int]: """Returns the exact size of this calldata, this is not normalized. :return: unnormalized call data size """ raise NotImplementedError() def concrete(self, model: Model) -> list: """Returns a concrete version of the calldata using the provided model. :param model: """ raise NotImplementedError class ConcreteCalldata(BaseCalldata): """A concrete call data representation.""" def __init__(self, tx_id: str, calldata: list) -> None: """Initializes the ConcreteCalldata object. :param tx_id: Id of the transaction that the calldata is for. :param calldata: The concrete calldata content """ self._concrete_calldata = calldata self._calldata = K(256, 8, 0) for i, element in enumerate(calldata, 0): element = ( symbol_factory.BitVecVal(element, 8) if isinstance(element, int) else element ) self._calldata[symbol_factory.BitVecVal(i, 256)] = element super().__init__(tx_id) def _load(self, item: Union[int, BitVec]) -> BitVec: """ :param item: :return: """ item = symbol_factory.BitVecVal(item, 256) if isinstance(item, int) else item return simplify(self._calldata[item]) def concrete(self, model: Model) -> list: """ :param model: :return: """ return self._concrete_calldata @property def size(self) -> int: """ :return: """ return len(self._concrete_calldata) class BasicConcreteCalldata(BaseCalldata): """A base class to represent concrete call data.""" def __init__(self, tx_id: str, calldata: list) -> None: """Initializes the ConcreteCalldata object, that doesn't use z3 arrays. :param tx_id: Id of the transaction that the calldata is for. :param calldata: The concrete calldata content """ self._calldata = calldata super().__init__(tx_id) def _load(self, item: Union[int, Expression]) -> Any: """ :param item: :return: """ if isinstance(item, int): try: return self._calldata[item] except IndexError: return 0 value = symbol_factory.BitVecVal(0x0, 8) for i in range(self.size): value = If(cast(Union[BitVec, Bool], item) == i, self._calldata[i], value) return value def concrete(self, model: Model) -> list: """ :param model: :return: """ return self._calldata @property def size(self) -> int: """ :return: """ return len(self._calldata) class SymbolicCalldata(BaseCalldata): """A class for representing symbolic call data.""" def __init__(self, tx_id: str) -> None: """Initializes the SymbolicCalldata object. :param tx_id: Id of the transaction that the calldata is for. """ self._size = symbol_factory.BitVecSym(str(tx_id) + "_calldatasize", 256) self._calldata = Array("{}_calldata".format(tx_id), 256, 8) super().__init__(tx_id) def _load(self, item: Union[int, BitVec]) -> Any: """ :param item: :return: """ item = symbol_factory.BitVecVal(item, 256) if isinstance(item, int) else item return simplify( If( item < self._size, simplify(self._calldata[cast(BitVec, item)]), symbol_factory.BitVecVal(0, 8), ) ) def concrete(self, model: Model) -> list: """ :param model: :return: """ concrete_length = model.eval(self.size.raw, model_completion=True).as_long() result = [] for i in range(concrete_length): value = self._load(i) c_value = model.eval(value.raw, model_completion=True).as_long() result.append(c_value) return result @property def size(self) -> BitVec: """ :return: """ return self._size class BasicSymbolicCalldata(BaseCalldata): """A basic class representing symbolic call data.""" def __init__(self, tx_id: str) -> None: """Initializes the SymbolicCalldata object. :param tx_id: Id of the transaction that the calldata is for. """ self._reads = [] # type: List[Tuple[Union[int, BitVec], BitVec]] self._size = symbol_factory.BitVecSym(str(tx_id) + "_calldatasize", 256) super().__init__(tx_id) def _load(self, item: Union[int, BitVec], clean=False) -> Any: expr_item = ( symbol_factory.BitVecVal(item, 256) if isinstance(item, int) else item ) # type: BitVec symbolic_base_value = If( expr_item >= self._size, symbol_factory.BitVecVal(0, 8), BitVec( symbol_factory.BitVecSym( "{}_calldata_{}".format(self.tx_id, str(item)), 8 ) ), ) return_value = symbolic_base_value for r_index, r_value in self._reads: return_value = If(r_index == expr_item, r_value, return_value) if not clean: self._reads.append((expr_item, symbolic_base_value)) return simplify(return_value) def concrete(self, model: Model) -> list: """ :param model: :return: """ concrete_length = get_concrete_int(model.eval(self.size, model_completion=True)) result = [] for i in range(concrete_length): value = self._load(i, clean=True) c_value = get_concrete_int(model.eval(value, model_completion=True)) result.append(c_value) return result @property def size(self) -> BitVec: """ :return: """ return self._size
27.364217
88
0.563806
from typing import cast, Union, Tuple, List from enum import Enum from typing import Any, Union from z3 import Model from z3.z3types import Z3Exception from mythril.laser.ethereum.util import get_concrete_int from mythril.laser.smt import ( Array, BitVec, Bool, Concat, Expression, If, K, simplify, symbol_factory, ) class BaseCalldata: def __init__(self, tx_id: str) -> None: self.tx_id = tx_id @property def calldatasize(self) -> BitVec: result = self.size if isinstance(result, int): return symbol_factory.BitVecVal(result, 256) return result def get_word_at(self, offset: int) -> Expression: parts = self[offset : offset + 32] return simplify(Concat(parts)) def __getitem__(self, item: Union[int, slice, BitVec]) -> Any: if isinstance(item, int) or isinstance(item, Expression): return self._load(item) if isinstance(item, slice): start = 0 if item.start is None else item.start step = 1 if item.step is None else item.step stop = self.size if item.stop is None else item.stop try: current_index = ( start if isinstance(start, BitVec) else symbol_factory.BitVecVal(start, 256) ) parts = [] while simplify(current_index != stop): element = self._load(current_index) if not isinstance(element, Expression): element = symbol_factory.BitVecVal(element, 8) parts.append(element) current_index = simplify(current_index + step) except Z3Exception: raise IndexError("Invalid Calldata Slice") return parts raise ValueError def _load(self, item: Union[int, BitVec]) -> Any: raise NotImplementedError() @property def size(self) -> Union[BitVec, int]: raise NotImplementedError() def concrete(self, model: Model) -> list: raise NotImplementedError class ConcreteCalldata(BaseCalldata): def __init__(self, tx_id: str, calldata: list) -> None: self._concrete_calldata = calldata self._calldata = K(256, 8, 0) for i, element in enumerate(calldata, 0): element = ( symbol_factory.BitVecVal(element, 8) if isinstance(element, int) else element ) self._calldata[symbol_factory.BitVecVal(i, 256)] = element super().__init__(tx_id) def _load(self, item: Union[int, BitVec]) -> BitVec: item = symbol_factory.BitVecVal(item, 256) if isinstance(item, int) else item return simplify(self._calldata[item]) def concrete(self, model: Model) -> list: return self._concrete_calldata @property def size(self) -> int: return len(self._concrete_calldata) class BasicConcreteCalldata(BaseCalldata): def __init__(self, tx_id: str, calldata: list) -> None: self._calldata = calldata super().__init__(tx_id) def _load(self, item: Union[int, Expression]) -> Any: if isinstance(item, int): try: return self._calldata[item] except IndexError: return 0 value = symbol_factory.BitVecVal(0x0, 8) for i in range(self.size): value = If(cast(Union[BitVec, Bool], item) == i, self._calldata[i], value) return value def concrete(self, model: Model) -> list: return self._calldata @property def size(self) -> int: return len(self._calldata) class SymbolicCalldata(BaseCalldata): def __init__(self, tx_id: str) -> None: self._size = symbol_factory.BitVecSym(str(tx_id) + "_calldatasize", 256) self._calldata = Array("{}_calldata".format(tx_id), 256, 8) super().__init__(tx_id) def _load(self, item: Union[int, BitVec]) -> Any: item = symbol_factory.BitVecVal(item, 256) if isinstance(item, int) else item return simplify( If( item < self._size, simplify(self._calldata[cast(BitVec, item)]), symbol_factory.BitVecVal(0, 8), ) ) def concrete(self, model: Model) -> list: concrete_length = model.eval(self.size.raw, model_completion=True).as_long() result = [] for i in range(concrete_length): value = self._load(i) c_value = model.eval(value.raw, model_completion=True).as_long() result.append(c_value) return result @property def size(self) -> BitVec: return self._size class BasicSymbolicCalldata(BaseCalldata): def __init__(self, tx_id: str) -> None: self._reads = [] self._size = symbol_factory.BitVecSym(str(tx_id) + "_calldatasize", 256) super().__init__(tx_id) def _load(self, item: Union[int, BitVec], clean=False) -> Any: expr_item = ( symbol_factory.BitVecVal(item, 256) if isinstance(item, int) else item ) symbolic_base_value = If( expr_item >= self._size, symbol_factory.BitVecVal(0, 8), BitVec( symbol_factory.BitVecSym( "{}_calldata_{}".format(self.tx_id, str(item)), 8 ) ), ) return_value = symbolic_base_value for r_index, r_value in self._reads: return_value = If(r_index == expr_item, r_value, return_value) if not clean: self._reads.append((expr_item, symbolic_base_value)) return simplify(return_value) def concrete(self, model: Model) -> list: concrete_length = get_concrete_int(model.eval(self.size, model_completion=True)) result = [] for i in range(concrete_length): value = self._load(i, clean=True) c_value = get_concrete_int(model.eval(value, model_completion=True)) result.append(c_value) return result @property def size(self) -> BitVec: return self._size
true
true
f7fa005819f849751b9d6eebee5b9aab4d7921ae
2,302
py
Python
Basic in Python.py
Akirahori/Hello-Word
96a8307aaec1e7d4544e246a4bdf63b34af4c3c5
[ "MIT" ]
1
2021-12-11T23:10:49.000Z
2021-12-11T23:10:49.000Z
Basic in Python.py
Akirahori/Hello-Word
96a8307aaec1e7d4544e246a4bdf63b34af4c3c5
[ "MIT" ]
null
null
null
Basic in Python.py
Akirahori/Hello-Word
96a8307aaec1e7d4544e246a4bdf63b34af4c3c5
[ "MIT" ]
null
null
null
# Percorrendo uma lista inteira com um laço magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician) # Executando mais tarefas em um laço for magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician.title() + ", that was a great trick") print("I can't wait to see your next trick, " + magician.title() + ".\n") # Identação aqui acontece um erro de lógica # Agora está certo a identação é a questão do espaçamento magicians = ['bruce', 'jolene', 'samanta'] for magician in magicians: print(magician.title() + ", that was a great trick!") print("I can't wait to see your next trick, " + magician.title() +".\n") # Identar desnecessariamente message = "Hello Python world!" print(message) #Usando a função range for value in range(1,5): print(value) #Usando range para criar uma lista númerica numbers = list(range(1,6)) print(numbers) even_numbers = list(range(2,11,2)) print(even_numbers) #Exponenciais squares = [] for value in range(1,11): square = value**2 squares.append(square) print(squares) #Estatisticas Simples digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] min(digits) #List comprehensions squares = [value**2 for value in range(1,11)] print(squares) #Fatiando uma lista players = ['charles', 'robson', 'ferdinand','john', 'eli'] print(players[0:3]) players = ['charles', 'robson', 'ferdinand','john', 'eli'] print(players[1:4]) players = ['charles', 'robson', 'ferdinand','john', 'eli'] print(players[:4]) #sintaxe permite apresentar todos os elementos players = ['charles', 'robson', 'ferdinand','john', 'eli'] print(players[-1]) #Percorrendo uma fatia com um laço players = ['charles', 'robson', 'ferdinand','john', 'eli'] print("here are the first three players on my team") for player in players[:3]: print(player.title()) #Copiando uma lista my_foods = ['pizza', 'gyudon', 'sushi','chocolate'] friend_foods = my_foods[:] my_foods.append('cannoli') friend_foods.append('ice cream') print("My favorite foods are: ") print(my_foods) print("\nMy friend's favorite foods are:") print(friend_foods) #Tupla dimensions = (200,50) print(dimensions[0]) print(dimensions[1]) #Percorrendo todos os valores de uma tupla com um laço dimensions = (200, 50) for dimension in dimensions: print(dimension)
26.159091
77
0.700261
magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician) magicians = ['alice', 'david', 'carolina'] for magician in magicians: print(magician.title() + ", that was a great trick") print("I can't wait to see your next trick, " + magician.title() + ".\n") # Identação aqui acontece um erro de lógica # Agora está certo a identação é a questão do espaçamento magicians = ['bruce', 'jolene', 'samanta'] for magician in magicians: print(magician.title() + ", that was a great trick!") print("I can't wait to see your next trick, " + magician.title() +".\n") message = "Hello Python world!" print(message) for value in range(1,5): print(value) numbers = list(range(1,6)) print(numbers) even_numbers = list(range(2,11,2)) print(even_numbers) squares = [] for value in range(1,11): square = value**2 squares.append(square) print(squares) digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] min(digits) squares = [value**2 for value in range(1,11)] print(squares) players = ['charles', 'robson', 'ferdinand','john', 'eli'] print(players[0:3]) players = ['charles', 'robson', 'ferdinand','john', 'eli'] print(players[1:4]) players = ['charles', 'robson', 'ferdinand','john', 'eli'] print(players[:4]) players = ['charles', 'robson', 'ferdinand','john', 'eli'] print(players[-1]) players = ['charles', 'robson', 'ferdinand','john', 'eli'] print("here are the first three players on my team") for player in players[:3]: print(player.title()) my_foods = ['pizza', 'gyudon', 'sushi','chocolate'] friend_foods = my_foods[:] my_foods.append('cannoli') friend_foods.append('ice cream') print("My favorite foods are: ") print(my_foods) print("\nMy friend's favorite foods are:") print(friend_foods) #Tupla dimensions = (200,50) print(dimensions[0]) print(dimensions[1]) #Percorrendo todos os valores de uma tupla com um laço dimensions = (200, 50) for dimension in dimensions: print(dimension)
true
true
f7fa022816bef93d89d5455feb6728875711065d
429
py
Python
water_jug/app.py
justinnhli/justinnhli-oxy
27d7890375b632ad99654d401302c125027dcfa3
[ "MIT" ]
4
2019-03-24T19:27:31.000Z
2021-12-10T07:14:02.000Z
water_jug/app.py
justinnhli/justinnhli-oxy
27d7890375b632ad99654d401302c125027dcfa3
[ "MIT" ]
1
2017-04-13T18:36:08.000Z
2017-04-24T02:39:40.000Z
water_jug/app.py
justinnhli/justinnhli-oxy
27d7890375b632ad99654d401302c125027dcfa3
[ "MIT" ]
1
2017-04-12T00:30:29.000Z
2017-04-12T00:30:29.000Z
from os.path import basename, dirname, join as join_path from flask import Blueprint, render_template APP_NAME = basename(dirname(__file__)) app = Blueprint( APP_NAME, APP_NAME, url_prefix=('/' + APP_NAME), static_folder='static', static_url_path=join_path('/static', APP_NAME), template_folder='templates', ) @app.route('/') def root(): return render_template(join_path(APP_NAME, 'index.html'))
21.45
61
0.710956
from os.path import basename, dirname, join as join_path from flask import Blueprint, render_template APP_NAME = basename(dirname(__file__)) app = Blueprint( APP_NAME, APP_NAME, url_prefix=('/' + APP_NAME), static_folder='static', static_url_path=join_path('/static', APP_NAME), template_folder='templates', ) @app.route('/') def root(): return render_template(join_path(APP_NAME, 'index.html'))
true
true
f7fa02c61201b915ab3e32ac72f9424fec9af8c7
5,495
py
Python
script/payload-compare.py
zyjj1/APM_Elastic_Server
5ad98d03cafdb50625e220fee601b35655b1de9d
[ "ECL-2.0", "Apache-2.0" ]
1,047
2017-08-17T12:12:56.000Z
2022-03-31T23:30:59.000Z
script/payload-compare.py
zyjj1/APM_Elastic_Server
5ad98d03cafdb50625e220fee601b35655b1de9d
[ "ECL-2.0", "Apache-2.0" ]
5,826
2017-08-17T13:53:17.000Z
2022-03-31T18:40:01.000Z
script/payload-compare.py
zyjj1/APM_Elastic_Server
5ad98d03cafdb50625e220fee601b35655b1de9d
[ "ECL-2.0", "Apache-2.0" ]
426
2017-08-17T12:20:36.000Z
2022-03-08T21:03:38.000Z
#!/usr/bin/env python3 from uuid import uuid4 from collections import defaultdict import json import random import zlib NUM_ENDPOINTS = 10 SAMPLE_RATE = 0.1 SPANS_PER_TRANSACTION = 30 NUM_TRANSACTIONS = 10000 print "{:25} {}".format("NUM_ENDPOINTS:", NUM_ENDPOINTS) print "{:25} {}".format("SAMPLE_RATE:", SAMPLE_RATE) print "{:25} {}".format("SPANS_PER_TRANSACTION:", SPANS_PER_TRANSACTION) print "{:25} {}".format("NUM_TRANSACTIONS:", NUM_TRANSACTIONS) # print "SAMPLE_RATE:", SAMPLE_RATE # print "SPANS_PER_TRANSACTION:", SPANS_PER_TRANSACTION # print "NUM_TRANSACTIONS:", NUM_TRANSACTIONS # SHOULD_GROUP = False # SPAN_UUIDS = False # TRANSACTION_UUIDS = True MATRIX_RUNS = [ {"SHOULD_GROUP": False, "SPAN_UUIDS": False, "TRANSACTION_UUIDS": False}, {"SHOULD_GROUP": True, "SPAN_UUIDS": False, "TRANSACTION_UUIDS": False}, {"SHOULD_GROUP": False, "SPAN_UUIDS": True, "TRANSACTION_UUIDS": False}, {"SHOULD_GROUP": False, "SPAN_UUIDS": False, "TRANSACTION_UUIDS": False}, {"SHOULD_GROUP": False, "SPAN_UUIDS": False, "TRANSACTION_UUIDS": True}, {"SHOULD_GROUP": False, "SPAN_UUIDS": False, "TRANSACTION_UUIDS": False}, ] shop = ["shop", "store", "butik", "sklep", "hranut"] foot = ["shoe", "foot", "fod", "stopa", "regel"] filewords = shop + foot methods = ["GET", "POST", "PUT"] endpoints = [ "/api/{}/{}".format(random.choice(shop), random.choice(foot)) for _ in range(NUM_ENDPOINTS) ] def sizeof_fmt(num, suffix='B'): for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix) def gen_transaction(TRANSACTION_UUIDS, SPAN_UUIDS): if random.random() < SAMPLE_RATE: transaction = { "name": random.choice(endpoints), "type": "request", "duration": 251.1, "timestamp": "2017-05-09T10:23:{}Z".format(random.randint(0, 60)), "context": { "user": { "email": "ron@elastic.com" }, "request": { "headers": { "User-Agent": "Mozilla Chrome Edge", "Cookies": "c1=v1;c2=v2" }, "path": "/api/v9/1", "method": "POST" }, "response": { "size": 9232, "headers": { "Content-Type": "application/json" } } }, "spans": [gen_span(SPAN_UUIDS) for _ in range(SPANS_PER_TRANSACTION)] } if TRANSACTION_UUIDS: transaction['id'] = str(uuid4()) return transaction return { "name": random.choice(endpoints), "type": "request", "duration": 251.1, "timestamp": "2017-05-09T10:23:{:02}Z".format(random.randint(0, 60)), } def gen_span(SPAN_UUIDS): span = { "name": "{} /{}/{}".format(random.choice(methods), random.choice(shop), random.choice(foot)), "type": "http", "start": 25.2, "end": 40.1, "parent": str(uuid4()) if SPAN_UUIDS else random.randint(0, SPANS_PER_TRANSACTION), "context": { "request": { "path": "/{}/{}".format(random.choice(methods), random.choice(shop), random.choice(foot)), "host": "internal-backendservice.com", "port": 80, "query": "q1=v1&q2=v2", "headers": { "Accept": "application/json" }, }, "response": { "headers": { "Content-Type": "application/json" }, "size": random.randint(100, 100000) }, "stacktrace": [ {"filename": "/".join([random.choice(filewords) for _ in range(random.randint(1, 5))]), "lineno": random.randint(1, 10000)} for _1 in range(random.randint(3, 20)) ], } } if SPAN_UUIDS: span['id'] = str(uuid4()) return span def run(SHOULD_GROUP, SPAN_UUIDS, TRANSACTION_UUIDS): transactions = [gen_transaction(TRANSACTION_UUIDS, SPAN_UUIDS) for _ in range(NUM_TRANSACTIONS)] if SHOULD_GROUP: groups = defaultdict(list) for tx in transactions: name = tx['name'] del tx['name'] del tx['type'] groups[name].append(tx) transactions = [] for name, group in groups.items(): transactions.append( { "name": name, "type": "http", "timestamp": "2017-05-09T10:23:{:02}Z".format(random.randint(0, 60)), "durations": group } ) payload = { "app_id": "my-app", "agent": "elastic-node/4.1.4", "platform": "lang=python/2.7.1 platform=CPython framework=Django/1.11.1", "transactions": transactions } return json.dumps(payload) for args in MATRIX_RUNS: payload = run(**args) size = len(payload) compressed = len(zlib.compress(payload)) print " ".join(["{:<25}".format("{}: {}".format(k, v)) for k, v in args.items()]) + \ ":", sizeof_fmt(compressed), "(uncompressed: {})".format(sizeof_fmt(size))
32.134503
114
0.522839
from uuid import uuid4 from collections import defaultdict import json import random import zlib NUM_ENDPOINTS = 10 SAMPLE_RATE = 0.1 SPANS_PER_TRANSACTION = 30 NUM_TRANSACTIONS = 10000 print "{:25} {}".format("NUM_ENDPOINTS:", NUM_ENDPOINTS) print "{:25} {}".format("SAMPLE_RATE:", SAMPLE_RATE) print "{:25} {}".format("SPANS_PER_TRANSACTION:", SPANS_PER_TRANSACTION) print "{:25} {}".format("NUM_TRANSACTIONS:", NUM_TRANSACTIONS) MATRIX_RUNS = [ {"SHOULD_GROUP": False, "SPAN_UUIDS": False, "TRANSACTION_UUIDS": False}, {"SHOULD_GROUP": True, "SPAN_UUIDS": False, "TRANSACTION_UUIDS": False}, {"SHOULD_GROUP": False, "SPAN_UUIDS": True, "TRANSACTION_UUIDS": False}, {"SHOULD_GROUP": False, "SPAN_UUIDS": False, "TRANSACTION_UUIDS": False}, {"SHOULD_GROUP": False, "SPAN_UUIDS": False, "TRANSACTION_UUIDS": True}, {"SHOULD_GROUP": False, "SPAN_UUIDS": False, "TRANSACTION_UUIDS": False}, ] shop = ["shop", "store", "butik", "sklep", "hranut"] foot = ["shoe", "foot", "fod", "stopa", "regel"] filewords = shop + foot methods = ["GET", "POST", "PUT"] endpoints = [ "/api/{}/{}".format(random.choice(shop), random.choice(foot)) for _ in range(NUM_ENDPOINTS) ] def sizeof_fmt(num, suffix='B'): for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, 'Yi', suffix) def gen_transaction(TRANSACTION_UUIDS, SPAN_UUIDS): if random.random() < SAMPLE_RATE: transaction = { "name": random.choice(endpoints), "type": "request", "duration": 251.1, "timestamp": "2017-05-09T10:23:{}Z".format(random.randint(0, 60)), "context": { "user": { "email": "ron@elastic.com" }, "request": { "headers": { "User-Agent": "Mozilla Chrome Edge", "Cookies": "c1=v1;c2=v2" }, "path": "/api/v9/1", "method": "POST" }, "response": { "size": 9232, "headers": { "Content-Type": "application/json" } } }, "spans": [gen_span(SPAN_UUIDS) for _ in range(SPANS_PER_TRANSACTION)] } if TRANSACTION_UUIDS: transaction['id'] = str(uuid4()) return transaction return { "name": random.choice(endpoints), "type": "request", "duration": 251.1, "timestamp": "2017-05-09T10:23:{:02}Z".format(random.randint(0, 60)), } def gen_span(SPAN_UUIDS): span = { "name": "{} /{}/{}".format(random.choice(methods), random.choice(shop), random.choice(foot)), "type": "http", "start": 25.2, "end": 40.1, "parent": str(uuid4()) if SPAN_UUIDS else random.randint(0, SPANS_PER_TRANSACTION), "context": { "request": { "path": "/{}/{}".format(random.choice(methods), random.choice(shop), random.choice(foot)), "host": "internal-backendservice.com", "port": 80, "query": "q1=v1&q2=v2", "headers": { "Accept": "application/json" }, }, "response": { "headers": { "Content-Type": "application/json" }, "size": random.randint(100, 100000) }, "stacktrace": [ {"filename": "/".join([random.choice(filewords) for _ in range(random.randint(1, 5))]), "lineno": random.randint(1, 10000)} for _1 in range(random.randint(3, 20)) ], } } if SPAN_UUIDS: span['id'] = str(uuid4()) return span def run(SHOULD_GROUP, SPAN_UUIDS, TRANSACTION_UUIDS): transactions = [gen_transaction(TRANSACTION_UUIDS, SPAN_UUIDS) for _ in range(NUM_TRANSACTIONS)] if SHOULD_GROUP: groups = defaultdict(list) for tx in transactions: name = tx['name'] del tx['name'] del tx['type'] groups[name].append(tx) transactions = [] for name, group in groups.items(): transactions.append( { "name": name, "type": "http", "timestamp": "2017-05-09T10:23:{:02}Z".format(random.randint(0, 60)), "durations": group } ) payload = { "app_id": "my-app", "agent": "elastic-node/4.1.4", "platform": "lang=python/2.7.1 platform=CPython framework=Django/1.11.1", "transactions": transactions } return json.dumps(payload) for args in MATRIX_RUNS: payload = run(**args) size = len(payload) compressed = len(zlib.compress(payload)) print " ".join(["{:<25}".format("{}: {}".format(k, v)) for k, v in args.items()]) + \ ":", sizeof_fmt(compressed), "(uncompressed: {})".format(sizeof_fmt(size))
false
true
f7fa02ded7f4751e8fea9a4bac6de3ef50dfba36
20,158
py
Python
bonneville/modules/git.py
lowsodium/bonneville
02a016380b56345594f20ee007c62e7e92821a8b
[ "Apache-2.0" ]
null
null
null
bonneville/modules/git.py
lowsodium/bonneville
02a016380b56345594f20ee007c62e7e92821a8b
[ "Apache-2.0" ]
null
null
null
bonneville/modules/git.py
lowsodium/bonneville
02a016380b56345594f20ee007c62e7e92821a8b
[ "Apache-2.0" ]
3
2020-05-10T02:08:44.000Z
2020-11-06T11:01:57.000Z
# -*- coding: utf-8 -*- ''' Support for the Git SCM ''' # Import python libs import os import tempfile try: import pipes HAS_PIPES = True except ImportError: HAS_PIPES = False # Import bonneville libs from bonneville import utils, exceptions def __virtual__(): ''' Only load if git exists on the system ''' if not all((utils.which('git'), HAS_PIPES)): return False return 'git' def _git_ssh_helper(identity): ''' Returns the path to a helper script which can be used in the GIT_SSH env var to use a custom private key file. ''' opts = { 'StrictHostKeyChecking': 'no', 'PasswordAuthentication': 'no', 'KbdInteractiveAuthentication': 'no', 'ChallengeResponseAuthentication': 'no', } helper = tempfile.NamedTemporaryFile(delete=False) helper.writelines([ '#!/bin/sh\n', 'exec ssh {opts} -i {identity} $*\n'.format( opts=' '.join('-o%s=%s' % (key, value) for key, value in opts.items()), identity=identity, ) ]) helper.close() os.chmod(helper.name, 0o755) return helper.name def _git_run(cmd, cwd=None, runas=None, identity=None, **kwargs): ''' simple, throw an exception with the error message on an error return code. this function may be moved to the command module, spliced with 'cmd.run_all', and used as an alternative to 'cmd.run_all'. Some commands don't return proper retcodes, so this can't replace 'cmd.run_all'. ''' env = {} if identity: helper = _git_ssh_helper(identity) env = { 'GIT_SSH': helper } result = __salt__['cmd.run_all'](cmd, cwd=cwd, runas=runas, env=env, **kwargs) if identity: os.unlink(helper) retcode = result['retcode'] if retcode == 0: return result['stdout'] else: raise exceptions.CommandExecutionError(result['stderr']) def _git_getdir(cwd, user=None): ''' Returns the absolute path to the top-level of a given repo because some Git commands are sensitive to where they're run from (archive for one) ''' cmd_bare = 'git rev-parse --is-bare-repository' is_bare = __salt__['cmd.run_stdout'](cmd_bare, cwd, runas=user) == 'true' if is_bare: return cwd cmd_toplvl = 'git rev-parse --show-toplevel' return __salt__['cmd.run'](cmd_toplvl, cwd) def _check_git(): ''' Check if git is available ''' utils.check_or_die('git') def current_branch(cwd, user=None): ''' Returns the current branch name, if on a branch. CLI Example: .. code-block:: bash salt '*' git.current_branch /path/to/repo ''' cmd = r'git branch | grep "^*\ " | cut -d " " -f 2 | ' + \ 'grep -v "(detached"' return __salt__['cmd.run_stdout'](cmd, cwd=cwd, runas=user) def revision(cwd, rev='HEAD', short=False, user=None): ''' Returns the long hash of a given identifier (hash, branch, tag, HEAD, etc) cwd The path to the Git repository rev: HEAD The revision short: False Return an abbreviated SHA1 git hash user : None Run git as a user other than what the minion runs as CLI Example: .. code-block:: bash salt '*' git.revision /path/to/repo mybranch ''' _check_git() cmd = 'git rev-parse {0}{1}'.format('--short ' if short else '', rev) return _git_run(cmd, cwd, runas=user) def clone(cwd, repository, opts=None, user=None, identity=None): ''' Clone a new repository cwd The path to the Git repository repository The git URI of the repository opts : None Any additional options to add to the command line user : None Run git as a user other than what the minion runs as identity : None A path to a private key to use over SSH CLI Example: .. code-block:: bash salt '*' git.clone /path/to/repo git://github.com/saltstack/bonneville.git salt '*' git.clone /path/to/repo.git\\ git://github.com/saltstack/bonneville.git '--bare --origin github' ''' _check_git() if not opts: opts = '' cmd = 'git clone {0} {1} {2}'.format(repository, cwd, opts) return _git_run(cmd, runas=user, identity=identity) def describe(cwd, rev='HEAD', user=None): ''' Returns the git describe string (or the SHA hash if there are no tags) for the given revision cwd The path to the Git repository rev: HEAD The revision to describe user : None Run git as a user other than what the minion runs as CLI Examples: .. code-block:: bash salt '*' git.describe /path/to/repo salt '*' git.describe /path/to/repo develop ''' cmd = 'git describe {0}'.format(rev) return __salt__['cmd.run_stdout'](cmd, cwd=cwd, runas=user) def archive(cwd, output, rev='HEAD', fmt=None, prefix=None, user=None): ''' Export a tarball from the repository cwd The path to the Git repository output The path to the archive tarball rev: HEAD The revision to create an archive from fmt: None Format of the resulting archive, zip and tar are commonly used prefix : None Prepend <prefix>/ to every filename in the archive user : None Run git as a user other than what the minion runs as If ``prefix`` is not specified it defaults to the basename of the repo directory. CLI Example: .. code-block:: bash salt '*' git.archive /path/to/repo /path/to/archive.tar.gz ''' _check_git() basename = '{0}/'.format(os.path.basename(_git_getdir(cwd, user=user))) cmd = 'git archive{prefix}{fmt} -o {output} {rev}'.format( rev=rev, output=output, fmt=' --format={0}'.format(fmt) if fmt else '', prefix=' --prefix="{0}"'.format(prefix if prefix else basename) ) return _git_run(cmd, cwd=cwd, runas=user) def fetch(cwd, opts=None, user=None, identity=None): ''' Perform a fetch on the given repository cwd The path to the Git repository opts : None Any additional options to add to the command line user : None Run git as a user other than what the minion runs as identity : None A path to a private key to use over SSH CLI Example: .. code-block:: bash salt '*' git.fetch /path/to/repo '--all' salt '*' git.fetch cwd=/path/to/repo opts='--all' user=johnny ''' _check_git() if not opts: opts = '' cmd = 'git fetch {0}'.format(opts) return _git_run(cmd, cwd=cwd, runas=user, identity=identity) def pull(cwd, opts=None, user=None, identity=None): ''' Perform a pull on the given repository cwd The path to the Git repository opts : None Any additional options to add to the command line user : None Run git as a user other than what the minion runs as identity : None A path to a private key to use over SSH CLI Example: .. code-block:: bash salt '*' git.pull /path/to/repo opts='--rebase origin master' ''' _check_git() if not opts: opts = '' return _git_run('git pull {0}'.format(opts), cwd=cwd, runas=user, identity=identity) def rebase(cwd, rev='master', opts=None, user=None): ''' Rebase the current branch cwd The path to the Git repository rev : master The revision to rebase onto the current branch opts : None Any additional options to add to the command line user : None Run git as a user other than what the minion runs as CLI Example: .. code-block:: bash salt '*' git.rebase /path/to/repo master salt '*' git.rebase /path/to/repo 'origin master' That is the same as: .. code-block:: bash git rebase master git rebase origin master ''' _check_git() if not opts: opts = '' return _git_run('git rebase {0} {1}'.format(opts, rev), cwd=cwd, runas=user) def checkout(cwd, rev, force=False, opts=None, user=None): ''' Checkout a given revision cwd The path to the Git repository rev The remote branch or revision to checkout force : False Force a checkout even if there might be overwritten changes opts : None Any additional options to add to the command line user : None Run git as a user other than what the minion runs as CLI Examples: .. code-block:: bash salt '*' git.checkout /path/to/repo somebranch user=jeff salt '*' git.checkout /path/to/repo opts='testbranch -- conf/file1 file2' salt '*' git.checkout /path/to/repo rev=origin/mybranch opts=--track ''' _check_git() if not opts: opts = '' cmd = 'git checkout {0} {1} {2}'.format(' -f' if force else '', rev, opts) return _git_run(cmd, cwd=cwd, runas=user) def merge(cwd, branch='@{upstream}', opts=None, user=None): ''' Merge a given branch cwd The path to the Git repository branch : @{upstream} The remote branch or revision to merge into the current branch opts : None Any additional options to add to the command line user : None Run git as a user other than what the minion runs as CLI Example: .. code-block:: bash salt '*' git.fetch /path/to/repo salt '*' git.merge /path/to/repo @{upstream} ''' _check_git() if not opts: opts = '' cmd = 'git merge {0} {1}'.format(branch, opts) return _git_run(cmd, cwd, runas=user) def init(cwd, opts=None, user=None): ''' Initialize a new git repository cwd The path to the Git repository opts : None Any additional options to add to the command line user : None Run git as a user other than what the minion runs as CLI Example: .. code-block:: bash salt '*' git.init /path/to/repo.git opts='--bare' ''' _check_git() cmd = 'git init {0} {1}'.format(cwd, opts) return _git_run(cmd, runas=user) def submodule(cwd, init=True, opts=None, user=None, identity=None): ''' Initialize git submodules cwd The path to the Git repository init : True Ensure that new submodules are initialized opts : None Any additional options to add to the command line user : None Run git as a user other than what the minion runs as identity : None A path to a private key to use over SSH CLI Example: .. code-block:: bash salt '*' git.submodule /path/to/repo.git/sub/repo ''' _check_git() if not opts: opts = '' cmd = 'git submodule update {0} {1}'.format('--init' if init else '', opts) return _git_run(cmd, cwd=cwd, runas=user, identity=identity) def status(cwd, user=None): ''' Return the status of the repository. The returned format uses the status codes of gits 'porcelain' output mode cwd The path to the Git repository user : None Run git as a user other than what the minion runs as CLI Example: .. code-block:: bash salt '*' git.status /path/to/git/repo ''' cmd = 'git status -z --porcelain' stdout = _git_run(cmd, cwd=cwd, runas=user) state_by_file = [] for line in stdout.split("\0"): state = line[:2] filename = line[3:] if filename != '' and state != '': state_by_file.append((state, filename)) return state_by_file def add(cwd, file_name, user=None, opts=None): ''' add a file to git cwd The path to the Git repository file_name Path to the file in the cwd opts : None Any additional options to add to the command line user : None Run git as a user other than what the minion runs as CLI Example: .. code-block:: bash salt '*' git.add /path/to/git/repo /path/to/file ''' if not opts: opts = '' cmd = 'git add {0} {1}'.format(file_name, opts) return _git_run(cmd, cwd=cwd, runas=user) def rm(cwd, file_name, user=None, opts=None): ''' Remove a file from git cwd The path to the Git repository file_name Path to the file in the cwd opts : None Any additional options to add to the command line user : None Run git as a user other than what the minion runs as CLI Example: .. code-block:: bash salt '*' git.rm /path/to/git/repo /path/to/file ''' if not opts: opts = '' cmd = 'git rm {0} {1}'.format(file_name, opts) return _git_run(cmd, cwd=cwd, runas=user) def commit(cwd, message, user=None, opts=None): ''' create a commit cwd The path to the Git repository message The commit message opts : None Any additional options to add to the command line user : None Run git as a user other than what the minion runs as CLI Example: .. code-block:: bash salt '*' git.commit /path/to/git/repo 'The commit message' ''' if not opts: opts = '' cmd = 'git commit -m {0} {1}'.format(pipes.quote(message), opts) return _git_run(cmd, cwd=cwd, runas=user) def push(cwd, remote_name, branch='master', user=None, opts=None, identity=None): ''' Push to remote cwd The path to the Git repository remote_name Name of the remote to push to branch : master Name of the branch to push opts : None Any additional options to add to the command line user : None Run git as a user other than what the minion runs as identity : None A path to a private key to use over SSH CLI Example: .. code-block:: bash salt '*' git.push /path/to/git/repo remote-name ''' if not opts: opts = '' cmd = 'git push {0} {1} {2}'.format(remote_name, branch, opts) return _git_run(cmd, cwd=cwd, runas=user, identity=identity) def remotes(cwd, user=None): ''' Get remotes like git remote -v cwd The path to the Git repository user : None Run git as a user other than what the minion runs as CLI Example: .. code-block:: bash salt '*' git.remotes /path/to/repo ''' cmd = 'git remote' ret = _git_run(cmd, cwd=cwd, runas=user) res = dict() for remote_name in ret.splitlines(): remote = remote_name.strip() res[remote] = remote_get(cwd, remote, user=user) return res def remote_get(cwd, remote='origin', user=None): ''' get the fetch and push URL for a specified remote name remote : origin the remote name used to define the fetch and push URL user : None Run git as a user other than what the minion runs as CLI Example: .. code-block:: bash salt '*' git.remote_get /path/to/repo salt '*' git.remote_get /path/to/repo upstream ''' try: cmd = 'git remote show -n {0}'.format(remote) ret = _git_run(cmd, cwd=cwd, runas=user) lines = ret.splitlines() remote_fetch_url = lines[1].replace('Fetch URL: ', '').strip() remote_push_url = lines[2].replace('Push URL: ', '').strip() if remote_fetch_url != remote and remote_push_url != remote: res = (remote_fetch_url, remote_push_url) return res else: return None except exceptions.CommandExecutionError: return None def remote_set(cwd, name='origin', url=None, user=None): ''' sets a remote with name and URL like git remote add <remote_name> <remote_url> remote_name : origin defines the remote name remote_url : None defines the remote URL; should not be None! user : None Run git as a user other than what the minion runs as CLI Example: .. code-block:: bash salt '*' git.remote_set /path/to/repo remote_url=git@github.com:saltstack/bonneville.git salt '*' git.remote_set /path/to/repo origin git@github.com:saltstack/bonneville.git ''' if remote_get(cwd, name): cmd = 'git remote rm {0}'.format(name) _git_run(cmd, cwd=cwd, runas=user) cmd = 'git remote add {0} {1}'.format(name, url) _git_run(cmd, cwd=cwd, runas=user) return remote_get(cwd=cwd, remote=name, user=None) def reset(cwd, opts=None, user=None): ''' Reset the repository checkout cwd The path to the Git repository opts : None Any additional options to add to the command line user : None Run git as a user other than what the minion runs as CLI Example: .. code-block:: bash salt '*' git.reset /path/to/repo master ''' _check_git() if not opts: opts = '' return _git_run('git reset {0}'.format(opts), cwd=cwd, runas=user) def stash(cwd, opts=None, user=None): ''' Stash changes in the repository checkout cwd The path to the Git repository opts : None Any additional options to add to the command line user : None Run git as a user other than what the minion runs as CLI Example: .. code-block:: bash salt '*' git.stash /path/to/repo master ''' _check_git() if not opts: opts = '' return _git_run('git stash {0}'.format(opts), cwd=cwd, runas=user) def config_set(cwd, setting_name, setting_value, user=None, is_global=False): ''' Set a key in the git configuration file (.git/config) of the repository or globally. cwd The path to the Git repository setting_name The name of the configuration key to set setting_value The (new) value to set user : None Run git as a user other than what the minion runs as is_global : False Set to True to use the '--global' flag with 'git config' CLI Example: .. code-block:: bash salt '*' git.config_set /path/to/repo user.email me@example.com ''' scope = '--local' if is_global: scope = '--global' _check_git() return _git_run('git config {0} {1} {2}'.format(scope, setting_name, setting_value), cwd=cwd, runas=user) def config_get(cwd, setting_name, user=None): ''' Get a key from the git configuration file (.git/config) of the repository. cwd The path to the Git repository setting_name The name of the configuration key to get user : None Run git as a user other than what the minion runs as CLI Example: .. code-block:: bash salt '*' git.config_get /path/to/repo user.email ''' _check_git() return _git_run('git config {0}'.format(setting_name), cwd=cwd, runas=user) def ls_remote(cwd, repository="origin", branch="master", user=None, identity=None): ''' Returns the upstream hash for any given URL and branch. cwd The path to the Git repository repository: origin The name of the repository to get the revision from. Can be the name of a remote, an URL, etc. branch: master The name of the branch to get the revision from. user : none run git as a user other than what the minion runs as identity : none a path to a private key to use over ssh CLI Example: .. code-block:: bash salt '*' git.ls_remote /pat/to/repo origin master ''' _check_git() cmd = "git ls-remote -h " + repository + " " + branch + " | cut -f 1" return _git_run(cmd, cwd=cwd, runas=user, identity=identity)
22.958998
109
0.598075
import os import tempfile try: import pipes HAS_PIPES = True except ImportError: HAS_PIPES = False from bonneville import utils, exceptions def __virtual__(): if not all((utils.which('git'), HAS_PIPES)): return False return 'git' def _git_ssh_helper(identity): opts = { 'StrictHostKeyChecking': 'no', 'PasswordAuthentication': 'no', 'KbdInteractiveAuthentication': 'no', 'ChallengeResponseAuthentication': 'no', } helper = tempfile.NamedTemporaryFile(delete=False) helper.writelines([ '#!/bin/sh\n', 'exec ssh {opts} -i {identity} $*\n'.format( opts=' '.join('-o%s=%s' % (key, value) for key, value in opts.items()), identity=identity, ) ]) helper.close() os.chmod(helper.name, 0o755) return helper.name def _git_run(cmd, cwd=None, runas=None, identity=None, **kwargs): env = {} if identity: helper = _git_ssh_helper(identity) env = { 'GIT_SSH': helper } result = __salt__['cmd.run_all'](cmd, cwd=cwd, runas=runas, env=env, **kwargs) if identity: os.unlink(helper) retcode = result['retcode'] if retcode == 0: return result['stdout'] else: raise exceptions.CommandExecutionError(result['stderr']) def _git_getdir(cwd, user=None): cmd_bare = 'git rev-parse --is-bare-repository' is_bare = __salt__['cmd.run_stdout'](cmd_bare, cwd, runas=user) == 'true' if is_bare: return cwd cmd_toplvl = 'git rev-parse --show-toplevel' return __salt__['cmd.run'](cmd_toplvl, cwd) def _check_git(): utils.check_or_die('git') def current_branch(cwd, user=None): cmd = r'git branch | grep "^*\ " | cut -d " " -f 2 | ' + \ 'grep -v "(detached"' return __salt__['cmd.run_stdout'](cmd, cwd=cwd, runas=user) def revision(cwd, rev='HEAD', short=False, user=None): _check_git() cmd = 'git rev-parse {0}{1}'.format('--short ' if short else '', rev) return _git_run(cmd, cwd, runas=user) def clone(cwd, repository, opts=None, user=None, identity=None): _check_git() if not opts: opts = '' cmd = 'git clone {0} {1} {2}'.format(repository, cwd, opts) return _git_run(cmd, runas=user, identity=identity) def describe(cwd, rev='HEAD', user=None): cmd = 'git describe {0}'.format(rev) return __salt__['cmd.run_stdout'](cmd, cwd=cwd, runas=user) def archive(cwd, output, rev='HEAD', fmt=None, prefix=None, user=None): _check_git() basename = '{0}/'.format(os.path.basename(_git_getdir(cwd, user=user))) cmd = 'git archive{prefix}{fmt} -o {output} {rev}'.format( rev=rev, output=output, fmt=' --format={0}'.format(fmt) if fmt else '', prefix=' --prefix="{0}"'.format(prefix if prefix else basename) ) return _git_run(cmd, cwd=cwd, runas=user) def fetch(cwd, opts=None, user=None, identity=None): _check_git() if not opts: opts = '' cmd = 'git fetch {0}'.format(opts) return _git_run(cmd, cwd=cwd, runas=user, identity=identity) def pull(cwd, opts=None, user=None, identity=None): _check_git() if not opts: opts = '' return _git_run('git pull {0}'.format(opts), cwd=cwd, runas=user, identity=identity) def rebase(cwd, rev='master', opts=None, user=None): _check_git() if not opts: opts = '' return _git_run('git rebase {0} {1}'.format(opts, rev), cwd=cwd, runas=user) def checkout(cwd, rev, force=False, opts=None, user=None): _check_git() if not opts: opts = '' cmd = 'git checkout {0} {1} {2}'.format(' -f' if force else '', rev, opts) return _git_run(cmd, cwd=cwd, runas=user) def merge(cwd, branch='@{upstream}', opts=None, user=None): _check_git() if not opts: opts = '' cmd = 'git merge {0} {1}'.format(branch, opts) return _git_run(cmd, cwd, runas=user) def init(cwd, opts=None, user=None): _check_git() cmd = 'git init {0} {1}'.format(cwd, opts) return _git_run(cmd, runas=user) def submodule(cwd, init=True, opts=None, user=None, identity=None): _check_git() if not opts: opts = '' cmd = 'git submodule update {0} {1}'.format('--init' if init else '', opts) return _git_run(cmd, cwd=cwd, runas=user, identity=identity) def status(cwd, user=None): cmd = 'git status -z --porcelain' stdout = _git_run(cmd, cwd=cwd, runas=user) state_by_file = [] for line in stdout.split("\0"): state = line[:2] filename = line[3:] if filename != '' and state != '': state_by_file.append((state, filename)) return state_by_file def add(cwd, file_name, user=None, opts=None): if not opts: opts = '' cmd = 'git add {0} {1}'.format(file_name, opts) return _git_run(cmd, cwd=cwd, runas=user) def rm(cwd, file_name, user=None, opts=None): if not opts: opts = '' cmd = 'git rm {0} {1}'.format(file_name, opts) return _git_run(cmd, cwd=cwd, runas=user) def commit(cwd, message, user=None, opts=None): if not opts: opts = '' cmd = 'git commit -m {0} {1}'.format(pipes.quote(message), opts) return _git_run(cmd, cwd=cwd, runas=user) def push(cwd, remote_name, branch='master', user=None, opts=None, identity=None): if not opts: opts = '' cmd = 'git push {0} {1} {2}'.format(remote_name, branch, opts) return _git_run(cmd, cwd=cwd, runas=user, identity=identity) def remotes(cwd, user=None): cmd = 'git remote' ret = _git_run(cmd, cwd=cwd, runas=user) res = dict() for remote_name in ret.splitlines(): remote = remote_name.strip() res[remote] = remote_get(cwd, remote, user=user) return res def remote_get(cwd, remote='origin', user=None): try: cmd = 'git remote show -n {0}'.format(remote) ret = _git_run(cmd, cwd=cwd, runas=user) lines = ret.splitlines() remote_fetch_url = lines[1].replace('Fetch URL: ', '').strip() remote_push_url = lines[2].replace('Push URL: ', '').strip() if remote_fetch_url != remote and remote_push_url != remote: res = (remote_fetch_url, remote_push_url) return res else: return None except exceptions.CommandExecutionError: return None def remote_set(cwd, name='origin', url=None, user=None): if remote_get(cwd, name): cmd = 'git remote rm {0}'.format(name) _git_run(cmd, cwd=cwd, runas=user) cmd = 'git remote add {0} {1}'.format(name, url) _git_run(cmd, cwd=cwd, runas=user) return remote_get(cwd=cwd, remote=name, user=None) def reset(cwd, opts=None, user=None): _check_git() if not opts: opts = '' return _git_run('git reset {0}'.format(opts), cwd=cwd, runas=user) def stash(cwd, opts=None, user=None): _check_git() if not opts: opts = '' return _git_run('git stash {0}'.format(opts), cwd=cwd, runas=user) def config_set(cwd, setting_name, setting_value, user=None, is_global=False): scope = '--local' if is_global: scope = '--global' _check_git() return _git_run('git config {0} {1} {2}'.format(scope, setting_name, setting_value), cwd=cwd, runas=user) def config_get(cwd, setting_name, user=None): _check_git() return _git_run('git config {0}'.format(setting_name), cwd=cwd, runas=user) def ls_remote(cwd, repository="origin", branch="master", user=None, identity=None): _check_git() cmd = "git ls-remote -h " + repository + " " + branch + " | cut -f 1" return _git_run(cmd, cwd=cwd, runas=user, identity=identity)
true
true
f7fa030a742a453268be46a56f4cef688012241a
387
py
Python
demo_Run_One_Python_Script_From_within_another.py
OSHI7/Learning1
fa8014066e226465bb7989fbbb82a35412c4f634
[ "MIT" ]
null
null
null
demo_Run_One_Python_Script_From_within_another.py
OSHI7/Learning1
fa8014066e226465bb7989fbbb82a35412c4f634
[ "MIT" ]
3
2020-03-24T18:02:39.000Z
2020-10-06T21:32:23.000Z
demo_Run_One_Python_Script_From_within_another.py
OSHI7/Learning1
fa8014066e226465bb7989fbbb82a35412c4f634
[ "MIT" ]
1
2017-07-31T13:15:54.000Z
2017-07-31T13:15:54.000Z
# EDITOR > File and Code Templates put this here! # runfile('D:/Works/Python/Learning1/mySimpleClassExample.py', wdir='D:/Works/Python/Learning1') # runfile('D:/Works/Python/Learning1/mySimpleClassExample.py', wdir='D:/Works/Python/Learning1') #%% from subprocess import call call(["python", "mySimpleClassExample.py"]) call(["python", "mySimpleClassExample.py"]) print('hi') # %%
24.1875
96
0.728682
from subprocess import call call(["python", "mySimpleClassExample.py"]) call(["python", "mySimpleClassExample.py"]) print('hi')
true
true
f7fa03701088dda9555ccf4eecd3ac6b044a02c4
102
py
Python
suites/Operations/Sidechain/ERC20.py
echoprotocol/pytests
5dce698558c2ba703aea03aab79906af1437da5d
[ "MIT" ]
1
2021-03-12T05:17:02.000Z
2021-03-12T05:17:02.000Z
suites/Operations/Sidechain/ERC20.py
echoprotocol/pytests
5dce698558c2ba703aea03aab79906af1437da5d
[ "MIT" ]
1
2019-11-19T12:10:59.000Z
2019-11-19T12:10:59.000Z
suites/Operations/Sidechain/ERC20.py
echoprotocol/pytests
5dce698558c2ba703aea03aab79906af1437da5d
[ "MIT" ]
2
2019-04-29T10:46:48.000Z
2019-10-29T10:01:03.000Z
# -*- coding: utf-8 -*- import lemoncheesecake.api as lcc @lcc.suite("ERC20") class ERC20: pass
12.75
33
0.647059
import lemoncheesecake.api as lcc @lcc.suite("ERC20") class ERC20: pass
true
true
f7fa03c5dde285160c1688b5d8d829965b654d85
6,958
py
Python
examples/example.py
buttplugio/buttplug-py
ad1972e23143beb5fcb67586f1612d264f87fb17
[ "Apache-2.0" ]
58
2018-11-06T12:08:33.000Z
2022-02-18T07:10:48.000Z
examples/example.py
buttplugio/buttplug-py
ad1972e23143beb5fcb67586f1612d264f87fb17
[ "Apache-2.0" ]
13
2019-07-23T01:54:00.000Z
2021-06-11T17:54:14.000Z
examples/example.py
buttplugio/buttplug-py
ad1972e23143beb5fcb67586f1612d264f87fb17
[ "Apache-2.0" ]
11
2019-10-16T03:11:15.000Z
2022-02-25T02:40:49.000Z
# buttplug-py example code # # Buttplug Clients are fairly simple things, in charge of the following # tasks: # # - Connect to a Buttplug Server and Identify Itself # - Enumerate Devices # - Control Found Devices # # That's about it, really. # # This is a program that connects to a server, scans for devices, and runs # commands on them when they are found. It'll be copiously commented so you # have some idea of what's going on and can maybe make something yourself. # # NOTE: We'll be talking about this in terms of execution flow, so you'll want # to start at the bottom and work your way up. # These are really the only things you actually need out of the library. The # Client and ClientDevice classes wrap all of the functionality you'll need to # talk to servers and access toys. from buttplug.client import (ButtplugClientWebsocketConnector, ButtplugClient, ButtplugClientDevice, ButtplugClientConnectorError) from buttplug.core import ButtplugLogLevel import asyncio import logging import sys async def cancel_me(): logging.debug('cancel_me(): before sleep') try: await asyncio.sleep(3600) except asyncio.CancelledError: pass async def device_added_task(dev: ButtplugClientDevice): # Ok, so we got a new device in! Neat! # # First off, we'll print the name of the devices. logging.info("Device Added: {}".format(dev.name)) # Once we've done that, we can send some commands to the device, depending # on what it can do. As of the current version I'm writing this for # (v0.0.3), all the client can send to devices are generic messages. # Specifically: # # - VibrateCmd # - RotateCmd # - LinearCmd # # However, this is good enough to still do a lot of stuff. # # These capabilities are held in the "messages" member of the # ButtplugClientDevice. if "VibrateCmd" in dev.allowed_messages.keys(): # If we see that "VibrateCmd" is an allowed message, it means the # device can vibrate. We can call send_vibrate_cmd on the device and # it'll tell the server to make the device start vibrating. await dev.send_vibrate_cmd(0.5) # We let it vibrate at 50% speed for 1 second, then we stop it. await asyncio.sleep(1) # We can use send_stop_device_cmd to stop the device from vibrating, as # well as anything else it's doing. If the device was vibrating AND # rotating, we could use send_vibrate_cmd(0) to just stop the # vibration. await dev.send_stop_device_cmd() if "LinearCmd" in dev.allowed_messages.keys(): # If we see that "LinearCmd" is an allowed message, it means the device # can move back and forth. We can call send_linear_cmd on the device # and it'll tell the server to make the device move to 90% of the # maximum position over 1 second (1000ms). await dev.send_linear_cmd((1000, 0.9)) # We wait 1 second for the move, then we move it back to the 0% # position. await asyncio.sleep(1) await dev.send_linear_cmd((1000, 0)) def device_added(emitter, dev: ButtplugClientDevice): asyncio.create_task(device_added_task(dev)) def device_removed(emitter, dev: ButtplugClientDevice): logging.info("Device removed: ", dev) async def main(): # And now we're in the main function. # # First, we'll need to set up a client object. This is our conduit to the # server. # # We create a Client object, passing it the name we want for the client. # Names are shown in things like the Intiface Desktop Server GUI. client = ButtplugClient("Test Client") # Now we have a client called "Test Client", but it's not connected to # anything yet. We can fix that by creating a connector. Connectors # allow clients to talk to servers through different methods, including: # # - Websockets # - IPC (Not currently available in Python) # - WebRTC (Not currently available in Python) # - TCP/UDP (Not currently available in Python) # # For now, all we've implemented in python is a Websocket connector, so # we'll use that. connector = ButtplugClientWebsocketConnector("ws://127.0.0.1:12345") # This connector will connect to Intiface Desktop on the local machine, # using the default port for insecure websockets. # # There's one more step before we connect to a client, and that's # setting up an event handler. client.device_added_handler += device_added client.device_removed_handler += device_removed # Whenever we connect to a client, we'll instantly get a list of devices # already connected (yes, this sometimes happens, mostly due to windows # weirdness). We'll want to make sure we know about those. # # Finally, we connect. try: await client.connect(connector) except ButtplugClientConnectorError as e: logging.error("Could not connect to server, exiting: {}".format(e.message)) return # If this succeeds, we'll be connected. If not, we'll probably have some # sort of exception thrown of type ButtplugClientConnectorException # # Let's receive log messages, since they're a handy way to find out what # the server is doing. We can choose the level from the ButtplugLogLevel # object. # await client.request_log(ButtplugLogLevel.info) # Now we move on to looking for devices. await client.start_scanning() # This will tell the server to start scanning for devices, and returns # while it's scanning. If we get any new devices, the device_added_task # function that we assigned as an event handler earlier will be called. # # Since everything interesting happens after devices have connected, now # all we have to do here is wait. So we do, asynchronously, so other things # can continue running. Now that you've made it this far, go look at what # the device_added_task does. task = asyncio.create_task(cancel_me()) try: await task except asyncio.CancelledError: pass # Ok so someone hit Ctrl-C or something and we've broken out of our task # wait. Let's tell the server to stop scanning. await client.stop_scanning() # Now that we've done that, we just disconnect and we're done! await client.disconnect() logging.info("Disconnected, quitting") # Here we are. The beginning. We'll spin up an asyncio event loop that runs the # main function. Remember that if you don't want to make your whole program # async (because, for instance, it's already written in a non-async way), you # can always create a thread for the asyncio loop to run in, and do some sort # of communication in/out of that thread to the rest of your program. # # But first, set up logging logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) asyncio.run(main(), debug=True)
38.655556
83
0.699483
# # This is a program that connects to a server, scans for devices, and runs # commands on them when they are found. It'll be copiously commented so you # # NOTE: We'll be talking about this in terms of execution flow, so you'll want # to start at the bottom and work your way up. # These are really the only things you actually need out of the library. The # Client and ClientDevice classes wrap all of the functionality you'll need to from buttplug.client import (ButtplugClientWebsocketConnector, ButtplugClient, ButtplugClientDevice, ButtplugClientConnectorError) from buttplug.core import ButtplugLogLevel import asyncio import logging import sys async def cancel_me(): logging.debug('cancel_me(): before sleep') try: await asyncio.sleep(3600) except asyncio.CancelledError: pass async def device_added_task(dev: ButtplugClientDevice): logging.info("Device Added: {}".format(dev.name)) # Once we've done that, we can send some commands to the device, depending # (v0.0.3), all the client can send to devices are generic messages. # Specifically: # # - VibrateCmd # - RotateCmd # - LinearCmd # # However, this is good enough to still do a lot of stuff. # # These capabilities are held in the "messages" member of the # ButtplugClientDevice. if "VibrateCmd" in dev.allowed_messages.keys(): # If we see that "VibrateCmd" is an allowed message, it means the # device can vibrate. We can call send_vibrate_cmd on the device and # it'll tell the server to make the device start vibrating. await dev.send_vibrate_cmd(0.5) await asyncio.sleep(1) # rotating, we could use send_vibrate_cmd(0) to just stop the # vibration. await dev.send_stop_device_cmd() if "LinearCmd" in dev.allowed_messages.keys(): # If we see that "LinearCmd" is an allowed message, it means the device # can move back and forth. We can call send_linear_cmd on the device # and it'll tell the server to make the device move to 90% of the await dev.send_linear_cmd((1000, 0.9)) await asyncio.sleep(1) await dev.send_linear_cmd((1000, 0)) def device_added(emitter, dev: ButtplugClientDevice): asyncio.create_task(device_added_task(dev)) def device_removed(emitter, dev: ButtplugClientDevice): logging.info("Device removed: ", dev) async def main(): # # First, we'll need to set up a client object. This is our conduit to the client = ButtplugClient("Test Client") # anything yet. We can fix that by creating a connector. Connectors # allow clients to talk to servers through different methods, including: # # - Websockets # - IPC (Not currently available in Python) # - WebRTC (Not currently available in Python) # - TCP/UDP (Not currently available in Python) # # For now, all we've implemented in python is a Websocket connector, so connector = ButtplugClientWebsocketConnector("ws://127.0.0.1:12345") # This connector will connect to Intiface Desktop on the local machine, # using the default port for insecure websockets. # # There's one more step before we connect to a client, and that's # setting up an event handler. client.device_added_handler += device_added client.device_removed_handler += device_removed # Whenever we connect to a client, we'll instantly get a list of devices # # Finally, we connect. try: await client.connect(connector) except ButtplugClientConnectorError as e: logging.error("Could not connect to server, exiting: {}".format(e.message)) return # If this succeeds, we'll be connected. If not, we'll probably have some # sort of exception thrown of type ButtplugClientConnectorException # # Let's receive log messages, since they're a handy way to find out what # the server is doing. We can choose the level from the ButtplugLogLevel # object. # await client.request_log(ButtplugLogLevel.info) # Now we move on to looking for devices. await client.start_scanning() # This will tell the server to start scanning for devices, and returns # while it's scanning. If we get any new devices, the device_added_task # the device_added_task does. task = asyncio.create_task(cancel_me()) try: await task except asyncio.CancelledError: pass # Ok so someone hit Ctrl-C or something and we've broken out of our task await client.stop_scanning() # Now that we've done that, we just disconnect and we're done! await client.disconnect() logging.info("Disconnected, quitting") # Here we are. The beginning. We'll spin up an asyncio event loop that runs the # async (because, for instance, it's already written in a non-async way), you logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) asyncio.run(main(), debug=True)
true
true
f7fa03d78efb1f827c11da63ae39c5e9dd95ea51
12,400
py
Python
aiida/cmdline/utils/ascii_vis.py
aiace9/aiida-core
09ac91654648adb684a58d5d2d7b1c11a503dae8
[ "MIT", "BSD-3-Clause" ]
1
2016-09-12T10:51:00.000Z
2016-09-12T10:51:00.000Z
aiida/cmdline/utils/ascii_vis.py
blokhin/aiida-core
29331b558b45ba74acf1ca633a2d8bfabc1bdd05
[ "MIT", "BSD-3-Clause" ]
17
2020-03-11T17:04:05.000Z
2020-05-01T09:34:45.000Z
aiida/cmdline/utils/ascii_vis.py
blokhin/aiida-core
29331b558b45ba74acf1ca633a2d8bfabc1bdd05
[ "MIT", "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # # # The code is hosted on GitHub at https://github.com/aiidateam/aiida-core # # For further information on the license, see the LICENSE.txt file # # For further information please visit http://www.aiida.net # ########################################################################### """Utility functions to draw ASCII diagrams to the command line.""" from aiida.common.links import LinkType __all__ = ('draw_children', 'draw_parents', 'format_call_graph') TREE_LAST_ENTRY = '\u2514\u2500\u2500 ' TREE_MIDDLE_ENTRY = '\u251C\u2500\u2500 ' TREE_FIRST_ENTRY = TREE_MIDDLE_ENTRY class NodeTreePrinter: """Utility functions for printing node trees. .. deprecated:: 1.1.0 Will be removed in `v2.0.0`. """ # Note: when removing this code, also remove the `ete3` as a dependency as it will no longer be used. @classmethod def print_node_tree(cls, node, max_depth, follow_links=()): """Top-level function for printing node tree.""" import warnings from aiida.common.warnings import AiidaDeprecationWarning warnings.warn('class is deprecated and will be removed in `aiida-core==2.0.0`.', AiidaDeprecationWarning) # pylint: disable=no-member from ete3 import Tree from aiida.cmdline.utils.common import get_node_summary from aiida.cmdline.utils import echo echo.echo(get_node_summary(node)) tree_string = f'({cls._build_tree(node, max_depth=max_depth, follow_links=follow_links)});' tmp = Tree(tree_string, format=1) echo.echo(tmp.get_ascii(show_internal=True)) @staticmethod def _ctime(link_triple): return link_triple.node.ctime @classmethod def _build_tree(cls, node, show_pk=True, max_depth=None, follow_links=(), depth=0): """Return string with tree.""" if max_depth is not None and depth > max_depth: return None children = [] for entry in sorted(node.get_outgoing(link_type=follow_links).all(), key=cls._ctime): child_str = cls._build_tree( entry.node, show_pk, follow_links=follow_links, max_depth=max_depth, depth=depth + 1 ) if child_str: children.append(child_str) out_values = [] if children: out_values.append('(') out_values.append(', '.join(children)) out_values.append(')') lab = node.__class__.__name__ if show_pk: lab += f' [{node.pk}]' out_values.append(lab) return ''.join(out_values) def draw_parents(node, node_label=None, show_pk=True, dist=2, follow_links_of_type=None): """ Print an ASCII tree of the parents of the given node. .. deprecated:: 1.1.0 Will be removed in `v2.0.0`. :param node: The node to draw for :type node: :class:`aiida.orm.nodes.data.Data` :param node_label: The label to use for the nodes :type node_label: str :param show_pk: Show the PK of nodes alongside the label :type show_pk: bool :param dist: The number of steps away from this node to branch out :type dist: int :param follow_links_of_type: Follow links of this type when making steps, if None then it will follow CREATE and INPUT links :type follow_links_of_type: str """ import warnings from aiida.common.warnings import AiidaDeprecationWarning warnings.warn('function is deprecated and will be removed in `aiida-core==2.0.0`.', AiidaDeprecationWarning) # pylint: disable=no-member return get_ascii_tree(node, node_label, show_pk, dist, follow_links_of_type, False) def draw_children(node, node_label=None, show_pk=True, dist=2, follow_links_of_type=None): """ Print an ASCII tree of the parents of the given node. .. deprecated:: 1.1.0 Will be removed in `v2.0.0`. :param node: The node to draw for :type node: :class:`aiida.orm.nodes.data.Data` :param node_label: The label to use for the nodes :type node_label: str :param show_pk: Show the PK of nodes alongside the label :type show_pk: bool :param dist: The number of steps away from this node to branch out :type dist: int :param follow_links_of_type: Follow links of this type when making steps, if None then it will follow CREATE and INPUT links :type follow_links_of_type: str """ import warnings from aiida.common.warnings import AiidaDeprecationWarning warnings.warn('function is deprecated and will be removed in `aiida-core==2.0.0`.', AiidaDeprecationWarning) # pylint: disable=no-member return get_ascii_tree(node, node_label, show_pk, dist, follow_links_of_type, True) def get_ascii_tree(node, node_label=None, show_pk=True, max_depth=1, follow_links_of_type=None, descend=True): """ Get a string representing an ASCII tree for the given node. .. deprecated:: 1.1.0 Will be removed in `v2.0.0`. :param node: The node to get the tree for :type node: :class:`aiida.orm.nodes.node.Node` :param node_label: What to label the nodes with (can be an attribute name) :type node_label: str :param show_pk: If True, show the pk with the node label :type show_pk: bool :param max_depth: The maximum depth to follow starting from the node :type max_depth: int :param follow_links_of_type: Follow links of a given type, can be None :type follow_links_of_type: One of the members from :class:`aiida.common.links.LinkType` :param descend: if True will follow outputs, if False inputs :type descend: bool :return: The string giving an ASCII representation of the tree from the node :rtype: str """ import warnings from aiida.common.warnings import AiidaDeprecationWarning warnings.warn('function is deprecated and will be removed in `aiida-core==2.0.0`.', AiidaDeprecationWarning) # pylint: disable=no-member from ete3 import Tree tree_string = build_tree(node, node_label, show_pk, max_depth, follow_links_of_type, descend) tree = Tree(f'({tree_string});', format=1) return tree.get_ascii(show_internal=True) def build_tree(node, node_label=None, show_pk=True, max_depth=1, follow_links_of_type=None, descend=True, depth=0): """ Recursively build an ASCII string representation of the node tree .. deprecated:: 1.1.0 Will be removed in `v2.0.0`. :param node: The node to get the tree for :type node: :class:`aiida.orm.nodes.node.Node` :param node_label: What to label the nodes with (can be an attribute name) :type node_label: str :param show_pk: If True, show the pk with the node label :type show_pk: bool :param max_depth: The maximum depth to follow starting from the node :type max_depth: int :param follow_links_of_type: Follow links of a given type, can be None :type follow_links_of_type: One of the members from :class:`aiida.common.links.LinkType` :param descend: if True will follow outputs, if False inputs :type descend: bool :param depth: the current depth :type depth: int :return: The string giving an ASCII representation of the tree from the node :rtype: str """ # pylint: disable=too-many-arguments import warnings from aiida.common.warnings import AiidaDeprecationWarning warnings.warn('function is deprecated and will be removed in `aiida-core==2.0.0`.', AiidaDeprecationWarning) # pylint: disable=no-member out_values = [] if depth < max_depth: relatives = [] if descend: outputs = node.get_outgoing(link_type=follow_links_of_type).all_nodes() else: # ascend if follow_links_of_type is None: follow_links_of_type = (LinkType.CREATE, LinkType.INPUT_CALC, LinkType.INPUT_WORK) outputs = node.get_incoming(link_type=follow_links_of_type).all_nodes() for child in sorted(outputs, key=lambda node: node.ctime): relatives.append( build_tree(child, node_label, show_pk, max_depth, follow_links_of_type, descend, depth + 1) ) if relatives: out_values.append(f"({', '.join(relatives)})") out_values.append(_generate_node_label(node, node_label, show_pk)) return ''.join(out_values) def _generate_node_label(node, node_attr, show_pk): """ Generate a label for the node. .. deprecated:: 1.1.0 Will be removed in `v2.0.0`. :param node: The node to generate the label for :type node: :class:`aiida.orm.nodes.node.Node` :param node_attr: The attribute to use as the label, can be None :type node_attr: str :param show_pk: if True, show the PK alongside the label :type show_pk: bool :return: The generated label :rtype: str """ import warnings from aiida.common.warnings import AiidaDeprecationWarning warnings.warn('function is deprecated and will be removed in `aiida-core==2.0.0`.', AiidaDeprecationWarning) # pylint: disable=no-member label = None if node_attr is None: try: label = node.process_label except AttributeError: label = None else: try: label = str(getattr(node, node_attr)) except AttributeError: try: label = node.get_attribute(node_attr) except AttributeError: pass # Couldn't find one, so just use the class name if label is None: label = node.__class__.__name__ if show_pk: label += f' [{node.pk}]' return label def calc_info(node): """Return a string with the summary of the state of a CalculationNode.""" from aiida.orm import ProcessNode, WorkChainNode if not isinstance(node, ProcessNode): raise TypeError(f'Unknown type: {type(node)}') process_label = node.process_label process_state = node.process_state.value.capitalize() exit_status = node.exit_status if exit_status is not None: string = f'{process_label}<{node.pk}> {process_state} [{exit_status}]' else: string = f'{process_label}<{node.pk}> {process_state}' if isinstance(node, WorkChainNode) and node.stepper_state_info: string += f' [{node.stepper_state_info}]' return string def format_call_graph(calc_node, info_fn=calc_info): """ Print a tree like the POSIX tree command for the calculation call graph :param calc_node: The calculation node :param info_fn: An optional function that takes the node and returns a string of information to be displayed for each node. """ call_tree = build_call_graph(calc_node, info_fn=info_fn) return format_tree_descending(call_tree) def build_call_graph(calc_node, info_fn=calc_info): """Build the call graph of a given node.""" info_string = info_fn(calc_node) called = calc_node.called called.sort(key=lambda x: x.ctime) if called: return info_string, [build_call_graph(child, info_fn) for child in called] return info_string def format_tree_descending(tree, prefix='', pos=-1): """Format a descending tree.""" # pylint: disable=too-many-branches text = [] if isinstance(tree, tuple): info = tree[0] else: info = tree if pos == -1: pre = '' elif pos == 0: pre = f'{prefix}{TREE_FIRST_ENTRY}' elif pos == 1: pre = f'{prefix}{TREE_MIDDLE_ENTRY}' else: pre = f'{prefix}{TREE_LAST_ENTRY}' text.append(f'{pre}{info}') if isinstance(tree, tuple): _, value = tree num_entries = len(value) if pos in [-1, 2]: new_prefix = f'{prefix} ' else: new_prefix = f'{prefix}│ ' for i, entry in enumerate(value): if i == num_entries - 1: pos = 2 elif i == 0: pos = 0 else: pos = 1 text.append(format_tree_descending(entry, new_prefix, pos)) return '\n'.join(text)
36.25731
142
0.649677
tate}' if isinstance(node, WorkChainNode) and node.stepper_state_info: string += f' [{node.stepper_state_info}]' return string def format_call_graph(calc_node, info_fn=calc_info): call_tree = build_call_graph(calc_node, info_fn=info_fn) return format_tree_descending(call_tree) def build_call_graph(calc_node, info_fn=calc_info): info_string = info_fn(calc_node) called = calc_node.called called.sort(key=lambda x: x.ctime) if called: return info_string, [build_call_graph(child, info_fn) for child in called] return info_string def format_tree_descending(tree, prefix='', pos=-1): # pylint: disable=too-many-branches text = [] if isinstance(tree, tuple): info = tree[0] else: info = tree if pos == -1: pre = '' elif pos == 0: pre = f'{prefix}{TREE_FIRST_ENTRY}' elif pos == 1: pre = f'{prefix}{TREE_MIDDLE_ENTRY}' else: pre = f'{prefix}{TREE_LAST_ENTRY}' text.append(f'{pre}{info}') if isinstance(tree, tuple): _, value = tree num_entries = len(value) if pos in [-1, 2]: new_prefix = f'{prefix} ' else: new_prefix = f'{prefix}│ ' for i, entry in enumerate(value): if i == num_entries - 1: pos = 2 elif i == 0: pos = 0 else: pos = 1 text.append(format_tree_descending(entry, new_prefix, pos)) return '\n'.join(text)
true
true
f7fa0509cdaae0288a44e4986f3df8c6537dcf1c
428
py
Python
models/MinMaxCaracteresRegla.py
zamudio-fabian/recuperacion-informacion
71751344b69ba6f822912319e02971da3fc02780
[ "MIT" ]
null
null
null
models/MinMaxCaracteresRegla.py
zamudio-fabian/recuperacion-informacion
71751344b69ba6f822912319e02971da3fc02780
[ "MIT" ]
null
null
null
models/MinMaxCaracteresRegla.py
zamudio-fabian/recuperacion-informacion
71751344b69ba6f822912319e02971da3fc02780
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import re from models.Regla import * class MinMaxCaracteresRegla(Regla): minCarac = 3 maxCarac = 20 def __init__(self): pass def run(self,tokens): tokensAux = [] for token in tokens: if len(token) >= self.minCarac and len(token) <= self.maxCarac : tokensAux.append(token) return tokensAux
20.380952
76
0.570093
import re from models.Regla import * class MinMaxCaracteresRegla(Regla): minCarac = 3 maxCarac = 20 def __init__(self): pass def run(self,tokens): tokensAux = [] for token in tokens: if len(token) >= self.minCarac and len(token) <= self.maxCarac : tokensAux.append(token) return tokensAux
true
true
f7fa0600f828e84b643a8ea7b4de0dd7c5a20724
600
py
Python
business/migrations/0003_businessprofile_ownby.py
koatse/ilikethem
962374ff8179a533dba3b00422d11bb819d8acde
[ "MIT" ]
null
null
null
business/migrations/0003_businessprofile_ownby.py
koatse/ilikethem
962374ff8179a533dba3b00422d11bb819d8acde
[ "MIT" ]
null
null
null
business/migrations/0003_businessprofile_ownby.py
koatse/ilikethem
962374ff8179a533dba3b00422d11bb819d8acde
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-04-08 22:36 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0005_userprofile_intro'), ('business', '0002_auto_20170408_2133'), ] operations = [ migrations.AddField( model_name='businessprofile', name='ownby', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='core.UserProfile'), ), ]
26.086957
115
0.651667
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0005_userprofile_intro'), ('business', '0002_auto_20170408_2133'), ] operations = [ migrations.AddField( model_name='businessprofile', name='ownby', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='core.UserProfile'), ), ]
true
true
f7fa065087f7105ee5795562f1524a3369c9eb2d
705
py
Python
40 Algorithm challenge/challenge 22.py
T0dCNg/All-In-One
f86d7f46d3a4fafde5c5d087cffe1e3414870c48
[ "Unlicense" ]
1
2022-01-27T16:28:51.000Z
2022-01-27T16:28:51.000Z
40 Algorithm challenge/challenge 22.py
T0dCNg/All-In-One
f86d7f46d3a4fafde5c5d087cffe1e3414870c48
[ "Unlicense" ]
null
null
null
40 Algorithm challenge/challenge 22.py
T0dCNg/All-In-One
f86d7f46d3a4fafde5c5d087cffe1e3414870c48
[ "Unlicense" ]
null
null
null
#Challenge 22 #Write an algorithm that: # Asks the user to input how many marks they got on a test. # It should then convert this to a grade between 1 to 9 using the table below and then output the grade to the user. # If they have not scored enough to be given a grade than a ‘U’ grade must be output. mark = int(imput("how many marks did you get on the test")) if mark >= 10: print("1") elif mark >= 20: print("2") elif mark >= 30: print("3") elif mark >= 40: print("4") elif mark >= 50: print("5") elif mark >= 60: print("6") elif mark >= 70: print("7") elif mark >= 80: print("8") elif mark >= 90: print("9")
20.735294
120
0.584397
mark = int(imput("how many marks did you get on the test")) if mark >= 10: print("1") elif mark >= 20: print("2") elif mark >= 30: print("3") elif mark >= 40: print("4") elif mark >= 50: print("5") elif mark >= 60: print("6") elif mark >= 70: print("7") elif mark >= 80: print("8") elif mark >= 90: print("9")
true
true
f7fa069a622caa04f1688563b7007a0fb5eadda0
759
py
Python
percms/celery.py
NicolasKiely/percms
dbfae2406a9ea79c273197d96c5b0e70010ad114
[ "MIT" ]
null
null
null
percms/celery.py
NicolasKiely/percms
dbfae2406a9ea79c273197d96c5b0e70010ad114
[ "MIT" ]
9
2016-09-15T05:12:36.000Z
2016-10-27T21:38:40.000Z
percms/celery.py
NicolasKiely/percms
dbfae2406a9ea79c273197d96c5b0e70010ad114
[ "MIT" ]
null
null
null
from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'percms.settings') app = Celery('percms', backend='redis://localhost') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self, x, y): print('%s + %s = %s ' % (x, y, x+y)) return x + y
31.625
66
0.747036
from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'percms.settings') app = Celery('percms', backend='redis://localhost') # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self, x, y): print('%s + %s = %s ' % (x, y, x+y)) return x + y
true
true
f7fa06ab8a487cdfc008a1e00e65fa6ce80e2f38
8,718
py
Python
spectral_cube/io/casa_image.py
low-sky/spectral-cube
d1a775c76bf329c23253d27a9f5a28ad40957b1c
[ "BSD-3-Clause" ]
null
null
null
spectral_cube/io/casa_image.py
low-sky/spectral-cube
d1a775c76bf329c23253d27a9f5a28ad40957b1c
[ "BSD-3-Clause" ]
null
null
null
spectral_cube/io/casa_image.py
low-sky/spectral-cube
d1a775c76bf329c23253d27a9f5a28ad40957b1c
[ "BSD-3-Clause" ]
null
null
null
from __future__ import print_function, absolute_import, division import warnings from astropy import units as u from astropy.io import registry as io_registry from radio_beam import Beam, Beams from .. import DaskSpectralCube, StokesSpectralCube, BooleanArrayMask, DaskVaryingResolutionSpectralCube from ..spectral_cube import BaseSpectralCube from .. import cube_utils from .. utils import BeamWarning from .. import wcs_utils from casa_formats_io import getdesc, coordsys_to_astropy_wcs, image_to_dask # Read and write from a CASA image. This has a few # complications. First, by default CASA does not return the # "python order" and so we either have to transpose the cube on # read or have dueling conventions. Second, CASA often has # degenerate stokes axes present in unpredictable places (3rd or # 4th without a clear expectation). We need to replicate these # when writing but don't want them in memory. By default, try to # yield the same array in memory that we would get from astropy. def is_casa_image(origin, filepath, fileobj, *args, **kwargs): # See note before StringWrapper definition from .core import StringWrapper if filepath is None and len(args) > 0: if isinstance(args[0], StringWrapper): filepath = args[0].value elif isinstance(args[0], str): filepath = args[0] return filepath is not None and filepath.lower().endswith('.image') def load_casa_image(filename, skipdata=False, memmap=True, skipvalid=False, skipcs=False, target_cls=None, use_dask=None, **kwargs): """ Load a cube (into memory?) from a CASA image. By default it will transpose the cube into a 'python' order and drop degenerate axes. These options can be suppressed. The object holds the coordsys object from the image in memory. """ if use_dask is None: use_dask = True if not use_dask: raise ValueError("Loading CASA datasets is not possible with use_dask=False") from .core import StringWrapper if isinstance(filename, StringWrapper): filename = filename.value # read in the data if not skipdata: data = image_to_dask(filename, memmap=memmap) # CASA stores validity of data as a mask if skipvalid: valid = None else: try: valid = image_to_dask(filename, memmap=memmap, mask=True) except FileNotFoundError: valid = None # transpose is dealt with within the cube object # read in coordinate system object desc = getdesc(filename) casa_cs = desc['_keywords_']['coords'] if 'units' in desc['_keywords_']: unit = desc['_keywords_']['units'] else: unit = '' imageinfo = desc['_keywords_']['imageinfo'] if 'perplanebeams' in imageinfo: beam_ = {'beams': imageinfo['perplanebeams']} beam_['nStokes'] = beam_['beams'].pop('nStokes') beam_['nChannels'] = beam_['beams'].pop('nChannels') beam_['beams'] = {key: {'*0': value} for key, value in list(beam_['beams'].items())} elif 'restoringbeam' in imageinfo: beam_ = imageinfo['restoringbeam'] else: beam_ = {} wcs = coordsys_to_astropy_wcs(casa_cs) del casa_cs if 'major' in beam_: beam = Beam(major=u.Quantity(beam_['major']['value'], unit=beam_['major']['unit']), minor=u.Quantity(beam_['minor']['value'], unit=beam_['minor']['unit']), pa=u.Quantity(beam_['positionangle']['value'], unit=beam_['positionangle']['unit']), ) elif 'beams' in beam_: bdict = beam_['beams'] if beam_['nStokes'] > 1: raise NotImplementedError() nbeams = len(bdict) assert nbeams == beam_['nChannels'] stokesidx = '*0' majors = [u.Quantity(bdict['*{0}'.format(ii)][stokesidx]['major']['value'], bdict['*{0}'.format(ii)][stokesidx]['major']['unit']) for ii in range(nbeams)] minors = [u.Quantity(bdict['*{0}'.format(ii)][stokesidx]['minor']['value'], bdict['*{0}'.format(ii)][stokesidx]['minor']['unit']) for ii in range(nbeams)] pas = [u.Quantity(bdict['*{0}'.format(ii)][stokesidx]['positionangle']['value'], bdict['*{0}'.format(ii)][stokesidx]['positionangle']['unit']) for ii in range(nbeams)] beams = Beams(major=u.Quantity(majors), minor=u.Quantity(minors), pa=u.Quantity(pas)) else: warnings.warn("No beam information found in CASA image.", BeamWarning) # don't need this yet # stokes = get_casa_axis(temp_cs, wanttype="Stokes", skipdeg=False,) # if stokes == None: # order = np.arange(self.data.ndim) # else: # order = [] # for ax in np.arange(self.data.ndim+1): # if ax == stokes: # continue # order.append(ax) # self.casa_cs = ia.coordsys(order) # This should work, but coordsys.reorder() has a bug # on the error checking. JIRA filed. Until then the # axes will be reversed from the original. # if transpose == True: # new_order = np.arange(self.data.ndim) # new_order = new_order[-1*np.arange(self.data.ndim)-1] # print new_order # self.casa_cs.reorder(new_order) meta = {'filename': filename, 'BUNIT': unit} if wcs.naxis == 3: data, wcs_slice = cube_utils._orient(data, wcs) if valid is not None: valid, _ = cube_utils._orient(valid, wcs) mask = BooleanArrayMask(valid, wcs_slice) else: mask = None if 'beam' in locals(): cube = DaskSpectralCube(data, wcs_slice, mask, meta=meta, beam=beam) elif 'beams' in locals(): cube = DaskVaryingResolutionSpectralCube(data, wcs_slice, mask, meta=meta, beams=beams) else: cube = DaskSpectralCube(data, wcs_slice, mask, meta=meta) # with #592, this is no longer true # we've already loaded the cube into memory because of CASA # limitations, so there's no reason to disallow operations # cube.allow_huge_operations = True if mask is not None: assert cube.mask.shape == cube.shape elif wcs.naxis == 4: if valid is not None: valid, _ = cube_utils._split_stokes(valid, wcs) data, wcs = cube_utils._split_stokes(data, wcs) mask = {} for component in data: data_, wcs_slice = cube_utils._orient(data[component], wcs) if valid is not None: valid_, _ = cube_utils._orient(valid[component], wcs) mask[component] = BooleanArrayMask(valid_, wcs_slice) else: mask[component] = None if 'beam' in locals(): data[component] = DaskSpectralCube(data_, wcs_slice, mask[component], meta=meta, beam=beam) elif 'beams' in locals(): data[component] = DaskVaryingResolutionSpectralCube(data_, wcs_slice, mask[component], meta=meta, beams=beams) else: data[component] = DaskSpectralCube(data_, wcs_slice, mask[component], meta=meta) data[component].allow_huge_operations = True cube = StokesSpectralCube(stokes_data=data) if mask['I'] is not None: assert cube.I.mask.shape == cube.shape assert wcs_utils.check_equality(cube.I.mask._wcs, cube.wcs) else: raise ValueError("CASA image has {0} dimensions, and therefore " "is not readable by spectral-cube.".format(wcs.naxis)) from .core import normalize_cube_stokes return normalize_cube_stokes(cube, target_cls=target_cls) io_registry.register_reader('casa', BaseSpectralCube, load_casa_image) io_registry.register_reader('casa_image', BaseSpectralCube, load_casa_image) io_registry.register_identifier('casa', BaseSpectralCube, is_casa_image) io_registry.register_reader('casa', StokesSpectralCube, load_casa_image) io_registry.register_reader('casa_image', StokesSpectralCube, load_casa_image) io_registry.register_identifier('casa', StokesSpectralCube, is_casa_image)
38.575221
112
0.602661
from __future__ import print_function, absolute_import, division import warnings from astropy import units as u from astropy.io import registry as io_registry from radio_beam import Beam, Beams from .. import DaskSpectralCube, StokesSpectralCube, BooleanArrayMask, DaskVaryingResolutionSpectralCube from ..spectral_cube import BaseSpectralCube from .. import cube_utils from .. utils import BeamWarning from .. import wcs_utils from casa_formats_io import getdesc, coordsys_to_astropy_wcs, image_to_dask # yield the same array in memory that we would get from astropy. def is_casa_image(origin, filepath, fileobj, *args, **kwargs): # See note before StringWrapper definition from .core import StringWrapper if filepath is None and len(args) > 0: if isinstance(args[0], StringWrapper): filepath = args[0].value elif isinstance(args[0], str): filepath = args[0] return filepath is not None and filepath.lower().endswith('.image') def load_casa_image(filename, skipdata=False, memmap=True, skipvalid=False, skipcs=False, target_cls=None, use_dask=None, **kwargs): if use_dask is None: use_dask = True if not use_dask: raise ValueError("Loading CASA datasets is not possible with use_dask=False") from .core import StringWrapper if isinstance(filename, StringWrapper): filename = filename.value # read in the data if not skipdata: data = image_to_dask(filename, memmap=memmap) # CASA stores validity of data as a mask if skipvalid: valid = None else: try: valid = image_to_dask(filename, memmap=memmap, mask=True) except FileNotFoundError: valid = None # transpose is dealt with within the cube object # read in coordinate system object desc = getdesc(filename) casa_cs = desc['_keywords_']['coords'] if 'units' in desc['_keywords_']: unit = desc['_keywords_']['units'] else: unit = '' imageinfo = desc['_keywords_']['imageinfo'] if 'perplanebeams' in imageinfo: beam_ = {'beams': imageinfo['perplanebeams']} beam_['nStokes'] = beam_['beams'].pop('nStokes') beam_['nChannels'] = beam_['beams'].pop('nChannels') beam_['beams'] = {key: {'*0': value} for key, value in list(beam_['beams'].items())} elif 'restoringbeam' in imageinfo: beam_ = imageinfo['restoringbeam'] else: beam_ = {} wcs = coordsys_to_astropy_wcs(casa_cs) del casa_cs if 'major' in beam_: beam = Beam(major=u.Quantity(beam_['major']['value'], unit=beam_['major']['unit']), minor=u.Quantity(beam_['minor']['value'], unit=beam_['minor']['unit']), pa=u.Quantity(beam_['positionangle']['value'], unit=beam_['positionangle']['unit']), ) elif 'beams' in beam_: bdict = beam_['beams'] if beam_['nStokes'] > 1: raise NotImplementedError() nbeams = len(bdict) assert nbeams == beam_['nChannels'] stokesidx = '*0' majors = [u.Quantity(bdict['*{0}'.format(ii)][stokesidx]['major']['value'], bdict['*{0}'.format(ii)][stokesidx]['major']['unit']) for ii in range(nbeams)] minors = [u.Quantity(bdict['*{0}'.format(ii)][stokesidx]['minor']['value'], bdict['*{0}'.format(ii)][stokesidx]['minor']['unit']) for ii in range(nbeams)] pas = [u.Quantity(bdict['*{0}'.format(ii)][stokesidx]['positionangle']['value'], bdict['*{0}'.format(ii)][stokesidx]['positionangle']['unit']) for ii in range(nbeams)] beams = Beams(major=u.Quantity(majors), minor=u.Quantity(minors), pa=u.Quantity(pas)) else: warnings.warn("No beam information found in CASA image.", BeamWarning) # don't need this yet meta = {'filename': filename, 'BUNIT': unit} if wcs.naxis == 3: data, wcs_slice = cube_utils._orient(data, wcs) if valid is not None: valid, _ = cube_utils._orient(valid, wcs) mask = BooleanArrayMask(valid, wcs_slice) else: mask = None if 'beam' in locals(): cube = DaskSpectralCube(data, wcs_slice, mask, meta=meta, beam=beam) elif 'beams' in locals(): cube = DaskVaryingResolutionSpectralCube(data, wcs_slice, mask, meta=meta, beams=beams) else: cube = DaskSpectralCube(data, wcs_slice, mask, meta=meta) ons, so there's no reason to disallow operations if mask is not None: assert cube.mask.shape == cube.shape elif wcs.naxis == 4: if valid is not None: valid, _ = cube_utils._split_stokes(valid, wcs) data, wcs = cube_utils._split_stokes(data, wcs) mask = {} for component in data: data_, wcs_slice = cube_utils._orient(data[component], wcs) if valid is not None: valid_, _ = cube_utils._orient(valid[component], wcs) mask[component] = BooleanArrayMask(valid_, wcs_slice) else: mask[component] = None if 'beam' in locals(): data[component] = DaskSpectralCube(data_, wcs_slice, mask[component], meta=meta, beam=beam) elif 'beams' in locals(): data[component] = DaskVaryingResolutionSpectralCube(data_, wcs_slice, mask[component], meta=meta, beams=beams) else: data[component] = DaskSpectralCube(data_, wcs_slice, mask[component], meta=meta) data[component].allow_huge_operations = True cube = StokesSpectralCube(stokes_data=data) if mask['I'] is not None: assert cube.I.mask.shape == cube.shape assert wcs_utils.check_equality(cube.I.mask._wcs, cube.wcs) else: raise ValueError("CASA image has {0} dimensions, and therefore " "is not readable by spectral-cube.".format(wcs.naxis)) from .core import normalize_cube_stokes return normalize_cube_stokes(cube, target_cls=target_cls) io_registry.register_reader('casa', BaseSpectralCube, load_casa_image) io_registry.register_reader('casa_image', BaseSpectralCube, load_casa_image) io_registry.register_identifier('casa', BaseSpectralCube, is_casa_image) io_registry.register_reader('casa', StokesSpectralCube, load_casa_image) io_registry.register_reader('casa_image', StokesSpectralCube, load_casa_image) io_registry.register_identifier('casa', StokesSpectralCube, is_casa_image)
true
true
f7fa070f60c6d6b5aad5a2bb5d8ef8e7121c88fa
153
py
Python
froide/account/profile_urls.py
rufuspollock/froide
8ef4dbdd54a74f8c986d59e90348dfdbd85c5da4
[ "MIT" ]
1
2015-10-25T22:51:28.000Z
2015-10-25T22:51:28.000Z
froide/account/profile_urls.py
okfse/froide
5ed80cf6550fb4cbc757029b2c860b53e784eb93
[ "MIT" ]
null
null
null
froide/account/profile_urls.py
okfse/froide
5ed80cf6550fb4cbc757029b2c860b53e784eb93
[ "MIT" ]
null
null
null
from django.conf.urls import patterns urlpatterns = patterns("froide.account.views", (r'^(?P<slug>[-\w\.]+)/$', 'profile', {}, 'account-profile') )
25.5
64
0.633987
from django.conf.urls import patterns urlpatterns = patterns("froide.account.views", (r'^(?P<slug>[-\w\.]+)/$', 'profile', {}, 'account-profile') )
true
true
f7fa0728074ca8565162c609a550899f58bb1480
1,021
py
Python
var/spack/repos/builtin/packages/py-azure-keyvault-certificates/package.py
player1537-forks/spack
822b7632222ec5a91dc7b7cda5fc0e08715bd47c
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
11
2015-10-04T02:17:46.000Z
2018-02-07T18:23:00.000Z
var/spack/repos/builtin/packages/py-azure-keyvault-certificates/package.py
player1537-forks/spack
822b7632222ec5a91dc7b7cda5fc0e08715bd47c
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
22
2017-08-01T22:45:10.000Z
2022-03-10T07:46:31.000Z
var/spack/repos/builtin/packages/py-azure-keyvault-certificates/package.py
player1537-forks/spack
822b7632222ec5a91dc7b7cda5fc0e08715bd47c
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
4
2016-06-10T17:57:39.000Z
2018-09-11T04:59:38.000Z
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) class PyAzureKeyvaultCertificates(PythonPackage): """Microsoft Azure Key Vault Certificates Client Library for Python.""" homepage = "https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-certificates" pypi = "azure-keyvault-certificates/azure-keyvault-certificates-4.1.0.zip" version('4.1.0', sha256='544f56480619e1db350f2e7b117b22af778e02174bd6bcb0af9ae00c50353419') depends_on('py-setuptools', type='build') depends_on('py-azure-core@1.2.1:1', type=('build', 'run')) depends_on('py-msrest@0.6.0:', type=('build', 'run')) depends_on('py-azure-keyvault-nspkg', when='^python@:2', type=('build', 'run')) depends_on('py-enum34@1.0.4:', when='^python@:3.3', type=('build', 'run')) depends_on('py-typing', when='^python@:3.4', type=('build', 'run'))
48.619048
115
0.711068
class PyAzureKeyvaultCertificates(PythonPackage): homepage = "https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/keyvault/azure-keyvault-certificates" pypi = "azure-keyvault-certificates/azure-keyvault-certificates-4.1.0.zip" version('4.1.0', sha256='544f56480619e1db350f2e7b117b22af778e02174bd6bcb0af9ae00c50353419') depends_on('py-setuptools', type='build') depends_on('py-azure-core@1.2.1:1', type=('build', 'run')) depends_on('py-msrest@0.6.0:', type=('build', 'run')) depends_on('py-azure-keyvault-nspkg', when='^python@:2', type=('build', 'run')) depends_on('py-enum34@1.0.4:', when='^python@:3.3', type=('build', 'run')) depends_on('py-typing', when='^python@:3.4', type=('build', 'run'))
true
true
f7fa0786f2059f8fb280ceb1dd9b69088add0f19
4,421
py
Python
action/event.py
RayaneCTX/discord-queue-bot
6f140a27c9daa6087b4cf12b871fc52f5eb8aa53
[ "MIT" ]
null
null
null
action/event.py
RayaneCTX/discord-queue-bot
6f140a27c9daa6087b4cf12b871fc52f5eb8aa53
[ "MIT" ]
null
null
null
action/event.py
RayaneCTX/discord-queue-bot
6f140a27c9daa6087b4cf12b871fc52f5eb8aa53
[ "MIT" ]
null
null
null
import os import discord from .helper import * from dotenv import load_dotenv load_dotenv() QUEUE_SERVER_NAME = os.getenv('QUEUE_SERVER_NAME') QUEUE_CHANNEL_NAME = os.getenv('QUEUE_CHANNEL_NAME') # Defines how the bot should respond to specific Discord events. def define_events(bot): # Retrieve the queue text channel. server = discord.utils.get(bot.guilds, name=QUEUE_SERVER_NAME) queue = discord.utils.get(server.text_channels, name=QUEUE_CHANNEL_NAME) # Event: the bot is connected and is ready. @bot.event async def on_ready(): print("{0.user} connected and ready.".format(bot)) # Clear the queue of all tickets. await purge_text_channel(queue) print("{0.name} purged.".format(queue)) # Event: a message was sent on the server. @bot.event async def on_message(message): # Ignore messages from the bot itself. if message.author is bot.user: return # If message was sent to the queue channel... if message.channel is queue: # Delete the message await message.delete() await bot.process_commands(message) # # Event: a message was sent on the server. # @queueBot.event # async def on_message(message): # global deletedByManager # # If message is from queueBot, ignore it. # if message.author == queueBot.user: # return # # Let the queueBot process the commands. # if message.content.startswith('!'): # await queueBot.process_commands(message) # return # # If message is from the queue channel... # if message.channel.name == CHANNEL_NAME: # # Delete the message before replacing it with a formal ticket. # deletedByManager = message # await message.delete() # # If client already has a message in the queue... # if message.author in [ticket.message.author for ticket in ticketQueue]: # # Do not create a formal ticket. Send reply instead. # reply = "You already have a request in the queue. You may not" \ # " have more than one request in a the queue at any given time." # await message.author.send(reply) # else: # # Create a formal ticket. # newTicket = Ticket(message) # ticketQueue.add(newTicket) # await output_ticket_queue(message.channel, ticketQueue, newTicket) # # Event: an error occured after a command issue. # @queueBot.event # async def on_command_error(context, exception): # # Because the client does not have permissions. # if isinstance(exception, commands.errors.MissingRole): # # Send a reply to the author in a private message. # reply = "You do not have permissions to execute this command." \ # " Make sure your message does not begin with '!' if did not intend" \ # " to type a command." # await context.author.send(reply) # # If the message is from the queue channel, delete it. # if context.channel.name == CHANNEL_NAME: # await context.message.delete() # elif isinstance(exception, commands.errors.NoPrivateMessage): # # Send a reply to the author in a private message. # reply = "You cannot execute this command in private messages." # await context.author.send(reply) # else: # print(type(exception)) # print(exception) # # # # # # # # # # Event: a message was deleted by a client. # @queueBot.event # async def on_message_delete(message): # global deletedByManager # global bulkDelete # global deletedCommand # # Ignore this event if the message was deleted by the queueBot. # if deletedByManager is message: # deletedByManager = None # return # # Ignore delete if part of a bulk deletion. # if bulkDelete is True: # return # # Ignore if this is a deleted command. # if message.content.startswith('!'): # return # # If message was from the queue channel... # if message.channel.name == CHANNEL_NAME: # # Remove the corresponding ticket from the queue. # for ticket in ticketQueue: # if ticket.message.author == message.author: # break # ticketQueue.remove(ticket) # reply = "Your request was removed from the wait queue." # await message.author.send(reply)
35.943089
81
0.642162
import os import discord from .helper import * from dotenv import load_dotenv load_dotenv() QUEUE_SERVER_NAME = os.getenv('QUEUE_SERVER_NAME') QUEUE_CHANNEL_NAME = os.getenv('QUEUE_CHANNEL_NAME') def define_events(bot): server = discord.utils.get(bot.guilds, name=QUEUE_SERVER_NAME) queue = discord.utils.get(server.text_channels, name=QUEUE_CHANNEL_NAME) @bot.event async def on_ready(): print("{0.user} connected and ready.".format(bot)) await purge_text_channel(queue) print("{0.name} purged.".format(queue)) @bot.event async def on_message(message): if message.author is bot.user: return if message.channel is queue: await message.delete() await bot.process_commands(message)
true
true
f7fa07916ca74301915131997b07be6ae25bb3a3
202,102
py
Python
pandas/tests/indexing/test_indexing.py
GeNikolja/pandas
7bb498083ce163f92822487dd4b15e9659dd45d7
[ "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "MIT", "BSD-3-Clause" ]
1
2019-04-28T13:48:34.000Z
2019-04-28T13:48:34.000Z
pandas/tests/indexing/test_indexing.py
GeNikolja/pandas
7bb498083ce163f92822487dd4b15e9659dd45d7
[ "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "MIT", "BSD-3-Clause" ]
null
null
null
pandas/tests/indexing/test_indexing.py
GeNikolja/pandas
7bb498083ce163f92822487dd4b15e9659dd45d7
[ "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "MIT", "BSD-3-Clause" ]
1
2019-04-28T13:48:35.000Z
2019-04-28T13:48:35.000Z
# -*- coding: utf-8 -*- # pylint: disable-msg=W0612,E1101 import sys import nose import itertools import warnings from warnings import catch_warnings from datetime import datetime from pandas.types.common import (is_integer_dtype, is_float_dtype, is_scalar) from pandas.compat import range, lrange, lzip, StringIO, lmap, map from pandas.tslib import NaT from numpy import nan from numpy.random import randn import numpy as np import pandas as pd import pandas.core.common as com from pandas import option_context from pandas.core.indexing import _non_reducing_slice, _maybe_numeric_slice from pandas.core.api import (DataFrame, Index, Series, Panel, isnull, MultiIndex, Timestamp, Timedelta, UInt64Index) from pandas.formats.printing import pprint_thing from pandas import concat from pandas.core.common import PerformanceWarning, UnsortedIndexError import pandas.util.testing as tm from pandas import date_range _verbose = False # ------------------------------------------------------------------------ # Indexing test cases def _generate_indices(f, values=False): """ generate the indicies if values is True , use the axis values is False, use the range """ axes = f.axes if values: axes = [lrange(len(a)) for a in axes] return itertools.product(*axes) def _get_value(f, i, values=False): """ return the value for the location i """ # check agains values if values: return f.values[i] # this is equiv of f[col][row]..... # v = f # for a in reversed(i): # v = v.__getitem__(a) # return v with catch_warnings(record=True): return f.ix[i] def _get_result(obj, method, key, axis): """ return the result for this obj with this key and this axis """ if isinstance(key, dict): key = key[axis] # use an artifical conversion to map the key as integers to the labels # so ix can work for comparisions if method == 'indexer': method = 'ix' key = obj._get_axis(axis)[key] # in case we actually want 0 index slicing try: xp = getattr(obj, method).__getitem__(_axify(obj, key, axis)) except: xp = getattr(obj, method).__getitem__(key) return xp def _axify(obj, key, axis): # create a tuple accessor axes = [slice(None)] * obj.ndim axes[axis] = key return tuple(axes) def _mklbl(prefix, n): return ["%s%s" % (prefix, i) for i in range(n)] class TestIndexing(tm.TestCase): _multiprocess_can_split_ = True _objs = set(['series', 'frame', 'panel']) _typs = set(['ints', 'uints', 'labels', 'mixed', 'ts', 'floats', 'empty', 'ts_rev']) def setUp(self): self.series_ints = Series(np.random.rand(4), index=lrange(0, 8, 2)) self.frame_ints = DataFrame(np.random.randn(4, 4), index=lrange(0, 8, 2), columns=lrange(0, 12, 3)) self.panel_ints = Panel(np.random.rand(4, 4, 4), items=lrange(0, 8, 2), major_axis=lrange(0, 12, 3), minor_axis=lrange(0, 16, 4)) self.series_uints = Series(np.random.rand(4), index=UInt64Index(lrange(0, 8, 2))) self.frame_uints = DataFrame(np.random.randn(4, 4), index=UInt64Index(lrange(0, 8, 2)), columns=UInt64Index(lrange(0, 12, 3))) self.panel_uints = Panel(np.random.rand(4, 4, 4), items=UInt64Index(lrange(0, 8, 2)), major_axis=UInt64Index(lrange(0, 12, 3)), minor_axis=UInt64Index(lrange(0, 16, 4))) self.series_labels = Series(np.random.randn(4), index=list('abcd')) self.frame_labels = DataFrame(np.random.randn(4, 4), index=list('abcd'), columns=list('ABCD')) self.panel_labels = Panel(np.random.randn(4, 4, 4), items=list('abcd'), major_axis=list('ABCD'), minor_axis=list('ZYXW')) self.series_mixed = Series(np.random.randn(4), index=[2, 4, 'null', 8]) self.frame_mixed = DataFrame(np.random.randn(4, 4), index=[2, 4, 'null', 8]) self.panel_mixed = Panel(np.random.randn(4, 4, 4), items=[2, 4, 'null', 8]) self.series_ts = Series(np.random.randn(4), index=date_range('20130101', periods=4)) self.frame_ts = DataFrame(np.random.randn(4, 4), index=date_range('20130101', periods=4)) self.panel_ts = Panel(np.random.randn(4, 4, 4), items=date_range('20130101', periods=4)) dates_rev = (date_range('20130101', periods=4) .sort_values(ascending=False)) self.series_ts_rev = Series(np.random.randn(4), index=dates_rev) self.frame_ts_rev = DataFrame(np.random.randn(4, 4), index=dates_rev) self.panel_ts_rev = Panel(np.random.randn(4, 4, 4), items=dates_rev) self.frame_empty = DataFrame({}) self.series_empty = Series({}) self.panel_empty = Panel({}) # form agglomerates for o in self._objs: d = dict() for t in self._typs: d[t] = getattr(self, '%s_%s' % (o, t), None) setattr(self, o, d) def check_values(self, f, func, values=False): if f is None: return axes = f.axes indicies = itertools.product(*axes) for i in indicies: result = getattr(f, func)[i] # check agains values if values: expected = f.values[i] else: expected = f for a in reversed(i): expected = expected.__getitem__(a) tm.assert_almost_equal(result, expected) def check_result(self, name, method1, key1, method2, key2, typs=None, objs=None, axes=None, fails=None): def _eq(t, o, a, obj, k1, k2): """ compare equal for these 2 keys """ if a is not None and a > obj.ndim - 1: return def _print(result, error=None): if error is not None: error = str(error) v = ("%-16.16s [%-16.16s]: [typ->%-8.8s,obj->%-8.8s," "key1->(%-4.4s),key2->(%-4.4s),axis->%s] %s" % (name, result, t, o, method1, method2, a, error or '')) if _verbose: pprint_thing(v) try: rs = getattr(obj, method1).__getitem__(_axify(obj, k1, a)) try: xp = _get_result(obj, method2, k2, a) except: result = 'no comp' _print(result) return detail = None try: if is_scalar(rs) and is_scalar(xp): self.assertEqual(rs, xp) elif xp.ndim == 1: tm.assert_series_equal(rs, xp) elif xp.ndim == 2: tm.assert_frame_equal(rs, xp) elif xp.ndim == 3: tm.assert_panel_equal(rs, xp) result = 'ok' except AssertionError as e: detail = str(e) result = 'fail' # reverse the checks if fails is True: if result == 'fail': result = 'ok (fail)' _print(result) if not result.startswith('ok'): raise AssertionError(detail) except AssertionError: raise except Exception as detail: # if we are in fails, the ok, otherwise raise it if fails is not None: if isinstance(detail, fails): result = 'ok (%s)' % type(detail).__name__ _print(result) return result = type(detail).__name__ raise AssertionError(_print(result, error=detail)) if typs is None: typs = self._typs if objs is None: objs = self._objs if axes is not None: if not isinstance(axes, (tuple, list)): axes = [axes] else: axes = list(axes) else: axes = [0, 1, 2] # check for o in objs: if o not in self._objs: continue d = getattr(self, o) for a in axes: for t in typs: if t not in self._typs: continue obj = d[t] if obj is not None: obj = obj.copy() k2 = key2 _eq(t, o, a, obj, key1, k2) def test_ix_deprecation(self): # GH 15114 df = DataFrame({'A': [1, 2, 3]}) with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False): df.ix[1, 'A'] def test_indexer_caching(self): # GH5727 # make sure that indexers are in the _internal_names_set n = 1000001 arrays = [lrange(n), lrange(n)] index = MultiIndex.from_tuples(lzip(*arrays)) s = Series(np.zeros(n), index=index) str(s) # setitem expected = Series(np.ones(n), index=index) s = Series(np.zeros(n), index=index) s[s == 0] = 1 tm.assert_series_equal(s, expected) def test_at_and_iat_get(self): def _check(f, func, values=False): if f is not None: indicies = _generate_indices(f, values) for i in indicies: result = getattr(f, func)[i] expected = _get_value(f, i, values) tm.assert_almost_equal(result, expected) for o in self._objs: d = getattr(self, o) # iat for f in [d['ints'], d['uints']]: _check(f, 'iat', values=True) for f in [d['labels'], d['ts'], d['floats']]: if f is not None: self.assertRaises(ValueError, self.check_values, f, 'iat') # at for f in [d['ints'], d['uints'], d['labels'], d['ts'], d['floats']]: _check(f, 'at') def test_at_and_iat_set(self): def _check(f, func, values=False): if f is not None: indicies = _generate_indices(f, values) for i in indicies: getattr(f, func)[i] = 1 expected = _get_value(f, i, values) tm.assert_almost_equal(expected, 1) for t in self._objs: d = getattr(self, t) # iat for f in [d['ints'], d['uints']]: _check(f, 'iat', values=True) for f in [d['labels'], d['ts'], d['floats']]: if f is not None: self.assertRaises(ValueError, _check, f, 'iat') # at for f in [d['ints'], d['uints'], d['labels'], d['ts'], d['floats']]: _check(f, 'at') def test_at_iat_coercion(self): # as timestamp is not a tuple! dates = date_range('1/1/2000', periods=8) df = DataFrame(randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D']) s = df['A'] result = s.at[dates[5]] xp = s.values[5] self.assertEqual(result, xp) # GH 7729 # make sure we are boxing the returns s = Series(['2014-01-01', '2014-02-02'], dtype='datetime64[ns]') expected = Timestamp('2014-02-02') for r in [lambda: s.iat[1], lambda: s.iloc[1]]: result = r() self.assertEqual(result, expected) s = Series(['1 days', '2 days'], dtype='timedelta64[ns]') expected = Timedelta('2 days') for r in [lambda: s.iat[1], lambda: s.iloc[1]]: result = r() self.assertEqual(result, expected) def test_iat_invalid_args(self): pass def test_imethods_with_dups(self): # GH6493 # iat/iloc with dups s = Series(range(5), index=[1, 1, 2, 2, 3], dtype='int64') result = s.iloc[2] self.assertEqual(result, 2) result = s.iat[2] self.assertEqual(result, 2) self.assertRaises(IndexError, lambda: s.iat[10]) self.assertRaises(IndexError, lambda: s.iat[-10]) result = s.iloc[[2, 3]] expected = Series([2, 3], [2, 2], dtype='int64') tm.assert_series_equal(result, expected) df = s.to_frame() result = df.iloc[2] expected = Series(2, index=[0], name=2) tm.assert_series_equal(result, expected) result = df.iat[2, 0] expected = 2 self.assertEqual(result, 2) def test_repeated_getitem_dups(self): # GH 5678 # repeated gettitems on a dup index returing a ndarray df = DataFrame( np.random.random_sample((20, 5)), index=['ABCDE' [x % 5] for x in range(20)]) expected = df.loc['A', 0] result = df.loc[:, 0].loc['A'] tm.assert_series_equal(result, expected) def test_iloc_exceeds_bounds(self): # GH6296 # iloc should allow indexers that exceed the bounds df = DataFrame(np.random.random_sample((20, 5)), columns=list('ABCDE')) expected = df # lists of positions should raise IndexErrror! with tm.assertRaisesRegexp(IndexError, 'positional indexers are out-of-bounds'): df.iloc[:, [0, 1, 2, 3, 4, 5]] self.assertRaises(IndexError, lambda: df.iloc[[1, 30]]) self.assertRaises(IndexError, lambda: df.iloc[[1, -30]]) self.assertRaises(IndexError, lambda: df.iloc[[100]]) s = df['A'] self.assertRaises(IndexError, lambda: s.iloc[[100]]) self.assertRaises(IndexError, lambda: s.iloc[[-100]]) # still raise on a single indexer msg = 'single positional indexer is out-of-bounds' with tm.assertRaisesRegexp(IndexError, msg): df.iloc[30] self.assertRaises(IndexError, lambda: df.iloc[-30]) # GH10779 # single positive/negative indexer exceeding Series bounds should raise # an IndexError with tm.assertRaisesRegexp(IndexError, msg): s.iloc[30] self.assertRaises(IndexError, lambda: s.iloc[-30]) # slices are ok result = df.iloc[:, 4:10] # 0 < start < len < stop expected = df.iloc[:, 4:] tm.assert_frame_equal(result, expected) result = df.iloc[:, -4:-10] # stop < 0 < start < len expected = df.iloc[:, :0] tm.assert_frame_equal(result, expected) result = df.iloc[:, 10:4:-1] # 0 < stop < len < start (down) expected = df.iloc[:, :4:-1] tm.assert_frame_equal(result, expected) result = df.iloc[:, 4:-10:-1] # stop < 0 < start < len (down) expected = df.iloc[:, 4::-1] tm.assert_frame_equal(result, expected) result = df.iloc[:, -10:4] # start < 0 < stop < len expected = df.iloc[:, :4] tm.assert_frame_equal(result, expected) result = df.iloc[:, 10:4] # 0 < stop < len < start expected = df.iloc[:, :0] tm.assert_frame_equal(result, expected) result = df.iloc[:, -10:-11:-1] # stop < start < 0 < len (down) expected = df.iloc[:, :0] tm.assert_frame_equal(result, expected) result = df.iloc[:, 10:11] # 0 < len < start < stop expected = df.iloc[:, :0] tm.assert_frame_equal(result, expected) # slice bounds exceeding is ok result = s.iloc[18:30] expected = s.iloc[18:] tm.assert_series_equal(result, expected) result = s.iloc[30:] expected = s.iloc[:0] tm.assert_series_equal(result, expected) result = s.iloc[30::-1] expected = s.iloc[::-1] tm.assert_series_equal(result, expected) # doc example def check(result, expected): str(result) result.dtypes tm.assert_frame_equal(result, expected) dfl = DataFrame(np.random.randn(5, 2), columns=list('AB')) check(dfl.iloc[:, 2:3], DataFrame(index=dfl.index)) check(dfl.iloc[:, 1:3], dfl.iloc[:, [1]]) check(dfl.iloc[4:6], dfl.iloc[[4]]) self.assertRaises(IndexError, lambda: dfl.iloc[[4, 5, 6]]) self.assertRaises(IndexError, lambda: dfl.iloc[:, 4]) def test_iloc_getitem_int(self): # integer self.check_result('integer', 'iloc', 2, 'ix', {0: 4, 1: 6, 2: 8}, typs=['ints', 'uints']) self.check_result('integer', 'iloc', 2, 'indexer', 2, typs=['labels', 'mixed', 'ts', 'floats', 'empty'], fails=IndexError) def test_iloc_getitem_neg_int(self): # neg integer self.check_result('neg int', 'iloc', -1, 'ix', {0: 6, 1: 9, 2: 12}, typs=['ints', 'uints']) self.check_result('neg int', 'iloc', -1, 'indexer', -1, typs=['labels', 'mixed', 'ts', 'floats', 'empty'], fails=IndexError) def test_iloc_getitem_list_int(self): # list of ints self.check_result('list int', 'iloc', [0, 1, 2], 'ix', {0: [0, 2, 4], 1: [0, 3, 6], 2: [0, 4, 8]}, typs=['ints', 'uints']) self.check_result('list int', 'iloc', [2], 'ix', {0: [4], 1: [6], 2: [8]}, typs=['ints', 'uints']) self.check_result('list int', 'iloc', [0, 1, 2], 'indexer', [0, 1, 2], typs=['labels', 'mixed', 'ts', 'floats', 'empty'], fails=IndexError) # array of ints (GH5006), make sure that a single indexer is returning # the correct type self.check_result('array int', 'iloc', np.array([0, 1, 2]), 'ix', {0: [0, 2, 4], 1: [0, 3, 6], 2: [0, 4, 8]}, typs=['ints', 'uints']) self.check_result('array int', 'iloc', np.array([2]), 'ix', {0: [4], 1: [6], 2: [8]}, typs=['ints', 'uints']) self.check_result('array int', 'iloc', np.array([0, 1, 2]), 'indexer', [0, 1, 2], typs=['labels', 'mixed', 'ts', 'floats', 'empty'], fails=IndexError) def test_iloc_getitem_neg_int_can_reach_first_index(self): # GH10547 and GH10779 # negative integers should be able to reach index 0 df = DataFrame({'A': [2, 3, 5], 'B': [7, 11, 13]}) s = df['A'] expected = df.iloc[0] result = df.iloc[-3] tm.assert_series_equal(result, expected) expected = df.iloc[[0]] result = df.iloc[[-3]] tm.assert_frame_equal(result, expected) expected = s.iloc[0] result = s.iloc[-3] self.assertEqual(result, expected) expected = s.iloc[[0]] result = s.iloc[[-3]] tm.assert_series_equal(result, expected) # check the length 1 Series case highlighted in GH10547 expected = pd.Series(['a'], index=['A']) result = expected.iloc[[-1]] tm.assert_series_equal(result, expected) def test_iloc_getitem_dups(self): # no dups in panel (bug?) self.check_result('list int (dups)', 'iloc', [0, 1, 1, 3], 'ix', {0: [0, 2, 2, 6], 1: [0, 3, 3, 9]}, objs=['series', 'frame'], typs=['ints', 'uints']) # GH 6766 df1 = DataFrame([{'A': None, 'B': 1}, {'A': 2, 'B': 2}]) df2 = DataFrame([{'A': 3, 'B': 3}, {'A': 4, 'B': 4}]) df = concat([df1, df2], axis=1) # cross-sectional indexing result = df.iloc[0, 0] self.assertTrue(isnull(result)) result = df.iloc[0, :] expected = Series([np.nan, 1, 3, 3], index=['A', 'B', 'A', 'B'], name=0) tm.assert_series_equal(result, expected) def test_iloc_getitem_array(self): # array like s = Series(index=lrange(1, 4)) self.check_result('array like', 'iloc', s.index, 'ix', {0: [2, 4, 6], 1: [3, 6, 9], 2: [4, 8, 12]}, typs=['ints', 'uints']) def test_iloc_getitem_bool(self): # boolean indexers b = [True, False, True, False, ] self.check_result('bool', 'iloc', b, 'ix', b, typs=['ints', 'uints']) self.check_result('bool', 'iloc', b, 'ix', b, typs=['labels', 'mixed', 'ts', 'floats', 'empty'], fails=IndexError) def test_iloc_getitem_slice(self): # slices self.check_result('slice', 'iloc', slice(1, 3), 'ix', {0: [2, 4], 1: [3, 6], 2: [4, 8]}, typs=['ints', 'uints']) self.check_result('slice', 'iloc', slice(1, 3), 'indexer', slice(1, 3), typs=['labels', 'mixed', 'ts', 'floats', 'empty'], fails=IndexError) def test_iloc_getitem_slice_dups(self): df1 = DataFrame(np.random.randn(10, 4), columns=['A', 'A', 'B', 'B']) df2 = DataFrame(np.random.randint(0, 10, size=20).reshape(10, 2), columns=['A', 'C']) # axis=1 df = concat([df1, df2], axis=1) tm.assert_frame_equal(df.iloc[:, :4], df1) tm.assert_frame_equal(df.iloc[:, 4:], df2) df = concat([df2, df1], axis=1) tm.assert_frame_equal(df.iloc[:, :2], df2) tm.assert_frame_equal(df.iloc[:, 2:], df1) exp = concat([df2, df1.iloc[:, [0]]], axis=1) tm.assert_frame_equal(df.iloc[:, 0:3], exp) # axis=0 df = concat([df, df], axis=0) tm.assert_frame_equal(df.iloc[0:10, :2], df2) tm.assert_frame_equal(df.iloc[0:10, 2:], df1) tm.assert_frame_equal(df.iloc[10:, :2], df2) tm.assert_frame_equal(df.iloc[10:, 2:], df1) def test_iloc_getitem_multiindex2(self): # TODO(wesm): fix this raise nose.SkipTest('this test was being suppressed, ' 'needs to be fixed') arr = np.random.randn(3, 3) df = DataFrame(arr, columns=[[2, 2, 4], [6, 8, 10]], index=[[4, 4, 8], [8, 10, 12]]) rs = df.iloc[2] xp = Series(arr[2], index=df.columns) tm.assert_series_equal(rs, xp) rs = df.iloc[:, 2] xp = Series(arr[:, 2], index=df.index) tm.assert_series_equal(rs, xp) rs = df.iloc[2, 2] xp = df.values[2, 2] self.assertEqual(rs, xp) # for multiple items # GH 5528 rs = df.iloc[[0, 1]] xp = df.xs(4, drop_level=False) tm.assert_frame_equal(rs, xp) tup = zip(*[['a', 'a', 'b', 'b'], ['x', 'y', 'x', 'y']]) index = MultiIndex.from_tuples(tup) df = DataFrame(np.random.randn(4, 4), index=index) rs = df.iloc[[2, 3]] xp = df.xs('b', drop_level=False) tm.assert_frame_equal(rs, xp) def test_iloc_setitem(self): df = self.frame_ints df.iloc[1, 1] = 1 result = df.iloc[1, 1] self.assertEqual(result, 1) df.iloc[:, 2:3] = 0 expected = df.iloc[:, 2:3] result = df.iloc[:, 2:3] tm.assert_frame_equal(result, expected) # GH5771 s = Series(0, index=[4, 5, 6]) s.iloc[1:2] += 1 expected = Series([0, 1, 0], index=[4, 5, 6]) tm.assert_series_equal(s, expected) def test_loc_setitem_slice(self): # GH10503 # assigning the same type should not change the type df1 = DataFrame({'a': [0, 1, 1], 'b': Series([100, 200, 300], dtype='uint32')}) ix = df1['a'] == 1 newb1 = df1.loc[ix, 'b'] + 1 df1.loc[ix, 'b'] = newb1 expected = DataFrame({'a': [0, 1, 1], 'b': Series([100, 201, 301], dtype='uint32')}) tm.assert_frame_equal(df1, expected) # assigning a new type should get the inferred type df2 = DataFrame({'a': [0, 1, 1], 'b': [100, 200, 300]}, dtype='uint64') ix = df1['a'] == 1 newb2 = df2.loc[ix, 'b'] df1.loc[ix, 'b'] = newb2 expected = DataFrame({'a': [0, 1, 1], 'b': [100, 200, 300]}, dtype='uint64') tm.assert_frame_equal(df2, expected) def test_ix_loc_setitem_consistency(self): # GH 5771 # loc with slice and series s = Series(0, index=[4, 5, 6]) s.loc[4:5] += 1 expected = Series([1, 1, 0], index=[4, 5, 6]) tm.assert_series_equal(s, expected) # GH 5928 # chained indexing assignment df = DataFrame({'a': [0, 1, 2]}) expected = df.copy() with catch_warnings(record=True): expected.ix[[0, 1, 2], 'a'] = -expected.ix[[0, 1, 2], 'a'] with catch_warnings(record=True): df['a'].ix[[0, 1, 2]] = -df['a'].ix[[0, 1, 2]] tm.assert_frame_equal(df, expected) df = DataFrame({'a': [0, 1, 2], 'b': [0, 1, 2]}) with catch_warnings(record=True): df['a'].ix[[0, 1, 2]] = -df['a'].ix[[0, 1, 2]].astype( 'float64') + 0.5 expected = DataFrame({'a': [0.5, -0.5, -1.5], 'b': [0, 1, 2]}) tm.assert_frame_equal(df, expected) # GH 8607 # ix setitem consistency df = DataFrame({'timestamp': [1413840976, 1413842580, 1413760580], 'delta': [1174, 904, 161], 'elapsed': [7673, 9277, 1470]}) expected = DataFrame({'timestamp': pd.to_datetime( [1413840976, 1413842580, 1413760580], unit='s'), 'delta': [1174, 904, 161], 'elapsed': [7673, 9277, 1470]}) df2 = df.copy() df2['timestamp'] = pd.to_datetime(df['timestamp'], unit='s') tm.assert_frame_equal(df2, expected) df2 = df.copy() df2.loc[:, 'timestamp'] = pd.to_datetime(df['timestamp'], unit='s') tm.assert_frame_equal(df2, expected) df2 = df.copy() with catch_warnings(record=True): df2.ix[:, 2] = pd.to_datetime(df['timestamp'], unit='s') tm.assert_frame_equal(df2, expected) def test_ix_loc_consistency(self): # GH 8613 # some edge cases where ix/loc should return the same # this is not an exhaustive case def compare(result, expected): if is_scalar(expected): self.assertEqual(result, expected) else: self.assertTrue(expected.equals(result)) # failure cases for .loc, but these work for .ix df = pd.DataFrame(np.random.randn(5, 4), columns=list('ABCD')) for key in [slice(1, 3), tuple([slice(0, 2), slice(0, 2)]), tuple([slice(0, 2), df.columns[0:2]])]: for index in [tm.makeStringIndex, tm.makeUnicodeIndex, tm.makeDateIndex, tm.makePeriodIndex, tm.makeTimedeltaIndex]: df.index = index(len(df.index)) with catch_warnings(record=True): df.ix[key] self.assertRaises(TypeError, lambda: df.loc[key]) df = pd.DataFrame(np.random.randn(5, 4), columns=list('ABCD'), index=pd.date_range('2012-01-01', periods=5)) for key in ['2012-01-03', '2012-01-31', slice('2012-01-03', '2012-01-03'), slice('2012-01-03', '2012-01-04'), slice('2012-01-03', '2012-01-06', 2), slice('2012-01-03', '2012-01-31'), tuple([[True, True, True, False, True]]), ]: # getitem # if the expected raises, then compare the exceptions try: with catch_warnings(record=True): expected = df.ix[key] except KeyError: self.assertRaises(KeyError, lambda: df.loc[key]) continue result = df.loc[key] compare(result, expected) # setitem df1 = df.copy() df2 = df.copy() with catch_warnings(record=True): df1.ix[key] = 10 df2.loc[key] = 10 compare(df2, df1) # edge cases s = Series([1, 2, 3, 4], index=list('abde')) result1 = s['a':'c'] with catch_warnings(record=True): result2 = s.ix['a':'c'] result3 = s.loc['a':'c'] tm.assert_series_equal(result1, result2) tm.assert_series_equal(result1, result3) # now work rather than raising KeyError s = Series(range(5), [-2, -1, 1, 2, 3]) with catch_warnings(record=True): result1 = s.ix[-10:3] result2 = s.loc[-10:3] tm.assert_series_equal(result1, result2) with catch_warnings(record=True): result1 = s.ix[0:3] result2 = s.loc[0:3] tm.assert_series_equal(result1, result2) def test_setitem_multiindex(self): for index_fn in ('ix', 'loc'): def check(target, indexers, value, compare_fn, expected=None): fn = getattr(target, index_fn) fn.__setitem__(indexers, value) result = fn.__getitem__(indexers) if expected is None: expected = value compare_fn(result, expected) # GH7190 index = pd.MultiIndex.from_product([np.arange(0, 100), np.arange(0, 80)], names=['time', 'firm']) t, n = 0, 2 df = DataFrame(np.nan, columns=['A', 'w', 'l', 'a', 'x', 'X', 'd', 'profit'], index=index) check(target=df, indexers=((t, n), 'X'), value=0, compare_fn=self.assertEqual) df = DataFrame(-999, columns=['A', 'w', 'l', 'a', 'x', 'X', 'd', 'profit'], index=index) check(target=df, indexers=((t, n), 'X'), value=1, compare_fn=self.assertEqual) df = DataFrame(columns=['A', 'w', 'l', 'a', 'x', 'X', 'd', 'profit'], index=index) check(target=df, indexers=((t, n), 'X'), value=2, compare_fn=self.assertEqual) # GH 7218, assinging with 0-dim arrays df = DataFrame(-999, columns=['A', 'w', 'l', 'a', 'x', 'X', 'd', 'profit'], index=index) check(target=df, indexers=((t, n), 'X'), value=np.array(3), compare_fn=self.assertEqual, expected=3, ) # GH5206 df = pd.DataFrame(np.arange(25).reshape(5, 5), columns='A,B,C,D,E'.split(','), dtype=float) df['F'] = 99 row_selection = df['A'] % 2 == 0 col_selection = ['B', 'C'] with catch_warnings(record=True): df.ix[row_selection, col_selection] = df['F'] output = pd.DataFrame(99., index=[0, 2, 4], columns=['B', 'C']) with catch_warnings(record=True): tm.assert_frame_equal(df.ix[row_selection, col_selection], output) check(target=df, indexers=(row_selection, col_selection), value=df['F'], compare_fn=tm.assert_frame_equal, expected=output, ) # GH11372 idx = pd.MultiIndex.from_product([ ['A', 'B', 'C'], pd.date_range('2015-01-01', '2015-04-01', freq='MS')]) cols = pd.MultiIndex.from_product([ ['foo', 'bar'], pd.date_range('2016-01-01', '2016-02-01', freq='MS')]) df = pd.DataFrame(np.random.random((12, 4)), index=idx, columns=cols) subidx = pd.MultiIndex.from_tuples( [('A', pd.Timestamp('2015-01-01')), ('A', pd.Timestamp('2015-02-01'))]) subcols = pd.MultiIndex.from_tuples( [('foo', pd.Timestamp('2016-01-01')), ('foo', pd.Timestamp('2016-02-01'))]) vals = pd.DataFrame(np.random.random((2, 2)), index=subidx, columns=subcols) check(target=df, indexers=(subidx, subcols), value=vals, compare_fn=tm.assert_frame_equal, ) # set all columns vals = pd.DataFrame( np.random.random((2, 4)), index=subidx, columns=cols) check(target=df, indexers=(subidx, slice(None, None, None)), value=vals, compare_fn=tm.assert_frame_equal, ) # identity copy = df.copy() check(target=df, indexers=(df.index, df.columns), value=df, compare_fn=tm.assert_frame_equal, expected=copy) def test_indexing_with_datetime_tz(self): # 8260 # support datetime64 with tz idx = Index(date_range('20130101', periods=3, tz='US/Eastern'), name='foo') dr = date_range('20130110', periods=3) df = DataFrame({'A': idx, 'B': dr}) df['C'] = idx df.iloc[1, 1] = pd.NaT df.iloc[1, 2] = pd.NaT # indexing result = df.iloc[1] expected = Series([Timestamp('2013-01-02 00:00:00-0500', tz='US/Eastern'), np.nan, np.nan], index=list('ABC'), dtype='object', name=1) tm.assert_series_equal(result, expected) result = df.loc[1] expected = Series([Timestamp('2013-01-02 00:00:00-0500', tz='US/Eastern'), np.nan, np.nan], index=list('ABC'), dtype='object', name=1) tm.assert_series_equal(result, expected) # indexing - fast_xs df = DataFrame({'a': date_range('2014-01-01', periods=10, tz='UTC')}) result = df.iloc[5] expected = Timestamp('2014-01-06 00:00:00+0000', tz='UTC', freq='D') self.assertEqual(result, expected) result = df.loc[5] self.assertEqual(result, expected) # indexing - boolean result = df[df.a > df.a[3]] expected = df.iloc[4:] tm.assert_frame_equal(result, expected) # indexing - setting an element df = DataFrame(data=pd.to_datetime( ['2015-03-30 20:12:32', '2015-03-12 00:11:11']), columns=['time']) df['new_col'] = ['new', 'old'] df.time = df.set_index('time').index.tz_localize('UTC') v = df[df.new_col == 'new'].set_index('time').index.tz_convert( 'US/Pacific') # trying to set a single element on a part of a different timezone def f(): df.loc[df.new_col == 'new', 'time'] = v self.assertRaises(ValueError, f) v = df.loc[df.new_col == 'new', 'time'] + pd.Timedelta('1s') df.loc[df.new_col == 'new', 'time'] = v tm.assert_series_equal(df.loc[df.new_col == 'new', 'time'], v) def test_indexing_with_datetimeindex_tz(self): # GH 12050 # indexing on a series with a datetimeindex with tz index = pd.date_range('2015-01-01', periods=2, tz='utc') ser = pd.Series(range(2), index=index, dtype='int64') # list-like indexing for sel in (index, list(index)): # getitem tm.assert_series_equal(ser[sel], ser) # setitem result = ser.copy() result[sel] = 1 expected = pd.Series(1, index=index) tm.assert_series_equal(result, expected) # .loc getitem tm.assert_series_equal(ser.loc[sel], ser) # .loc setitem result = ser.copy() result.loc[sel] = 1 expected = pd.Series(1, index=index) tm.assert_series_equal(result, expected) # single element indexing # getitem self.assertEqual(ser[index[1]], 1) # setitem result = ser.copy() result[index[1]] = 5 expected = pd.Series([0, 5], index=index) tm.assert_series_equal(result, expected) # .loc getitem self.assertEqual(ser.loc[index[1]], 1) # .loc setitem result = ser.copy() result.loc[index[1]] = 5 expected = pd.Series([0, 5], index=index) tm.assert_series_equal(result, expected) def test_loc_setitem_dups(self): # GH 6541 df_orig = DataFrame( {'me': list('rttti'), 'foo': list('aaade'), 'bar': np.arange(5, dtype='float64') * 1.34 + 2, 'bar2': np.arange(5, dtype='float64') * -.34 + 2}).set_index('me') indexer = tuple(['r', ['bar', 'bar2']]) df = df_orig.copy() df.loc[indexer] *= 2.0 tm.assert_series_equal(df.loc[indexer], 2.0 * df_orig.loc[indexer]) indexer = tuple(['r', 'bar']) df = df_orig.copy() df.loc[indexer] *= 2.0 self.assertEqual(df.loc[indexer], 2.0 * df_orig.loc[indexer]) indexer = tuple(['t', ['bar', 'bar2']]) df = df_orig.copy() df.loc[indexer] *= 2.0 tm.assert_frame_equal(df.loc[indexer], 2.0 * df_orig.loc[indexer]) def test_iloc_setitem_dups(self): # GH 6766 # iloc with a mask aligning from another iloc df1 = DataFrame([{'A': None, 'B': 1}, {'A': 2, 'B': 2}]) df2 = DataFrame([{'A': 3, 'B': 3}, {'A': 4, 'B': 4}]) df = concat([df1, df2], axis=1) expected = df.fillna(3) expected['A'] = expected['A'].astype('float64') inds = np.isnan(df.iloc[:, 0]) mask = inds[inds].index df.iloc[mask, 0] = df.iloc[mask, 2] tm.assert_frame_equal(df, expected) # del a dup column across blocks expected = DataFrame({0: [1, 2], 1: [3, 4]}) expected.columns = ['B', 'B'] del df['A'] tm.assert_frame_equal(df, expected) # assign back to self df.iloc[[0, 1], [0, 1]] = df.iloc[[0, 1], [0, 1]] tm.assert_frame_equal(df, expected) # reversed x 2 df.iloc[[1, 0], [0, 1]] = df.iloc[[1, 0], [0, 1]].reset_index( drop=True) df.iloc[[1, 0], [0, 1]] = df.iloc[[1, 0], [0, 1]].reset_index( drop=True) tm.assert_frame_equal(df, expected) def test_chained_getitem_with_lists(self): # GH6394 # Regression in chained getitem indexing with embedded list-like from # 0.12 def check(result, expected): tm.assert_numpy_array_equal(result, expected) tm.assertIsInstance(result, np.ndarray) df = DataFrame({'A': 5 * [np.zeros(3)], 'B': 5 * [np.ones(3)]}) expected = df['A'].iloc[2] result = df.loc[2, 'A'] check(result, expected) result2 = df.iloc[2]['A'] check(result2, expected) result3 = df['A'].loc[2] check(result3, expected) result4 = df['A'].iloc[2] check(result4, expected) def test_loc_getitem_int(self): # int label self.check_result('int label', 'loc', 2, 'ix', 2, typs=['ints', 'uints'], axes=0) self.check_result('int label', 'loc', 3, 'ix', 3, typs=['ints', 'uints'], axes=1) self.check_result('int label', 'loc', 4, 'ix', 4, typs=['ints', 'uints'], axes=2) self.check_result('int label', 'loc', 2, 'ix', 2, typs=['label'], fails=KeyError) def test_loc_getitem_label(self): # label self.check_result('label', 'loc', 'c', 'ix', 'c', typs=['labels'], axes=0) self.check_result('label', 'loc', 'null', 'ix', 'null', typs=['mixed'], axes=0) self.check_result('label', 'loc', 8, 'ix', 8, typs=['mixed'], axes=0) self.check_result('label', 'loc', Timestamp('20130102'), 'ix', 1, typs=['ts'], axes=0) self.check_result('label', 'loc', 'c', 'ix', 'c', typs=['empty'], fails=KeyError) def test_loc_getitem_label_out_of_range(self): # out of range label self.check_result('label range', 'loc', 'f', 'ix', 'f', typs=['ints', 'uints', 'labels', 'mixed', 'ts'], fails=KeyError) self.check_result('label range', 'loc', 'f', 'ix', 'f', typs=['floats'], fails=TypeError) self.check_result('label range', 'loc', 20, 'ix', 20, typs=['ints', 'uints', 'mixed'], fails=KeyError) self.check_result('label range', 'loc', 20, 'ix', 20, typs=['labels'], fails=TypeError) self.check_result('label range', 'loc', 20, 'ix', 20, typs=['ts'], axes=0, fails=TypeError) self.check_result('label range', 'loc', 20, 'ix', 20, typs=['floats'], axes=0, fails=TypeError) def test_loc_getitem_label_list(self): # list of labels self.check_result('list lbl', 'loc', [0, 2, 4], 'ix', [0, 2, 4], typs=['ints', 'uints'], axes=0) self.check_result('list lbl', 'loc', [3, 6, 9], 'ix', [3, 6, 9], typs=['ints', 'uints'], axes=1) self.check_result('list lbl', 'loc', [4, 8, 12], 'ix', [4, 8, 12], typs=['ints', 'uints'], axes=2) self.check_result('list lbl', 'loc', ['a', 'b', 'd'], 'ix', ['a', 'b', 'd'], typs=['labels'], axes=0) self.check_result('list lbl', 'loc', ['A', 'B', 'C'], 'ix', ['A', 'B', 'C'], typs=['labels'], axes=1) self.check_result('list lbl', 'loc', ['Z', 'Y', 'W'], 'ix', ['Z', 'Y', 'W'], typs=['labels'], axes=2) self.check_result('list lbl', 'loc', [2, 8, 'null'], 'ix', [2, 8, 'null'], typs=['mixed'], axes=0) self.check_result('list lbl', 'loc', [Timestamp('20130102'), Timestamp('20130103')], 'ix', [Timestamp('20130102'), Timestamp('20130103')], typs=['ts'], axes=0) self.check_result('list lbl', 'loc', [0, 1, 2], 'indexer', [0, 1, 2], typs=['empty'], fails=KeyError) self.check_result('list lbl', 'loc', [0, 2, 3], 'ix', [0, 2, 3], typs=['ints', 'uints'], axes=0, fails=KeyError) self.check_result('list lbl', 'loc', [3, 6, 7], 'ix', [3, 6, 7], typs=['ints', 'uints'], axes=1, fails=KeyError) self.check_result('list lbl', 'loc', [4, 8, 10], 'ix', [4, 8, 10], typs=['ints', 'uints'], axes=2, fails=KeyError) def test_loc_getitem_label_list_fails(self): # fails self.check_result('list lbl', 'loc', [20, 30, 40], 'ix', [20, 30, 40], typs=['ints', 'uints'], axes=1, fails=KeyError) self.check_result('list lbl', 'loc', [20, 30, 40], 'ix', [20, 30, 40], typs=['ints', 'uints'], axes=2, fails=KeyError) def test_loc_getitem_label_array_like(self): # array like self.check_result('array like', 'loc', Series(index=[0, 2, 4]).index, 'ix', [0, 2, 4], typs=['ints', 'uints'], axes=0) self.check_result('array like', 'loc', Series(index=[3, 6, 9]).index, 'ix', [3, 6, 9], typs=['ints', 'uints'], axes=1) self.check_result('array like', 'loc', Series(index=[4, 8, 12]).index, 'ix', [4, 8, 12], typs=['ints', 'uints'], axes=2) def test_loc_getitem_series(self): # GH14730 # passing a series as a key with a MultiIndex index = MultiIndex.from_product([[1, 2, 3], ['A', 'B', 'C']]) x = Series(index=index, data=range(9), dtype=np.float64) y = Series([1, 3]) expected = Series( data=[0, 1, 2, 6, 7, 8], index=MultiIndex.from_product([[1, 3], ['A', 'B', 'C']]), dtype=np.float64) result = x.loc[y] tm.assert_series_equal(result, expected) result = x.loc[[1, 3]] tm.assert_series_equal(result, expected) empty = Series(data=[], dtype=np.float64) expected = Series([], index=MultiIndex( levels=index.levels, labels=[[], []], dtype=np.float64)) result = x.loc[empty] tm.assert_series_equal(result, expected) def test_loc_getitem_bool(self): # boolean indexers b = [True, False, True, False] self.check_result('bool', 'loc', b, 'ix', b, typs=['ints', 'uints', 'labels', 'mixed', 'ts', 'floats']) self.check_result('bool', 'loc', b, 'ix', b, typs=['empty'], fails=KeyError) def test_loc_getitem_int_slice(self): # ok self.check_result('int slice2', 'loc', slice(2, 4), 'ix', [2, 4], typs=['ints', 'uints'], axes=0) self.check_result('int slice2', 'loc', slice(3, 6), 'ix', [3, 6], typs=['ints', 'uints'], axes=1) self.check_result('int slice2', 'loc', slice(4, 8), 'ix', [4, 8], typs=['ints', 'uints'], axes=2) # GH 3053 # loc should treat integer slices like label slices from itertools import product index = MultiIndex.from_tuples([t for t in product( [6, 7, 8], ['a', 'b'])]) df = DataFrame(np.random.randn(6, 6), index, index) result = df.loc[6:8, :] with catch_warnings(record=True): expected = df.ix[6:8, :] tm.assert_frame_equal(result, expected) index = MultiIndex.from_tuples([t for t in product( [10, 20, 30], ['a', 'b'])]) df = DataFrame(np.random.randn(6, 6), index, index) result = df.loc[20:30, :] with catch_warnings(record=True): expected = df.ix[20:30, :] tm.assert_frame_equal(result, expected) # doc examples result = df.loc[10, :] with catch_warnings(record=True): expected = df.ix[10, :] tm.assert_frame_equal(result, expected) result = df.loc[:, 10] # expected = df.ix[:,10] (this fails) expected = df[10] tm.assert_frame_equal(result, expected) def test_loc_to_fail(self): # GH3449 df = DataFrame(np.random.random((3, 3)), index=['a', 'b', 'c'], columns=['e', 'f', 'g']) # raise a KeyError? self.assertRaises(KeyError, df.loc.__getitem__, tuple([[1, 2], [1, 2]])) # GH 7496 # loc should not fallback s = Series() s.loc[1] = 1 s.loc['a'] = 2 self.assertRaises(KeyError, lambda: s.loc[-1]) self.assertRaises(KeyError, lambda: s.loc[[-1, -2]]) self.assertRaises(KeyError, lambda: s.loc[['4']]) s.loc[-1] = 3 result = s.loc[[-1, -2]] expected = Series([3, np.nan], index=[-1, -2]) tm.assert_series_equal(result, expected) s['a'] = 2 self.assertRaises(KeyError, lambda: s.loc[[-2]]) del s['a'] def f(): s.loc[[-2]] = 0 self.assertRaises(KeyError, f) # inconsistency between .loc[values] and .loc[values,:] # GH 7999 df = DataFrame([['a'], ['b']], index=[1, 2], columns=['value']) def f(): df.loc[[3], :] self.assertRaises(KeyError, f) def f(): df.loc[[3]] self.assertRaises(KeyError, f) def test_at_to_fail(self): # at should not fallback # GH 7814 s = Series([1, 2, 3], index=list('abc')) result = s.at['a'] self.assertEqual(result, 1) self.assertRaises(ValueError, lambda: s.at[0]) df = DataFrame({'A': [1, 2, 3]}, index=list('abc')) result = df.at['a', 'A'] self.assertEqual(result, 1) self.assertRaises(ValueError, lambda: df.at['a', 0]) s = Series([1, 2, 3], index=[3, 2, 1]) result = s.at[1] self.assertEqual(result, 3) self.assertRaises(ValueError, lambda: s.at['a']) df = DataFrame({0: [1, 2, 3]}, index=[3, 2, 1]) result = df.at[1, 0] self.assertEqual(result, 3) self.assertRaises(ValueError, lambda: df.at['a', 0]) # GH 13822, incorrect error string with non-unique columns when missing # column is accessed df = DataFrame({'x': [1.], 'y': [2.], 'z': [3.]}) df.columns = ['x', 'x', 'z'] # Check that we get the correct value in the KeyError self.assertRaisesRegexp(KeyError, r"\['y'\] not in index", lambda: df[['x', 'y', 'z']]) def test_loc_getitem_label_slice(self): # label slices (with ints) self.check_result('lab slice', 'loc', slice(1, 3), 'ix', slice(1, 3), typs=['labels', 'mixed', 'empty', 'ts', 'floats'], fails=TypeError) # real label slices self.check_result('lab slice', 'loc', slice('a', 'c'), 'ix', slice('a', 'c'), typs=['labels'], axes=0) self.check_result('lab slice', 'loc', slice('A', 'C'), 'ix', slice('A', 'C'), typs=['labels'], axes=1) self.check_result('lab slice', 'loc', slice('W', 'Z'), 'ix', slice('W', 'Z'), typs=['labels'], axes=2) self.check_result('ts slice', 'loc', slice('20130102', '20130104'), 'ix', slice('20130102', '20130104'), typs=['ts'], axes=0) self.check_result('ts slice', 'loc', slice('20130102', '20130104'), 'ix', slice('20130102', '20130104'), typs=['ts'], axes=1, fails=TypeError) self.check_result('ts slice', 'loc', slice('20130102', '20130104'), 'ix', slice('20130102', '20130104'), typs=['ts'], axes=2, fails=TypeError) # GH 14316 self.check_result('ts slice rev', 'loc', slice('20130104', '20130102'), 'indexer', [0, 1, 2], typs=['ts_rev'], axes=0) self.check_result('mixed slice', 'loc', slice(2, 8), 'ix', slice(2, 8), typs=['mixed'], axes=0, fails=TypeError) self.check_result('mixed slice', 'loc', slice(2, 8), 'ix', slice(2, 8), typs=['mixed'], axes=1, fails=KeyError) self.check_result('mixed slice', 'loc', slice(2, 8), 'ix', slice(2, 8), typs=['mixed'], axes=2, fails=KeyError) self.check_result('mixed slice', 'loc', slice(2, 4, 2), 'ix', slice( 2, 4, 2), typs=['mixed'], axes=0, fails=TypeError) def test_loc_general(self): df = DataFrame( np.random.rand(4, 4), columns=['A', 'B', 'C', 'D'], index=['A', 'B', 'C', 'D']) # want this to work result = df.loc[:, "A":"B"].iloc[0:2, :] self.assertTrue((result.columns == ['A', 'B']).all()) self.assertTrue((result.index == ['A', 'B']).all()) # mixed type result = DataFrame({'a': [Timestamp('20130101')], 'b': [1]}).iloc[0] expected = Series([Timestamp('20130101'), 1], index=['a', 'b'], name=0) tm.assert_series_equal(result, expected) self.assertEqual(result.dtype, object) def test_loc_setitem_consistency(self): # GH 6149 # coerce similary for setitem and loc when rows have a null-slice expected = DataFrame({'date': Series(0, index=range(5), dtype=np.int64), 'val': Series(range(5), dtype=np.int64)}) df = DataFrame({'date': date_range('2000-01-01', '2000-01-5'), 'val': Series( range(5), dtype=np.int64)}) df.loc[:, 'date'] = 0 tm.assert_frame_equal(df, expected) df = DataFrame({'date': date_range('2000-01-01', '2000-01-5'), 'val': Series(range(5), dtype=np.int64)}) df.loc[:, 'date'] = np.array(0, dtype=np.int64) tm.assert_frame_equal(df, expected) df = DataFrame({'date': date_range('2000-01-01', '2000-01-5'), 'val': Series(range(5), dtype=np.int64)}) df.loc[:, 'date'] = np.array([0, 0, 0, 0, 0], dtype=np.int64) tm.assert_frame_equal(df, expected) expected = DataFrame({'date': Series('foo', index=range(5)), 'val': Series(range(5), dtype=np.int64)}) df = DataFrame({'date': date_range('2000-01-01', '2000-01-5'), 'val': Series(range(5), dtype=np.int64)}) df.loc[:, 'date'] = 'foo' tm.assert_frame_equal(df, expected) expected = DataFrame({'date': Series(1.0, index=range(5)), 'val': Series(range(5), dtype=np.int64)}) df = DataFrame({'date': date_range('2000-01-01', '2000-01-5'), 'val': Series(range(5), dtype=np.int64)}) df.loc[:, 'date'] = 1.0 tm.assert_frame_equal(df, expected) def test_loc_setitem_consistency_empty(self): # empty (essentially noops) expected = DataFrame(columns=['x', 'y']) expected['x'] = expected['x'].astype(np.int64) df = DataFrame(columns=['x', 'y']) df.loc[:, 'x'] = 1 tm.assert_frame_equal(df, expected) df = DataFrame(columns=['x', 'y']) df['x'] = 1 tm.assert_frame_equal(df, expected) def test_loc_setitem_consistency_slice_column_len(self): # .loc[:,column] setting with slice == len of the column # GH10408 data = """Level_0,,,Respondent,Respondent,Respondent,OtherCat,OtherCat Level_1,,,Something,StartDate,EndDate,Yes/No,SomethingElse Region,Site,RespondentID,,,,, Region_1,Site_1,3987227376,A,5/25/2015 10:59,5/25/2015 11:22,Yes, Region_1,Site_1,3980680971,A,5/21/2015 9:40,5/21/2015 9:52,Yes,Yes Region_1,Site_2,3977723249,A,5/20/2015 8:27,5/20/2015 8:41,Yes, Region_1,Site_2,3977723089,A,5/20/2015 8:33,5/20/2015 9:09,Yes,No""" df = pd.read_csv(StringIO(data), header=[0, 1], index_col=[0, 1, 2]) df.loc[:, ('Respondent', 'StartDate')] = pd.to_datetime(df.loc[:, ( 'Respondent', 'StartDate')]) df.loc[:, ('Respondent', 'EndDate')] = pd.to_datetime(df.loc[:, ( 'Respondent', 'EndDate')]) df.loc[:, ('Respondent', 'Duration')] = df.loc[:, ( 'Respondent', 'EndDate')] - df.loc[:, ('Respondent', 'StartDate')] df.loc[:, ('Respondent', 'Duration')] = df.loc[:, ( 'Respondent', 'Duration')].astype('timedelta64[s]') expected = Series([1380, 720, 840, 2160.], index=df.index, name=('Respondent', 'Duration')) tm.assert_series_equal(df[('Respondent', 'Duration')], expected) def test_loc_setitem_frame(self): df = self.frame_labels result = df.iloc[0, 0] df.loc['a', 'A'] = 1 result = df.loc['a', 'A'] self.assertEqual(result, 1) result = df.iloc[0, 0] self.assertEqual(result, 1) df.loc[:, 'B':'D'] = 0 expected = df.loc[:, 'B':'D'] with catch_warnings(record=True): result = df.ix[:, 1:] tm.assert_frame_equal(result, expected) # GH 6254 # setting issue df = DataFrame(index=[3, 5, 4], columns=['A']) df.loc[[4, 3, 5], 'A'] = np.array([1, 2, 3], dtype='int64') expected = DataFrame(dict(A=Series( [1, 2, 3], index=[4, 3, 5]))).reindex(index=[3, 5, 4]) tm.assert_frame_equal(df, expected) # GH 6252 # setting with an empty frame keys1 = ['@' + str(i) for i in range(5)] val1 = np.arange(5, dtype='int64') keys2 = ['@' + str(i) for i in range(4)] val2 = np.arange(4, dtype='int64') index = list(set(keys1).union(keys2)) df = DataFrame(index=index) df['A'] = nan df.loc[keys1, 'A'] = val1 df['B'] = nan df.loc[keys2, 'B'] = val2 expected = DataFrame(dict(A=Series(val1, index=keys1), B=Series( val2, index=keys2))).reindex(index=index) tm.assert_frame_equal(df, expected) # GH 8669 # invalid coercion of nan -> int df = DataFrame({'A': [1, 2, 3], 'B': np.nan}) df.loc[df.B > df.A, 'B'] = df.A expected = DataFrame({'A': [1, 2, 3], 'B': np.nan}) tm.assert_frame_equal(df, expected) # GH 6546 # setting with mixed labels df = DataFrame({1: [1, 2], 2: [3, 4], 'a': ['a', 'b']}) result = df.loc[0, [1, 2]] expected = Series([1, 3], index=[1, 2], dtype=object, name=0) tm.assert_series_equal(result, expected) expected = DataFrame({1: [5, 2], 2: [6, 4], 'a': ['a', 'b']}) df.loc[0, [1, 2]] = [5, 6] tm.assert_frame_equal(df, expected) def test_loc_setitem_frame_multiples(self): # multiple setting df = DataFrame({'A': ['foo', 'bar', 'baz'], 'B': Series( range(3), dtype=np.int64)}) rhs = df.loc[1:2] rhs.index = df.index[0:2] df.loc[0:1] = rhs expected = DataFrame({'A': ['bar', 'baz', 'baz'], 'B': Series( [1, 2, 2], dtype=np.int64)}) tm.assert_frame_equal(df, expected) # multiple setting with frame on rhs (with M8) df = DataFrame({'date': date_range('2000-01-01', '2000-01-5'), 'val': Series( range(5), dtype=np.int64)}) expected = DataFrame({'date': [Timestamp('20000101'), Timestamp( '20000102'), Timestamp('20000101'), Timestamp('20000102'), Timestamp('20000103')], 'val': Series( [0, 1, 0, 1, 2], dtype=np.int64)}) rhs = df.loc[0:2] rhs.index = df.index[2:5] df.loc[2:4] = rhs tm.assert_frame_equal(df, expected) def test_iloc_getitem_frame(self): df = DataFrame(np.random.randn(10, 4), index=lrange(0, 20, 2), columns=lrange(0, 8, 2)) result = df.iloc[2] with catch_warnings(record=True): exp = df.ix[4] tm.assert_series_equal(result, exp) result = df.iloc[2, 2] with catch_warnings(record=True): exp = df.ix[4, 4] self.assertEqual(result, exp) # slice result = df.iloc[4:8] with catch_warnings(record=True): expected = df.ix[8:14] tm.assert_frame_equal(result, expected) result = df.iloc[:, 2:3] with catch_warnings(record=True): expected = df.ix[:, 4:5] tm.assert_frame_equal(result, expected) # list of integers result = df.iloc[[0, 1, 3]] with catch_warnings(record=True): expected = df.ix[[0, 2, 6]] tm.assert_frame_equal(result, expected) result = df.iloc[[0, 1, 3], [0, 1]] with catch_warnings(record=True): expected = df.ix[[0, 2, 6], [0, 2]] tm.assert_frame_equal(result, expected) # neg indicies result = df.iloc[[-1, 1, 3], [-1, 1]] with catch_warnings(record=True): expected = df.ix[[18, 2, 6], [6, 2]] tm.assert_frame_equal(result, expected) # dups indicies result = df.iloc[[-1, -1, 1, 3], [-1, 1]] with catch_warnings(record=True): expected = df.ix[[18, 18, 2, 6], [6, 2]] tm.assert_frame_equal(result, expected) # with index-like s = Series(index=lrange(1, 5)) result = df.iloc[s.index] with catch_warnings(record=True): expected = df.ix[[2, 4, 6, 8]] tm.assert_frame_equal(result, expected) def test_iloc_getitem_labelled_frame(self): # try with labelled frame df = DataFrame(np.random.randn(10, 4), index=list('abcdefghij'), columns=list('ABCD')) result = df.iloc[1, 1] exp = df.loc['b', 'B'] self.assertEqual(result, exp) result = df.iloc[:, 2:3] expected = df.loc[:, ['C']] tm.assert_frame_equal(result, expected) # negative indexing result = df.iloc[-1, -1] exp = df.loc['j', 'D'] self.assertEqual(result, exp) # out-of-bounds exception self.assertRaises(IndexError, df.iloc.__getitem__, tuple([10, 5])) # trying to use a label self.assertRaises(ValueError, df.iloc.__getitem__, tuple(['j', 'D'])) def test_iloc_getitem_panel(self): # GH 7189 p = Panel(np.arange(4 * 3 * 2).reshape(4, 3, 2), items=['A', 'B', 'C', 'D'], major_axis=['a', 'b', 'c'], minor_axis=['one', 'two']) result = p.iloc[1] expected = p.loc['B'] tm.assert_frame_equal(result, expected) result = p.iloc[1, 1] expected = p.loc['B', 'b'] tm.assert_series_equal(result, expected) result = p.iloc[1, 1, 1] expected = p.loc['B', 'b', 'two'] self.assertEqual(result, expected) # slice result = p.iloc[1:3] expected = p.loc[['B', 'C']] tm.assert_panel_equal(result, expected) result = p.iloc[:, 0:2] expected = p.loc[:, ['a', 'b']] tm.assert_panel_equal(result, expected) # list of integers result = p.iloc[[0, 2]] expected = p.loc[['A', 'C']] tm.assert_panel_equal(result, expected) # neg indicies result = p.iloc[[-1, 1], [-1, 1]] expected = p.loc[['D', 'B'], ['c', 'b']] tm.assert_panel_equal(result, expected) # dups indicies result = p.iloc[[-1, -1, 1], [-1, 1]] expected = p.loc[['D', 'D', 'B'], ['c', 'b']] tm.assert_panel_equal(result, expected) # combined result = p.iloc[0, [True, True], [0, 1]] expected = p.loc['A', ['a', 'b'], ['one', 'two']] tm.assert_frame_equal(result, expected) # out-of-bounds exception self.assertRaises(IndexError, p.iloc.__getitem__, tuple([10, 5])) def f(): p.iloc[0, [True, True], [0, 1, 2]] self.assertRaises(IndexError, f) # trying to use a label self.assertRaises(ValueError, p.iloc.__getitem__, tuple(['j', 'D'])) # GH p = Panel( np.random.rand(4, 3, 2), items=['A', 'B', 'C', 'D'], major_axis=['U', 'V', 'W'], minor_axis=['X', 'Y']) expected = p['A'] result = p.iloc[0, :, :] tm.assert_frame_equal(result, expected) result = p.iloc[0, [True, True, True], :] tm.assert_frame_equal(result, expected) result = p.iloc[0, [True, True, True], [0, 1]] tm.assert_frame_equal(result, expected) def f(): p.iloc[0, [True, True, True], [0, 1, 2]] self.assertRaises(IndexError, f) def f(): p.iloc[0, [True, True, True], [2]] self.assertRaises(IndexError, f) def test_iloc_getitem_panel_multiindex(self): # GH 7199 # Panel with multi-index multi_index = pd.MultiIndex.from_tuples([('ONE', 'one'), ('TWO', 'two'), ('THREE', 'three')], names=['UPPER', 'lower']) simple_index = [x[0] for x in multi_index] wd1 = Panel(items=['First', 'Second'], major_axis=['a', 'b', 'c', 'd'], minor_axis=multi_index) wd2 = Panel(items=['First', 'Second'], major_axis=['a', 'b', 'c', 'd'], minor_axis=simple_index) expected1 = wd1['First'].iloc[[True, True, True, False], [0, 2]] result1 = wd1.iloc[0, [True, True, True, False], [0, 2]] # WRONG tm.assert_frame_equal(result1, expected1) expected2 = wd2['First'].iloc[[True, True, True, False], [0, 2]] result2 = wd2.iloc[0, [True, True, True, False], [0, 2]] tm.assert_frame_equal(result2, expected2) expected1 = DataFrame(index=['a'], columns=multi_index, dtype='float64') result1 = wd1.iloc[0, [0], [0, 1, 2]] tm.assert_frame_equal(result1, expected1) expected2 = DataFrame(index=['a'], columns=simple_index, dtype='float64') result2 = wd2.iloc[0, [0], [0, 1, 2]] tm.assert_frame_equal(result2, expected2) # GH 7516 mi = MultiIndex.from_tuples([(0, 'x'), (1, 'y'), (2, 'z')]) p = Panel(np.arange(3 * 3 * 3, dtype='int64').reshape(3, 3, 3), items=['a', 'b', 'c'], major_axis=mi, minor_axis=['u', 'v', 'w']) result = p.iloc[:, 1, 0] expected = Series([3, 12, 21], index=['a', 'b', 'c'], name='u') tm.assert_series_equal(result, expected) result = p.loc[:, (1, 'y'), 'u'] tm.assert_series_equal(result, expected) def test_iloc_getitem_doc_issue(self): # multi axis slicing issue with single block # surfaced in GH 6059 arr = np.random.randn(6, 4) index = date_range('20130101', periods=6) columns = list('ABCD') df = DataFrame(arr, index=index, columns=columns) # defines ref_locs df.describe() result = df.iloc[3:5, 0:2] str(result) result.dtypes expected = DataFrame(arr[3:5, 0:2], index=index[3:5], columns=columns[0:2]) tm.assert_frame_equal(result, expected) # for dups df.columns = list('aaaa') result = df.iloc[3:5, 0:2] str(result) result.dtypes expected = DataFrame(arr[3:5, 0:2], index=index[3:5], columns=list('aa')) tm.assert_frame_equal(result, expected) # related arr = np.random.randn(6, 4) index = list(range(0, 12, 2)) columns = list(range(0, 8, 2)) df = DataFrame(arr, index=index, columns=columns) df._data.blocks[0].mgr_locs result = df.iloc[1:5, 2:4] str(result) result.dtypes expected = DataFrame(arr[1:5, 2:4], index=index[1:5], columns=columns[2:4]) tm.assert_frame_equal(result, expected) def test_setitem_ndarray_1d(self): # GH5508 # len of indexer vs length of the 1d ndarray df = DataFrame(index=Index(lrange(1, 11))) df['foo'] = np.zeros(10, dtype=np.float64) df['bar'] = np.zeros(10, dtype=np.complex) # invalid def f(): with catch_warnings(record=True): df.ix[2:5, 'bar'] = np.array([2.33j, 1.23 + 0.1j, 2.2]) self.assertRaises(ValueError, f) def f(): df.loc[df.index[2:5], 'bar'] = np.array([2.33j, 1.23 + 0.1j, 2.2, 1.0]) self.assertRaises(ValueError, f) # valid df.loc[df.index[2:6], 'bar'] = np.array([2.33j, 1.23 + 0.1j, 2.2, 1.0]) result = df.loc[df.index[2:6], 'bar'] expected = Series([2.33j, 1.23 + 0.1j, 2.2, 1.0], index=[3, 4, 5, 6], name='bar') tm.assert_series_equal(result, expected) # dtype getting changed? df = DataFrame(index=Index(lrange(1, 11))) df['foo'] = np.zeros(10, dtype=np.float64) df['bar'] = np.zeros(10, dtype=np.complex) def f(): df[2:5] = np.arange(1, 4) * 1j self.assertRaises(ValueError, f) def test_iloc_setitem_series(self): df = DataFrame(np.random.randn(10, 4), index=list('abcdefghij'), columns=list('ABCD')) df.iloc[1, 1] = 1 result = df.iloc[1, 1] self.assertEqual(result, 1) df.iloc[:, 2:3] = 0 expected = df.iloc[:, 2:3] result = df.iloc[:, 2:3] tm.assert_frame_equal(result, expected) s = Series(np.random.randn(10), index=lrange(0, 20, 2)) s.iloc[1] = 1 result = s.iloc[1] self.assertEqual(result, 1) s.iloc[:4] = 0 expected = s.iloc[:4] result = s.iloc[:4] tm.assert_series_equal(result, expected) s = Series([-1] * 6) s.iloc[0::2] = [0, 2, 4] s.iloc[1::2] = [1, 3, 5] result = s expected = Series([0, 1, 2, 3, 4, 5]) tm.assert_series_equal(result, expected) def test_iloc_setitem_list_of_lists(self): # GH 7551 # list-of-list is set incorrectly in mixed vs. single dtyped frames df = DataFrame(dict(A=np.arange(5, dtype='int64'), B=np.arange(5, 10, dtype='int64'))) df.iloc[2:4] = [[10, 11], [12, 13]] expected = DataFrame(dict(A=[0, 1, 10, 12, 4], B=[5, 6, 11, 13, 9])) tm.assert_frame_equal(df, expected) df = DataFrame( dict(A=list('abcde'), B=np.arange(5, 10, dtype='int64'))) df.iloc[2:4] = [['x', 11], ['y', 13]] expected = DataFrame(dict(A=['a', 'b', 'x', 'y', 'e'], B=[5, 6, 11, 13, 9])) tm.assert_frame_equal(df, expected) def test_iloc_getitem_multiindex(self): mi_labels = DataFrame(np.random.randn(4, 3), columns=[['i', 'i', 'j'], ['A', 'A', 'B']], index=[['i', 'i', 'j', 'k'], ['X', 'X', 'Y', 'Y']]) mi_int = DataFrame(np.random.randn(3, 3), columns=[[2, 2, 4], [6, 8, 10]], index=[[4, 4, 8], [8, 10, 12]]) # the first row rs = mi_int.iloc[0] with catch_warnings(record=True): xp = mi_int.ix[4].ix[8] tm.assert_series_equal(rs, xp, check_names=False) self.assertEqual(rs.name, (4, 8)) self.assertEqual(xp.name, 8) # 2nd (last) columns rs = mi_int.iloc[:, 2] with catch_warnings(record=True): xp = mi_int.ix[:, 2] tm.assert_series_equal(rs, xp) # corner column rs = mi_int.iloc[2, 2] with catch_warnings(record=True): xp = mi_int.ix[:, 2].ix[2] self.assertEqual(rs, xp) # this is basically regular indexing rs = mi_labels.iloc[2, 2] with catch_warnings(record=True): xp = mi_labels.ix['j'].ix[:, 'j'].ix[0, 0] self.assertEqual(rs, xp) def test_loc_multiindex(self): mi_labels = DataFrame(np.random.randn(3, 3), columns=[['i', 'i', 'j'], ['A', 'A', 'B']], index=[['i', 'i', 'j'], ['X', 'X', 'Y']]) mi_int = DataFrame(np.random.randn(3, 3), columns=[[2, 2, 4], [6, 8, 10]], index=[[4, 4, 8], [8, 10, 12]]) # the first row rs = mi_labels.loc['i'] with catch_warnings(record=True): xp = mi_labels.ix['i'] tm.assert_frame_equal(rs, xp) # 2nd (last) columns rs = mi_labels.loc[:, 'j'] with catch_warnings(record=True): xp = mi_labels.ix[:, 'j'] tm.assert_frame_equal(rs, xp) # corner column rs = mi_labels.loc['j'].loc[:, 'j'] with catch_warnings(record=True): xp = mi_labels.ix['j'].ix[:, 'j'] tm.assert_frame_equal(rs, xp) # with a tuple rs = mi_labels.loc[('i', 'X')] with catch_warnings(record=True): xp = mi_labels.ix[('i', 'X')] tm.assert_frame_equal(rs, xp) rs = mi_int.loc[4] with catch_warnings(record=True): xp = mi_int.ix[4] tm.assert_frame_equal(rs, xp) def test_loc_multiindex_indexer_none(self): # GH6788 # multi-index indexer is None (meaning take all) attributes = ['Attribute' + str(i) for i in range(1)] attribute_values = ['Value' + str(i) for i in range(5)] index = MultiIndex.from_product([attributes, attribute_values]) df = 0.1 * np.random.randn(10, 1 * 5) + 0.5 df = DataFrame(df, columns=index) result = df[attributes] tm.assert_frame_equal(result, df) # GH 7349 # loc with a multi-index seems to be doing fallback df = DataFrame(np.arange(12).reshape(-1, 1), index=pd.MultiIndex.from_product([[1, 2, 3, 4], [1, 2, 3]])) expected = df.loc[([1, 2], ), :] result = df.loc[[1, 2]] tm.assert_frame_equal(result, expected) def test_loc_multiindex_incomplete(self): # GH 7399 # incomplete indexers s = pd.Series(np.arange(15, dtype='int64'), MultiIndex.from_product([range(5), ['a', 'b', 'c']])) expected = s.loc[:, 'a':'c'] result = s.loc[0:4, 'a':'c'] tm.assert_series_equal(result, expected) tm.assert_series_equal(result, expected) result = s.loc[:4, 'a':'c'] tm.assert_series_equal(result, expected) tm.assert_series_equal(result, expected) result = s.loc[0:, 'a':'c'] tm.assert_series_equal(result, expected) tm.assert_series_equal(result, expected) # GH 7400 # multiindexer gettitem with list of indexers skips wrong element s = pd.Series(np.arange(15, dtype='int64'), MultiIndex.from_product([range(5), ['a', 'b', 'c']])) expected = s.iloc[[6, 7, 8, 12, 13, 14]] result = s.loc[2:4:2, 'a':'c'] tm.assert_series_equal(result, expected) def test_multiindex_perf_warn(self): if sys.version_info < (2, 7): raise nose.SkipTest('python version < 2.7') df = DataFrame({'jim': [0, 0, 1, 1], 'joe': ['x', 'x', 'z', 'y'], 'jolie': np.random.rand(4)}).set_index(['jim', 'joe']) with tm.assert_produces_warning(PerformanceWarning, clear=[pd.core.index]): df.loc[(1, 'z')] df = df.iloc[[2, 1, 3, 0]] with tm.assert_produces_warning(PerformanceWarning): df.loc[(0, )] def test_series_getitem_multiindex(self): # GH 6018 # series regression getitem with a multi-index s = Series([1, 2, 3]) s.index = MultiIndex.from_tuples([(0, 0), (1, 1), (2, 1)]) result = s[:, 0] expected = Series([1], index=[0]) tm.assert_series_equal(result, expected) result = s.loc[:, 1] expected = Series([2, 3], index=[1, 2]) tm.assert_series_equal(result, expected) # xs result = s.xs(0, level=0) expected = Series([1], index=[0]) tm.assert_series_equal(result, expected) result = s.xs(1, level=1) expected = Series([2, 3], index=[1, 2]) tm.assert_series_equal(result, expected) # GH6258 dt = list(date_range('20130903', periods=3)) idx = MultiIndex.from_product([list('AB'), dt]) s = Series([1, 3, 4, 1, 3, 4], index=idx) result = s.xs('20130903', level=1) expected = Series([1, 1], index=list('AB')) tm.assert_series_equal(result, expected) # GH5684 idx = MultiIndex.from_tuples([('a', 'one'), ('a', 'two'), ('b', 'one'), ('b', 'two')]) s = Series([1, 2, 3, 4], index=idx) s.index.set_names(['L1', 'L2'], inplace=True) result = s.xs('one', level='L2') expected = Series([1, 3], index=['a', 'b']) expected.index.set_names(['L1'], inplace=True) tm.assert_series_equal(result, expected) def test_ix_general(self): # ix general issues # GH 2817 data = {'amount': {0: 700, 1: 600, 2: 222, 3: 333, 4: 444}, 'col': {0: 3.5, 1: 3.5, 2: 4.0, 3: 4.0, 4: 4.0}, 'year': {0: 2012, 1: 2011, 2: 2012, 3: 2012, 4: 2012}} df = DataFrame(data).set_index(keys=['col', 'year']) key = 4.0, 2012 # emits a PerformanceWarning, ok with self.assert_produces_warning(PerformanceWarning): tm.assert_frame_equal(df.loc[key], df.iloc[2:]) # this is ok df.sort_index(inplace=True) res = df.loc[key] # col has float dtype, result should be Float64Index index = MultiIndex.from_arrays([[4.] * 3, [2012] * 3], names=['col', 'year']) expected = DataFrame({'amount': [222, 333, 444]}, index=index) tm.assert_frame_equal(res, expected) def test_ix_weird_slicing(self): # http://stackoverflow.com/q/17056560/1240268 df = DataFrame({'one': [1, 2, 3, np.nan, np.nan], 'two': [1, 2, 3, 4, 5]}) df.loc[df['one'] > 1, 'two'] = -df['two'] expected = DataFrame({'one': {0: 1.0, 1: 2.0, 2: 3.0, 3: nan, 4: nan}, 'two': {0: 1, 1: -2, 2: -3, 3: 4, 4: 5}}) tm.assert_frame_equal(df, expected) def test_xs_multiindex(self): # GH2903 columns = MultiIndex.from_tuples( [('a', 'foo'), ('a', 'bar'), ('b', 'hello'), ('b', 'world')], names=['lvl0', 'lvl1']) df = DataFrame(np.random.randn(4, 4), columns=columns) df.sort_index(axis=1, inplace=True) result = df.xs('a', level='lvl0', axis=1) expected = df.iloc[:, 0:2].loc[:, 'a'] tm.assert_frame_equal(result, expected) result = df.xs('foo', level='lvl1', axis=1) expected = df.iloc[:, 1:2].copy() expected.columns = expected.columns.droplevel('lvl1') tm.assert_frame_equal(result, expected) def test_per_axis_per_level_getitem(self): # GH6134 # example test case ix = MultiIndex.from_product([_mklbl('A', 5), _mklbl('B', 7), _mklbl( 'C', 4), _mklbl('D', 2)]) df = DataFrame(np.arange(len(ix.get_values())), index=ix) result = df.loc[(slice('A1', 'A3'), slice(None), ['C1', 'C3']), :] expected = df.loc[[tuple([a, b, c, d]) for a, b, c, d in df.index.values if (a == 'A1' or a == 'A2' or a == 'A3') and ( c == 'C1' or c == 'C3')]] tm.assert_frame_equal(result, expected) expected = df.loc[[tuple([a, b, c, d]) for a, b, c, d in df.index.values if (a == 'A1' or a == 'A2' or a == 'A3') and ( c == 'C1' or c == 'C2' or c == 'C3')]] result = df.loc[(slice('A1', 'A3'), slice(None), slice('C1', 'C3')), :] tm.assert_frame_equal(result, expected) # test multi-index slicing with per axis and per index controls index = MultiIndex.from_tuples([('A', 1), ('A', 2), ('A', 3), ('B', 1)], names=['one', 'two']) columns = MultiIndex.from_tuples([('a', 'foo'), ('a', 'bar'), ('b', 'foo'), ('b', 'bah')], names=['lvl0', 'lvl1']) df = DataFrame( np.arange(16, dtype='int64').reshape( 4, 4), index=index, columns=columns) df = df.sort_index(axis=0).sort_index(axis=1) # identity result = df.loc[(slice(None), slice(None)), :] tm.assert_frame_equal(result, df) result = df.loc[(slice(None), slice(None)), (slice(None), slice(None))] tm.assert_frame_equal(result, df) result = df.loc[:, (slice(None), slice(None))] tm.assert_frame_equal(result, df) # index result = df.loc[(slice(None), [1]), :] expected = df.iloc[[0, 3]] tm.assert_frame_equal(result, expected) result = df.loc[(slice(None), 1), :] expected = df.iloc[[0, 3]] tm.assert_frame_equal(result, expected) # columns result = df.loc[:, (slice(None), ['foo'])] expected = df.iloc[:, [1, 3]] tm.assert_frame_equal(result, expected) # both result = df.loc[(slice(None), 1), (slice(None), ['foo'])] expected = df.iloc[[0, 3], [1, 3]] tm.assert_frame_equal(result, expected) result = df.loc['A', 'a'] expected = DataFrame(dict(bar=[1, 5, 9], foo=[0, 4, 8]), index=Index([1, 2, 3], name='two'), columns=Index(['bar', 'foo'], name='lvl1')) tm.assert_frame_equal(result, expected) result = df.loc[(slice(None), [1, 2]), :] expected = df.iloc[[0, 1, 3]] tm.assert_frame_equal(result, expected) # multi-level series s = Series(np.arange(len(ix.get_values())), index=ix) result = s.loc['A1':'A3', :, ['C1', 'C3']] expected = s.loc[[tuple([a, b, c, d]) for a, b, c, d in s.index.values if (a == 'A1' or a == 'A2' or a == 'A3') and ( c == 'C1' or c == 'C3')]] tm.assert_series_equal(result, expected) # boolean indexers result = df.loc[(slice(None), df.loc[:, ('a', 'bar')] > 5), :] expected = df.iloc[[2, 3]] tm.assert_frame_equal(result, expected) def f(): df.loc[(slice(None), np.array([True, False])), :] self.assertRaises(ValueError, f) # ambiguous cases # these can be multiply interpreted (e.g. in this case # as df.loc[slice(None),[1]] as well self.assertRaises(KeyError, lambda: df.loc[slice(None), [1]]) result = df.loc[(slice(None), [1]), :] expected = df.iloc[[0, 3]] tm.assert_frame_equal(result, expected) # not lexsorted self.assertEqual(df.index.lexsort_depth, 2) df = df.sort_index(level=1, axis=0) self.assertEqual(df.index.lexsort_depth, 0) with tm.assertRaisesRegexp( UnsortedIndexError, 'MultiIndex Slicing requires the index to be fully ' r'lexsorted tuple len \(2\), lexsort depth \(0\)'): df.loc[(slice(None), df.loc[:, ('a', 'bar')] > 5), :] def test_multiindex_slicers_non_unique(self): # GH 7106 # non-unique mi index support df = (DataFrame(dict(A=['foo', 'foo', 'foo', 'foo'], B=['a', 'a', 'a', 'a'], C=[1, 2, 1, 3], D=[1, 2, 3, 4])) .set_index(['A', 'B', 'C']).sort_index()) self.assertFalse(df.index.is_unique) expected = (DataFrame(dict(A=['foo', 'foo'], B=['a', 'a'], C=[1, 1], D=[1, 3])) .set_index(['A', 'B', 'C']).sort_index()) result = df.loc[(slice(None), slice(None), 1), :] tm.assert_frame_equal(result, expected) # this is equivalent of an xs expression result = df.xs(1, level=2, drop_level=False) tm.assert_frame_equal(result, expected) df = (DataFrame(dict(A=['foo', 'foo', 'foo', 'foo'], B=['a', 'a', 'a', 'a'], C=[1, 2, 1, 2], D=[1, 2, 3, 4])) .set_index(['A', 'B', 'C']).sort_index()) self.assertFalse(df.index.is_unique) expected = (DataFrame(dict(A=['foo', 'foo'], B=['a', 'a'], C=[1, 1], D=[1, 3])) .set_index(['A', 'B', 'C']).sort_index()) result = df.loc[(slice(None), slice(None), 1), :] self.assertFalse(result.index.is_unique) tm.assert_frame_equal(result, expected) # GH12896 # numpy-implementation dependent bug ints = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 12, 13, 14, 14, 16, 17, 18, 19, 200000, 200000] n = len(ints) idx = MultiIndex.from_arrays([['a'] * n, ints]) result = Series([1] * n, index=idx) result = result.sort_index() result = result.loc[(slice(None), slice(100000))] expected = Series([1] * (n - 2), index=idx[:-2]).sort_index() tm.assert_series_equal(result, expected) def test_multiindex_slicers_datetimelike(self): # GH 7429 # buggy/inconsistent behavior when slicing with datetime-like import datetime dates = [datetime.datetime(2012, 1, 1, 12, 12, 12) + datetime.timedelta(days=i) for i in range(6)] freq = [1, 2] index = MultiIndex.from_product( [dates, freq], names=['date', 'frequency']) df = DataFrame( np.arange(6 * 2 * 4, dtype='int64').reshape( -1, 4), index=index, columns=list('ABCD')) # multi-axis slicing idx = pd.IndexSlice expected = df.iloc[[0, 2, 4], [0, 1]] result = df.loc[(slice(Timestamp('2012-01-01 12:12:12'), Timestamp('2012-01-03 12:12:12')), slice(1, 1)), slice('A', 'B')] tm.assert_frame_equal(result, expected) result = df.loc[(idx[Timestamp('2012-01-01 12:12:12'):Timestamp( '2012-01-03 12:12:12')], idx[1:1]), slice('A', 'B')] tm.assert_frame_equal(result, expected) result = df.loc[(slice(Timestamp('2012-01-01 12:12:12'), Timestamp('2012-01-03 12:12:12')), 1), slice('A', 'B')] tm.assert_frame_equal(result, expected) # with strings result = df.loc[(slice('2012-01-01 12:12:12', '2012-01-03 12:12:12'), slice(1, 1)), slice('A', 'B')] tm.assert_frame_equal(result, expected) result = df.loc[(idx['2012-01-01 12:12:12':'2012-01-03 12:12:12'], 1), idx['A', 'B']] tm.assert_frame_equal(result, expected) def test_multiindex_slicers_edges(self): # GH 8132 # various edge cases df = DataFrame( {'A': ['A0'] * 5 + ['A1'] * 5 + ['A2'] * 5, 'B': ['B0', 'B0', 'B1', 'B1', 'B2'] * 3, 'DATE': ["2013-06-11", "2013-07-02", "2013-07-09", "2013-07-30", "2013-08-06", "2013-06-11", "2013-07-02", "2013-07-09", "2013-07-30", "2013-08-06", "2013-09-03", "2013-10-01", "2013-07-09", "2013-08-06", "2013-09-03"], 'VALUES': [22, 35, 14, 9, 4, 40, 18, 4, 2, 5, 1, 2, 3, 4, 2]}) df['DATE'] = pd.to_datetime(df['DATE']) df1 = df.set_index(['A', 'B', 'DATE']) df1 = df1.sort_index() # A1 - Get all values under "A0" and "A1" result = df1.loc[(slice('A1')), :] expected = df1.iloc[0:10] tm.assert_frame_equal(result, expected) # A2 - Get all values from the start to "A2" result = df1.loc[(slice('A2')), :] expected = df1 tm.assert_frame_equal(result, expected) # A3 - Get all values under "B1" or "B2" result = df1.loc[(slice(None), slice('B1', 'B2')), :] expected = df1.iloc[[2, 3, 4, 7, 8, 9, 12, 13, 14]] tm.assert_frame_equal(result, expected) # A4 - Get all values between 2013-07-02 and 2013-07-09 result = df1.loc[(slice(None), slice(None), slice('20130702', '20130709')), :] expected = df1.iloc[[1, 2, 6, 7, 12]] tm.assert_frame_equal(result, expected) # B1 - Get all values in B0 that are also under A0, A1 and A2 result = df1.loc[(slice('A2'), slice('B0')), :] expected = df1.iloc[[0, 1, 5, 6, 10, 11]] tm.assert_frame_equal(result, expected) # B2 - Get all values in B0, B1 and B2 (similar to what #2 is doing for # the As) result = df1.loc[(slice(None), slice('B2')), :] expected = df1 tm.assert_frame_equal(result, expected) # B3 - Get all values from B1 to B2 and up to 2013-08-06 result = df1.loc[(slice(None), slice('B1', 'B2'), slice('2013-08-06')), :] expected = df1.iloc[[2, 3, 4, 7, 8, 9, 12, 13]] tm.assert_frame_equal(result, expected) # B4 - Same as A4 but the start of the date slice is not a key. # shows indexing on a partial selection slice result = df1.loc[(slice(None), slice(None), slice('20130701', '20130709')), :] expected = df1.iloc[[1, 2, 6, 7, 12]] tm.assert_frame_equal(result, expected) def test_per_axis_per_level_doc_examples(self): # test index maker idx = pd.IndexSlice # from indexing.rst / advanced index = MultiIndex.from_product([_mklbl('A', 4), _mklbl('B', 2), _mklbl('C', 4), _mklbl('D', 2)]) columns = MultiIndex.from_tuples([('a', 'foo'), ('a', 'bar'), ('b', 'foo'), ('b', 'bah')], names=['lvl0', 'lvl1']) df = DataFrame(np.arange(len(index) * len(columns), dtype='int64') .reshape((len(index), len(columns))), index=index, columns=columns) result = df.loc[(slice('A1', 'A3'), slice(None), ['C1', 'C3']), :] expected = df.loc[[tuple([a, b, c, d]) for a, b, c, d in df.index.values if (a == 'A1' or a == 'A2' or a == 'A3') and ( c == 'C1' or c == 'C3')]] tm.assert_frame_equal(result, expected) result = df.loc[idx['A1':'A3', :, ['C1', 'C3']], :] tm.assert_frame_equal(result, expected) result = df.loc[(slice(None), slice(None), ['C1', 'C3']), :] expected = df.loc[[tuple([a, b, c, d]) for a, b, c, d in df.index.values if (c == 'C1' or c == 'C3')]] tm.assert_frame_equal(result, expected) result = df.loc[idx[:, :, ['C1', 'C3']], :] tm.assert_frame_equal(result, expected) # not sorted def f(): df.loc['A1', (slice(None), 'foo')] self.assertRaises(UnsortedIndexError, f) df = df.sort_index(axis=1) # slicing df.loc['A1', (slice(None), 'foo')] df.loc[(slice(None), slice(None), ['C1', 'C3']), (slice(None), 'foo')] # setitem df.loc(axis=0)[:, :, ['C1', 'C3']] = -10 def test_loc_axis_arguments(self): index = MultiIndex.from_product([_mklbl('A', 4), _mklbl('B', 2), _mklbl('C', 4), _mklbl('D', 2)]) columns = MultiIndex.from_tuples([('a', 'foo'), ('a', 'bar'), ('b', 'foo'), ('b', 'bah')], names=['lvl0', 'lvl1']) df = DataFrame(np.arange(len(index) * len(columns), dtype='int64') .reshape((len(index), len(columns))), index=index, columns=columns).sort_index().sort_index(axis=1) # axis 0 result = df.loc(axis=0)['A1':'A3', :, ['C1', 'C3']] expected = df.loc[[tuple([a, b, c, d]) for a, b, c, d in df.index.values if (a == 'A1' or a == 'A2' or a == 'A3') and ( c == 'C1' or c == 'C3')]] tm.assert_frame_equal(result, expected) result = df.loc(axis='index')[:, :, ['C1', 'C3']] expected = df.loc[[tuple([a, b, c, d]) for a, b, c, d in df.index.values if (c == 'C1' or c == 'C3')]] tm.assert_frame_equal(result, expected) # axis 1 result = df.loc(axis=1)[:, 'foo'] expected = df.loc[:, (slice(None), 'foo')] tm.assert_frame_equal(result, expected) result = df.loc(axis='columns')[:, 'foo'] expected = df.loc[:, (slice(None), 'foo')] tm.assert_frame_equal(result, expected) # invalid axis def f(): df.loc(axis=-1)[:, :, ['C1', 'C3']] self.assertRaises(ValueError, f) def f(): df.loc(axis=2)[:, :, ['C1', 'C3']] self.assertRaises(ValueError, f) def f(): df.loc(axis='foo')[:, :, ['C1', 'C3']] self.assertRaises(ValueError, f) def test_loc_coerceion(self): # 12411 df = DataFrame({'date': [pd.Timestamp('20130101').tz_localize('UTC'), pd.NaT]}) expected = df.dtypes result = df.iloc[[0]] tm.assert_series_equal(result.dtypes, expected) result = df.iloc[[1]] tm.assert_series_equal(result.dtypes, expected) # 12045 import datetime df = DataFrame({'date': [datetime.datetime(2012, 1, 1), datetime.datetime(1012, 1, 2)]}) expected = df.dtypes result = df.iloc[[0]] tm.assert_series_equal(result.dtypes, expected) result = df.iloc[[1]] tm.assert_series_equal(result.dtypes, expected) # 11594 df = DataFrame({'text': ['some words'] + [None] * 9}) expected = df.dtypes result = df.iloc[0:2] tm.assert_series_equal(result.dtypes, expected) result = df.iloc[3:] tm.assert_series_equal(result.dtypes, expected) def test_per_axis_per_level_setitem(self): # test index maker idx = pd.IndexSlice # test multi-index slicing with per axis and per index controls index = MultiIndex.from_tuples([('A', 1), ('A', 2), ('A', 3), ('B', 1)], names=['one', 'two']) columns = MultiIndex.from_tuples([('a', 'foo'), ('a', 'bar'), ('b', 'foo'), ('b', 'bah')], names=['lvl0', 'lvl1']) df_orig = DataFrame( np.arange(16, dtype='int64').reshape( 4, 4), index=index, columns=columns) df_orig = df_orig.sort_index(axis=0).sort_index(axis=1) # identity df = df_orig.copy() df.loc[(slice(None), slice(None)), :] = 100 expected = df_orig.copy() expected.iloc[:, :] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc(axis=0)[:, :] = 100 expected = df_orig.copy() expected.iloc[:, :] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc[(slice(None), slice(None)), (slice(None), slice(None))] = 100 expected = df_orig.copy() expected.iloc[:, :] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc[:, (slice(None), slice(None))] = 100 expected = df_orig.copy() expected.iloc[:, :] = 100 tm.assert_frame_equal(df, expected) # index df = df_orig.copy() df.loc[(slice(None), [1]), :] = 100 expected = df_orig.copy() expected.iloc[[0, 3]] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc[(slice(None), 1), :] = 100 expected = df_orig.copy() expected.iloc[[0, 3]] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc(axis=0)[:, 1] = 100 expected = df_orig.copy() expected.iloc[[0, 3]] = 100 tm.assert_frame_equal(df, expected) # columns df = df_orig.copy() df.loc[:, (slice(None), ['foo'])] = 100 expected = df_orig.copy() expected.iloc[:, [1, 3]] = 100 tm.assert_frame_equal(df, expected) # both df = df_orig.copy() df.loc[(slice(None), 1), (slice(None), ['foo'])] = 100 expected = df_orig.copy() expected.iloc[[0, 3], [1, 3]] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc[idx[:, 1], idx[:, ['foo']]] = 100 expected = df_orig.copy() expected.iloc[[0, 3], [1, 3]] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc['A', 'a'] = 100 expected = df_orig.copy() expected.iloc[0:3, 0:2] = 100 tm.assert_frame_equal(df, expected) # setting with a list-like df = df_orig.copy() df.loc[(slice(None), 1), (slice(None), ['foo'])] = np.array( [[100, 100], [100, 100]], dtype='int64') expected = df_orig.copy() expected.iloc[[0, 3], [1, 3]] = 100 tm.assert_frame_equal(df, expected) # not enough values df = df_orig.copy() def f(): df.loc[(slice(None), 1), (slice(None), ['foo'])] = np.array( [[100], [100, 100]], dtype='int64') self.assertRaises(ValueError, f) def f(): df.loc[(slice(None), 1), (slice(None), ['foo'])] = np.array( [100, 100, 100, 100], dtype='int64') self.assertRaises(ValueError, f) # with an alignable rhs df = df_orig.copy() df.loc[(slice(None), 1), (slice(None), ['foo'])] = df.loc[(slice( None), 1), (slice(None), ['foo'])] * 5 expected = df_orig.copy() expected.iloc[[0, 3], [1, 3]] = expected.iloc[[0, 3], [1, 3]] * 5 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc[(slice(None), 1), (slice(None), ['foo'])] *= df.loc[(slice( None), 1), (slice(None), ['foo'])] expected = df_orig.copy() expected.iloc[[0, 3], [1, 3]] *= expected.iloc[[0, 3], [1, 3]] tm.assert_frame_equal(df, expected) rhs = df_orig.loc[(slice(None), 1), (slice(None), ['foo'])].copy() rhs.loc[:, ('c', 'bah')] = 10 df = df_orig.copy() df.loc[(slice(None), 1), (slice(None), ['foo'])] *= rhs expected = df_orig.copy() expected.iloc[[0, 3], [1, 3]] *= expected.iloc[[0, 3], [1, 3]] tm.assert_frame_equal(df, expected) def test_multiindex_setitem(self): # GH 3738 # setting with a multi-index right hand side arrays = [np.array(['bar', 'bar', 'baz', 'qux', 'qux', 'bar']), np.array(['one', 'two', 'one', 'one', 'two', 'one']), np.arange(0, 6, 1)] df_orig = pd.DataFrame(np.random.randn(6, 3), index=arrays, columns=['A', 'B', 'C']).sort_index() expected = df_orig.loc[['bar']] * 2 df = df_orig.copy() df.loc[['bar']] *= 2 tm.assert_frame_equal(df.loc[['bar']], expected) # raise because these have differing levels def f(): df.loc['bar'] *= 2 self.assertRaises(TypeError, f) # from SO # http://stackoverflow.com/questions/24572040/pandas-access-the-level-of-multiindex-for-inplace-operation df_orig = DataFrame.from_dict({'price': { ('DE', 'Coal', 'Stock'): 2, ('DE', 'Gas', 'Stock'): 4, ('DE', 'Elec', 'Demand'): 1, ('FR', 'Gas', 'Stock'): 5, ('FR', 'Solar', 'SupIm'): 0, ('FR', 'Wind', 'SupIm'): 0 }}) df_orig.index = MultiIndex.from_tuples(df_orig.index, names=['Sit', 'Com', 'Type']) expected = df_orig.copy() expected.iloc[[0, 2, 3]] *= 2 idx = pd.IndexSlice df = df_orig.copy() df.loc[idx[:, :, 'Stock'], :] *= 2 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc[idx[:, :, 'Stock'], 'price'] *= 2 tm.assert_frame_equal(df, expected) def test_getitem_multiindex(self): # GH 5725 the 'A' happens to be a valid Timestamp so the doesn't raise # the appropriate error, only in PY3 of course! index = MultiIndex(levels=[['D', 'B', 'C'], [0, 26, 27, 37, 57, 67, 75, 82]], labels=[[0, 0, 0, 1, 2, 2, 2, 2, 2, 2], [1, 3, 4, 6, 0, 2, 2, 3, 5, 7]], names=['tag', 'day']) arr = np.random.randn(len(index), 1) df = DataFrame(arr, index=index, columns=['val']) result = df.val['D'] expected = Series(arr.ravel()[0:3], name='val', index=Index( [26, 37, 57], name='day')) tm.assert_series_equal(result, expected) def f(): df.val['A'] self.assertRaises(KeyError, f) def f(): df.val['X'] self.assertRaises(KeyError, f) # A is treated as a special Timestamp index = MultiIndex(levels=[['A', 'B', 'C'], [0, 26, 27, 37, 57, 67, 75, 82]], labels=[[0, 0, 0, 1, 2, 2, 2, 2, 2, 2], [1, 3, 4, 6, 0, 2, 2, 3, 5, 7]], names=['tag', 'day']) df = DataFrame(arr, index=index, columns=['val']) result = df.val['A'] expected = Series(arr.ravel()[0:3], name='val', index=Index( [26, 37, 57], name='day')) tm.assert_series_equal(result, expected) def f(): df.val['X'] self.assertRaises(KeyError, f) # GH 7866 # multi-index slicing with missing indexers idx = pd.MultiIndex.from_product([['A', 'B', 'C'], ['foo', 'bar', 'baz']], names=['one', 'two']) s = pd.Series(np.arange(9, dtype='int64'), index=idx).sort_index() exp_idx = pd.MultiIndex.from_product([['A'], ['foo', 'bar', 'baz']], names=['one', 'two']) expected = pd.Series(np.arange(3, dtype='int64'), index=exp_idx).sort_index() result = s.loc[['A']] tm.assert_series_equal(result, expected) result = s.loc[['A', 'D']] tm.assert_series_equal(result, expected) # not any values found self.assertRaises(KeyError, lambda: s.loc[['D']]) # empty ok result = s.loc[[]] expected = s.iloc[[]] tm.assert_series_equal(result, expected) idx = pd.IndexSlice expected = pd.Series([0, 3, 6], index=pd.MultiIndex.from_product( [['A', 'B', 'C'], ['foo']], names=['one', 'two'])).sort_index() result = s.loc[idx[:, ['foo']]] tm.assert_series_equal(result, expected) result = s.loc[idx[:, ['foo', 'bah']]] tm.assert_series_equal(result, expected) # GH 8737 # empty indexer multi_index = pd.MultiIndex.from_product((['foo', 'bar', 'baz'], ['alpha', 'beta'])) df = DataFrame( np.random.randn(5, 6), index=range(5), columns=multi_index) df = df.sort_index(level=0, axis=1) expected = DataFrame(index=range(5), columns=multi_index.reindex([])[0]) result1 = df.loc[:, ([], slice(None))] result2 = df.loc[:, (['foo'], [])] tm.assert_frame_equal(result1, expected) tm.assert_frame_equal(result2, expected) # regression from < 0.14.0 # GH 7914 df = DataFrame([[np.mean, np.median], ['mean', 'median']], columns=MultiIndex.from_tuples([('functs', 'mean'), ('functs', 'median')]), index=['function', 'name']) result = df.loc['function', ('functs', 'mean')] self.assertEqual(result, np.mean) def test_setitem_dtype_upcast(self): # GH3216 df = DataFrame([{"a": 1}, {"a": 3, "b": 2}]) df['c'] = np.nan self.assertEqual(df['c'].dtype, np.float64) df.loc[0, 'c'] = 'foo' expected = DataFrame([{"a": 1, "c": 'foo'}, {"a": 3, "b": 2, "c": np.nan}]) tm.assert_frame_equal(df, expected) # GH10280 df = DataFrame(np.arange(6, dtype='int64').reshape(2, 3), index=list('ab'), columns=['foo', 'bar', 'baz']) for val in [3.14, 'wxyz']: left = df.copy() left.loc['a', 'bar'] = val right = DataFrame([[0, val, 2], [3, 4, 5]], index=list('ab'), columns=['foo', 'bar', 'baz']) tm.assert_frame_equal(left, right) self.assertTrue(is_integer_dtype(left['foo'])) self.assertTrue(is_integer_dtype(left['baz'])) left = DataFrame(np.arange(6, dtype='int64').reshape(2, 3) / 10.0, index=list('ab'), columns=['foo', 'bar', 'baz']) left.loc['a', 'bar'] = 'wxyz' right = DataFrame([[0, 'wxyz', .2], [.3, .4, .5]], index=list('ab'), columns=['foo', 'bar', 'baz']) tm.assert_frame_equal(left, right) self.assertTrue(is_float_dtype(left['foo'])) self.assertTrue(is_float_dtype(left['baz'])) def test_setitem_iloc(self): # setitem with an iloc list df = DataFrame(np.arange(9).reshape((3, 3)), index=["A", "B", "C"], columns=["A", "B", "C"]) df.iloc[[0, 1], [1, 2]] df.iloc[[0, 1], [1, 2]] += 100 expected = DataFrame( np.array([0, 101, 102, 3, 104, 105, 6, 7, 8]).reshape((3, 3)), index=["A", "B", "C"], columns=["A", "B", "C"]) tm.assert_frame_equal(df, expected) def test_dups_fancy_indexing(self): # GH 3455 from pandas.util.testing import makeCustomDataframe as mkdf df = mkdf(10, 3) df.columns = ['a', 'a', 'b'] result = df[['b', 'a']].columns expected = Index(['b', 'a', 'a']) self.assert_index_equal(result, expected) # across dtypes df = DataFrame([[1, 2, 1., 2., 3., 'foo', 'bar']], columns=list('aaaaaaa')) df.head() str(df) result = DataFrame([[1, 2, 1., 2., 3., 'foo', 'bar']]) result.columns = list('aaaaaaa') # TODO(wesm): unused? df_v = df.iloc[:, 4] # noqa res_v = result.iloc[:, 4] # noqa tm.assert_frame_equal(df, result) # GH 3561, dups not in selected order df = DataFrame( {'test': [5, 7, 9, 11], 'test1': [4., 5, 6, 7], 'other': list('abcd')}, index=['A', 'A', 'B', 'C']) rows = ['C', 'B'] expected = DataFrame( {'test': [11, 9], 'test1': [7., 6], 'other': ['d', 'c']}, index=rows) result = df.loc[rows] tm.assert_frame_equal(result, expected) result = df.loc[Index(rows)] tm.assert_frame_equal(result, expected) rows = ['C', 'B', 'E'] expected = DataFrame( {'test': [11, 9, np.nan], 'test1': [7., 6, np.nan], 'other': ['d', 'c', np.nan]}, index=rows) result = df.loc[rows] tm.assert_frame_equal(result, expected) # see GH5553, make sure we use the right indexer rows = ['F', 'G', 'H', 'C', 'B', 'E'] expected = DataFrame({'test': [np.nan, np.nan, np.nan, 11, 9, np.nan], 'test1': [np.nan, np.nan, np.nan, 7., 6, np.nan], 'other': [np.nan, np.nan, np.nan, 'd', 'c', np.nan]}, index=rows) result = df.loc[rows] tm.assert_frame_equal(result, expected) # inconsistent returns for unique/duplicate indices when values are # missing df = DataFrame(randn(4, 3), index=list('ABCD')) expected = df.ix[['E']] dfnu = DataFrame(randn(5, 3), index=list('AABCD')) result = dfnu.ix[['E']] tm.assert_frame_equal(result, expected) # ToDo: check_index_type can be True after GH 11497 # GH 4619; duplicate indexer with missing label df = DataFrame({"A": [0, 1, 2]}) result = df.ix[[0, 8, 0]] expected = DataFrame({"A": [0, np.nan, 0]}, index=[0, 8, 0]) tm.assert_frame_equal(result, expected, check_index_type=False) df = DataFrame({"A": list('abc')}) result = df.ix[[0, 8, 0]] expected = DataFrame({"A": ['a', np.nan, 'a']}, index=[0, 8, 0]) tm.assert_frame_equal(result, expected, check_index_type=False) # non unique with non unique selector df = DataFrame({'test': [5, 7, 9, 11]}, index=['A', 'A', 'B', 'C']) expected = DataFrame( {'test': [5, 7, 5, 7, np.nan]}, index=['A', 'A', 'A', 'A', 'E']) result = df.ix[['A', 'A', 'E']] tm.assert_frame_equal(result, expected) # GH 5835 # dups on index and missing values df = DataFrame( np.random.randn(5, 5), columns=['A', 'B', 'B', 'B', 'A']) expected = pd.concat( [df.ix[:, ['A', 'B']], DataFrame(np.nan, columns=['C'], index=df.index)], axis=1) result = df.ix[:, ['A', 'B', 'C']] tm.assert_frame_equal(result, expected) # GH 6504, multi-axis indexing df = DataFrame(np.random.randn(9, 2), index=[1, 1, 1, 2, 2, 2, 3, 3, 3], columns=['a', 'b']) expected = df.iloc[0:6] result = df.loc[[1, 2]] tm.assert_frame_equal(result, expected) expected = df result = df.loc[:, ['a', 'b']] tm.assert_frame_equal(result, expected) expected = df.iloc[0:6, :] result = df.loc[[1, 2], ['a', 'b']] tm.assert_frame_equal(result, expected) def test_indexing_mixed_frame_bug(self): # GH3492 df = DataFrame({'a': {1: 'aaa', 2: 'bbb', 3: 'ccc'}, 'b': {1: 111, 2: 222, 3: 333}}) # this works, new column is created correctly df['test'] = df['a'].apply(lambda x: '_' if x == 'aaa' else x) # this does not work, ie column test is not changed idx = df['test'] == '_' temp = df.ix[idx, 'a'].apply(lambda x: '-----' if x == 'aaa' else x) df.ix[idx, 'test'] = temp self.assertEqual(df.iloc[0, 2], '-----') # if I look at df, then element [0,2] equals '_'. If instead I type # df.ix[idx,'test'], I get '-----', finally by typing df.iloc[0,2] I # get '_'. def test_multitype_list_index_access(self): # GH 10610 df = pd.DataFrame(np.random.random((10, 5)), columns=["a"] + [20, 21, 22, 23]) with self.assertRaises(KeyError): df[[22, 26, -8]] self.assertEqual(df[21].shape[0], df.shape[0]) def test_set_index_nan(self): # GH 3586 df = DataFrame({'PRuid': {17: 'nonQC', 18: 'nonQC', 19: 'nonQC', 20: '10', 21: '11', 22: '12', 23: '13', 24: '24', 25: '35', 26: '46', 27: '47', 28: '48', 29: '59', 30: '10'}, 'QC': {17: 0.0, 18: 0.0, 19: 0.0, 20: nan, 21: nan, 22: nan, 23: nan, 24: 1.0, 25: nan, 26: nan, 27: nan, 28: nan, 29: nan, 30: nan}, 'data': {17: 7.9544899999999998, 18: 8.0142609999999994, 19: 7.8591520000000008, 20: 0.86140349999999999, 21: 0.87853110000000001, 22: 0.8427041999999999, 23: 0.78587700000000005, 24: 0.73062459999999996, 25: 0.81668560000000001, 26: 0.81927080000000008, 27: 0.80705009999999999, 28: 0.81440240000000008, 29: 0.80140849999999997, 30: 0.81307740000000006}, 'year': {17: 2006, 18: 2007, 19: 2008, 20: 1985, 21: 1985, 22: 1985, 23: 1985, 24: 1985, 25: 1985, 26: 1985, 27: 1985, 28: 1985, 29: 1985, 30: 1986}}).reset_index() result = df.set_index(['year', 'PRuid', 'QC']).reset_index().reindex( columns=df.columns) tm.assert_frame_equal(result, df) def test_multi_nan_indexing(self): # GH 3588 df = DataFrame({"a": ['R1', 'R2', np.nan, 'R4'], 'b': ["C1", "C2", "C3", "C4"], "c": [10, 15, np.nan, 20]}) result = df.set_index(['a', 'b'], drop=False) expected = DataFrame({"a": ['R1', 'R2', np.nan, 'R4'], 'b': ["C1", "C2", "C3", "C4"], "c": [10, 15, np.nan, 20]}, index=[Index(['R1', 'R2', np.nan, 'R4'], name='a'), Index(['C1', 'C2', 'C3', 'C4'], name='b')]) tm.assert_frame_equal(result, expected) def test_iloc_panel_issue(self): # GH 3617 p = Panel(randn(4, 4, 4)) self.assertEqual(p.iloc[:3, :3, :3].shape, (3, 3, 3)) self.assertEqual(p.iloc[1, :3, :3].shape, (3, 3)) self.assertEqual(p.iloc[:3, 1, :3].shape, (3, 3)) self.assertEqual(p.iloc[:3, :3, 1].shape, (3, 3)) self.assertEqual(p.iloc[1, 1, :3].shape, (3, )) self.assertEqual(p.iloc[1, :3, 1].shape, (3, )) self.assertEqual(p.iloc[:3, 1, 1].shape, (3, )) def test_panel_getitem(self): # GH4016, date selection returns a frame when a partial string # selection ind = date_range(start="2000", freq="D", periods=1000) df = DataFrame( np.random.randn( len(ind), 5), index=ind, columns=list('ABCDE')) panel = Panel(dict([('frame_' + c, df) for c in list('ABC')])) test2 = panel.ix[:, "2002":"2002-12-31"] test1 = panel.ix[:, "2002"] tm.assert_panel_equal(test1, test2) # GH8710 # multi-element getting with a list panel = tm.makePanel() expected = panel.iloc[[0, 1]] result = panel.loc[['ItemA', 'ItemB']] tm.assert_panel_equal(result, expected) result = panel.loc[['ItemA', 'ItemB'], :, :] tm.assert_panel_equal(result, expected) result = panel[['ItemA', 'ItemB']] tm.assert_panel_equal(result, expected) result = panel.loc['ItemA':'ItemB'] tm.assert_panel_equal(result, expected) result = panel.ix['ItemA':'ItemB'] tm.assert_panel_equal(result, expected) result = panel.ix[['ItemA', 'ItemB']] tm.assert_panel_equal(result, expected) # with an object-like # GH 9140 class TestObject: def __str__(self): return "TestObject" obj = TestObject() p = Panel(np.random.randn(1, 5, 4), items=[obj], major_axis=date_range('1/1/2000', periods=5), minor_axis=['A', 'B', 'C', 'D']) expected = p.iloc[0] result = p[obj] tm.assert_frame_equal(result, expected) def test_panel_setitem(self): # GH 7763 # loc and setitem have setting differences np.random.seed(0) index = range(3) columns = list('abc') panel = Panel({'A': DataFrame(np.random.randn(3, 3), index=index, columns=columns), 'B': DataFrame(np.random.randn(3, 3), index=index, columns=columns), 'C': DataFrame(np.random.randn(3, 3), index=index, columns=columns)}) replace = DataFrame(np.eye(3, 3), index=range(3), columns=columns) expected = Panel({'A': replace, 'B': replace, 'C': replace}) p = panel.copy() for idx in list('ABC'): p[idx] = replace tm.assert_panel_equal(p, expected) p = panel.copy() for idx in list('ABC'): p.loc[idx, :, :] = replace tm.assert_panel_equal(p, expected) def test_panel_setitem_with_multiindex(self): # 10360 # failing with a multi-index arr = np.array([[[1, 2, 3], [0, 0, 0]], [[0, 0, 0], [0, 0, 0]]], dtype=np.float64) # reg index axes = dict(items=['A', 'B'], major_axis=[0, 1], minor_axis=['X', 'Y', 'Z']) p1 = Panel(0., **axes) p1.iloc[0, 0, :] = [1, 2, 3] expected = Panel(arr, **axes) tm.assert_panel_equal(p1, expected) # multi-indexes axes['items'] = pd.MultiIndex.from_tuples([('A', 'a'), ('B', 'b')]) p2 = Panel(0., **axes) p2.iloc[0, 0, :] = [1, 2, 3] expected = Panel(arr, **axes) tm.assert_panel_equal(p2, expected) axes['major_axis'] = pd.MultiIndex.from_tuples([('A', 1), ('A', 2)]) p3 = Panel(0., **axes) p3.iloc[0, 0, :] = [1, 2, 3] expected = Panel(arr, **axes) tm.assert_panel_equal(p3, expected) axes['minor_axis'] = pd.MultiIndex.from_product([['X'], range(3)]) p4 = Panel(0., **axes) p4.iloc[0, 0, :] = [1, 2, 3] expected = Panel(arr, **axes) tm.assert_panel_equal(p4, expected) arr = np.array( [[[1, 0, 0], [2, 0, 0]], [[0, 0, 0], [0, 0, 0]]], dtype=np.float64) p5 = Panel(0., **axes) p5.iloc[0, :, 0] = [1, 2] expected = Panel(arr, **axes) tm.assert_panel_equal(p5, expected) def test_panel_assignment(self): # GH3777 wp = Panel(randn(2, 5, 4), items=['Item1', 'Item2'], major_axis=date_range('1/1/2000', periods=5), minor_axis=['A', 'B', 'C', 'D']) wp2 = Panel(randn(2, 5, 4), items=['Item1', 'Item2'], major_axis=date_range('1/1/2000', periods=5), minor_axis=['A', 'B', 'C', 'D']) # TODO: unused? # expected = wp.loc[['Item1', 'Item2'], :, ['A', 'B']] def f(): wp.loc[['Item1', 'Item2'], :, ['A', 'B']] = wp2.loc[ ['Item1', 'Item2'], :, ['A', 'B']] self.assertRaises(NotImplementedError, f) # to_assign = wp2.loc[['Item1', 'Item2'], :, ['A', 'B']] # wp.loc[['Item1', 'Item2'], :, ['A', 'B']] = to_assign # result = wp.loc[['Item1', 'Item2'], :, ['A', 'B']] # tm.assert_panel_equal(result,expected) def test_multiindex_assignment(self): # GH3777 part 2 # mixed dtype df = DataFrame(np.random.randint(5, 10, size=9).reshape(3, 3), columns=list('abc'), index=[[4, 4, 8], [8, 10, 12]]) df['d'] = np.nan arr = np.array([0., 1.]) df.ix[4, 'd'] = arr tm.assert_series_equal(df.ix[4, 'd'], Series(arr, index=[8, 10], name='d')) # single dtype df = DataFrame(np.random.randint(5, 10, size=9).reshape(3, 3), columns=list('abc'), index=[[4, 4, 8], [8, 10, 12]]) df.ix[4, 'c'] = arr exp = Series(arr, index=[8, 10], name='c', dtype='float64') tm.assert_series_equal(df.ix[4, 'c'], exp) # scalar ok df.ix[4, 'c'] = 10 exp = Series(10, index=[8, 10], name='c', dtype='float64') tm.assert_series_equal(df.ix[4, 'c'], exp) # invalid assignments def f(): df.ix[4, 'c'] = [0, 1, 2, 3] self.assertRaises(ValueError, f) def f(): df.ix[4, 'c'] = [0] self.assertRaises(ValueError, f) # groupby example NUM_ROWS = 100 NUM_COLS = 10 col_names = ['A' + num for num in map(str, np.arange(NUM_COLS).tolist())] index_cols = col_names[:5] df = DataFrame(np.random.randint(5, size=(NUM_ROWS, NUM_COLS)), dtype=np.int64, columns=col_names) df = df.set_index(index_cols).sort_index() grp = df.groupby(level=index_cols[:4]) df['new_col'] = np.nan f_index = np.arange(5) def f(name, df2): return Series(np.arange(df2.shape[0]), name=df2.index.values[0]).reindex(f_index) # TODO(wesm): unused? # new_df = pd.concat([f(name, df2) for name, df2 in grp], axis=1).T # we are actually operating on a copy here # but in this case, that's ok for name, df2 in grp: new_vals = np.arange(df2.shape[0]) df.ix[name, 'new_col'] = new_vals def test_multi_assign(self): # GH 3626, an assignement of a sub-df to a df df = DataFrame({'FC': ['a', 'b', 'a', 'b', 'a', 'b'], 'PF': [0, 0, 0, 0, 1, 1], 'col1': lrange(6), 'col2': lrange(6, 12)}) df.ix[1, 0] = np.nan df2 = df.copy() mask = ~df2.FC.isnull() cols = ['col1', 'col2'] dft = df2 * 2 dft.ix[3, 3] = np.nan expected = DataFrame({'FC': ['a', np.nan, 'a', 'b', 'a', 'b'], 'PF': [0, 0, 0, 0, 1, 1], 'col1': Series([0, 1, 4, 6, 8, 10]), 'col2': [12, 7, 16, np.nan, 20, 22]}) # frame on rhs df2.ix[mask, cols] = dft.ix[mask, cols] tm.assert_frame_equal(df2, expected) df2.ix[mask, cols] = dft.ix[mask, cols] tm.assert_frame_equal(df2, expected) # with an ndarray on rhs df2 = df.copy() df2.ix[mask, cols] = dft.ix[mask, cols].values tm.assert_frame_equal(df2, expected) df2.ix[mask, cols] = dft.ix[mask, cols].values tm.assert_frame_equal(df2, expected) # broadcasting on the rhs is required df = DataFrame(dict(A=[1, 2, 0, 0, 0], B=[0, 0, 0, 10, 11], C=[ 0, 0, 0, 10, 11], D=[3, 4, 5, 6, 7])) expected = df.copy() mask = expected['A'] == 0 for col in ['A', 'B']: expected.loc[mask, col] = df['D'] df.loc[df['A'] == 0, ['A', 'B']] = df['D'] tm.assert_frame_equal(df, expected) def test_ix_assign_column_mixed(self): # GH #1142 df = DataFrame(tm.getSeriesData()) df['foo'] = 'bar' orig = df.ix[:, 'B'].copy() df.ix[:, 'B'] = df.ix[:, 'B'] + 1 tm.assert_series_equal(df.B, orig + 1) # GH 3668, mixed frame with series value df = DataFrame({'x': lrange(10), 'y': lrange(10, 20), 'z': 'bar'}) expected = df.copy() for i in range(5): indexer = i * 2 v = 1000 + i * 200 expected.ix[indexer, 'y'] = v self.assertEqual(expected.ix[indexer, 'y'], v) df.ix[df.x % 2 == 0, 'y'] = df.ix[df.x % 2 == 0, 'y'] * 100 tm.assert_frame_equal(df, expected) # GH 4508, making sure consistency of assignments df = DataFrame({'a': [1, 2, 3], 'b': [0, 1, 2]}) df.ix[[0, 2, ], 'b'] = [100, -100] expected = DataFrame({'a': [1, 2, 3], 'b': [100, 1, -100]}) tm.assert_frame_equal(df, expected) df = pd.DataFrame({'a': lrange(4)}) df['b'] = np.nan df.ix[[1, 3], 'b'] = [100, -100] expected = DataFrame({'a': [0, 1, 2, 3], 'b': [np.nan, 100, np.nan, -100]}) tm.assert_frame_equal(df, expected) # ok, but chained assignments are dangerous # if we turn off chained assignement it will work with option_context('chained_assignment', None): df = pd.DataFrame({'a': lrange(4)}) df['b'] = np.nan df['b'].ix[[1, 3]] = [100, -100] tm.assert_frame_equal(df, expected) def test_ix_get_set_consistency(self): # GH 4544 # ix/loc get/set not consistent when # a mixed int/string index df = DataFrame(np.arange(16).reshape((4, 4)), columns=['a', 'b', 8, 'c'], index=['e', 7, 'f', 'g']) self.assertEqual(df.ix['e', 8], 2) self.assertEqual(df.loc['e', 8], 2) df.ix['e', 8] = 42 self.assertEqual(df.ix['e', 8], 42) self.assertEqual(df.loc['e', 8], 42) df.loc['e', 8] = 45 self.assertEqual(df.ix['e', 8], 45) self.assertEqual(df.loc['e', 8], 45) def test_setitem_list(self): # GH 6043 # ix with a list df = DataFrame(index=[0, 1], columns=[0]) df.ix[1, 0] = [1, 2, 3] df.ix[1, 0] = [1, 2] result = DataFrame(index=[0, 1], columns=[0]) result.ix[1, 0] = [1, 2] tm.assert_frame_equal(result, df) # ix with an object class TO(object): def __init__(self, value): self.value = value def __str__(self): return "[{0}]".format(self.value) __repr__ = __str__ def __eq__(self, other): return self.value == other.value def view(self): return self df = DataFrame(index=[0, 1], columns=[0]) df.ix[1, 0] = TO(1) df.ix[1, 0] = TO(2) result = DataFrame(index=[0, 1], columns=[0]) result.ix[1, 0] = TO(2) tm.assert_frame_equal(result, df) # remains object dtype even after setting it back df = DataFrame(index=[0, 1], columns=[0]) df.ix[1, 0] = TO(1) df.ix[1, 0] = np.nan result = DataFrame(index=[0, 1], columns=[0]) tm.assert_frame_equal(result, df) def test_iloc_mask(self): # GH 3631, iloc with a mask (of a series) should raise df = DataFrame(lrange(5), list('ABCDE'), columns=['a']) mask = (df.a % 2 == 0) self.assertRaises(ValueError, df.iloc.__getitem__, tuple([mask])) mask.index = lrange(len(mask)) self.assertRaises(NotImplementedError, df.iloc.__getitem__, tuple([mask])) # ndarray ok result = df.iloc[np.array([True] * len(mask), dtype=bool)] tm.assert_frame_equal(result, df) # the possibilities locs = np.arange(4) nums = 2 ** locs reps = lmap(bin, nums) df = DataFrame({'locs': locs, 'nums': nums}, reps) expected = { (None, ''): '0b1100', (None, '.loc'): '0b1100', (None, '.iloc'): '0b1100', ('index', ''): '0b11', ('index', '.loc'): '0b11', ('index', '.iloc'): ('iLocation based boolean indexing ' 'cannot use an indexable as a mask'), ('locs', ''): 'Unalignable boolean Series provided as indexer ' '(index of the boolean Series and of the indexed ' 'object do not match', ('locs', '.loc'): 'Unalignable boolean Series provided as indexer ' '(index of the boolean Series and of the ' 'indexed object do not match', ('locs', '.iloc'): ('iLocation based boolean indexing on an ' 'integer type is not available'), } # UserWarnings from reindex of a boolean mask with warnings.catch_warnings(record=True): result = dict() for idx in [None, 'index', 'locs']: mask = (df.nums > 2).values if idx: mask = Series(mask, list(reversed(getattr(df, idx)))) for method in ['', '.loc', '.iloc']: try: if method: accessor = getattr(df, method[1:]) else: accessor = df ans = str(bin(accessor[mask]['nums'].sum())) except Exception as e: ans = str(e) key = tuple([idx, method]) r = expected.get(key) if r != ans: raise AssertionError( "[%s] does not match [%s], received [%s]" % (key, ans, r)) def test_ix_slicing_strings(self): # GH3836 data = {'Classification': ['SA EQUITY CFD', 'bbb', 'SA EQUITY', 'SA SSF', 'aaa'], 'Random': [1, 2, 3, 4, 5], 'X': ['correct', 'wrong', 'correct', 'correct', 'wrong']} df = DataFrame(data) x = df[~df.Classification.isin(['SA EQUITY CFD', 'SA EQUITY', 'SA SSF' ])] df.ix[x.index, 'X'] = df['Classification'] expected = DataFrame({'Classification': {0: 'SA EQUITY CFD', 1: 'bbb', 2: 'SA EQUITY', 3: 'SA SSF', 4: 'aaa'}, 'Random': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}, 'X': {0: 'correct', 1: 'bbb', 2: 'correct', 3: 'correct', 4: 'aaa'}}) # bug was 4: 'bbb' tm.assert_frame_equal(df, expected) def test_non_unique_loc(self): # GH3659 # non-unique indexer with loc slice # https://groups.google.com/forum/?fromgroups#!topic/pydata/zTm2No0crYs # these are going to raise becuase the we are non monotonic df = DataFrame({'A': [1, 2, 3, 4, 5, 6], 'B': [3, 4, 5, 6, 7, 8]}, index=[0, 1, 0, 1, 2, 3]) self.assertRaises(KeyError, df.loc.__getitem__, tuple([slice(1, None)])) self.assertRaises(KeyError, df.loc.__getitem__, tuple([slice(0, None)])) self.assertRaises(KeyError, df.loc.__getitem__, tuple([slice(1, 2)])) # monotonic are ok df = DataFrame({'A': [1, 2, 3, 4, 5, 6], 'B': [3, 4, 5, 6, 7, 8]}, index=[0, 1, 0, 1, 2, 3]).sort_index(axis=0) result = df.loc[1:] expected = DataFrame({'A': [2, 4, 5, 6], 'B': [4, 6, 7, 8]}, index=[1, 1, 2, 3]) tm.assert_frame_equal(result, expected) result = df.loc[0:] tm.assert_frame_equal(result, df) result = df.loc[1:2] expected = DataFrame({'A': [2, 4, 5], 'B': [4, 6, 7]}, index=[1, 1, 2]) tm.assert_frame_equal(result, expected) def test_loc_name(self): # GH 3880 df = DataFrame([[1, 1], [1, 1]]) df.index.name = 'index_name' result = df.iloc[[0, 1]].index.name self.assertEqual(result, 'index_name') result = df.ix[[0, 1]].index.name self.assertEqual(result, 'index_name') result = df.loc[[0, 1]].index.name self.assertEqual(result, 'index_name') def test_iloc_non_unique_indexing(self): # GH 4017, non-unique indexing (on the axis) df = DataFrame({'A': [0.1] * 3000, 'B': [1] * 3000}) idx = np.array(lrange(30)) * 99 expected = df.iloc[idx] df3 = pd.concat([df, 2 * df, 3 * df]) result = df3.iloc[idx] tm.assert_frame_equal(result, expected) df2 = DataFrame({'A': [0.1] * 1000, 'B': [1] * 1000}) df2 = pd.concat([df2, 2 * df2, 3 * df2]) sidx = df2.index.to_series() expected = df2.iloc[idx[idx <= sidx.max()]] new_list = [] for r, s in expected.iterrows(): new_list.append(s) new_list.append(s * 2) new_list.append(s * 3) expected = DataFrame(new_list) expected = pd.concat([expected, DataFrame(index=idx[idx > sidx.max()]) ]) result = df2.loc[idx] tm.assert_frame_equal(result, expected, check_index_type=False) def test_string_slice(self): # GH 14424 # string indexing against datetimelike with object # dtype should properly raises KeyError df = pd.DataFrame([1], pd.Index([pd.Timestamp('2011-01-01')], dtype=object)) self.assertTrue(df.index.is_all_dates) with tm.assertRaises(KeyError): df['2011'] with tm.assertRaises(KeyError): df.loc['2011', 0] df = pd.DataFrame() self.assertFalse(df.index.is_all_dates) with tm.assertRaises(KeyError): df['2011'] with tm.assertRaises(KeyError): df.loc['2011', 0] def test_mi_access(self): # GH 4145 data = """h1 main h3 sub h5 0 a A 1 A1 1 1 b B 2 B1 2 2 c B 3 A1 3 3 d A 4 B2 4 4 e A 5 B2 5 5 f B 6 A2 6 """ df = pd.read_csv(StringIO(data), sep=r'\s+', index_col=0) df2 = df.set_index(['main', 'sub']).T.sort_index(1) index = Index(['h1', 'h3', 'h5']) columns = MultiIndex.from_tuples([('A', 'A1')], names=['main', 'sub']) expected = DataFrame([['a', 1, 1]], index=columns, columns=index).T result = df2.loc[:, ('A', 'A1')] tm.assert_frame_equal(result, expected) result = df2[('A', 'A1')] tm.assert_frame_equal(result, expected) # GH 4146, not returning a block manager when selecting a unique index # from a duplicate index # as of 4879, this returns a Series (which is similar to what happens # with a non-unique) expected = Series(['a', 1, 1], index=['h1', 'h3', 'h5'], name='A1') result = df2['A']['A1'] tm.assert_series_equal(result, expected) # selecting a non_unique from the 2nd level expected = DataFrame([['d', 4, 4], ['e', 5, 5]], index=Index(['B2', 'B2'], name='sub'), columns=['h1', 'h3', 'h5'], ).T result = df2['A']['B2'] tm.assert_frame_equal(result, expected) def test_non_unique_loc_memory_error(self): # GH 4280 # non_unique index with a large selection triggers a memory error columns = list('ABCDEFG') def gen_test(l, l2): return pd.concat([DataFrame(randn(l, len(columns)), index=lrange(l), columns=columns), DataFrame(np.ones((l2, len(columns))), index=[0] * l2, columns=columns)]) def gen_expected(df, mask): l = len(mask) return pd.concat([df.take([0], convert=False), DataFrame(np.ones((l, len(columns))), index=[0] * l, columns=columns), df.take(mask[1:], convert=False)]) df = gen_test(900, 100) self.assertFalse(df.index.is_unique) mask = np.arange(100) result = df.loc[mask] expected = gen_expected(df, mask) tm.assert_frame_equal(result, expected) df = gen_test(900000, 100000) self.assertFalse(df.index.is_unique) mask = np.arange(100000) result = df.loc[mask] expected = gen_expected(df, mask) tm.assert_frame_equal(result, expected) def test_astype_assignment(self): # GH4312 (iloc) df_orig = DataFrame([['1', '2', '3', '.4', 5, 6., 'foo']], columns=list('ABCDEFG')) df = df_orig.copy() df.iloc[:, 0:2] = df.iloc[:, 0:2].astype(np.int64) expected = DataFrame([[1, 2, '3', '.4', 5, 6., 'foo']], columns=list('ABCDEFG')) tm.assert_frame_equal(df, expected) df = df_orig.copy() df.iloc[:, 0:2] = df.iloc[:, 0:2]._convert(datetime=True, numeric=True) expected = DataFrame([[1, 2, '3', '.4', 5, 6., 'foo']], columns=list('ABCDEFG')) tm.assert_frame_equal(df, expected) # GH5702 (loc) df = df_orig.copy() df.loc[:, 'A'] = df.loc[:, 'A'].astype(np.int64) expected = DataFrame([[1, '2', '3', '.4', 5, 6., 'foo']], columns=list('ABCDEFG')) tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc[:, ['B', 'C']] = df.loc[:, ['B', 'C']].astype(np.int64) expected = DataFrame([['1', 2, 3, '.4', 5, 6., 'foo']], columns=list('ABCDEFG')) tm.assert_frame_equal(df, expected) # full replacements / no nans df = DataFrame({'A': [1., 2., 3., 4.]}) df.iloc[:, 0] = df['A'].astype(np.int64) expected = DataFrame({'A': [1, 2, 3, 4]}) tm.assert_frame_equal(df, expected) df = DataFrame({'A': [1., 2., 3., 4.]}) df.loc[:, 'A'] = df['A'].astype(np.int64) expected = DataFrame({'A': [1, 2, 3, 4]}) tm.assert_frame_equal(df, expected) def test_astype_assignment_with_dups(self): # GH 4686 # assignment with dups that has a dtype change cols = pd.MultiIndex.from_tuples([('A', '1'), ('B', '1'), ('A', '2')]) df = DataFrame(np.arange(3).reshape((1, 3)), columns=cols, dtype=object) index = df.index.copy() df['A'] = df['A'].astype(np.float64) self.assert_index_equal(df.index, index) # TODO(wesm): unused variables # result = df.get_dtype_counts().sort_index() # expected = Series({'float64': 2, 'object': 1}).sort_index() def test_dups_loc(self): # GH4726 # dup indexing with iloc/loc df = DataFrame([[1, 2, 'foo', 'bar', Timestamp('20130101')]], columns=['a', 'a', 'a', 'a', 'a'], index=[1]) expected = Series([1, 2, 'foo', 'bar', Timestamp('20130101')], index=['a', 'a', 'a', 'a', 'a'], name=1) result = df.iloc[0] tm.assert_series_equal(result, expected) result = df.loc[1] tm.assert_series_equal(result, expected) def test_partial_setting(self): # GH2578, allow ix and friends to partially set # series s_orig = Series([1, 2, 3]) s = s_orig.copy() s[5] = 5 expected = Series([1, 2, 3, 5], index=[0, 1, 2, 5]) tm.assert_series_equal(s, expected) s = s_orig.copy() s.loc[5] = 5 expected = Series([1, 2, 3, 5], index=[0, 1, 2, 5]) tm.assert_series_equal(s, expected) s = s_orig.copy() s[5] = 5. expected = Series([1, 2, 3, 5.], index=[0, 1, 2, 5]) tm.assert_series_equal(s, expected) s = s_orig.copy() s.loc[5] = 5. expected = Series([1, 2, 3, 5.], index=[0, 1, 2, 5]) tm.assert_series_equal(s, expected) # iloc/iat raise s = s_orig.copy() def f(): s.iloc[3] = 5. self.assertRaises(IndexError, f) def f(): s.iat[3] = 5. self.assertRaises(IndexError, f) # ## frame ## df_orig = DataFrame( np.arange(6).reshape(3, 2), columns=['A', 'B'], dtype='int64') # iloc/iat raise df = df_orig.copy() def f(): df.iloc[4, 2] = 5. self.assertRaises(IndexError, f) def f(): df.iat[4, 2] = 5. self.assertRaises(IndexError, f) # row setting where it exists expected = DataFrame(dict({'A': [0, 4, 4], 'B': [1, 5, 5]})) df = df_orig.copy() df.iloc[1] = df.iloc[2] tm.assert_frame_equal(df, expected) expected = DataFrame(dict({'A': [0, 4, 4], 'B': [1, 5, 5]})) df = df_orig.copy() df.loc[1] = df.loc[2] tm.assert_frame_equal(df, expected) # like 2578, partial setting with dtype preservation expected = DataFrame(dict({'A': [0, 2, 4, 4], 'B': [1, 3, 5, 5]})) df = df_orig.copy() df.loc[3] = df.loc[2] tm.assert_frame_equal(df, expected) # single dtype frame, overwrite expected = DataFrame(dict({'A': [0, 2, 4], 'B': [0, 2, 4]})) df = df_orig.copy() df.ix[:, 'B'] = df.ix[:, 'A'] tm.assert_frame_equal(df, expected) # mixed dtype frame, overwrite expected = DataFrame(dict({'A': [0, 2, 4], 'B': Series([0, 2, 4])})) df = df_orig.copy() df['B'] = df['B'].astype(np.float64) df.ix[:, 'B'] = df.ix[:, 'A'] tm.assert_frame_equal(df, expected) # single dtype frame, partial setting expected = df_orig.copy() expected['C'] = df['A'] df = df_orig.copy() df.ix[:, 'C'] = df.ix[:, 'A'] tm.assert_frame_equal(df, expected) # mixed frame, partial setting expected = df_orig.copy() expected['C'] = df['A'] df = df_orig.copy() df.ix[:, 'C'] = df.ix[:, 'A'] tm.assert_frame_equal(df, expected) # ## panel ## p_orig = Panel(np.arange(16).reshape(2, 4, 2), items=['Item1', 'Item2'], major_axis=pd.date_range('2001/1/12', periods=4), minor_axis=['A', 'B'], dtype='float64') # panel setting via item p_orig = Panel(np.arange(16).reshape(2, 4, 2), items=['Item1', 'Item2'], major_axis=pd.date_range('2001/1/12', periods=4), minor_axis=['A', 'B'], dtype='float64') expected = p_orig.copy() expected['Item3'] = expected['Item1'] p = p_orig.copy() p.loc['Item3'] = p['Item1'] tm.assert_panel_equal(p, expected) # panel with aligned series expected = p_orig.copy() expected = expected.transpose(2, 1, 0) expected['C'] = DataFrame({'Item1': [30, 30, 30, 30], 'Item2': [32, 32, 32, 32]}, index=p_orig.major_axis) expected = expected.transpose(2, 1, 0) p = p_orig.copy() p.loc[:, :, 'C'] = Series([30, 32], index=p_orig.items) tm.assert_panel_equal(p, expected) # GH 8473 dates = date_range('1/1/2000', periods=8) df_orig = DataFrame(np.random.randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D']) expected = pd.concat([df_orig, DataFrame( {'A': 7}, index=[dates[-1] + 1])]) df = df_orig.copy() df.loc[dates[-1] + 1, 'A'] = 7 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.at[dates[-1] + 1, 'A'] = 7 tm.assert_frame_equal(df, expected) exp_other = DataFrame({0: 7}, index=[dates[-1] + 1]) expected = pd.concat([df_orig, exp_other], axis=1) df = df_orig.copy() df.loc[dates[-1] + 1, 0] = 7 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.at[dates[-1] + 1, 0] = 7 tm.assert_frame_equal(df, expected) def test_partial_setting_mixed_dtype(self): # in a mixed dtype environment, try to preserve dtypes # by appending df = DataFrame([[True, 1], [False, 2]], columns=["female", "fitness"]) s = df.loc[1].copy() s.name = 2 expected = df.append(s) df.loc[2] = df.loc[1] tm.assert_frame_equal(df, expected) # columns will align df = DataFrame(columns=['A', 'B']) df.loc[0] = Series(1, index=range(4)) tm.assert_frame_equal(df, DataFrame(columns=['A', 'B'], index=[0])) # columns will align df = DataFrame(columns=['A', 'B']) df.loc[0] = Series(1, index=['B']) exp = DataFrame([[np.nan, 1]], columns=['A', 'B'], index=[0], dtype='float64') tm.assert_frame_equal(df, exp) # list-like must conform df = DataFrame(columns=['A', 'B']) def f(): df.loc[0] = [1, 2, 3] self.assertRaises(ValueError, f) # these are coerced to float unavoidably (as its a list-like to begin) df = DataFrame(columns=['A', 'B']) df.loc[3] = [6, 7] exp = DataFrame([[6, 7]], index=[3], columns=['A', 'B'], dtype='float64') tm.assert_frame_equal(df, exp) def test_partial_setting_with_datetimelike_dtype(self): # GH9478 # a datetimeindex alignment issue with partial setting df = pd.DataFrame(np.arange(6.).reshape(3, 2), columns=list('AB'), index=pd.date_range('1/1/2000', periods=3, freq='1H')) expected = df.copy() expected['C'] = [expected.index[0]] + [pd.NaT, pd.NaT] mask = df.A < 1 df.loc[mask, 'C'] = df.loc[mask].index tm.assert_frame_equal(df, expected) def test_loc_setitem_datetime(self): # GH 9516 dt1 = Timestamp('20130101 09:00:00') dt2 = Timestamp('20130101 10:00:00') for conv in [lambda x: x, lambda x: x.to_datetime64(), lambda x: x.to_pydatetime(), lambda x: np.datetime64(x)]: df = pd.DataFrame() df.loc[conv(dt1), 'one'] = 100 df.loc[conv(dt2), 'one'] = 200 expected = DataFrame({'one': [100.0, 200.0]}, index=[dt1, dt2]) tm.assert_frame_equal(df, expected) def test_series_partial_set(self): # partial set with new index # Regression from GH4825 ser = Series([0.1, 0.2], index=[1, 2]) # loc expected = Series([np.nan, 0.2, np.nan], index=[3, 2, 3]) result = ser.loc[[3, 2, 3]] tm.assert_series_equal(result, expected, check_index_type=True) expected = Series([np.nan, 0.2, np.nan, np.nan], index=[3, 2, 3, 'x']) result = ser.loc[[3, 2, 3, 'x']] tm.assert_series_equal(result, expected, check_index_type=True) expected = Series([0.2, 0.2, 0.1], index=[2, 2, 1]) result = ser.loc[[2, 2, 1]] tm.assert_series_equal(result, expected, check_index_type=True) expected = Series([0.2, 0.2, np.nan, 0.1], index=[2, 2, 'x', 1]) result = ser.loc[[2, 2, 'x', 1]] tm.assert_series_equal(result, expected, check_index_type=True) # raises as nothing in in the index self.assertRaises(KeyError, lambda: ser.loc[[3, 3, 3]]) expected = Series([0.2, 0.2, np.nan], index=[2, 2, 3]) result = ser.loc[[2, 2, 3]] tm.assert_series_equal(result, expected, check_index_type=True) expected = Series([0.3, np.nan, np.nan], index=[3, 4, 4]) result = Series([0.1, 0.2, 0.3], index=[1, 2, 3]).loc[[3, 4, 4]] tm.assert_series_equal(result, expected, check_index_type=True) expected = Series([np.nan, 0.3, 0.3], index=[5, 3, 3]) result = Series([0.1, 0.2, 0.3, 0.4], index=[1, 2, 3, 4]).loc[[5, 3, 3]] tm.assert_series_equal(result, expected, check_index_type=True) expected = Series([np.nan, 0.4, 0.4], index=[5, 4, 4]) result = Series([0.1, 0.2, 0.3, 0.4], index=[1, 2, 3, 4]).loc[[5, 4, 4]] tm.assert_series_equal(result, expected, check_index_type=True) expected = Series([0.4, np.nan, np.nan], index=[7, 2, 2]) result = Series([0.1, 0.2, 0.3, 0.4], index=[4, 5, 6, 7]).loc[[7, 2, 2]] tm.assert_series_equal(result, expected, check_index_type=True) expected = Series([0.4, np.nan, np.nan], index=[4, 5, 5]) result = Series([0.1, 0.2, 0.3, 0.4], index=[1, 2, 3, 4]).loc[[4, 5, 5]] tm.assert_series_equal(result, expected, check_index_type=True) # iloc expected = Series([0.2, 0.2, 0.1, 0.1], index=[2, 2, 1, 1]) result = ser.iloc[[1, 1, 0, 0]] tm.assert_series_equal(result, expected, check_index_type=True) def test_series_partial_set_with_name(self): # GH 11497 idx = Index([1, 2], dtype='int64', name='idx') ser = Series([0.1, 0.2], index=idx, name='s') # loc exp_idx = Index([3, 2, 3], dtype='int64', name='idx') expected = Series([np.nan, 0.2, np.nan], index=exp_idx, name='s') result = ser.loc[[3, 2, 3]] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([3, 2, 3, 'x'], dtype='object', name='idx') expected = Series([np.nan, 0.2, np.nan, np.nan], index=exp_idx, name='s') result = ser.loc[[3, 2, 3, 'x']] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([2, 2, 1], dtype='int64', name='idx') expected = Series([0.2, 0.2, 0.1], index=exp_idx, name='s') result = ser.loc[[2, 2, 1]] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([2, 2, 'x', 1], dtype='object', name='idx') expected = Series([0.2, 0.2, np.nan, 0.1], index=exp_idx, name='s') result = ser.loc[[2, 2, 'x', 1]] tm.assert_series_equal(result, expected, check_index_type=True) # raises as nothing in in the index self.assertRaises(KeyError, lambda: ser.loc[[3, 3, 3]]) exp_idx = Index([2, 2, 3], dtype='int64', name='idx') expected = Series([0.2, 0.2, np.nan], index=exp_idx, name='s') result = ser.loc[[2, 2, 3]] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([3, 4, 4], dtype='int64', name='idx') expected = Series([0.3, np.nan, np.nan], index=exp_idx, name='s') idx = Index([1, 2, 3], dtype='int64', name='idx') result = Series([0.1, 0.2, 0.3], index=idx, name='s').loc[[3, 4, 4]] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([5, 3, 3], dtype='int64', name='idx') expected = Series([np.nan, 0.3, 0.3], index=exp_idx, name='s') idx = Index([1, 2, 3, 4], dtype='int64', name='idx') result = Series([0.1, 0.2, 0.3, 0.4], index=idx, name='s').loc[[5, 3, 3]] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([5, 4, 4], dtype='int64', name='idx') expected = Series([np.nan, 0.4, 0.4], index=exp_idx, name='s') idx = Index([1, 2, 3, 4], dtype='int64', name='idx') result = Series([0.1, 0.2, 0.3, 0.4], index=idx, name='s').loc[[5, 4, 4]] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([7, 2, 2], dtype='int64', name='idx') expected = Series([0.4, np.nan, np.nan], index=exp_idx, name='s') idx = Index([4, 5, 6, 7], dtype='int64', name='idx') result = Series([0.1, 0.2, 0.3, 0.4], index=idx, name='s').loc[[7, 2, 2]] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([4, 5, 5], dtype='int64', name='idx') expected = Series([0.4, np.nan, np.nan], index=exp_idx, name='s') idx = Index([1, 2, 3, 4], dtype='int64', name='idx') result = Series([0.1, 0.2, 0.3, 0.4], index=idx, name='s').loc[[4, 5, 5]] tm.assert_series_equal(result, expected, check_index_type=True) # iloc exp_idx = Index([2, 2, 1, 1], dtype='int64', name='idx') expected = Series([0.2, 0.2, 0.1, 0.1], index=exp_idx, name='s') result = ser.iloc[[1, 1, 0, 0]] tm.assert_series_equal(result, expected, check_index_type=True) def test_series_partial_set_datetime(self): # GH 11497 idx = date_range('2011-01-01', '2011-01-02', freq='D', name='idx') ser = Series([0.1, 0.2], index=idx, name='s') result = ser.loc[[Timestamp('2011-01-01'), Timestamp('2011-01-02')]] exp = Series([0.1, 0.2], index=idx, name='s') tm.assert_series_equal(result, exp, check_index_type=True) keys = [Timestamp('2011-01-02'), Timestamp('2011-01-02'), Timestamp('2011-01-01')] exp = Series([0.2, 0.2, 0.1], index=pd.DatetimeIndex(keys, name='idx'), name='s') tm.assert_series_equal(ser.loc[keys], exp, check_index_type=True) keys = [Timestamp('2011-01-03'), Timestamp('2011-01-02'), Timestamp('2011-01-03')] exp = Series([np.nan, 0.2, np.nan], index=pd.DatetimeIndex(keys, name='idx'), name='s') tm.assert_series_equal(ser.loc[keys], exp, check_index_type=True) def test_series_partial_set_period(self): # GH 11497 idx = pd.period_range('2011-01-01', '2011-01-02', freq='D', name='idx') ser = Series([0.1, 0.2], index=idx, name='s') result = ser.loc[[pd.Period('2011-01-01', freq='D'), pd.Period('2011-01-02', freq='D')]] exp = Series([0.1, 0.2], index=idx, name='s') tm.assert_series_equal(result, exp, check_index_type=True) keys = [pd.Period('2011-01-02', freq='D'), pd.Period('2011-01-02', freq='D'), pd.Period('2011-01-01', freq='D')] exp = Series([0.2, 0.2, 0.1], index=pd.PeriodIndex(keys, name='idx'), name='s') tm.assert_series_equal(ser.loc[keys], exp, check_index_type=True) keys = [pd.Period('2011-01-03', freq='D'), pd.Period('2011-01-02', freq='D'), pd.Period('2011-01-03', freq='D')] exp = Series([np.nan, 0.2, np.nan], index=pd.PeriodIndex(keys, name='idx'), name='s') result = ser.loc[keys] tm.assert_series_equal(result, exp) def test_partial_set_invalid(self): # GH 4940 # allow only setting of 'valid' values orig = tm.makeTimeDataFrame() df = orig.copy() # don't allow not string inserts def f(): df.loc[100.0, :] = df.ix[0] self.assertRaises(TypeError, f) def f(): df.loc[100, :] = df.ix[0] self.assertRaises(TypeError, f) def f(): df.ix[100.0, :] = df.ix[0] self.assertRaises(TypeError, f) def f(): df.ix[100, :] = df.ix[0] self.assertRaises(ValueError, f) # allow object conversion here df = orig.copy() df.loc['a', :] = df.ix[0] exp = orig.append(pd.Series(df.ix[0], name='a')) tm.assert_frame_equal(df, exp) tm.assert_index_equal(df.index, pd.Index(orig.index.tolist() + ['a'])) self.assertEqual(df.index.dtype, 'object') def test_partial_set_empty_series(self): # GH5226 # partially set with an empty object series s = Series() s.loc[1] = 1 tm.assert_series_equal(s, Series([1], index=[1])) s.loc[3] = 3 tm.assert_series_equal(s, Series([1, 3], index=[1, 3])) s = Series() s.loc[1] = 1. tm.assert_series_equal(s, Series([1.], index=[1])) s.loc[3] = 3. tm.assert_series_equal(s, Series([1., 3.], index=[1, 3])) s = Series() s.loc['foo'] = 1 tm.assert_series_equal(s, Series([1], index=['foo'])) s.loc['bar'] = 3 tm.assert_series_equal(s, Series([1, 3], index=['foo', 'bar'])) s.loc[3] = 4 tm.assert_series_equal(s, Series([1, 3, 4], index=['foo', 'bar', 3])) def test_partial_set_empty_frame(self): # partially set with an empty object # frame df = DataFrame() def f(): df.loc[1] = 1 self.assertRaises(ValueError, f) def f(): df.loc[1] = Series([1], index=['foo']) self.assertRaises(ValueError, f) def f(): df.loc[:, 1] = 1 self.assertRaises(ValueError, f) # these work as they don't really change # anything but the index # GH5632 expected = DataFrame(columns=['foo'], index=pd.Index( [], dtype='int64')) def f(): df = DataFrame() df['foo'] = Series([], dtype='object') return df tm.assert_frame_equal(f(), expected) def f(): df = DataFrame() df['foo'] = Series(df.index) return df tm.assert_frame_equal(f(), expected) def f(): df = DataFrame() df['foo'] = df.index return df tm.assert_frame_equal(f(), expected) expected = DataFrame(columns=['foo'], index=pd.Index([], dtype='int64')) expected['foo'] = expected['foo'].astype('float64') def f(): df = DataFrame() df['foo'] = [] return df tm.assert_frame_equal(f(), expected) def f(): df = DataFrame() df['foo'] = Series(range(len(df))) return df tm.assert_frame_equal(f(), expected) def f(): df = DataFrame() tm.assert_index_equal(df.index, pd.Index([], dtype='object')) df['foo'] = range(len(df)) return df expected = DataFrame(columns=['foo'], index=pd.Index([], dtype='int64')) expected['foo'] = expected['foo'].astype('float64') tm.assert_frame_equal(f(), expected) df = DataFrame() tm.assert_index_equal(df.columns, pd.Index([], dtype=object)) df2 = DataFrame() df2[1] = Series([1], index=['foo']) df.loc[:, 1] = Series([1], index=['foo']) tm.assert_frame_equal(df, DataFrame([[1]], index=['foo'], columns=[1])) tm.assert_frame_equal(df, df2) # no index to start expected = DataFrame({0: Series(1, index=range(4))}, columns=['A', 'B', 0]) df = DataFrame(columns=['A', 'B']) df[0] = Series(1, index=range(4)) df.dtypes str(df) tm.assert_frame_equal(df, expected) df = DataFrame(columns=['A', 'B']) df.loc[:, 0] = Series(1, index=range(4)) df.dtypes str(df) tm.assert_frame_equal(df, expected) def test_partial_set_empty_frame_row(self): # GH5720, GH5744 # don't create rows when empty expected = DataFrame(columns=['A', 'B', 'New'], index=pd.Index([], dtype='int64')) expected['A'] = expected['A'].astype('int64') expected['B'] = expected['B'].astype('float64') expected['New'] = expected['New'].astype('float64') df = DataFrame({"A": [1, 2, 3], "B": [1.2, 4.2, 5.2]}) y = df[df.A > 5] y['New'] = np.nan tm.assert_frame_equal(y, expected) # tm.assert_frame_equal(y,expected) expected = DataFrame(columns=['a', 'b', 'c c', 'd']) expected['d'] = expected['d'].astype('int64') df = DataFrame(columns=['a', 'b', 'c c']) df['d'] = 3 tm.assert_frame_equal(df, expected) tm.assert_series_equal(df['c c'], Series(name='c c', dtype=object)) # reindex columns is ok df = DataFrame({"A": [1, 2, 3], "B": [1.2, 4.2, 5.2]}) y = df[df.A > 5] result = y.reindex(columns=['A', 'B', 'C']) expected = DataFrame(columns=['A', 'B', 'C'], index=pd.Index([], dtype='int64')) expected['A'] = expected['A'].astype('int64') expected['B'] = expected['B'].astype('float64') expected['C'] = expected['C'].astype('float64') tm.assert_frame_equal(result, expected) def test_partial_set_empty_frame_set_series(self): # GH 5756 # setting with empty Series df = DataFrame(Series()) tm.assert_frame_equal(df, DataFrame({0: Series()})) df = DataFrame(Series(name='foo')) tm.assert_frame_equal(df, DataFrame({'foo': Series()})) def test_partial_set_empty_frame_empty_copy_assignment(self): # GH 5932 # copy on empty with assignment fails df = DataFrame(index=[0]) df = df.copy() df['a'] = 0 expected = DataFrame(0, index=[0], columns=['a']) tm.assert_frame_equal(df, expected) def test_partial_set_empty_frame_empty_consistencies(self): # GH 6171 # consistency on empty frames df = DataFrame(columns=['x', 'y']) df['x'] = [1, 2] expected = DataFrame(dict(x=[1, 2], y=[np.nan, np.nan])) tm.assert_frame_equal(df, expected, check_dtype=False) df = DataFrame(columns=['x', 'y']) df['x'] = ['1', '2'] expected = DataFrame( dict(x=['1', '2'], y=[np.nan, np.nan]), dtype=object) tm.assert_frame_equal(df, expected) df = DataFrame(columns=['x', 'y']) df.loc[0, 'x'] = 1 expected = DataFrame(dict(x=[1], y=[np.nan])) tm.assert_frame_equal(df, expected, check_dtype=False) def test_cache_updating(self): # GH 4939, make sure to update the cache on setitem df = tm.makeDataFrame() df['A'] # cache series df.ix["Hello Friend"] = df.ix[0] self.assertIn("Hello Friend", df['A'].index) self.assertIn("Hello Friend", df['B'].index) panel = tm.makePanel() panel.ix[0] # get first item into cache panel.ix[:, :, 'A+1'] = panel.ix[:, :, 'A'] + 1 self.assertIn("A+1", panel.ix[0].columns) self.assertIn("A+1", panel.ix[1].columns) # 5216 # make sure that we don't try to set a dead cache a = np.random.rand(10, 3) df = DataFrame(a, columns=['x', 'y', 'z']) tuples = [(i, j) for i in range(5) for j in range(2)] index = MultiIndex.from_tuples(tuples) df.index = index # setting via chained assignment # but actually works, since everything is a view df.loc[0]['z'].iloc[0] = 1. result = df.loc[(0, 0), 'z'] self.assertEqual(result, 1) # correct setting df.loc[(0, 0), 'z'] = 2 result = df.loc[(0, 0), 'z'] self.assertEqual(result, 2) # 10264 df = DataFrame(np.zeros((5, 5), dtype='int64'), columns=[ 'a', 'b', 'c', 'd', 'e'], index=range(5)) df['f'] = 0 df.f.values[3] = 1 # TODO(wesm): unused? # y = df.iloc[np.arange(2, len(df))] df.f.values[3] = 2 expected = DataFrame(np.zeros((5, 6), dtype='int64'), columns=[ 'a', 'b', 'c', 'd', 'e', 'f'], index=range(5)) expected.at[3, 'f'] = 2 tm.assert_frame_equal(df, expected) expected = Series([0, 0, 0, 2, 0], name='f') tm.assert_series_equal(df.f, expected) def test_slice_consolidate_invalidate_item_cache(self): # this is chained assignment, but will 'work' with option_context('chained_assignment', None): # #3970 df = DataFrame({"aa": lrange(5), "bb": [2.2] * 5}) # Creates a second float block df["cc"] = 0.0 # caches a reference to the 'bb' series df["bb"] # repr machinery triggers consolidation repr(df) # Assignment to wrong series df['bb'].iloc[0] = 0.17 df._clear_item_cache() self.assertAlmostEqual(df['bb'][0], 0.17) def test_setitem_cache_updating(self): # GH 5424 cont = ['one', 'two', 'three', 'four', 'five', 'six', 'seven'] for do_ref in [False, False]: df = DataFrame({'a': cont, "b": cont[3:] + cont[:3], 'c': np.arange(7)}) # ref the cache if do_ref: df.ix[0, "c"] # set it df.ix[7, 'c'] = 1 self.assertEqual(df.ix[0, 'c'], 0.0) self.assertEqual(df.ix[7, 'c'], 1.0) # GH 7084 # not updating cache on series setting with slices expected = DataFrame({'A': [600, 600, 600]}, index=date_range('5/7/2014', '5/9/2014')) out = DataFrame({'A': [0, 0, 0]}, index=date_range('5/7/2014', '5/9/2014')) df = DataFrame({'C': ['A', 'A', 'A'], 'D': [100, 200, 300]}) # loop through df to update out six = Timestamp('5/7/2014') eix = Timestamp('5/9/2014') for ix, row in df.iterrows(): out.loc[six:eix, row['C']] = out.loc[six:eix, row['C']] + row['D'] tm.assert_frame_equal(out, expected) tm.assert_series_equal(out['A'], expected['A']) # try via a chain indexing # this actually works out = DataFrame({'A': [0, 0, 0]}, index=date_range('5/7/2014', '5/9/2014')) for ix, row in df.iterrows(): v = out[row['C']][six:eix] + row['D'] out[row['C']][six:eix] = v tm.assert_frame_equal(out, expected) tm.assert_series_equal(out['A'], expected['A']) out = DataFrame({'A': [0, 0, 0]}, index=date_range('5/7/2014', '5/9/2014')) for ix, row in df.iterrows(): out.loc[six:eix, row['C']] += row['D'] tm.assert_frame_equal(out, expected) tm.assert_series_equal(out['A'], expected['A']) def test_setitem_chained_setfault(self): # GH6026 # setfaults under numpy 1.7.1 (ok on 1.8) data = ['right', 'left', 'left', 'left', 'right', 'left', 'timeout'] mdata = ['right', 'left', 'left', 'left', 'right', 'left', 'none'] df = DataFrame({'response': np.array(data)}) mask = df.response == 'timeout' df.response[mask] = 'none' tm.assert_frame_equal(df, DataFrame({'response': mdata})) recarray = np.rec.fromarrays([data], names=['response']) df = DataFrame(recarray) mask = df.response == 'timeout' df.response[mask] = 'none' tm.assert_frame_equal(df, DataFrame({'response': mdata})) df = DataFrame({'response': data, 'response1': data}) mask = df.response == 'timeout' df.response[mask] = 'none' tm.assert_frame_equal(df, DataFrame({'response': mdata, 'response1': data})) # GH 6056 expected = DataFrame(dict(A=[np.nan, 'bar', 'bah', 'foo', 'bar'])) df = DataFrame(dict(A=np.array(['foo', 'bar', 'bah', 'foo', 'bar']))) df['A'].iloc[0] = np.nan result = df.head() tm.assert_frame_equal(result, expected) df = DataFrame(dict(A=np.array(['foo', 'bar', 'bah', 'foo', 'bar']))) df.A.iloc[0] = np.nan result = df.head() tm.assert_frame_equal(result, expected) def test_detect_chained_assignment(self): pd.set_option('chained_assignment', 'raise') # work with the chain expected = DataFrame([[-5, 1], [-6, 3]], columns=list('AB')) df = DataFrame(np.arange(4).reshape(2, 2), columns=list('AB'), dtype='int64') self.assertIsNone(df.is_copy) df['A'][0] = -5 df['A'][1] = -6 tm.assert_frame_equal(df, expected) # test with the chaining df = DataFrame({'A': Series(range(2), dtype='int64'), 'B': np.array(np.arange(2, 4), dtype=np.float64)}) self.assertIsNone(df.is_copy) def f(): df['A'][0] = -5 self.assertRaises(com.SettingWithCopyError, f) def f(): df['A'][1] = np.nan self.assertRaises(com.SettingWithCopyError, f) self.assertIsNone(df['A'].is_copy) # using a copy (the chain), fails df = DataFrame({'A': Series(range(2), dtype='int64'), 'B': np.array(np.arange(2, 4), dtype=np.float64)}) def f(): df.loc[0]['A'] = -5 self.assertRaises(com.SettingWithCopyError, f) # doc example df = DataFrame({'a': ['one', 'one', 'two', 'three', 'two', 'one', 'six'], 'c': Series(range(7), dtype='int64')}) self.assertIsNone(df.is_copy) expected = DataFrame({'a': ['one', 'one', 'two', 'three', 'two', 'one', 'six'], 'c': [42, 42, 2, 3, 4, 42, 6]}) def f(): indexer = df.a.str.startswith('o') df[indexer]['c'] = 42 self.assertRaises(com.SettingWithCopyError, f) expected = DataFrame({'A': [111, 'bbb', 'ccc'], 'B': [1, 2, 3]}) df = DataFrame({'A': ['aaa', 'bbb', 'ccc'], 'B': [1, 2, 3]}) def f(): df['A'][0] = 111 self.assertRaises(com.SettingWithCopyError, f) def f(): df.loc[0]['A'] = 111 self.assertRaises(com.SettingWithCopyError, f) df.loc[0, 'A'] = 111 tm.assert_frame_equal(df, expected) # make sure that is_copy is picked up reconstruction # GH5475 df = DataFrame({"A": [1, 2]}) self.assertIsNone(df.is_copy) with tm.ensure_clean('__tmp__pickle') as path: df.to_pickle(path) df2 = pd.read_pickle(path) df2["B"] = df2["A"] df2["B"] = df2["A"] # a suprious raise as we are setting the entire column here # GH5597 from string import ascii_letters as letters def random_text(nobs=100): df = [] for i in range(nobs): idx = np.random.randint(len(letters), size=2) idx.sort() df.append([letters[idx[0]:idx[1]]]) return DataFrame(df, columns=['letters']) df = random_text(100000) # always a copy x = df.iloc[[0, 1, 2]] self.assertIsNotNone(x.is_copy) x = df.iloc[[0, 1, 2, 4]] self.assertIsNotNone(x.is_copy) # explicity copy indexer = df.letters.apply(lambda x: len(x) > 10) df = df.ix[indexer].copy() self.assertIsNone(df.is_copy) df['letters'] = df['letters'].apply(str.lower) # implicity take df = random_text(100000) indexer = df.letters.apply(lambda x: len(x) > 10) df = df.ix[indexer] self.assertIsNotNone(df.is_copy) df['letters'] = df['letters'].apply(str.lower) # implicity take 2 df = random_text(100000) indexer = df.letters.apply(lambda x: len(x) > 10) df = df.ix[indexer] self.assertIsNotNone(df.is_copy) df.loc[:, 'letters'] = df['letters'].apply(str.lower) # should be ok even though it's a copy! self.assertIsNone(df.is_copy) df['letters'] = df['letters'].apply(str.lower) self.assertIsNone(df.is_copy) df = random_text(100000) indexer = df.letters.apply(lambda x: len(x) > 10) df.ix[indexer, 'letters'] = df.ix[indexer, 'letters'].apply(str.lower) # an identical take, so no copy df = DataFrame({'a': [1]}).dropna() self.assertIsNone(df.is_copy) df['a'] += 1 # inplace ops # original from: # http://stackoverflow.com/questions/20508968/series-fillna-in-a-multiindex-dataframe-does-not-fill-is-this-a-bug a = [12, 23] b = [123, None] c = [1234, 2345] d = [12345, 23456] tuples = [('eyes', 'left'), ('eyes', 'right'), ('ears', 'left'), ('ears', 'right')] events = {('eyes', 'left'): a, ('eyes', 'right'): b, ('ears', 'left'): c, ('ears', 'right'): d} multiind = MultiIndex.from_tuples(tuples, names=['part', 'side']) zed = DataFrame(events, index=['a', 'b'], columns=multiind) def f(): zed['eyes']['right'].fillna(value=555, inplace=True) self.assertRaises(com.SettingWithCopyError, f) df = DataFrame(np.random.randn(10, 4)) s = df.iloc[:, 0].sort_values() tm.assert_series_equal(s, df.iloc[:, 0].sort_values()) tm.assert_series_equal(s, df[0].sort_values()) # false positives GH6025 df = DataFrame({'column1': ['a', 'a', 'a'], 'column2': [4, 8, 9]}) str(df) df['column1'] = df['column1'] + 'b' str(df) df = df[df['column2'] != 8] str(df) df['column1'] = df['column1'] + 'c' str(df) # from SO: # http://stackoverflow.com/questions/24054495/potential-bug-setting-value-for-undefined-column-using-iloc df = DataFrame(np.arange(0, 9), columns=['count']) df['group'] = 'b' def f(): df.iloc[0:5]['group'] = 'a' self.assertRaises(com.SettingWithCopyError, f) # mixed type setting # same dtype & changing dtype df = DataFrame(dict(A=date_range('20130101', periods=5), B=np.random.randn(5), C=np.arange(5, dtype='int64'), D=list('abcde'))) def f(): df.ix[2]['D'] = 'foo' self.assertRaises(com.SettingWithCopyError, f) def f(): df.ix[2]['C'] = 'foo' self.assertRaises(com.SettingWithCopyError, f) def f(): df['C'][2] = 'foo' self.assertRaises(com.SettingWithCopyError, f) def test_setting_with_copy_bug(self): # operating on a copy df = pd.DataFrame({'a': list(range(4)), 'b': list('ab..'), 'c': ['a', 'b', np.nan, 'd']}) mask = pd.isnull(df.c) def f(): df[['c']][mask] = df[['b']][mask] self.assertRaises(com.SettingWithCopyError, f) # invalid warning as we are returning a new object # GH 8730 df1 = DataFrame({'x': Series(['a', 'b', 'c']), 'y': Series(['d', 'e', 'f'])}) df2 = df1[['x']] # this should not raise df2['y'] = ['g', 'h', 'i'] def test_detect_chained_assignment_warnings(self): # warnings with option_context('chained_assignment', 'warn'): df = DataFrame({'A': ['aaa', 'bbb', 'ccc'], 'B': [1, 2, 3]}) with tm.assert_produces_warning( expected_warning=com.SettingWithCopyWarning): df.loc[0]['A'] = 111 def test_float64index_slicing_bug(self): # GH 5557, related to slicing a float index ser = {256: 2321.0, 1: 78.0, 2: 2716.0, 3: 0.0, 4: 369.0, 5: 0.0, 6: 269.0, 7: 0.0, 8: 0.0, 9: 0.0, 10: 3536.0, 11: 0.0, 12: 24.0, 13: 0.0, 14: 931.0, 15: 0.0, 16: 101.0, 17: 78.0, 18: 9643.0, 19: 0.0, 20: 0.0, 21: 0.0, 22: 63761.0, 23: 0.0, 24: 446.0, 25: 0.0, 26: 34773.0, 27: 0.0, 28: 729.0, 29: 78.0, 30: 0.0, 31: 0.0, 32: 3374.0, 33: 0.0, 34: 1391.0, 35: 0.0, 36: 361.0, 37: 0.0, 38: 61808.0, 39: 0.0, 40: 0.0, 41: 0.0, 42: 6677.0, 43: 0.0, 44: 802.0, 45: 0.0, 46: 2691.0, 47: 0.0, 48: 3582.0, 49: 0.0, 50: 734.0, 51: 0.0, 52: 627.0, 53: 70.0, 54: 2584.0, 55: 0.0, 56: 324.0, 57: 0.0, 58: 605.0, 59: 0.0, 60: 0.0, 61: 0.0, 62: 3989.0, 63: 10.0, 64: 42.0, 65: 0.0, 66: 904.0, 67: 0.0, 68: 88.0, 69: 70.0, 70: 8172.0, 71: 0.0, 72: 0.0, 73: 0.0, 74: 64902.0, 75: 0.0, 76: 347.0, 77: 0.0, 78: 36605.0, 79: 0.0, 80: 379.0, 81: 70.0, 82: 0.0, 83: 0.0, 84: 3001.0, 85: 0.0, 86: 1630.0, 87: 7.0, 88: 364.0, 89: 0.0, 90: 67404.0, 91: 9.0, 92: 0.0, 93: 0.0, 94: 7685.0, 95: 0.0, 96: 1017.0, 97: 0.0, 98: 2831.0, 99: 0.0, 100: 2963.0, 101: 0.0, 102: 854.0, 103: 0.0, 104: 0.0, 105: 0.0, 106: 0.0, 107: 0.0, 108: 0.0, 109: 0.0, 110: 0.0, 111: 0.0, 112: 0.0, 113: 0.0, 114: 0.0, 115: 0.0, 116: 0.0, 117: 0.0, 118: 0.0, 119: 0.0, 120: 0.0, 121: 0.0, 122: 0.0, 123: 0.0, 124: 0.0, 125: 0.0, 126: 67744.0, 127: 22.0, 128: 264.0, 129: 0.0, 260: 197.0, 268: 0.0, 265: 0.0, 269: 0.0, 261: 0.0, 266: 1198.0, 267: 0.0, 262: 2629.0, 258: 775.0, 257: 0.0, 263: 0.0, 259: 0.0, 264: 163.0, 250: 10326.0, 251: 0.0, 252: 1228.0, 253: 0.0, 254: 2769.0, 255: 0.0} # smoke test for the repr s = Series(ser) result = s.value_counts() str(result) def test_set_ix_out_of_bounds_axis_0(self): df = pd.DataFrame( randn(2, 5), index=["row%s" % i for i in range(2)], columns=["col%s" % i for i in range(5)]) self.assertRaises(ValueError, df.ix.__setitem__, (2, 0), 100) def test_set_ix_out_of_bounds_axis_1(self): df = pd.DataFrame( randn(5, 2), index=["row%s" % i for i in range(5)], columns=["col%s" % i for i in range(2)]) self.assertRaises(ValueError, df.ix.__setitem__, (0, 2), 100) def test_iloc_empty_list_indexer_is_ok(self): from pandas.util.testing import makeCustomDataframe as mkdf df = mkdf(5, 2) # vertical empty tm.assert_frame_equal(df.iloc[:, []], df.iloc[:, :0], check_index_type=True, check_column_type=True) # horizontal empty tm.assert_frame_equal(df.iloc[[], :], df.iloc[:0, :], check_index_type=True, check_column_type=True) # horizontal empty tm.assert_frame_equal(df.iloc[[]], df.iloc[:0, :], check_index_type=True, check_column_type=True) def test_loc_empty_list_indexer_is_ok(self): from pandas.util.testing import makeCustomDataframe as mkdf df = mkdf(5, 2) # vertical empty tm.assert_frame_equal(df.loc[:, []], df.iloc[:, :0], check_index_type=True, check_column_type=True) # horizontal empty tm.assert_frame_equal(df.loc[[], :], df.iloc[:0, :], check_index_type=True, check_column_type=True) # horizontal empty tm.assert_frame_equal(df.loc[[]], df.iloc[:0, :], check_index_type=True, check_column_type=True) def test_ix_empty_list_indexer_is_ok(self): from pandas.util.testing import makeCustomDataframe as mkdf df = mkdf(5, 2) # vertical empty tm.assert_frame_equal(df.ix[:, []], df.iloc[:, :0], check_index_type=True, check_column_type=True) # horizontal empty tm.assert_frame_equal(df.ix[[], :], df.iloc[:0, :], check_index_type=True, check_column_type=True) # horizontal empty tm.assert_frame_equal(df.ix[[]], df.iloc[:0, :], check_index_type=True, check_column_type=True) def test_index_type_coercion(self): # GH 11836 # if we have an index type and set it with something that looks # to numpy like the same, but is actually, not # (e.g. setting with a float or string '0') # then we need to coerce to object # integer indexes for s in [Series(range(5)), Series(range(5), index=range(1, 6))]: self.assertTrue(s.index.is_integer()) for indexer in [lambda x: x.ix, lambda x: x.loc, lambda x: x]: s2 = s.copy() indexer(s2)[0.1] = 0 self.assertTrue(s2.index.is_floating()) self.assertTrue(indexer(s2)[0.1] == 0) s2 = s.copy() indexer(s2)[0.0] = 0 exp = s.index if 0 not in s: exp = Index(s.index.tolist() + [0]) tm.assert_index_equal(s2.index, exp) s2 = s.copy() indexer(s2)['0'] = 0 self.assertTrue(s2.index.is_object()) for s in [Series(range(5), index=np.arange(5.))]: self.assertTrue(s.index.is_floating()) for idxr in [lambda x: x.ix, lambda x: x.loc, lambda x: x]: s2 = s.copy() idxr(s2)[0.1] = 0 self.assertTrue(s2.index.is_floating()) self.assertTrue(idxr(s2)[0.1] == 0) s2 = s.copy() idxr(s2)[0.0] = 0 tm.assert_index_equal(s2.index, s.index) s2 = s.copy() idxr(s2)['0'] = 0 self.assertTrue(s2.index.is_object()) def test_float_index_to_mixed(self): df = DataFrame({0.0: np.random.rand(10), 1.0: np.random.rand(10)}) df['a'] = 10 tm.assert_frame_equal(DataFrame({0.0: df[0.0], 1.0: df[1.0], 'a': [10] * 10}), df) def test_duplicate_ix_returns_series(self): df = DataFrame(np.random.randn(3, 3), index=[0.1, 0.2, 0.2], columns=list('abc')) r = df.ix[0.2, 'a'] e = df.loc[0.2, 'a'] tm.assert_series_equal(r, e) def test_float_index_non_scalar_assignment(self): df = DataFrame({'a': [1, 2, 3], 'b': [3, 4, 5]}, index=[1., 2., 3.]) df.loc[df.index[:2]] = 1 expected = DataFrame({'a': [1, 1, 3], 'b': [1, 1, 5]}, index=df.index) tm.assert_frame_equal(expected, df) df = DataFrame({'a': [1, 2, 3], 'b': [3, 4, 5]}, index=[1., 2., 3.]) df2 = df.copy() df.loc[df.index] = df.loc[df.index] tm.assert_frame_equal(df, df2) def test_float_index_at_iat(self): s = pd.Series([1, 2, 3], index=[0.1, 0.2, 0.3]) for el, item in s.iteritems(): self.assertEqual(s.at[el], item) for i in range(len(s)): self.assertEqual(s.iat[i], i + 1) def test_rhs_alignment(self): # GH8258, tests that both rows & columns are aligned to what is # assigned to. covers both uniform data-type & multi-type cases def run_tests(df, rhs, right): # label, index, slice r, i, s = list('bcd'), [1, 2, 3], slice(1, 4) c, j, l = ['joe', 'jolie'], [1, 2], slice(1, 3) left = df.copy() left.loc[r, c] = rhs tm.assert_frame_equal(left, right) left = df.copy() left.iloc[i, j] = rhs tm.assert_frame_equal(left, right) left = df.copy() left.ix[s, l] = rhs tm.assert_frame_equal(left, right) left = df.copy() left.ix[i, j] = rhs tm.assert_frame_equal(left, right) left = df.copy() left.ix[r, c] = rhs tm.assert_frame_equal(left, right) xs = np.arange(20).reshape(5, 4) cols = ['jim', 'joe', 'jolie', 'joline'] df = pd.DataFrame(xs, columns=cols, index=list('abcde')) # right hand side; permute the indices and multiplpy by -2 rhs = -2 * df.iloc[3:0:-1, 2:0:-1] # expected `right` result; just multiply by -2 right = df.copy() right.iloc[1:4, 1:3] *= -2 # run tests with uniform dtypes run_tests(df, rhs, right) # make frames multi-type & re-run tests for frame in [df, rhs, right]: frame['joe'] = frame['joe'].astype('float64') frame['jolie'] = frame['jolie'].map('@{0}'.format) run_tests(df, rhs, right) def test_str_label_slicing_with_negative_step(self): SLC = pd.IndexSlice def assert_slices_equivalent(l_slc, i_slc): tm.assert_series_equal(s.loc[l_slc], s.iloc[i_slc]) if not idx.is_integer: # For integer indices, ix and plain getitem are position-based. tm.assert_series_equal(s[l_slc], s.iloc[i_slc]) tm.assert_series_equal(s.ix[l_slc], s.iloc[i_slc]) for idx in [_mklbl('A', 20), np.arange(20) + 100, np.linspace(100, 150, 20)]: idx = Index(idx) s = Series(np.arange(20), index=idx) assert_slices_equivalent(SLC[idx[9]::-1], SLC[9::-1]) assert_slices_equivalent(SLC[:idx[9]:-1], SLC[:8:-1]) assert_slices_equivalent(SLC[idx[13]:idx[9]:-1], SLC[13:8:-1]) assert_slices_equivalent(SLC[idx[9]:idx[13]:-1], SLC[:0]) def test_multiindex_label_slicing_with_negative_step(self): s = Series(np.arange(20), MultiIndex.from_product([list('abcde'), np.arange(4)])) SLC = pd.IndexSlice def assert_slices_equivalent(l_slc, i_slc): tm.assert_series_equal(s.loc[l_slc], s.iloc[i_slc]) tm.assert_series_equal(s[l_slc], s.iloc[i_slc]) tm.assert_series_equal(s.ix[l_slc], s.iloc[i_slc]) assert_slices_equivalent(SLC[::-1], SLC[::-1]) assert_slices_equivalent(SLC['d'::-1], SLC[15::-1]) assert_slices_equivalent(SLC[('d', )::-1], SLC[15::-1]) assert_slices_equivalent(SLC[:'d':-1], SLC[:11:-1]) assert_slices_equivalent(SLC[:('d', ):-1], SLC[:11:-1]) assert_slices_equivalent(SLC['d':'b':-1], SLC[15:3:-1]) assert_slices_equivalent(SLC[('d', ):'b':-1], SLC[15:3:-1]) assert_slices_equivalent(SLC['d':('b', ):-1], SLC[15:3:-1]) assert_slices_equivalent(SLC[('d', ):('b', ):-1], SLC[15:3:-1]) assert_slices_equivalent(SLC['b':'d':-1], SLC[:0]) assert_slices_equivalent(SLC[('c', 2)::-1], SLC[10::-1]) assert_slices_equivalent(SLC[:('c', 2):-1], SLC[:9:-1]) assert_slices_equivalent(SLC[('e', 0):('c', 2):-1], SLC[16:9:-1]) def test_slice_with_zero_step_raises(self): s = Series(np.arange(20), index=_mklbl('A', 20)) self.assertRaisesRegexp(ValueError, 'slice step cannot be zero', lambda: s[::0]) self.assertRaisesRegexp(ValueError, 'slice step cannot be zero', lambda: s.loc[::0]) self.assertRaisesRegexp(ValueError, 'slice step cannot be zero', lambda: s.ix[::0]) def test_indexing_assignment_dict_already_exists(self): df = pd.DataFrame({'x': [1, 2, 6], 'y': [2, 2, 8], 'z': [-5, 0, 5]}).set_index('z') expected = df.copy() rhs = dict(x=9, y=99) df.loc[5] = rhs expected.loc[5] = [9, 99] tm.assert_frame_equal(df, expected) def test_indexing_dtypes_on_empty(self): # Check that .iloc and .ix return correct dtypes GH9983 df = DataFrame({'a': [1, 2, 3], 'b': ['b', 'b2', 'b3']}) df2 = df.ix[[], :] self.assertEqual(df2.loc[:, 'a'].dtype, np.int64) tm.assert_series_equal(df2.loc[:, 'a'], df2.iloc[:, 0]) tm.assert_series_equal(df2.loc[:, 'a'], df2.ix[:, 0]) def test_range_in_series_indexing(self): # range can cause an indexing error # GH 11652 for x in [5, 999999, 1000000]: s = pd.Series(index=range(x)) s.loc[range(1)] = 42 tm.assert_series_equal(s.loc[range(1)], Series(42.0, index=[0])) s.loc[range(2)] = 43 tm.assert_series_equal(s.loc[range(2)], Series(43.0, index=[0, 1])) def test_non_reducing_slice(self): df = pd.DataFrame([[0, 1], [2, 3]]) slices = [ # pd.IndexSlice[:, :], pd.IndexSlice[:, 1], pd.IndexSlice[1, :], pd.IndexSlice[[1], [1]], pd.IndexSlice[1, [1]], pd.IndexSlice[[1], 1], pd.IndexSlice[1], pd.IndexSlice[1, 1], slice(None, None, None), [0, 1], np.array([0, 1]), pd.Series([0, 1]) ] for slice_ in slices: tslice_ = _non_reducing_slice(slice_) self.assertTrue(isinstance(df.loc[tslice_], DataFrame)) def test_list_slice(self): # like dataframe getitem slices = [['A'], pd.Series(['A']), np.array(['A'])] df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}, index=['A', 'B']) expected = pd.IndexSlice[:, ['A']] for subset in slices: result = _non_reducing_slice(subset) tm.assert_frame_equal(df.loc[result], df.loc[expected]) def test_maybe_numeric_slice(self): df = pd.DataFrame({'A': [1, 2], 'B': ['c', 'd'], 'C': [True, False]}) result = _maybe_numeric_slice(df, slice_=None) expected = pd.IndexSlice[:, ['A']] self.assertEqual(result, expected) result = _maybe_numeric_slice(df, None, include_bool=True) expected = pd.IndexSlice[:, ['A', 'C']] result = _maybe_numeric_slice(df, [1]) expected = [1] self.assertEqual(result, expected) def test_multiindex_slice_first_level(self): # GH 12697 freq = ['a', 'b', 'c', 'd'] idx = pd.MultiIndex.from_product([freq, np.arange(500)]) df = pd.DataFrame(list(range(2000)), index=idx, columns=['Test']) df_slice = df.loc[pd.IndexSlice[:, 30:70], :] result = df_slice.loc['a'] expected = pd.DataFrame(list(range(30, 71)), columns=['Test'], index=range(30, 71)) tm.assert_frame_equal(result, expected) result = df_slice.loc['d'] expected = pd.DataFrame(list(range(1530, 1571)), columns=['Test'], index=range(30, 71)) tm.assert_frame_equal(result, expected) class TestSeriesNoneCoercion(tm.TestCase): EXPECTED_RESULTS = [ # For numeric series, we should coerce to NaN. ([1, 2, 3], [np.nan, 2, 3]), ([1.0, 2.0, 3.0], [np.nan, 2.0, 3.0]), # For datetime series, we should coerce to NaT. ([datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)], [NaT, datetime(2000, 1, 2), datetime(2000, 1, 3)]), # For objects, we should preserve the None value. (["foo", "bar", "baz"], [None, "bar", "baz"]), ] def test_coercion_with_setitem(self): for start_data, expected_result in self.EXPECTED_RESULTS: start_series = Series(start_data) start_series[0] = None expected_series = Series(expected_result) tm.assert_series_equal(start_series, expected_series) def test_coercion_with_loc_setitem(self): for start_data, expected_result in self.EXPECTED_RESULTS: start_series = Series(start_data) start_series.loc[0] = None expected_series = Series(expected_result) tm.assert_series_equal(start_series, expected_series) def test_coercion_with_setitem_and_series(self): for start_data, expected_result in self.EXPECTED_RESULTS: start_series = Series(start_data) start_series[start_series == start_series[0]] = None expected_series = Series(expected_result) tm.assert_series_equal(start_series, expected_series) def test_coercion_with_loc_and_series(self): for start_data, expected_result in self.EXPECTED_RESULTS: start_series = Series(start_data) start_series.loc[start_series == start_series[0]] = None expected_series = Series(expected_result) tm.assert_series_equal(start_series, expected_series) class TestDataframeNoneCoercion(tm.TestCase): EXPECTED_SINGLE_ROW_RESULTS = [ # For numeric series, we should coerce to NaN. ([1, 2, 3], [np.nan, 2, 3]), ([1.0, 2.0, 3.0], [np.nan, 2.0, 3.0]), # For datetime series, we should coerce to NaT. ([datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)], [NaT, datetime(2000, 1, 2), datetime(2000, 1, 3)]), # For objects, we should preserve the None value. (["foo", "bar", "baz"], [None, "bar", "baz"]), ] def test_coercion_with_loc(self): for start_data, expected_result, in self.EXPECTED_SINGLE_ROW_RESULTS: start_dataframe = DataFrame({'foo': start_data}) start_dataframe.loc[0, ['foo']] = None expected_dataframe = DataFrame({'foo': expected_result}) tm.assert_frame_equal(start_dataframe, expected_dataframe) def test_coercion_with_setitem_and_dataframe(self): for start_data, expected_result, in self.EXPECTED_SINGLE_ROW_RESULTS: start_dataframe = DataFrame({'foo': start_data}) start_dataframe[start_dataframe['foo'] == start_dataframe['foo'][ 0]] = None expected_dataframe = DataFrame({'foo': expected_result}) tm.assert_frame_equal(start_dataframe, expected_dataframe) def test_none_coercion_loc_and_dataframe(self): for start_data, expected_result, in self.EXPECTED_SINGLE_ROW_RESULTS: start_dataframe = DataFrame({'foo': start_data}) start_dataframe.loc[start_dataframe['foo'] == start_dataframe[ 'foo'][0]] = None expected_dataframe = DataFrame({'foo': expected_result}) tm.assert_frame_equal(start_dataframe, expected_dataframe) def test_none_coercion_mixed_dtypes(self): start_dataframe = DataFrame({ 'a': [1, 2, 3], 'b': [1.0, 2.0, 3.0], 'c': [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)], 'd': ['a', 'b', 'c'] }) start_dataframe.iloc[0] = None exp = DataFrame({'a': [np.nan, 2, 3], 'b': [np.nan, 2.0, 3.0], 'c': [NaT, datetime(2000, 1, 2), datetime(2000, 1, 3)], 'd': [None, 'b', 'c']}) tm.assert_frame_equal(start_dataframe, exp) class TestTimedeltaIndexing(tm.TestCase): def test_boolean_indexing(self): # GH 14946 df = pd.DataFrame({'x': range(10)}) df.index = pd.to_timedelta(range(10), unit='s') conditions = [df['x'] > 3, df['x'] == 3, df['x'] < 3] expected_data = [[0, 1, 2, 3, 10, 10, 10, 10, 10, 10], [0, 1, 2, 10, 4, 5, 6, 7, 8, 9], [10, 10, 10, 3, 4, 5, 6, 7, 8, 9]] for cond, data in zip(conditions, expected_data): result = df.copy() result.loc[cond, 'x'] = 10 expected = pd.DataFrame(data, index=pd.to_timedelta(range(10), unit='s'), columns=['x']) tm.assert_frame_equal(expected, result) if __name__ == '__main__': nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], exit=False)
36.480505
121
0.487002
import sys import nose import itertools import warnings from warnings import catch_warnings from datetime import datetime from pandas.types.common import (is_integer_dtype, is_float_dtype, is_scalar) from pandas.compat import range, lrange, lzip, StringIO, lmap, map from pandas.tslib import NaT from numpy import nan from numpy.random import randn import numpy as np import pandas as pd import pandas.core.common as com from pandas import option_context from pandas.core.indexing import _non_reducing_slice, _maybe_numeric_slice from pandas.core.api import (DataFrame, Index, Series, Panel, isnull, MultiIndex, Timestamp, Timedelta, UInt64Index) from pandas.formats.printing import pprint_thing from pandas import concat from pandas.core.common import PerformanceWarning, UnsortedIndexError import pandas.util.testing as tm from pandas import date_range _verbose = False def _generate_indices(f, values=False): axes = f.axes if values: axes = [lrange(len(a)) for a in axes] return itertools.product(*axes) def _get_value(f, i, values=False): if values: return f.values[i] with catch_warnings(record=True): return f.ix[i] def _get_result(obj, method, key, axis): if isinstance(key, dict): key = key[axis] if method == 'indexer': method = 'ix' key = obj._get_axis(axis)[key] try: xp = getattr(obj, method).__getitem__(_axify(obj, key, axis)) except: xp = getattr(obj, method).__getitem__(key) return xp def _axify(obj, key, axis): axes = [slice(None)] * obj.ndim axes[axis] = key return tuple(axes) def _mklbl(prefix, n): return ["%s%s" % (prefix, i) for i in range(n)] class TestIndexing(tm.TestCase): _multiprocess_can_split_ = True _objs = set(['series', 'frame', 'panel']) _typs = set(['ints', 'uints', 'labels', 'mixed', 'ts', 'floats', 'empty', 'ts_rev']) def setUp(self): self.series_ints = Series(np.random.rand(4), index=lrange(0, 8, 2)) self.frame_ints = DataFrame(np.random.randn(4, 4), index=lrange(0, 8, 2), columns=lrange(0, 12, 3)) self.panel_ints = Panel(np.random.rand(4, 4, 4), items=lrange(0, 8, 2), major_axis=lrange(0, 12, 3), minor_axis=lrange(0, 16, 4)) self.series_uints = Series(np.random.rand(4), index=UInt64Index(lrange(0, 8, 2))) self.frame_uints = DataFrame(np.random.randn(4, 4), index=UInt64Index(lrange(0, 8, 2)), columns=UInt64Index(lrange(0, 12, 3))) self.panel_uints = Panel(np.random.rand(4, 4, 4), items=UInt64Index(lrange(0, 8, 2)), major_axis=UInt64Index(lrange(0, 12, 3)), minor_axis=UInt64Index(lrange(0, 16, 4))) self.series_labels = Series(np.random.randn(4), index=list('abcd')) self.frame_labels = DataFrame(np.random.randn(4, 4), index=list('abcd'), columns=list('ABCD')) self.panel_labels = Panel(np.random.randn(4, 4, 4), items=list('abcd'), major_axis=list('ABCD'), minor_axis=list('ZYXW')) self.series_mixed = Series(np.random.randn(4), index=[2, 4, 'null', 8]) self.frame_mixed = DataFrame(np.random.randn(4, 4), index=[2, 4, 'null', 8]) self.panel_mixed = Panel(np.random.randn(4, 4, 4), items=[2, 4, 'null', 8]) self.series_ts = Series(np.random.randn(4), index=date_range('20130101', periods=4)) self.frame_ts = DataFrame(np.random.randn(4, 4), index=date_range('20130101', periods=4)) self.panel_ts = Panel(np.random.randn(4, 4, 4), items=date_range('20130101', periods=4)) dates_rev = (date_range('20130101', periods=4) .sort_values(ascending=False)) self.series_ts_rev = Series(np.random.randn(4), index=dates_rev) self.frame_ts_rev = DataFrame(np.random.randn(4, 4), index=dates_rev) self.panel_ts_rev = Panel(np.random.randn(4, 4, 4), items=dates_rev) self.frame_empty = DataFrame({}) self.series_empty = Series({}) self.panel_empty = Panel({}) for o in self._objs: d = dict() for t in self._typs: d[t] = getattr(self, '%s_%s' % (o, t), None) setattr(self, o, d) def check_values(self, f, func, values=False): if f is None: return axes = f.axes indicies = itertools.product(*axes) for i in indicies: result = getattr(f, func)[i] if values: expected = f.values[i] else: expected = f for a in reversed(i): expected = expected.__getitem__(a) tm.assert_almost_equal(result, expected) def check_result(self, name, method1, key1, method2, key2, typs=None, objs=None, axes=None, fails=None): def _eq(t, o, a, obj, k1, k2): if a is not None and a > obj.ndim - 1: return def _print(result, error=None): if error is not None: error = str(error) v = ("%-16.16s [%-16.16s]: [typ->%-8.8s,obj->%-8.8s," "key1->(%-4.4s),key2->(%-4.4s),axis->%s] %s" % (name, result, t, o, method1, method2, a, error or '')) if _verbose: pprint_thing(v) try: rs = getattr(obj, method1).__getitem__(_axify(obj, k1, a)) try: xp = _get_result(obj, method2, k2, a) except: result = 'no comp' _print(result) return detail = None try: if is_scalar(rs) and is_scalar(xp): self.assertEqual(rs, xp) elif xp.ndim == 1: tm.assert_series_equal(rs, xp) elif xp.ndim == 2: tm.assert_frame_equal(rs, xp) elif xp.ndim == 3: tm.assert_panel_equal(rs, xp) result = 'ok' except AssertionError as e: detail = str(e) result = 'fail' if fails is True: if result == 'fail': result = 'ok (fail)' _print(result) if not result.startswith('ok'): raise AssertionError(detail) except AssertionError: raise except Exception as detail: if fails is not None: if isinstance(detail, fails): result = 'ok (%s)' % type(detail).__name__ _print(result) return result = type(detail).__name__ raise AssertionError(_print(result, error=detail)) if typs is None: typs = self._typs if objs is None: objs = self._objs if axes is not None: if not isinstance(axes, (tuple, list)): axes = [axes] else: axes = list(axes) else: axes = [0, 1, 2] for o in objs: if o not in self._objs: continue d = getattr(self, o) for a in axes: for t in typs: if t not in self._typs: continue obj = d[t] if obj is not None: obj = obj.copy() k2 = key2 _eq(t, o, a, obj, key1, k2) def test_ix_deprecation(self): df = DataFrame({'A': [1, 2, 3]}) with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False): df.ix[1, 'A'] def test_indexer_caching(self): n = 1000001 arrays = [lrange(n), lrange(n)] index = MultiIndex.from_tuples(lzip(*arrays)) s = Series(np.zeros(n), index=index) str(s) expected = Series(np.ones(n), index=index) s = Series(np.zeros(n), index=index) s[s == 0] = 1 tm.assert_series_equal(s, expected) def test_at_and_iat_get(self): def _check(f, func, values=False): if f is not None: indicies = _generate_indices(f, values) for i in indicies: result = getattr(f, func)[i] expected = _get_value(f, i, values) tm.assert_almost_equal(result, expected) for o in self._objs: d = getattr(self, o) for f in [d['ints'], d['uints']]: _check(f, 'iat', values=True) for f in [d['labels'], d['ts'], d['floats']]: if f is not None: self.assertRaises(ValueError, self.check_values, f, 'iat') for f in [d['ints'], d['uints'], d['labels'], d['ts'], d['floats']]: _check(f, 'at') def test_at_and_iat_set(self): def _check(f, func, values=False): if f is not None: indicies = _generate_indices(f, values) for i in indicies: getattr(f, func)[i] = 1 expected = _get_value(f, i, values) tm.assert_almost_equal(expected, 1) for t in self._objs: d = getattr(self, t) for f in [d['ints'], d['uints']]: _check(f, 'iat', values=True) for f in [d['labels'], d['ts'], d['floats']]: if f is not None: self.assertRaises(ValueError, _check, f, 'iat') for f in [d['ints'], d['uints'], d['labels'], d['ts'], d['floats']]: _check(f, 'at') def test_at_iat_coercion(self): dates = date_range('1/1/2000', periods=8) df = DataFrame(randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D']) s = df['A'] result = s.at[dates[5]] xp = s.values[5] self.assertEqual(result, xp) s = Series(['2014-01-01', '2014-02-02'], dtype='datetime64[ns]') expected = Timestamp('2014-02-02') for r in [lambda: s.iat[1], lambda: s.iloc[1]]: result = r() self.assertEqual(result, expected) s = Series(['1 days', '2 days'], dtype='timedelta64[ns]') expected = Timedelta('2 days') for r in [lambda: s.iat[1], lambda: s.iloc[1]]: result = r() self.assertEqual(result, expected) def test_iat_invalid_args(self): pass def test_imethods_with_dups(self): s = Series(range(5), index=[1, 1, 2, 2, 3], dtype='int64') result = s.iloc[2] self.assertEqual(result, 2) result = s.iat[2] self.assertEqual(result, 2) self.assertRaises(IndexError, lambda: s.iat[10]) self.assertRaises(IndexError, lambda: s.iat[-10]) result = s.iloc[[2, 3]] expected = Series([2, 3], [2, 2], dtype='int64') tm.assert_series_equal(result, expected) df = s.to_frame() result = df.iloc[2] expected = Series(2, index=[0], name=2) tm.assert_series_equal(result, expected) result = df.iat[2, 0] expected = 2 self.assertEqual(result, 2) def test_repeated_getitem_dups(self): df = DataFrame( np.random.random_sample((20, 5)), index=['ABCDE' [x % 5] for x in range(20)]) expected = df.loc['A', 0] result = df.loc[:, 0].loc['A'] tm.assert_series_equal(result, expected) def test_iloc_exceeds_bounds(self): df = DataFrame(np.random.random_sample((20, 5)), columns=list('ABCDE')) expected = df with tm.assertRaisesRegexp(IndexError, 'positional indexers are out-of-bounds'): df.iloc[:, [0, 1, 2, 3, 4, 5]] self.assertRaises(IndexError, lambda: df.iloc[[1, 30]]) self.assertRaises(IndexError, lambda: df.iloc[[1, -30]]) self.assertRaises(IndexError, lambda: df.iloc[[100]]) s = df['A'] self.assertRaises(IndexError, lambda: s.iloc[[100]]) self.assertRaises(IndexError, lambda: s.iloc[[-100]]) msg = 'single positional indexer is out-of-bounds' with tm.assertRaisesRegexp(IndexError, msg): df.iloc[30] self.assertRaises(IndexError, lambda: df.iloc[-30]) with tm.assertRaisesRegexp(IndexError, msg): s.iloc[30] self.assertRaises(IndexError, lambda: s.iloc[-30]) result = df.iloc[:, 4:10] expected = df.iloc[:, 4:] tm.assert_frame_equal(result, expected) result = df.iloc[:, -4:-10] expected = df.iloc[:, :0] tm.assert_frame_equal(result, expected) result = df.iloc[:, 10:4:-1] expected = df.iloc[:, :4:-1] tm.assert_frame_equal(result, expected) result = df.iloc[:, 4:-10:-1] expected = df.iloc[:, 4::-1] tm.assert_frame_equal(result, expected) result = df.iloc[:, -10:4] expected = df.iloc[:, :4] tm.assert_frame_equal(result, expected) result = df.iloc[:, 10:4] expected = df.iloc[:, :0] tm.assert_frame_equal(result, expected) result = df.iloc[:, -10:-11:-1] expected = df.iloc[:, :0] tm.assert_frame_equal(result, expected) result = df.iloc[:, 10:11] expected = df.iloc[:, :0] tm.assert_frame_equal(result, expected) result = s.iloc[18:30] expected = s.iloc[18:] tm.assert_series_equal(result, expected) result = s.iloc[30:] expected = s.iloc[:0] tm.assert_series_equal(result, expected) result = s.iloc[30::-1] expected = s.iloc[::-1] tm.assert_series_equal(result, expected) def check(result, expected): str(result) result.dtypes tm.assert_frame_equal(result, expected) dfl = DataFrame(np.random.randn(5, 2), columns=list('AB')) check(dfl.iloc[:, 2:3], DataFrame(index=dfl.index)) check(dfl.iloc[:, 1:3], dfl.iloc[:, [1]]) check(dfl.iloc[4:6], dfl.iloc[[4]]) self.assertRaises(IndexError, lambda: dfl.iloc[[4, 5, 6]]) self.assertRaises(IndexError, lambda: dfl.iloc[:, 4]) def test_iloc_getitem_int(self): self.check_result('integer', 'iloc', 2, 'ix', {0: 4, 1: 6, 2: 8}, typs=['ints', 'uints']) self.check_result('integer', 'iloc', 2, 'indexer', 2, typs=['labels', 'mixed', 'ts', 'floats', 'empty'], fails=IndexError) def test_iloc_getitem_neg_int(self): self.check_result('neg int', 'iloc', -1, 'ix', {0: 6, 1: 9, 2: 12}, typs=['ints', 'uints']) self.check_result('neg int', 'iloc', -1, 'indexer', -1, typs=['labels', 'mixed', 'ts', 'floats', 'empty'], fails=IndexError) def test_iloc_getitem_list_int(self): self.check_result('list int', 'iloc', [0, 1, 2], 'ix', {0: [0, 2, 4], 1: [0, 3, 6], 2: [0, 4, 8]}, typs=['ints', 'uints']) self.check_result('list int', 'iloc', [2], 'ix', {0: [4], 1: [6], 2: [8]}, typs=['ints', 'uints']) self.check_result('list int', 'iloc', [0, 1, 2], 'indexer', [0, 1, 2], typs=['labels', 'mixed', 'ts', 'floats', 'empty'], fails=IndexError) self.check_result('array int', 'iloc', np.array([0, 1, 2]), 'ix', {0: [0, 2, 4], 1: [0, 3, 6], 2: [0, 4, 8]}, typs=['ints', 'uints']) self.check_result('array int', 'iloc', np.array([2]), 'ix', {0: [4], 1: [6], 2: [8]}, typs=['ints', 'uints']) self.check_result('array int', 'iloc', np.array([0, 1, 2]), 'indexer', [0, 1, 2], typs=['labels', 'mixed', 'ts', 'floats', 'empty'], fails=IndexError) def test_iloc_getitem_neg_int_can_reach_first_index(self): df = DataFrame({'A': [2, 3, 5], 'B': [7, 11, 13]}) s = df['A'] expected = df.iloc[0] result = df.iloc[-3] tm.assert_series_equal(result, expected) expected = df.iloc[[0]] result = df.iloc[[-3]] tm.assert_frame_equal(result, expected) expected = s.iloc[0] result = s.iloc[-3] self.assertEqual(result, expected) expected = s.iloc[[0]] result = s.iloc[[-3]] tm.assert_series_equal(result, expected) expected = pd.Series(['a'], index=['A']) result = expected.iloc[[-1]] tm.assert_series_equal(result, expected) def test_iloc_getitem_dups(self): self.check_result('list int (dups)', 'iloc', [0, 1, 1, 3], 'ix', {0: [0, 2, 2, 6], 1: [0, 3, 3, 9]}, objs=['series', 'frame'], typs=['ints', 'uints']) df1 = DataFrame([{'A': None, 'B': 1}, {'A': 2, 'B': 2}]) df2 = DataFrame([{'A': 3, 'B': 3}, {'A': 4, 'B': 4}]) df = concat([df1, df2], axis=1) result = df.iloc[0, 0] self.assertTrue(isnull(result)) result = df.iloc[0, :] expected = Series([np.nan, 1, 3, 3], index=['A', 'B', 'A', 'B'], name=0) tm.assert_series_equal(result, expected) def test_iloc_getitem_array(self): s = Series(index=lrange(1, 4)) self.check_result('array like', 'iloc', s.index, 'ix', {0: [2, 4, 6], 1: [3, 6, 9], 2: [4, 8, 12]}, typs=['ints', 'uints']) def test_iloc_getitem_bool(self): b = [True, False, True, False, ] self.check_result('bool', 'iloc', b, 'ix', b, typs=['ints', 'uints']) self.check_result('bool', 'iloc', b, 'ix', b, typs=['labels', 'mixed', 'ts', 'floats', 'empty'], fails=IndexError) def test_iloc_getitem_slice(self): self.check_result('slice', 'iloc', slice(1, 3), 'ix', {0: [2, 4], 1: [3, 6], 2: [4, 8]}, typs=['ints', 'uints']) self.check_result('slice', 'iloc', slice(1, 3), 'indexer', slice(1, 3), typs=['labels', 'mixed', 'ts', 'floats', 'empty'], fails=IndexError) def test_iloc_getitem_slice_dups(self): df1 = DataFrame(np.random.randn(10, 4), columns=['A', 'A', 'B', 'B']) df2 = DataFrame(np.random.randint(0, 10, size=20).reshape(10, 2), columns=['A', 'C']) df = concat([df1, df2], axis=1) tm.assert_frame_equal(df.iloc[:, :4], df1) tm.assert_frame_equal(df.iloc[:, 4:], df2) df = concat([df2, df1], axis=1) tm.assert_frame_equal(df.iloc[:, :2], df2) tm.assert_frame_equal(df.iloc[:, 2:], df1) exp = concat([df2, df1.iloc[:, [0]]], axis=1) tm.assert_frame_equal(df.iloc[:, 0:3], exp) df = concat([df, df], axis=0) tm.assert_frame_equal(df.iloc[0:10, :2], df2) tm.assert_frame_equal(df.iloc[0:10, 2:], df1) tm.assert_frame_equal(df.iloc[10:, :2], df2) tm.assert_frame_equal(df.iloc[10:, 2:], df1) def test_iloc_getitem_multiindex2(self): raise nose.SkipTest('this test was being suppressed, ' 'needs to be fixed') arr = np.random.randn(3, 3) df = DataFrame(arr, columns=[[2, 2, 4], [6, 8, 10]], index=[[4, 4, 8], [8, 10, 12]]) rs = df.iloc[2] xp = Series(arr[2], index=df.columns) tm.assert_series_equal(rs, xp) rs = df.iloc[:, 2] xp = Series(arr[:, 2], index=df.index) tm.assert_series_equal(rs, xp) rs = df.iloc[2, 2] xp = df.values[2, 2] self.assertEqual(rs, xp) rs = df.iloc[[0, 1]] xp = df.xs(4, drop_level=False) tm.assert_frame_equal(rs, xp) tup = zip(*[['a', 'a', 'b', 'b'], ['x', 'y', 'x', 'y']]) index = MultiIndex.from_tuples(tup) df = DataFrame(np.random.randn(4, 4), index=index) rs = df.iloc[[2, 3]] xp = df.xs('b', drop_level=False) tm.assert_frame_equal(rs, xp) def test_iloc_setitem(self): df = self.frame_ints df.iloc[1, 1] = 1 result = df.iloc[1, 1] self.assertEqual(result, 1) df.iloc[:, 2:3] = 0 expected = df.iloc[:, 2:3] result = df.iloc[:, 2:3] tm.assert_frame_equal(result, expected) s = Series(0, index=[4, 5, 6]) s.iloc[1:2] += 1 expected = Series([0, 1, 0], index=[4, 5, 6]) tm.assert_series_equal(s, expected) def test_loc_setitem_slice(self): df1 = DataFrame({'a': [0, 1, 1], 'b': Series([100, 200, 300], dtype='uint32')}) ix = df1['a'] == 1 newb1 = df1.loc[ix, 'b'] + 1 df1.loc[ix, 'b'] = newb1 expected = DataFrame({'a': [0, 1, 1], 'b': Series([100, 201, 301], dtype='uint32')}) tm.assert_frame_equal(df1, expected) df2 = DataFrame({'a': [0, 1, 1], 'b': [100, 200, 300]}, dtype='uint64') ix = df1['a'] == 1 newb2 = df2.loc[ix, 'b'] df1.loc[ix, 'b'] = newb2 expected = DataFrame({'a': [0, 1, 1], 'b': [100, 200, 300]}, dtype='uint64') tm.assert_frame_equal(df2, expected) def test_ix_loc_setitem_consistency(self): s = Series(0, index=[4, 5, 6]) s.loc[4:5] += 1 expected = Series([1, 1, 0], index=[4, 5, 6]) tm.assert_series_equal(s, expected) df = DataFrame({'a': [0, 1, 2]}) expected = df.copy() with catch_warnings(record=True): expected.ix[[0, 1, 2], 'a'] = -expected.ix[[0, 1, 2], 'a'] with catch_warnings(record=True): df['a'].ix[[0, 1, 2]] = -df['a'].ix[[0, 1, 2]] tm.assert_frame_equal(df, expected) df = DataFrame({'a': [0, 1, 2], 'b': [0, 1, 2]}) with catch_warnings(record=True): df['a'].ix[[0, 1, 2]] = -df['a'].ix[[0, 1, 2]].astype( 'float64') + 0.5 expected = DataFrame({'a': [0.5, -0.5, -1.5], 'b': [0, 1, 2]}) tm.assert_frame_equal(df, expected) df = DataFrame({'timestamp': [1413840976, 1413842580, 1413760580], 'delta': [1174, 904, 161], 'elapsed': [7673, 9277, 1470]}) expected = DataFrame({'timestamp': pd.to_datetime( [1413840976, 1413842580, 1413760580], unit='s'), 'delta': [1174, 904, 161], 'elapsed': [7673, 9277, 1470]}) df2 = df.copy() df2['timestamp'] = pd.to_datetime(df['timestamp'], unit='s') tm.assert_frame_equal(df2, expected) df2 = df.copy() df2.loc[:, 'timestamp'] = pd.to_datetime(df['timestamp'], unit='s') tm.assert_frame_equal(df2, expected) df2 = df.copy() with catch_warnings(record=True): df2.ix[:, 2] = pd.to_datetime(df['timestamp'], unit='s') tm.assert_frame_equal(df2, expected) def test_ix_loc_consistency(self): def compare(result, expected): if is_scalar(expected): self.assertEqual(result, expected) else: self.assertTrue(expected.equals(result)) df = pd.DataFrame(np.random.randn(5, 4), columns=list('ABCD')) for key in [slice(1, 3), tuple([slice(0, 2), slice(0, 2)]), tuple([slice(0, 2), df.columns[0:2]])]: for index in [tm.makeStringIndex, tm.makeUnicodeIndex, tm.makeDateIndex, tm.makePeriodIndex, tm.makeTimedeltaIndex]: df.index = index(len(df.index)) with catch_warnings(record=True): df.ix[key] self.assertRaises(TypeError, lambda: df.loc[key]) df = pd.DataFrame(np.random.randn(5, 4), columns=list('ABCD'), index=pd.date_range('2012-01-01', periods=5)) for key in ['2012-01-03', '2012-01-31', slice('2012-01-03', '2012-01-03'), slice('2012-01-03', '2012-01-04'), slice('2012-01-03', '2012-01-06', 2), slice('2012-01-03', '2012-01-31'), tuple([[True, True, True, False, True]]), ]: try: with catch_warnings(record=True): expected = df.ix[key] except KeyError: self.assertRaises(KeyError, lambda: df.loc[key]) continue result = df.loc[key] compare(result, expected) df1 = df.copy() df2 = df.copy() with catch_warnings(record=True): df1.ix[key] = 10 df2.loc[key] = 10 compare(df2, df1) s = Series([1, 2, 3, 4], index=list('abde')) result1 = s['a':'c'] with catch_warnings(record=True): result2 = s.ix['a':'c'] result3 = s.loc['a':'c'] tm.assert_series_equal(result1, result2) tm.assert_series_equal(result1, result3) s = Series(range(5), [-2, -1, 1, 2, 3]) with catch_warnings(record=True): result1 = s.ix[-10:3] result2 = s.loc[-10:3] tm.assert_series_equal(result1, result2) with catch_warnings(record=True): result1 = s.ix[0:3] result2 = s.loc[0:3] tm.assert_series_equal(result1, result2) def test_setitem_multiindex(self): for index_fn in ('ix', 'loc'): def check(target, indexers, value, compare_fn, expected=None): fn = getattr(target, index_fn) fn.__setitem__(indexers, value) result = fn.__getitem__(indexers) if expected is None: expected = value compare_fn(result, expected) index = pd.MultiIndex.from_product([np.arange(0, 100), np.arange(0, 80)], names=['time', 'firm']) t, n = 0, 2 df = DataFrame(np.nan, columns=['A', 'w', 'l', 'a', 'x', 'X', 'd', 'profit'], index=index) check(target=df, indexers=((t, n), 'X'), value=0, compare_fn=self.assertEqual) df = DataFrame(-999, columns=['A', 'w', 'l', 'a', 'x', 'X', 'd', 'profit'], index=index) check(target=df, indexers=((t, n), 'X'), value=1, compare_fn=self.assertEqual) df = DataFrame(columns=['A', 'w', 'l', 'a', 'x', 'X', 'd', 'profit'], index=index) check(target=df, indexers=((t, n), 'X'), value=2, compare_fn=self.assertEqual) df = DataFrame(-999, columns=['A', 'w', 'l', 'a', 'x', 'X', 'd', 'profit'], index=index) check(target=df, indexers=((t, n), 'X'), value=np.array(3), compare_fn=self.assertEqual, expected=3, ) df = pd.DataFrame(np.arange(25).reshape(5, 5), columns='A,B,C,D,E'.split(','), dtype=float) df['F'] = 99 row_selection = df['A'] % 2 == 0 col_selection = ['B', 'C'] with catch_warnings(record=True): df.ix[row_selection, col_selection] = df['F'] output = pd.DataFrame(99., index=[0, 2, 4], columns=['B', 'C']) with catch_warnings(record=True): tm.assert_frame_equal(df.ix[row_selection, col_selection], output) check(target=df, indexers=(row_selection, col_selection), value=df['F'], compare_fn=tm.assert_frame_equal, expected=output, ) idx = pd.MultiIndex.from_product([ ['A', 'B', 'C'], pd.date_range('2015-01-01', '2015-04-01', freq='MS')]) cols = pd.MultiIndex.from_product([ ['foo', 'bar'], pd.date_range('2016-01-01', '2016-02-01', freq='MS')]) df = pd.DataFrame(np.random.random((12, 4)), index=idx, columns=cols) subidx = pd.MultiIndex.from_tuples( [('A', pd.Timestamp('2015-01-01')), ('A', pd.Timestamp('2015-02-01'))]) subcols = pd.MultiIndex.from_tuples( [('foo', pd.Timestamp('2016-01-01')), ('foo', pd.Timestamp('2016-02-01'))]) vals = pd.DataFrame(np.random.random((2, 2)), index=subidx, columns=subcols) check(target=df, indexers=(subidx, subcols), value=vals, compare_fn=tm.assert_frame_equal, ) vals = pd.DataFrame( np.random.random((2, 4)), index=subidx, columns=cols) check(target=df, indexers=(subidx, slice(None, None, None)), value=vals, compare_fn=tm.assert_frame_equal, ) copy = df.copy() check(target=df, indexers=(df.index, df.columns), value=df, compare_fn=tm.assert_frame_equal, expected=copy) def test_indexing_with_datetime_tz(self): idx = Index(date_range('20130101', periods=3, tz='US/Eastern'), name='foo') dr = date_range('20130110', periods=3) df = DataFrame({'A': idx, 'B': dr}) df['C'] = idx df.iloc[1, 1] = pd.NaT df.iloc[1, 2] = pd.NaT result = df.iloc[1] expected = Series([Timestamp('2013-01-02 00:00:00-0500', tz='US/Eastern'), np.nan, np.nan], index=list('ABC'), dtype='object', name=1) tm.assert_series_equal(result, expected) result = df.loc[1] expected = Series([Timestamp('2013-01-02 00:00:00-0500', tz='US/Eastern'), np.nan, np.nan], index=list('ABC'), dtype='object', name=1) tm.assert_series_equal(result, expected) df = DataFrame({'a': date_range('2014-01-01', periods=10, tz='UTC')}) result = df.iloc[5] expected = Timestamp('2014-01-06 00:00:00+0000', tz='UTC', freq='D') self.assertEqual(result, expected) result = df.loc[5] self.assertEqual(result, expected) result = df[df.a > df.a[3]] expected = df.iloc[4:] tm.assert_frame_equal(result, expected) df = DataFrame(data=pd.to_datetime( ['2015-03-30 20:12:32', '2015-03-12 00:11:11']), columns=['time']) df['new_col'] = ['new', 'old'] df.time = df.set_index('time').index.tz_localize('UTC') v = df[df.new_col == 'new'].set_index('time').index.tz_convert( 'US/Pacific') def f(): df.loc[df.new_col == 'new', 'time'] = v self.assertRaises(ValueError, f) v = df.loc[df.new_col == 'new', 'time'] + pd.Timedelta('1s') df.loc[df.new_col == 'new', 'time'] = v tm.assert_series_equal(df.loc[df.new_col == 'new', 'time'], v) def test_indexing_with_datetimeindex_tz(self): index = pd.date_range('2015-01-01', periods=2, tz='utc') ser = pd.Series(range(2), index=index, dtype='int64') for sel in (index, list(index)): tm.assert_series_equal(ser[sel], ser) result = ser.copy() result[sel] = 1 expected = pd.Series(1, index=index) tm.assert_series_equal(result, expected) tm.assert_series_equal(ser.loc[sel], ser) result = ser.copy() result.loc[sel] = 1 expected = pd.Series(1, index=index) tm.assert_series_equal(result, expected) self.assertEqual(ser[index[1]], 1) result = ser.copy() result[index[1]] = 5 expected = pd.Series([0, 5], index=index) tm.assert_series_equal(result, expected) self.assertEqual(ser.loc[index[1]], 1) result = ser.copy() result.loc[index[1]] = 5 expected = pd.Series([0, 5], index=index) tm.assert_series_equal(result, expected) def test_loc_setitem_dups(self): df_orig = DataFrame( {'me': list('rttti'), 'foo': list('aaade'), 'bar': np.arange(5, dtype='float64') * 1.34 + 2, 'bar2': np.arange(5, dtype='float64') * -.34 + 2}).set_index('me') indexer = tuple(['r', ['bar', 'bar2']]) df = df_orig.copy() df.loc[indexer] *= 2.0 tm.assert_series_equal(df.loc[indexer], 2.0 * df_orig.loc[indexer]) indexer = tuple(['r', 'bar']) df = df_orig.copy() df.loc[indexer] *= 2.0 self.assertEqual(df.loc[indexer], 2.0 * df_orig.loc[indexer]) indexer = tuple(['t', ['bar', 'bar2']]) df = df_orig.copy() df.loc[indexer] *= 2.0 tm.assert_frame_equal(df.loc[indexer], 2.0 * df_orig.loc[indexer]) def test_iloc_setitem_dups(self): df1 = DataFrame([{'A': None, 'B': 1}, {'A': 2, 'B': 2}]) df2 = DataFrame([{'A': 3, 'B': 3}, {'A': 4, 'B': 4}]) df = concat([df1, df2], axis=1) expected = df.fillna(3) expected['A'] = expected['A'].astype('float64') inds = np.isnan(df.iloc[:, 0]) mask = inds[inds].index df.iloc[mask, 0] = df.iloc[mask, 2] tm.assert_frame_equal(df, expected) expected = DataFrame({0: [1, 2], 1: [3, 4]}) expected.columns = ['B', 'B'] del df['A'] tm.assert_frame_equal(df, expected) df.iloc[[0, 1], [0, 1]] = df.iloc[[0, 1], [0, 1]] tm.assert_frame_equal(df, expected) df.iloc[[1, 0], [0, 1]] = df.iloc[[1, 0], [0, 1]].reset_index( drop=True) df.iloc[[1, 0], [0, 1]] = df.iloc[[1, 0], [0, 1]].reset_index( drop=True) tm.assert_frame_equal(df, expected) def test_chained_getitem_with_lists(self): def check(result, expected): tm.assert_numpy_array_equal(result, expected) tm.assertIsInstance(result, np.ndarray) df = DataFrame({'A': 5 * [np.zeros(3)], 'B': 5 * [np.ones(3)]}) expected = df['A'].iloc[2] result = df.loc[2, 'A'] check(result, expected) result2 = df.iloc[2]['A'] check(result2, expected) result3 = df['A'].loc[2] check(result3, expected) result4 = df['A'].iloc[2] check(result4, expected) def test_loc_getitem_int(self): self.check_result('int label', 'loc', 2, 'ix', 2, typs=['ints', 'uints'], axes=0) self.check_result('int label', 'loc', 3, 'ix', 3, typs=['ints', 'uints'], axes=1) self.check_result('int label', 'loc', 4, 'ix', 4, typs=['ints', 'uints'], axes=2) self.check_result('int label', 'loc', 2, 'ix', 2, typs=['label'], fails=KeyError) def test_loc_getitem_label(self): self.check_result('label', 'loc', 'c', 'ix', 'c', typs=['labels'], axes=0) self.check_result('label', 'loc', 'null', 'ix', 'null', typs=['mixed'], axes=0) self.check_result('label', 'loc', 8, 'ix', 8, typs=['mixed'], axes=0) self.check_result('label', 'loc', Timestamp('20130102'), 'ix', 1, typs=['ts'], axes=0) self.check_result('label', 'loc', 'c', 'ix', 'c', typs=['empty'], fails=KeyError) def test_loc_getitem_label_out_of_range(self): self.check_result('label range', 'loc', 'f', 'ix', 'f', typs=['ints', 'uints', 'labels', 'mixed', 'ts'], fails=KeyError) self.check_result('label range', 'loc', 'f', 'ix', 'f', typs=['floats'], fails=TypeError) self.check_result('label range', 'loc', 20, 'ix', 20, typs=['ints', 'uints', 'mixed'], fails=KeyError) self.check_result('label range', 'loc', 20, 'ix', 20, typs=['labels'], fails=TypeError) self.check_result('label range', 'loc', 20, 'ix', 20, typs=['ts'], axes=0, fails=TypeError) self.check_result('label range', 'loc', 20, 'ix', 20, typs=['floats'], axes=0, fails=TypeError) def test_loc_getitem_label_list(self): self.check_result('list lbl', 'loc', [0, 2, 4], 'ix', [0, 2, 4], typs=['ints', 'uints'], axes=0) self.check_result('list lbl', 'loc', [3, 6, 9], 'ix', [3, 6, 9], typs=['ints', 'uints'], axes=1) self.check_result('list lbl', 'loc', [4, 8, 12], 'ix', [4, 8, 12], typs=['ints', 'uints'], axes=2) self.check_result('list lbl', 'loc', ['a', 'b', 'd'], 'ix', ['a', 'b', 'd'], typs=['labels'], axes=0) self.check_result('list lbl', 'loc', ['A', 'B', 'C'], 'ix', ['A', 'B', 'C'], typs=['labels'], axes=1) self.check_result('list lbl', 'loc', ['Z', 'Y', 'W'], 'ix', ['Z', 'Y', 'W'], typs=['labels'], axes=2) self.check_result('list lbl', 'loc', [2, 8, 'null'], 'ix', [2, 8, 'null'], typs=['mixed'], axes=0) self.check_result('list lbl', 'loc', [Timestamp('20130102'), Timestamp('20130103')], 'ix', [Timestamp('20130102'), Timestamp('20130103')], typs=['ts'], axes=0) self.check_result('list lbl', 'loc', [0, 1, 2], 'indexer', [0, 1, 2], typs=['empty'], fails=KeyError) self.check_result('list lbl', 'loc', [0, 2, 3], 'ix', [0, 2, 3], typs=['ints', 'uints'], axes=0, fails=KeyError) self.check_result('list lbl', 'loc', [3, 6, 7], 'ix', [3, 6, 7], typs=['ints', 'uints'], axes=1, fails=KeyError) self.check_result('list lbl', 'loc', [4, 8, 10], 'ix', [4, 8, 10], typs=['ints', 'uints'], axes=2, fails=KeyError) def test_loc_getitem_label_list_fails(self): self.check_result('list lbl', 'loc', [20, 30, 40], 'ix', [20, 30, 40], typs=['ints', 'uints'], axes=1, fails=KeyError) self.check_result('list lbl', 'loc', [20, 30, 40], 'ix', [20, 30, 40], typs=['ints', 'uints'], axes=2, fails=KeyError) def test_loc_getitem_label_array_like(self): self.check_result('array like', 'loc', Series(index=[0, 2, 4]).index, 'ix', [0, 2, 4], typs=['ints', 'uints'], axes=0) self.check_result('array like', 'loc', Series(index=[3, 6, 9]).index, 'ix', [3, 6, 9], typs=['ints', 'uints'], axes=1) self.check_result('array like', 'loc', Series(index=[4, 8, 12]).index, 'ix', [4, 8, 12], typs=['ints', 'uints'], axes=2) def test_loc_getitem_series(self): index = MultiIndex.from_product([[1, 2, 3], ['A', 'B', 'C']]) x = Series(index=index, data=range(9), dtype=np.float64) y = Series([1, 3]) expected = Series( data=[0, 1, 2, 6, 7, 8], index=MultiIndex.from_product([[1, 3], ['A', 'B', 'C']]), dtype=np.float64) result = x.loc[y] tm.assert_series_equal(result, expected) result = x.loc[[1, 3]] tm.assert_series_equal(result, expected) empty = Series(data=[], dtype=np.float64) expected = Series([], index=MultiIndex( levels=index.levels, labels=[[], []], dtype=np.float64)) result = x.loc[empty] tm.assert_series_equal(result, expected) def test_loc_getitem_bool(self): b = [True, False, True, False] self.check_result('bool', 'loc', b, 'ix', b, typs=['ints', 'uints', 'labels', 'mixed', 'ts', 'floats']) self.check_result('bool', 'loc', b, 'ix', b, typs=['empty'], fails=KeyError) def test_loc_getitem_int_slice(self): self.check_result('int slice2', 'loc', slice(2, 4), 'ix', [2, 4], typs=['ints', 'uints'], axes=0) self.check_result('int slice2', 'loc', slice(3, 6), 'ix', [3, 6], typs=['ints', 'uints'], axes=1) self.check_result('int slice2', 'loc', slice(4, 8), 'ix', [4, 8], typs=['ints', 'uints'], axes=2) from itertools import product index = MultiIndex.from_tuples([t for t in product( [6, 7, 8], ['a', 'b'])]) df = DataFrame(np.random.randn(6, 6), index, index) result = df.loc[6:8, :] with catch_warnings(record=True): expected = df.ix[6:8, :] tm.assert_frame_equal(result, expected) index = MultiIndex.from_tuples([t for t in product( [10, 20, 30], ['a', 'b'])]) df = DataFrame(np.random.randn(6, 6), index, index) result = df.loc[20:30, :] with catch_warnings(record=True): expected = df.ix[20:30, :] tm.assert_frame_equal(result, expected) result = df.loc[10, :] with catch_warnings(record=True): expected = df.ix[10, :] tm.assert_frame_equal(result, expected) result = df.loc[:, 10] expected = df[10] tm.assert_frame_equal(result, expected) def test_loc_to_fail(self): df = DataFrame(np.random.random((3, 3)), index=['a', 'b', 'c'], columns=['e', 'f', 'g']) self.assertRaises(KeyError, df.loc.__getitem__, tuple([[1, 2], [1, 2]])) s = Series() s.loc[1] = 1 s.loc['a'] = 2 self.assertRaises(KeyError, lambda: s.loc[-1]) self.assertRaises(KeyError, lambda: s.loc[[-1, -2]]) self.assertRaises(KeyError, lambda: s.loc[['4']]) s.loc[-1] = 3 result = s.loc[[-1, -2]] expected = Series([3, np.nan], index=[-1, -2]) tm.assert_series_equal(result, expected) s['a'] = 2 self.assertRaises(KeyError, lambda: s.loc[[-2]]) del s['a'] def f(): s.loc[[-2]] = 0 self.assertRaises(KeyError, f) df = DataFrame([['a'], ['b']], index=[1, 2], columns=['value']) def f(): df.loc[[3], :] self.assertRaises(KeyError, f) def f(): df.loc[[3]] self.assertRaises(KeyError, f) def test_at_to_fail(self): s = Series([1, 2, 3], index=list('abc')) result = s.at['a'] self.assertEqual(result, 1) self.assertRaises(ValueError, lambda: s.at[0]) df = DataFrame({'A': [1, 2, 3]}, index=list('abc')) result = df.at['a', 'A'] self.assertEqual(result, 1) self.assertRaises(ValueError, lambda: df.at['a', 0]) s = Series([1, 2, 3], index=[3, 2, 1]) result = s.at[1] self.assertEqual(result, 3) self.assertRaises(ValueError, lambda: s.at['a']) df = DataFrame({0: [1, 2, 3]}, index=[3, 2, 1]) result = df.at[1, 0] self.assertEqual(result, 3) self.assertRaises(ValueError, lambda: df.at['a', 0]) df = DataFrame({'x': [1.], 'y': [2.], 'z': [3.]}) df.columns = ['x', 'x', 'z'] self.assertRaisesRegexp(KeyError, r"\['y'\] not in index", lambda: df[['x', 'y', 'z']]) def test_loc_getitem_label_slice(self): self.check_result('lab slice', 'loc', slice(1, 3), 'ix', slice(1, 3), typs=['labels', 'mixed', 'empty', 'ts', 'floats'], fails=TypeError) self.check_result('lab slice', 'loc', slice('a', 'c'), 'ix', slice('a', 'c'), typs=['labels'], axes=0) self.check_result('lab slice', 'loc', slice('A', 'C'), 'ix', slice('A', 'C'), typs=['labels'], axes=1) self.check_result('lab slice', 'loc', slice('W', 'Z'), 'ix', slice('W', 'Z'), typs=['labels'], axes=2) self.check_result('ts slice', 'loc', slice('20130102', '20130104'), 'ix', slice('20130102', '20130104'), typs=['ts'], axes=0) self.check_result('ts slice', 'loc', slice('20130102', '20130104'), 'ix', slice('20130102', '20130104'), typs=['ts'], axes=1, fails=TypeError) self.check_result('ts slice', 'loc', slice('20130102', '20130104'), 'ix', slice('20130102', '20130104'), typs=['ts'], axes=2, fails=TypeError) self.check_result('ts slice rev', 'loc', slice('20130104', '20130102'), 'indexer', [0, 1, 2], typs=['ts_rev'], axes=0) self.check_result('mixed slice', 'loc', slice(2, 8), 'ix', slice(2, 8), typs=['mixed'], axes=0, fails=TypeError) self.check_result('mixed slice', 'loc', slice(2, 8), 'ix', slice(2, 8), typs=['mixed'], axes=1, fails=KeyError) self.check_result('mixed slice', 'loc', slice(2, 8), 'ix', slice(2, 8), typs=['mixed'], axes=2, fails=KeyError) self.check_result('mixed slice', 'loc', slice(2, 4, 2), 'ix', slice( 2, 4, 2), typs=['mixed'], axes=0, fails=TypeError) def test_loc_general(self): df = DataFrame( np.random.rand(4, 4), columns=['A', 'B', 'C', 'D'], index=['A', 'B', 'C', 'D']) result = df.loc[:, "A":"B"].iloc[0:2, :] self.assertTrue((result.columns == ['A', 'B']).all()) self.assertTrue((result.index == ['A', 'B']).all()) result = DataFrame({'a': [Timestamp('20130101')], 'b': [1]}).iloc[0] expected = Series([Timestamp('20130101'), 1], index=['a', 'b'], name=0) tm.assert_series_equal(result, expected) self.assertEqual(result.dtype, object) def test_loc_setitem_consistency(self): expected = DataFrame({'date': Series(0, index=range(5), dtype=np.int64), 'val': Series(range(5), dtype=np.int64)}) df = DataFrame({'date': date_range('2000-01-01', '2000-01-5'), 'val': Series( range(5), dtype=np.int64)}) df.loc[:, 'date'] = 0 tm.assert_frame_equal(df, expected) df = DataFrame({'date': date_range('2000-01-01', '2000-01-5'), 'val': Series(range(5), dtype=np.int64)}) df.loc[:, 'date'] = np.array(0, dtype=np.int64) tm.assert_frame_equal(df, expected) df = DataFrame({'date': date_range('2000-01-01', '2000-01-5'), 'val': Series(range(5), dtype=np.int64)}) df.loc[:, 'date'] = np.array([0, 0, 0, 0, 0], dtype=np.int64) tm.assert_frame_equal(df, expected) expected = DataFrame({'date': Series('foo', index=range(5)), 'val': Series(range(5), dtype=np.int64)}) df = DataFrame({'date': date_range('2000-01-01', '2000-01-5'), 'val': Series(range(5), dtype=np.int64)}) df.loc[:, 'date'] = 'foo' tm.assert_frame_equal(df, expected) expected = DataFrame({'date': Series(1.0, index=range(5)), 'val': Series(range(5), dtype=np.int64)}) df = DataFrame({'date': date_range('2000-01-01', '2000-01-5'), 'val': Series(range(5), dtype=np.int64)}) df.loc[:, 'date'] = 1.0 tm.assert_frame_equal(df, expected) def test_loc_setitem_consistency_empty(self): expected = DataFrame(columns=['x', 'y']) expected['x'] = expected['x'].astype(np.int64) df = DataFrame(columns=['x', 'y']) df.loc[:, 'x'] = 1 tm.assert_frame_equal(df, expected) df = DataFrame(columns=['x', 'y']) df['x'] = 1 tm.assert_frame_equal(df, expected) def test_loc_setitem_consistency_slice_column_len(self): data = """Level_0,,,Respondent,Respondent,Respondent,OtherCat,OtherCat Level_1,,,Something,StartDate,EndDate,Yes/No,SomethingElse Region,Site,RespondentID,,,,, Region_1,Site_1,3987227376,A,5/25/2015 10:59,5/25/2015 11:22,Yes, Region_1,Site_1,3980680971,A,5/21/2015 9:40,5/21/2015 9:52,Yes,Yes Region_1,Site_2,3977723249,A,5/20/2015 8:27,5/20/2015 8:41,Yes, Region_1,Site_2,3977723089,A,5/20/2015 8:33,5/20/2015 9:09,Yes,No""" df = pd.read_csv(StringIO(data), header=[0, 1], index_col=[0, 1, 2]) df.loc[:, ('Respondent', 'StartDate')] = pd.to_datetime(df.loc[:, ( 'Respondent', 'StartDate')]) df.loc[:, ('Respondent', 'EndDate')] = pd.to_datetime(df.loc[:, ( 'Respondent', 'EndDate')]) df.loc[:, ('Respondent', 'Duration')] = df.loc[:, ( 'Respondent', 'EndDate')] - df.loc[:, ('Respondent', 'StartDate')] df.loc[:, ('Respondent', 'Duration')] = df.loc[:, ( 'Respondent', 'Duration')].astype('timedelta64[s]') expected = Series([1380, 720, 840, 2160.], index=df.index, name=('Respondent', 'Duration')) tm.assert_series_equal(df[('Respondent', 'Duration')], expected) def test_loc_setitem_frame(self): df = self.frame_labels result = df.iloc[0, 0] df.loc['a', 'A'] = 1 result = df.loc['a', 'A'] self.assertEqual(result, 1) result = df.iloc[0, 0] self.assertEqual(result, 1) df.loc[:, 'B':'D'] = 0 expected = df.loc[:, 'B':'D'] with catch_warnings(record=True): result = df.ix[:, 1:] tm.assert_frame_equal(result, expected) df = DataFrame(index=[3, 5, 4], columns=['A']) df.loc[[4, 3, 5], 'A'] = np.array([1, 2, 3], dtype='int64') expected = DataFrame(dict(A=Series( [1, 2, 3], index=[4, 3, 5]))).reindex(index=[3, 5, 4]) tm.assert_frame_equal(df, expected) keys1 = ['@' + str(i) for i in range(5)] val1 = np.arange(5, dtype='int64') keys2 = ['@' + str(i) for i in range(4)] val2 = np.arange(4, dtype='int64') index = list(set(keys1).union(keys2)) df = DataFrame(index=index) df['A'] = nan df.loc[keys1, 'A'] = val1 df['B'] = nan df.loc[keys2, 'B'] = val2 expected = DataFrame(dict(A=Series(val1, index=keys1), B=Series( val2, index=keys2))).reindex(index=index) tm.assert_frame_equal(df, expected) df = DataFrame({'A': [1, 2, 3], 'B': np.nan}) df.loc[df.B > df.A, 'B'] = df.A expected = DataFrame({'A': [1, 2, 3], 'B': np.nan}) tm.assert_frame_equal(df, expected) df = DataFrame({1: [1, 2], 2: [3, 4], 'a': ['a', 'b']}) result = df.loc[0, [1, 2]] expected = Series([1, 3], index=[1, 2], dtype=object, name=0) tm.assert_series_equal(result, expected) expected = DataFrame({1: [5, 2], 2: [6, 4], 'a': ['a', 'b']}) df.loc[0, [1, 2]] = [5, 6] tm.assert_frame_equal(df, expected) def test_loc_setitem_frame_multiples(self): df = DataFrame({'A': ['foo', 'bar', 'baz'], 'B': Series( range(3), dtype=np.int64)}) rhs = df.loc[1:2] rhs.index = df.index[0:2] df.loc[0:1] = rhs expected = DataFrame({'A': ['bar', 'baz', 'baz'], 'B': Series( [1, 2, 2], dtype=np.int64)}) tm.assert_frame_equal(df, expected) df = DataFrame({'date': date_range('2000-01-01', '2000-01-5'), 'val': Series( range(5), dtype=np.int64)}) expected = DataFrame({'date': [Timestamp('20000101'), Timestamp( '20000102'), Timestamp('20000101'), Timestamp('20000102'), Timestamp('20000103')], 'val': Series( [0, 1, 0, 1, 2], dtype=np.int64)}) rhs = df.loc[0:2] rhs.index = df.index[2:5] df.loc[2:4] = rhs tm.assert_frame_equal(df, expected) def test_iloc_getitem_frame(self): df = DataFrame(np.random.randn(10, 4), index=lrange(0, 20, 2), columns=lrange(0, 8, 2)) result = df.iloc[2] with catch_warnings(record=True): exp = df.ix[4] tm.assert_series_equal(result, exp) result = df.iloc[2, 2] with catch_warnings(record=True): exp = df.ix[4, 4] self.assertEqual(result, exp) result = df.iloc[4:8] with catch_warnings(record=True): expected = df.ix[8:14] tm.assert_frame_equal(result, expected) result = df.iloc[:, 2:3] with catch_warnings(record=True): expected = df.ix[:, 4:5] tm.assert_frame_equal(result, expected) result = df.iloc[[0, 1, 3]] with catch_warnings(record=True): expected = df.ix[[0, 2, 6]] tm.assert_frame_equal(result, expected) result = df.iloc[[0, 1, 3], [0, 1]] with catch_warnings(record=True): expected = df.ix[[0, 2, 6], [0, 2]] tm.assert_frame_equal(result, expected) result = df.iloc[[-1, 1, 3], [-1, 1]] with catch_warnings(record=True): expected = df.ix[[18, 2, 6], [6, 2]] tm.assert_frame_equal(result, expected) result = df.iloc[[-1, -1, 1, 3], [-1, 1]] with catch_warnings(record=True): expected = df.ix[[18, 18, 2, 6], [6, 2]] tm.assert_frame_equal(result, expected) s = Series(index=lrange(1, 5)) result = df.iloc[s.index] with catch_warnings(record=True): expected = df.ix[[2, 4, 6, 8]] tm.assert_frame_equal(result, expected) def test_iloc_getitem_labelled_frame(self): df = DataFrame(np.random.randn(10, 4), index=list('abcdefghij'), columns=list('ABCD')) result = df.iloc[1, 1] exp = df.loc['b', 'B'] self.assertEqual(result, exp) result = df.iloc[:, 2:3] expected = df.loc[:, ['C']] tm.assert_frame_equal(result, expected) result = df.iloc[-1, -1] exp = df.loc['j', 'D'] self.assertEqual(result, exp) self.assertRaises(IndexError, df.iloc.__getitem__, tuple([10, 5])) self.assertRaises(ValueError, df.iloc.__getitem__, tuple(['j', 'D'])) def test_iloc_getitem_panel(self): p = Panel(np.arange(4 * 3 * 2).reshape(4, 3, 2), items=['A', 'B', 'C', 'D'], major_axis=['a', 'b', 'c'], minor_axis=['one', 'two']) result = p.iloc[1] expected = p.loc['B'] tm.assert_frame_equal(result, expected) result = p.iloc[1, 1] expected = p.loc['B', 'b'] tm.assert_series_equal(result, expected) result = p.iloc[1, 1, 1] expected = p.loc['B', 'b', 'two'] self.assertEqual(result, expected) result = p.iloc[1:3] expected = p.loc[['B', 'C']] tm.assert_panel_equal(result, expected) result = p.iloc[:, 0:2] expected = p.loc[:, ['a', 'b']] tm.assert_panel_equal(result, expected) result = p.iloc[[0, 2]] expected = p.loc[['A', 'C']] tm.assert_panel_equal(result, expected) result = p.iloc[[-1, 1], [-1, 1]] expected = p.loc[['D', 'B'], ['c', 'b']] tm.assert_panel_equal(result, expected) result = p.iloc[[-1, -1, 1], [-1, 1]] expected = p.loc[['D', 'D', 'B'], ['c', 'b']] tm.assert_panel_equal(result, expected) result = p.iloc[0, [True, True], [0, 1]] expected = p.loc['A', ['a', 'b'], ['one', 'two']] tm.assert_frame_equal(result, expected) self.assertRaises(IndexError, p.iloc.__getitem__, tuple([10, 5])) def f(): p.iloc[0, [True, True], [0, 1, 2]] self.assertRaises(IndexError, f) self.assertRaises(ValueError, p.iloc.__getitem__, tuple(['j', 'D'])) p = Panel( np.random.rand(4, 3, 2), items=['A', 'B', 'C', 'D'], major_axis=['U', 'V', 'W'], minor_axis=['X', 'Y']) expected = p['A'] result = p.iloc[0, :, :] tm.assert_frame_equal(result, expected) result = p.iloc[0, [True, True, True], :] tm.assert_frame_equal(result, expected) result = p.iloc[0, [True, True, True], [0, 1]] tm.assert_frame_equal(result, expected) def f(): p.iloc[0, [True, True, True], [0, 1, 2]] self.assertRaises(IndexError, f) def f(): p.iloc[0, [True, True, True], [2]] self.assertRaises(IndexError, f) def test_iloc_getitem_panel_multiindex(self): multi_index = pd.MultiIndex.from_tuples([('ONE', 'one'), ('TWO', 'two'), ('THREE', 'three')], names=['UPPER', 'lower']) simple_index = [x[0] for x in multi_index] wd1 = Panel(items=['First', 'Second'], major_axis=['a', 'b', 'c', 'd'], minor_axis=multi_index) wd2 = Panel(items=['First', 'Second'], major_axis=['a', 'b', 'c', 'd'], minor_axis=simple_index) expected1 = wd1['First'].iloc[[True, True, True, False], [0, 2]] result1 = wd1.iloc[0, [True, True, True, False], [0, 2]] tm.assert_frame_equal(result1, expected1) expected2 = wd2['First'].iloc[[True, True, True, False], [0, 2]] result2 = wd2.iloc[0, [True, True, True, False], [0, 2]] tm.assert_frame_equal(result2, expected2) expected1 = DataFrame(index=['a'], columns=multi_index, dtype='float64') result1 = wd1.iloc[0, [0], [0, 1, 2]] tm.assert_frame_equal(result1, expected1) expected2 = DataFrame(index=['a'], columns=simple_index, dtype='float64') result2 = wd2.iloc[0, [0], [0, 1, 2]] tm.assert_frame_equal(result2, expected2) mi = MultiIndex.from_tuples([(0, 'x'), (1, 'y'), (2, 'z')]) p = Panel(np.arange(3 * 3 * 3, dtype='int64').reshape(3, 3, 3), items=['a', 'b', 'c'], major_axis=mi, minor_axis=['u', 'v', 'w']) result = p.iloc[:, 1, 0] expected = Series([3, 12, 21], index=['a', 'b', 'c'], name='u') tm.assert_series_equal(result, expected) result = p.loc[:, (1, 'y'), 'u'] tm.assert_series_equal(result, expected) def test_iloc_getitem_doc_issue(self): arr = np.random.randn(6, 4) index = date_range('20130101', periods=6) columns = list('ABCD') df = DataFrame(arr, index=index, columns=columns) df.describe() result = df.iloc[3:5, 0:2] str(result) result.dtypes expected = DataFrame(arr[3:5, 0:2], index=index[3:5], columns=columns[0:2]) tm.assert_frame_equal(result, expected) df.columns = list('aaaa') result = df.iloc[3:5, 0:2] str(result) result.dtypes expected = DataFrame(arr[3:5, 0:2], index=index[3:5], columns=list('aa')) tm.assert_frame_equal(result, expected) arr = np.random.randn(6, 4) index = list(range(0, 12, 2)) columns = list(range(0, 8, 2)) df = DataFrame(arr, index=index, columns=columns) df._data.blocks[0].mgr_locs result = df.iloc[1:5, 2:4] str(result) result.dtypes expected = DataFrame(arr[1:5, 2:4], index=index[1:5], columns=columns[2:4]) tm.assert_frame_equal(result, expected) def test_setitem_ndarray_1d(self): df = DataFrame(index=Index(lrange(1, 11))) df['foo'] = np.zeros(10, dtype=np.float64) df['bar'] = np.zeros(10, dtype=np.complex) def f(): with catch_warnings(record=True): df.ix[2:5, 'bar'] = np.array([2.33j, 1.23 + 0.1j, 2.2]) self.assertRaises(ValueError, f) def f(): df.loc[df.index[2:5], 'bar'] = np.array([2.33j, 1.23 + 0.1j, 2.2, 1.0]) self.assertRaises(ValueError, f) df.loc[df.index[2:6], 'bar'] = np.array([2.33j, 1.23 + 0.1j, 2.2, 1.0]) result = df.loc[df.index[2:6], 'bar'] expected = Series([2.33j, 1.23 + 0.1j, 2.2, 1.0], index=[3, 4, 5, 6], name='bar') tm.assert_series_equal(result, expected) df = DataFrame(index=Index(lrange(1, 11))) df['foo'] = np.zeros(10, dtype=np.float64) df['bar'] = np.zeros(10, dtype=np.complex) def f(): df[2:5] = np.arange(1, 4) * 1j self.assertRaises(ValueError, f) def test_iloc_setitem_series(self): df = DataFrame(np.random.randn(10, 4), index=list('abcdefghij'), columns=list('ABCD')) df.iloc[1, 1] = 1 result = df.iloc[1, 1] self.assertEqual(result, 1) df.iloc[:, 2:3] = 0 expected = df.iloc[:, 2:3] result = df.iloc[:, 2:3] tm.assert_frame_equal(result, expected) s = Series(np.random.randn(10), index=lrange(0, 20, 2)) s.iloc[1] = 1 result = s.iloc[1] self.assertEqual(result, 1) s.iloc[:4] = 0 expected = s.iloc[:4] result = s.iloc[:4] tm.assert_series_equal(result, expected) s = Series([-1] * 6) s.iloc[0::2] = [0, 2, 4] s.iloc[1::2] = [1, 3, 5] result = s expected = Series([0, 1, 2, 3, 4, 5]) tm.assert_series_equal(result, expected) def test_iloc_setitem_list_of_lists(self): df = DataFrame(dict(A=np.arange(5, dtype='int64'), B=np.arange(5, 10, dtype='int64'))) df.iloc[2:4] = [[10, 11], [12, 13]] expected = DataFrame(dict(A=[0, 1, 10, 12, 4], B=[5, 6, 11, 13, 9])) tm.assert_frame_equal(df, expected) df = DataFrame( dict(A=list('abcde'), B=np.arange(5, 10, dtype='int64'))) df.iloc[2:4] = [['x', 11], ['y', 13]] expected = DataFrame(dict(A=['a', 'b', 'x', 'y', 'e'], B=[5, 6, 11, 13, 9])) tm.assert_frame_equal(df, expected) def test_iloc_getitem_multiindex(self): mi_labels = DataFrame(np.random.randn(4, 3), columns=[['i', 'i', 'j'], ['A', 'A', 'B']], index=[['i', 'i', 'j', 'k'], ['X', 'X', 'Y', 'Y']]) mi_int = DataFrame(np.random.randn(3, 3), columns=[[2, 2, 4], [6, 8, 10]], index=[[4, 4, 8], [8, 10, 12]]) rs = mi_int.iloc[0] with catch_warnings(record=True): xp = mi_int.ix[4].ix[8] tm.assert_series_equal(rs, xp, check_names=False) self.assertEqual(rs.name, (4, 8)) self.assertEqual(xp.name, 8) rs = mi_int.iloc[:, 2] with catch_warnings(record=True): xp = mi_int.ix[:, 2] tm.assert_series_equal(rs, xp) rs = mi_int.iloc[2, 2] with catch_warnings(record=True): xp = mi_int.ix[:, 2].ix[2] self.assertEqual(rs, xp) rs = mi_labels.iloc[2, 2] with catch_warnings(record=True): xp = mi_labels.ix['j'].ix[:, 'j'].ix[0, 0] self.assertEqual(rs, xp) def test_loc_multiindex(self): mi_labels = DataFrame(np.random.randn(3, 3), columns=[['i', 'i', 'j'], ['A', 'A', 'B']], index=[['i', 'i', 'j'], ['X', 'X', 'Y']]) mi_int = DataFrame(np.random.randn(3, 3), columns=[[2, 2, 4], [6, 8, 10]], index=[[4, 4, 8], [8, 10, 12]]) rs = mi_labels.loc['i'] with catch_warnings(record=True): xp = mi_labels.ix['i'] tm.assert_frame_equal(rs, xp) rs = mi_labels.loc[:, 'j'] with catch_warnings(record=True): xp = mi_labels.ix[:, 'j'] tm.assert_frame_equal(rs, xp) rs = mi_labels.loc['j'].loc[:, 'j'] with catch_warnings(record=True): xp = mi_labels.ix['j'].ix[:, 'j'] tm.assert_frame_equal(rs, xp) rs = mi_labels.loc[('i', 'X')] with catch_warnings(record=True): xp = mi_labels.ix[('i', 'X')] tm.assert_frame_equal(rs, xp) rs = mi_int.loc[4] with catch_warnings(record=True): xp = mi_int.ix[4] tm.assert_frame_equal(rs, xp) def test_loc_multiindex_indexer_none(self): attributes = ['Attribute' + str(i) for i in range(1)] attribute_values = ['Value' + str(i) for i in range(5)] index = MultiIndex.from_product([attributes, attribute_values]) df = 0.1 * np.random.randn(10, 1 * 5) + 0.5 df = DataFrame(df, columns=index) result = df[attributes] tm.assert_frame_equal(result, df) df = DataFrame(np.arange(12).reshape(-1, 1), index=pd.MultiIndex.from_product([[1, 2, 3, 4], [1, 2, 3]])) expected = df.loc[([1, 2], ), :] result = df.loc[[1, 2]] tm.assert_frame_equal(result, expected) def test_loc_multiindex_incomplete(self): s = pd.Series(np.arange(15, dtype='int64'), MultiIndex.from_product([range(5), ['a', 'b', 'c']])) expected = s.loc[:, 'a':'c'] result = s.loc[0:4, 'a':'c'] tm.assert_series_equal(result, expected) tm.assert_series_equal(result, expected) result = s.loc[:4, 'a':'c'] tm.assert_series_equal(result, expected) tm.assert_series_equal(result, expected) result = s.loc[0:, 'a':'c'] tm.assert_series_equal(result, expected) tm.assert_series_equal(result, expected) s = pd.Series(np.arange(15, dtype='int64'), MultiIndex.from_product([range(5), ['a', 'b', 'c']])) expected = s.iloc[[6, 7, 8, 12, 13, 14]] result = s.loc[2:4:2, 'a':'c'] tm.assert_series_equal(result, expected) def test_multiindex_perf_warn(self): if sys.version_info < (2, 7): raise nose.SkipTest('python version < 2.7') df = DataFrame({'jim': [0, 0, 1, 1], 'joe': ['x', 'x', 'z', 'y'], 'jolie': np.random.rand(4)}).set_index(['jim', 'joe']) with tm.assert_produces_warning(PerformanceWarning, clear=[pd.core.index]): df.loc[(1, 'z')] df = df.iloc[[2, 1, 3, 0]] with tm.assert_produces_warning(PerformanceWarning): df.loc[(0, )] def test_series_getitem_multiindex(self): s = Series([1, 2, 3]) s.index = MultiIndex.from_tuples([(0, 0), (1, 1), (2, 1)]) result = s[:, 0] expected = Series([1], index=[0]) tm.assert_series_equal(result, expected) result = s.loc[:, 1] expected = Series([2, 3], index=[1, 2]) tm.assert_series_equal(result, expected) result = s.xs(0, level=0) expected = Series([1], index=[0]) tm.assert_series_equal(result, expected) result = s.xs(1, level=1) expected = Series([2, 3], index=[1, 2]) tm.assert_series_equal(result, expected) dt = list(date_range('20130903', periods=3)) idx = MultiIndex.from_product([list('AB'), dt]) s = Series([1, 3, 4, 1, 3, 4], index=idx) result = s.xs('20130903', level=1) expected = Series([1, 1], index=list('AB')) tm.assert_series_equal(result, expected) idx = MultiIndex.from_tuples([('a', 'one'), ('a', 'two'), ('b', 'one'), ('b', 'two')]) s = Series([1, 2, 3, 4], index=idx) s.index.set_names(['L1', 'L2'], inplace=True) result = s.xs('one', level='L2') expected = Series([1, 3], index=['a', 'b']) expected.index.set_names(['L1'], inplace=True) tm.assert_series_equal(result, expected) def test_ix_general(self): data = {'amount': {0: 700, 1: 600, 2: 222, 3: 333, 4: 444}, 'col': {0: 3.5, 1: 3.5, 2: 4.0, 3: 4.0, 4: 4.0}, 'year': {0: 2012, 1: 2011, 2: 2012, 3: 2012, 4: 2012}} df = DataFrame(data).set_index(keys=['col', 'year']) key = 4.0, 2012 with self.assert_produces_warning(PerformanceWarning): tm.assert_frame_equal(df.loc[key], df.iloc[2:]) df.sort_index(inplace=True) res = df.loc[key] index = MultiIndex.from_arrays([[4.] * 3, [2012] * 3], names=['col', 'year']) expected = DataFrame({'amount': [222, 333, 444]}, index=index) tm.assert_frame_equal(res, expected) def test_ix_weird_slicing(self): df = DataFrame({'one': [1, 2, 3, np.nan, np.nan], 'two': [1, 2, 3, 4, 5]}) df.loc[df['one'] > 1, 'two'] = -df['two'] expected = DataFrame({'one': {0: 1.0, 1: 2.0, 2: 3.0, 3: nan, 4: nan}, 'two': {0: 1, 1: -2, 2: -3, 3: 4, 4: 5}}) tm.assert_frame_equal(df, expected) def test_xs_multiindex(self): columns = MultiIndex.from_tuples( [('a', 'foo'), ('a', 'bar'), ('b', 'hello'), ('b', 'world')], names=['lvl0', 'lvl1']) df = DataFrame(np.random.randn(4, 4), columns=columns) df.sort_index(axis=1, inplace=True) result = df.xs('a', level='lvl0', axis=1) expected = df.iloc[:, 0:2].loc[:, 'a'] tm.assert_frame_equal(result, expected) result = df.xs('foo', level='lvl1', axis=1) expected = df.iloc[:, 1:2].copy() expected.columns = expected.columns.droplevel('lvl1') tm.assert_frame_equal(result, expected) def test_per_axis_per_level_getitem(self): ix = MultiIndex.from_product([_mklbl('A', 5), _mklbl('B', 7), _mklbl( 'C', 4), _mklbl('D', 2)]) df = DataFrame(np.arange(len(ix.get_values())), index=ix) result = df.loc[(slice('A1', 'A3'), slice(None), ['C1', 'C3']), :] expected = df.loc[[tuple([a, b, c, d]) for a, b, c, d in df.index.values if (a == 'A1' or a == 'A2' or a == 'A3') and ( c == 'C1' or c == 'C3')]] tm.assert_frame_equal(result, expected) expected = df.loc[[tuple([a, b, c, d]) for a, b, c, d in df.index.values if (a == 'A1' or a == 'A2' or a == 'A3') and ( c == 'C1' or c == 'C2' or c == 'C3')]] result = df.loc[(slice('A1', 'A3'), slice(None), slice('C1', 'C3')), :] tm.assert_frame_equal(result, expected) index = MultiIndex.from_tuples([('A', 1), ('A', 2), ('A', 3), ('B', 1)], names=['one', 'two']) columns = MultiIndex.from_tuples([('a', 'foo'), ('a', 'bar'), ('b', 'foo'), ('b', 'bah')], names=['lvl0', 'lvl1']) df = DataFrame( np.arange(16, dtype='int64').reshape( 4, 4), index=index, columns=columns) df = df.sort_index(axis=0).sort_index(axis=1) result = df.loc[(slice(None), slice(None)), :] tm.assert_frame_equal(result, df) result = df.loc[(slice(None), slice(None)), (slice(None), slice(None))] tm.assert_frame_equal(result, df) result = df.loc[:, (slice(None), slice(None))] tm.assert_frame_equal(result, df) result = df.loc[(slice(None), [1]), :] expected = df.iloc[[0, 3]] tm.assert_frame_equal(result, expected) result = df.loc[(slice(None), 1), :] expected = df.iloc[[0, 3]] tm.assert_frame_equal(result, expected) result = df.loc[:, (slice(None), ['foo'])] expected = df.iloc[:, [1, 3]] tm.assert_frame_equal(result, expected) result = df.loc[(slice(None), 1), (slice(None), ['foo'])] expected = df.iloc[[0, 3], [1, 3]] tm.assert_frame_equal(result, expected) result = df.loc['A', 'a'] expected = DataFrame(dict(bar=[1, 5, 9], foo=[0, 4, 8]), index=Index([1, 2, 3], name='two'), columns=Index(['bar', 'foo'], name='lvl1')) tm.assert_frame_equal(result, expected) result = df.loc[(slice(None), [1, 2]), :] expected = df.iloc[[0, 1, 3]] tm.assert_frame_equal(result, expected) s = Series(np.arange(len(ix.get_values())), index=ix) result = s.loc['A1':'A3', :, ['C1', 'C3']] expected = s.loc[[tuple([a, b, c, d]) for a, b, c, d in s.index.values if (a == 'A1' or a == 'A2' or a == 'A3') and ( c == 'C1' or c == 'C3')]] tm.assert_series_equal(result, expected) result = df.loc[(slice(None), df.loc[:, ('a', 'bar')] > 5), :] expected = df.iloc[[2, 3]] tm.assert_frame_equal(result, expected) def f(): df.loc[(slice(None), np.array([True, False])), :] self.assertRaises(ValueError, f) self.assertRaises(KeyError, lambda: df.loc[slice(None), [1]]) result = df.loc[(slice(None), [1]), :] expected = df.iloc[[0, 3]] tm.assert_frame_equal(result, expected) self.assertEqual(df.index.lexsort_depth, 2) df = df.sort_index(level=1, axis=0) self.assertEqual(df.index.lexsort_depth, 0) with tm.assertRaisesRegexp( UnsortedIndexError, 'MultiIndex Slicing requires the index to be fully ' r'lexsorted tuple len \(2\), lexsort depth \(0\)'): df.loc[(slice(None), df.loc[:, ('a', 'bar')] > 5), :] def test_multiindex_slicers_non_unique(self): df = (DataFrame(dict(A=['foo', 'foo', 'foo', 'foo'], B=['a', 'a', 'a', 'a'], C=[1, 2, 1, 3], D=[1, 2, 3, 4])) .set_index(['A', 'B', 'C']).sort_index()) self.assertFalse(df.index.is_unique) expected = (DataFrame(dict(A=['foo', 'foo'], B=['a', 'a'], C=[1, 1], D=[1, 3])) .set_index(['A', 'B', 'C']).sort_index()) result = df.loc[(slice(None), slice(None), 1), :] tm.assert_frame_equal(result, expected) result = df.xs(1, level=2, drop_level=False) tm.assert_frame_equal(result, expected) df = (DataFrame(dict(A=['foo', 'foo', 'foo', 'foo'], B=['a', 'a', 'a', 'a'], C=[1, 2, 1, 2], D=[1, 2, 3, 4])) .set_index(['A', 'B', 'C']).sort_index()) self.assertFalse(df.index.is_unique) expected = (DataFrame(dict(A=['foo', 'foo'], B=['a', 'a'], C=[1, 1], D=[1, 3])) .set_index(['A', 'B', 'C']).sort_index()) result = df.loc[(slice(None), slice(None), 1), :] self.assertFalse(result.index.is_unique) tm.assert_frame_equal(result, expected) ints = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 12, 13, 14, 14, 16, 17, 18, 19, 200000, 200000] n = len(ints) idx = MultiIndex.from_arrays([['a'] * n, ints]) result = Series([1] * n, index=idx) result = result.sort_index() result = result.loc[(slice(None), slice(100000))] expected = Series([1] * (n - 2), index=idx[:-2]).sort_index() tm.assert_series_equal(result, expected) def test_multiindex_slicers_datetimelike(self): import datetime dates = [datetime.datetime(2012, 1, 1, 12, 12, 12) + datetime.timedelta(days=i) for i in range(6)] freq = [1, 2] index = MultiIndex.from_product( [dates, freq], names=['date', 'frequency']) df = DataFrame( np.arange(6 * 2 * 4, dtype='int64').reshape( -1, 4), index=index, columns=list('ABCD')) idx = pd.IndexSlice expected = df.iloc[[0, 2, 4], [0, 1]] result = df.loc[(slice(Timestamp('2012-01-01 12:12:12'), Timestamp('2012-01-03 12:12:12')), slice(1, 1)), slice('A', 'B')] tm.assert_frame_equal(result, expected) result = df.loc[(idx[Timestamp('2012-01-01 12:12:12'):Timestamp( '2012-01-03 12:12:12')], idx[1:1]), slice('A', 'B')] tm.assert_frame_equal(result, expected) result = df.loc[(slice(Timestamp('2012-01-01 12:12:12'), Timestamp('2012-01-03 12:12:12')), 1), slice('A', 'B')] tm.assert_frame_equal(result, expected) result = df.loc[(slice('2012-01-01 12:12:12', '2012-01-03 12:12:12'), slice(1, 1)), slice('A', 'B')] tm.assert_frame_equal(result, expected) result = df.loc[(idx['2012-01-01 12:12:12':'2012-01-03 12:12:12'], 1), idx['A', 'B']] tm.assert_frame_equal(result, expected) def test_multiindex_slicers_edges(self): df = DataFrame( {'A': ['A0'] * 5 + ['A1'] * 5 + ['A2'] * 5, 'B': ['B0', 'B0', 'B1', 'B1', 'B2'] * 3, 'DATE': ["2013-06-11", "2013-07-02", "2013-07-09", "2013-07-30", "2013-08-06", "2013-06-11", "2013-07-02", "2013-07-09", "2013-07-30", "2013-08-06", "2013-09-03", "2013-10-01", "2013-07-09", "2013-08-06", "2013-09-03"], 'VALUES': [22, 35, 14, 9, 4, 40, 18, 4, 2, 5, 1, 2, 3, 4, 2]}) df['DATE'] = pd.to_datetime(df['DATE']) df1 = df.set_index(['A', 'B', 'DATE']) df1 = df1.sort_index() result = df1.loc[(slice('A1')), :] expected = df1.iloc[0:10] tm.assert_frame_equal(result, expected) result = df1.loc[(slice('A2')), :] expected = df1 tm.assert_frame_equal(result, expected) result = df1.loc[(slice(None), slice('B1', 'B2')), :] expected = df1.iloc[[2, 3, 4, 7, 8, 9, 12, 13, 14]] tm.assert_frame_equal(result, expected) result = df1.loc[(slice(None), slice(None), slice('20130702', '20130709')), :] expected = df1.iloc[[1, 2, 6, 7, 12]] tm.assert_frame_equal(result, expected) result = df1.loc[(slice('A2'), slice('B0')), :] expected = df1.iloc[[0, 1, 5, 6, 10, 11]] tm.assert_frame_equal(result, expected) result = df1.loc[(slice(None), slice('B2')), :] expected = df1 tm.assert_frame_equal(result, expected) result = df1.loc[(slice(None), slice('B1', 'B2'), slice('2013-08-06')), :] expected = df1.iloc[[2, 3, 4, 7, 8, 9, 12, 13]] tm.assert_frame_equal(result, expected) result = df1.loc[(slice(None), slice(None), slice('20130701', '20130709')), :] expected = df1.iloc[[1, 2, 6, 7, 12]] tm.assert_frame_equal(result, expected) def test_per_axis_per_level_doc_examples(self): idx = pd.IndexSlice index = MultiIndex.from_product([_mklbl('A', 4), _mklbl('B', 2), _mklbl('C', 4), _mklbl('D', 2)]) columns = MultiIndex.from_tuples([('a', 'foo'), ('a', 'bar'), ('b', 'foo'), ('b', 'bah')], names=['lvl0', 'lvl1']) df = DataFrame(np.arange(len(index) * len(columns), dtype='int64') .reshape((len(index), len(columns))), index=index, columns=columns) result = df.loc[(slice('A1', 'A3'), slice(None), ['C1', 'C3']), :] expected = df.loc[[tuple([a, b, c, d]) for a, b, c, d in df.index.values if (a == 'A1' or a == 'A2' or a == 'A3') and ( c == 'C1' or c == 'C3')]] tm.assert_frame_equal(result, expected) result = df.loc[idx['A1':'A3', :, ['C1', 'C3']], :] tm.assert_frame_equal(result, expected) result = df.loc[(slice(None), slice(None), ['C1', 'C3']), :] expected = df.loc[[tuple([a, b, c, d]) for a, b, c, d in df.index.values if (c == 'C1' or c == 'C3')]] tm.assert_frame_equal(result, expected) result = df.loc[idx[:, :, ['C1', 'C3']], :] tm.assert_frame_equal(result, expected) def f(): df.loc['A1', (slice(None), 'foo')] self.assertRaises(UnsortedIndexError, f) df = df.sort_index(axis=1) df.loc['A1', (slice(None), 'foo')] df.loc[(slice(None), slice(None), ['C1', 'C3']), (slice(None), 'foo')] df.loc(axis=0)[:, :, ['C1', 'C3']] = -10 def test_loc_axis_arguments(self): index = MultiIndex.from_product([_mklbl('A', 4), _mklbl('B', 2), _mklbl('C', 4), _mklbl('D', 2)]) columns = MultiIndex.from_tuples([('a', 'foo'), ('a', 'bar'), ('b', 'foo'), ('b', 'bah')], names=['lvl0', 'lvl1']) df = DataFrame(np.arange(len(index) * len(columns), dtype='int64') .reshape((len(index), len(columns))), index=index, columns=columns).sort_index().sort_index(axis=1) result = df.loc(axis=0)['A1':'A3', :, ['C1', 'C3']] expected = df.loc[[tuple([a, b, c, d]) for a, b, c, d in df.index.values if (a == 'A1' or a == 'A2' or a == 'A3') and ( c == 'C1' or c == 'C3')]] tm.assert_frame_equal(result, expected) result = df.loc(axis='index')[:, :, ['C1', 'C3']] expected = df.loc[[tuple([a, b, c, d]) for a, b, c, d in df.index.values if (c == 'C1' or c == 'C3')]] tm.assert_frame_equal(result, expected) result = df.loc(axis=1)[:, 'foo'] expected = df.loc[:, (slice(None), 'foo')] tm.assert_frame_equal(result, expected) result = df.loc(axis='columns')[:, 'foo'] expected = df.loc[:, (slice(None), 'foo')] tm.assert_frame_equal(result, expected) def f(): df.loc(axis=-1)[:, :, ['C1', 'C3']] self.assertRaises(ValueError, f) def f(): df.loc(axis=2)[:, :, ['C1', 'C3']] self.assertRaises(ValueError, f) def f(): df.loc(axis='foo')[:, :, ['C1', 'C3']] self.assertRaises(ValueError, f) def test_loc_coerceion(self): df = DataFrame({'date': [pd.Timestamp('20130101').tz_localize('UTC'), pd.NaT]}) expected = df.dtypes result = df.iloc[[0]] tm.assert_series_equal(result.dtypes, expected) result = df.iloc[[1]] tm.assert_series_equal(result.dtypes, expected) import datetime df = DataFrame({'date': [datetime.datetime(2012, 1, 1), datetime.datetime(1012, 1, 2)]}) expected = df.dtypes result = df.iloc[[0]] tm.assert_series_equal(result.dtypes, expected) result = df.iloc[[1]] tm.assert_series_equal(result.dtypes, expected) df = DataFrame({'text': ['some words'] + [None] * 9}) expected = df.dtypes result = df.iloc[0:2] tm.assert_series_equal(result.dtypes, expected) result = df.iloc[3:] tm.assert_series_equal(result.dtypes, expected) def test_per_axis_per_level_setitem(self): idx = pd.IndexSlice index = MultiIndex.from_tuples([('A', 1), ('A', 2), ('A', 3), ('B', 1)], names=['one', 'two']) columns = MultiIndex.from_tuples([('a', 'foo'), ('a', 'bar'), ('b', 'foo'), ('b', 'bah')], names=['lvl0', 'lvl1']) df_orig = DataFrame( np.arange(16, dtype='int64').reshape( 4, 4), index=index, columns=columns) df_orig = df_orig.sort_index(axis=0).sort_index(axis=1) df = df_orig.copy() df.loc[(slice(None), slice(None)), :] = 100 expected = df_orig.copy() expected.iloc[:, :] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc(axis=0)[:, :] = 100 expected = df_orig.copy() expected.iloc[:, :] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc[(slice(None), slice(None)), (slice(None), slice(None))] = 100 expected = df_orig.copy() expected.iloc[:, :] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc[:, (slice(None), slice(None))] = 100 expected = df_orig.copy() expected.iloc[:, :] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc[(slice(None), [1]), :] = 100 expected = df_orig.copy() expected.iloc[[0, 3]] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc[(slice(None), 1), :] = 100 expected = df_orig.copy() expected.iloc[[0, 3]] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc(axis=0)[:, 1] = 100 expected = df_orig.copy() expected.iloc[[0, 3]] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc[:, (slice(None), ['foo'])] = 100 expected = df_orig.copy() expected.iloc[:, [1, 3]] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc[(slice(None), 1), (slice(None), ['foo'])] = 100 expected = df_orig.copy() expected.iloc[[0, 3], [1, 3]] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc[idx[:, 1], idx[:, ['foo']]] = 100 expected = df_orig.copy() expected.iloc[[0, 3], [1, 3]] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc['A', 'a'] = 100 expected = df_orig.copy() expected.iloc[0:3, 0:2] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc[(slice(None), 1), (slice(None), ['foo'])] = np.array( [[100, 100], [100, 100]], dtype='int64') expected = df_orig.copy() expected.iloc[[0, 3], [1, 3]] = 100 tm.assert_frame_equal(df, expected) df = df_orig.copy() def f(): df.loc[(slice(None), 1), (slice(None), ['foo'])] = np.array( [[100], [100, 100]], dtype='int64') self.assertRaises(ValueError, f) def f(): df.loc[(slice(None), 1), (slice(None), ['foo'])] = np.array( [100, 100, 100, 100], dtype='int64') self.assertRaises(ValueError, f) df = df_orig.copy() df.loc[(slice(None), 1), (slice(None), ['foo'])] = df.loc[(slice( None), 1), (slice(None), ['foo'])] * 5 expected = df_orig.copy() expected.iloc[[0, 3], [1, 3]] = expected.iloc[[0, 3], [1, 3]] * 5 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc[(slice(None), 1), (slice(None), ['foo'])] *= df.loc[(slice( None), 1), (slice(None), ['foo'])] expected = df_orig.copy() expected.iloc[[0, 3], [1, 3]] *= expected.iloc[[0, 3], [1, 3]] tm.assert_frame_equal(df, expected) rhs = df_orig.loc[(slice(None), 1), (slice(None), ['foo'])].copy() rhs.loc[:, ('c', 'bah')] = 10 df = df_orig.copy() df.loc[(slice(None), 1), (slice(None), ['foo'])] *= rhs expected = df_orig.copy() expected.iloc[[0, 3], [1, 3]] *= expected.iloc[[0, 3], [1, 3]] tm.assert_frame_equal(df, expected) def test_multiindex_setitem(self): arrays = [np.array(['bar', 'bar', 'baz', 'qux', 'qux', 'bar']), np.array(['one', 'two', 'one', 'one', 'two', 'one']), np.arange(0, 6, 1)] df_orig = pd.DataFrame(np.random.randn(6, 3), index=arrays, columns=['A', 'B', 'C']).sort_index() expected = df_orig.loc[['bar']] * 2 df = df_orig.copy() df.loc[['bar']] *= 2 tm.assert_frame_equal(df.loc[['bar']], expected) def f(): df.loc['bar'] *= 2 self.assertRaises(TypeError, f) df_orig = DataFrame.from_dict({'price': { ('DE', 'Coal', 'Stock'): 2, ('DE', 'Gas', 'Stock'): 4, ('DE', 'Elec', 'Demand'): 1, ('FR', 'Gas', 'Stock'): 5, ('FR', 'Solar', 'SupIm'): 0, ('FR', 'Wind', 'SupIm'): 0 }}) df_orig.index = MultiIndex.from_tuples(df_orig.index, names=['Sit', 'Com', 'Type']) expected = df_orig.copy() expected.iloc[[0, 2, 3]] *= 2 idx = pd.IndexSlice df = df_orig.copy() df.loc[idx[:, :, 'Stock'], :] *= 2 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc[idx[:, :, 'Stock'], 'price'] *= 2 tm.assert_frame_equal(df, expected) def test_getitem_multiindex(self): # the appropriate error, only in PY3 of course! index = MultiIndex(levels=[['D', 'B', 'C'], [0, 26, 27, 37, 57, 67, 75, 82]], labels=[[0, 0, 0, 1, 2, 2, 2, 2, 2, 2], [1, 3, 4, 6, 0, 2, 2, 3, 5, 7]], names=['tag', 'day']) arr = np.random.randn(len(index), 1) df = DataFrame(arr, index=index, columns=['val']) result = df.val['D'] expected = Series(arr.ravel()[0:3], name='val', index=Index( [26, 37, 57], name='day')) tm.assert_series_equal(result, expected) def f(): df.val['A'] self.assertRaises(KeyError, f) def f(): df.val['X'] self.assertRaises(KeyError, f) # A is treated as a special Timestamp index = MultiIndex(levels=[['A', 'B', 'C'], [0, 26, 27, 37, 57, 67, 75, 82]], labels=[[0, 0, 0, 1, 2, 2, 2, 2, 2, 2], [1, 3, 4, 6, 0, 2, 2, 3, 5, 7]], names=['tag', 'day']) df = DataFrame(arr, index=index, columns=['val']) result = df.val['A'] expected = Series(arr.ravel()[0:3], name='val', index=Index( [26, 37, 57], name='day')) tm.assert_series_equal(result, expected) def f(): df.val['X'] self.assertRaises(KeyError, f) # GH 7866 # multi-index slicing with missing indexers idx = pd.MultiIndex.from_product([['A', 'B', 'C'], ['foo', 'bar', 'baz']], names=['one', 'two']) s = pd.Series(np.arange(9, dtype='int64'), index=idx).sort_index() exp_idx = pd.MultiIndex.from_product([['A'], ['foo', 'bar', 'baz']], names=['one', 'two']) expected = pd.Series(np.arange(3, dtype='int64'), index=exp_idx).sort_index() result = s.loc[['A']] tm.assert_series_equal(result, expected) result = s.loc[['A', 'D']] tm.assert_series_equal(result, expected) # not any values found self.assertRaises(KeyError, lambda: s.loc[['D']]) # empty ok result = s.loc[[]] expected = s.iloc[[]] tm.assert_series_equal(result, expected) idx = pd.IndexSlice expected = pd.Series([0, 3, 6], index=pd.MultiIndex.from_product( [['A', 'B', 'C'], ['foo']], names=['one', 'two'])).sort_index() result = s.loc[idx[:, ['foo']]] tm.assert_series_equal(result, expected) result = s.loc[idx[:, ['foo', 'bah']]] tm.assert_series_equal(result, expected) # GH 8737 # empty indexer multi_index = pd.MultiIndex.from_product((['foo', 'bar', 'baz'], ['alpha', 'beta'])) df = DataFrame( np.random.randn(5, 6), index=range(5), columns=multi_index) df = df.sort_index(level=0, axis=1) expected = DataFrame(index=range(5), columns=multi_index.reindex([])[0]) result1 = df.loc[:, ([], slice(None))] result2 = df.loc[:, (['foo'], [])] tm.assert_frame_equal(result1, expected) tm.assert_frame_equal(result2, expected) # regression from < 0.14.0 # GH 7914 df = DataFrame([[np.mean, np.median], ['mean', 'median']], columns=MultiIndex.from_tuples([('functs', 'mean'), ('functs', 'median')]), index=['function', 'name']) result = df.loc['function', ('functs', 'mean')] self.assertEqual(result, np.mean) def test_setitem_dtype_upcast(self): # GH3216 df = DataFrame([{"a": 1}, {"a": 3, "b": 2}]) df['c'] = np.nan self.assertEqual(df['c'].dtype, np.float64) df.loc[0, 'c'] = 'foo' expected = DataFrame([{"a": 1, "c": 'foo'}, {"a": 3, "b": 2, "c": np.nan}]) tm.assert_frame_equal(df, expected) # GH10280 df = DataFrame(np.arange(6, dtype='int64').reshape(2, 3), index=list('ab'), columns=['foo', 'bar', 'baz']) for val in [3.14, 'wxyz']: left = df.copy() left.loc['a', 'bar'] = val right = DataFrame([[0, val, 2], [3, 4, 5]], index=list('ab'), columns=['foo', 'bar', 'baz']) tm.assert_frame_equal(left, right) self.assertTrue(is_integer_dtype(left['foo'])) self.assertTrue(is_integer_dtype(left['baz'])) left = DataFrame(np.arange(6, dtype='int64').reshape(2, 3) / 10.0, index=list('ab'), columns=['foo', 'bar', 'baz']) left.loc['a', 'bar'] = 'wxyz' right = DataFrame([[0, 'wxyz', .2], [.3, .4, .5]], index=list('ab'), columns=['foo', 'bar', 'baz']) tm.assert_frame_equal(left, right) self.assertTrue(is_float_dtype(left['foo'])) self.assertTrue(is_float_dtype(left['baz'])) def test_setitem_iloc(self): # setitem with an iloc list df = DataFrame(np.arange(9).reshape((3, 3)), index=["A", "B", "C"], columns=["A", "B", "C"]) df.iloc[[0, 1], [1, 2]] df.iloc[[0, 1], [1, 2]] += 100 expected = DataFrame( np.array([0, 101, 102, 3, 104, 105, 6, 7, 8]).reshape((3, 3)), index=["A", "B", "C"], columns=["A", "B", "C"]) tm.assert_frame_equal(df, expected) def test_dups_fancy_indexing(self): # GH 3455 from pandas.util.testing import makeCustomDataframe as mkdf df = mkdf(10, 3) df.columns = ['a', 'a', 'b'] result = df[['b', 'a']].columns expected = Index(['b', 'a', 'a']) self.assert_index_equal(result, expected) # across dtypes df = DataFrame([[1, 2, 1., 2., 3., 'foo', 'bar']], columns=list('aaaaaaa')) df.head() str(df) result = DataFrame([[1, 2, 1., 2., 3., 'foo', 'bar']]) result.columns = list('aaaaaaa') # TODO(wesm): unused? df_v = df.iloc[:, 4] # noqa res_v = result.iloc[:, 4] # noqa tm.assert_frame_equal(df, result) # GH 3561, dups not in selected order df = DataFrame( {'test': [5, 7, 9, 11], 'test1': [4., 5, 6, 7], 'other': list('abcd')}, index=['A', 'A', 'B', 'C']) rows = ['C', 'B'] expected = DataFrame( {'test': [11, 9], 'test1': [7., 6], 'other': ['d', 'c']}, index=rows) result = df.loc[rows] tm.assert_frame_equal(result, expected) result = df.loc[Index(rows)] tm.assert_frame_equal(result, expected) rows = ['C', 'B', 'E'] expected = DataFrame( {'test': [11, 9, np.nan], 'test1': [7., 6, np.nan], 'other': ['d', 'c', np.nan]}, index=rows) result = df.loc[rows] tm.assert_frame_equal(result, expected) # see GH5553, make sure we use the right indexer rows = ['F', 'G', 'H', 'C', 'B', 'E'] expected = DataFrame({'test': [np.nan, np.nan, np.nan, 11, 9, np.nan], 'test1': [np.nan, np.nan, np.nan, 7., 6, np.nan], 'other': [np.nan, np.nan, np.nan, 'd', 'c', np.nan]}, index=rows) result = df.loc[rows] tm.assert_frame_equal(result, expected) # inconsistent returns for unique/duplicate indices when values are # missing df = DataFrame(randn(4, 3), index=list('ABCD')) expected = df.ix[['E']] dfnu = DataFrame(randn(5, 3), index=list('AABCD')) result = dfnu.ix[['E']] tm.assert_frame_equal(result, expected) # ToDo: check_index_type can be True after GH 11497 # GH 4619; duplicate indexer with missing label df = DataFrame({"A": [0, 1, 2]}) result = df.ix[[0, 8, 0]] expected = DataFrame({"A": [0, np.nan, 0]}, index=[0, 8, 0]) tm.assert_frame_equal(result, expected, check_index_type=False) df = DataFrame({"A": list('abc')}) result = df.ix[[0, 8, 0]] expected = DataFrame({"A": ['a', np.nan, 'a']}, index=[0, 8, 0]) tm.assert_frame_equal(result, expected, check_index_type=False) # non unique with non unique selector df = DataFrame({'test': [5, 7, 9, 11]}, index=['A', 'A', 'B', 'C']) expected = DataFrame( {'test': [5, 7, 5, 7, np.nan]}, index=['A', 'A', 'A', 'A', 'E']) result = df.ix[['A', 'A', 'E']] tm.assert_frame_equal(result, expected) # GH 5835 # dups on index and missing values df = DataFrame( np.random.randn(5, 5), columns=['A', 'B', 'B', 'B', 'A']) expected = pd.concat( [df.ix[:, ['A', 'B']], DataFrame(np.nan, columns=['C'], index=df.index)], axis=1) result = df.ix[:, ['A', 'B', 'C']] tm.assert_frame_equal(result, expected) # GH 6504, multi-axis indexing df = DataFrame(np.random.randn(9, 2), index=[1, 1, 1, 2, 2, 2, 3, 3, 3], columns=['a', 'b']) expected = df.iloc[0:6] result = df.loc[[1, 2]] tm.assert_frame_equal(result, expected) expected = df result = df.loc[:, ['a', 'b']] tm.assert_frame_equal(result, expected) expected = df.iloc[0:6, :] result = df.loc[[1, 2], ['a', 'b']] tm.assert_frame_equal(result, expected) def test_indexing_mixed_frame_bug(self): # GH3492 df = DataFrame({'a': {1: 'aaa', 2: 'bbb', 3: 'ccc'}, 'b': {1: 111, 2: 222, 3: 333}}) # this works, new column is created correctly df['test'] = df['a'].apply(lambda x: '_' if x == 'aaa' else x) # this does not work, ie column test is not changed idx = df['test'] == '_' temp = df.ix[idx, 'a'].apply(lambda x: '-----' if x == 'aaa' else x) df.ix[idx, 'test'] = temp self.assertEqual(df.iloc[0, 2], '-----') # if I look at df, then element [0,2] equals '_'. If instead I type # df.ix[idx,'test'], I get '-----', finally by typing df.iloc[0,2] I # get '_'. def test_multitype_list_index_access(self): # GH 10610 df = pd.DataFrame(np.random.random((10, 5)), columns=["a"] + [20, 21, 22, 23]) with self.assertRaises(KeyError): df[[22, 26, -8]] self.assertEqual(df[21].shape[0], df.shape[0]) def test_set_index_nan(self): # GH 3586 df = DataFrame({'PRuid': {17: 'nonQC', 18: 'nonQC', 19: 'nonQC', 20: '10', 21: '11', 22: '12', 23: '13', 24: '24', 25: '35', 26: '46', 27: '47', 28: '48', 29: '59', 30: '10'}, 'QC': {17: 0.0, 18: 0.0, 19: 0.0, 20: nan, 21: nan, 22: nan, 23: nan, 24: 1.0, 25: nan, 26: nan, 27: nan, 28: nan, 29: nan, 30: nan}, 'data': {17: 7.9544899999999998, 18: 8.0142609999999994, 19: 7.8591520000000008, 20: 0.86140349999999999, 21: 0.87853110000000001, 22: 0.8427041999999999, 23: 0.78587700000000005, 24: 0.73062459999999996, 25: 0.81668560000000001, 26: 0.81927080000000008, 27: 0.80705009999999999, 28: 0.81440240000000008, 29: 0.80140849999999997, 30: 0.81307740000000006}, 'year': {17: 2006, 18: 2007, 19: 2008, 20: 1985, 21: 1985, 22: 1985, 23: 1985, 24: 1985, 25: 1985, 26: 1985, 27: 1985, 28: 1985, 29: 1985, 30: 1986}}).reset_index() result = df.set_index(['year', 'PRuid', 'QC']).reset_index().reindex( columns=df.columns) tm.assert_frame_equal(result, df) def test_multi_nan_indexing(self): # GH 3588 df = DataFrame({"a": ['R1', 'R2', np.nan, 'R4'], 'b': ["C1", "C2", "C3", "C4"], "c": [10, 15, np.nan, 20]}) result = df.set_index(['a', 'b'], drop=False) expected = DataFrame({"a": ['R1', 'R2', np.nan, 'R4'], 'b': ["C1", "C2", "C3", "C4"], "c": [10, 15, np.nan, 20]}, index=[Index(['R1', 'R2', np.nan, 'R4'], name='a'), Index(['C1', 'C2', 'C3', 'C4'], name='b')]) tm.assert_frame_equal(result, expected) def test_iloc_panel_issue(self): # GH 3617 p = Panel(randn(4, 4, 4)) self.assertEqual(p.iloc[:3, :3, :3].shape, (3, 3, 3)) self.assertEqual(p.iloc[1, :3, :3].shape, (3, 3)) self.assertEqual(p.iloc[:3, 1, :3].shape, (3, 3)) self.assertEqual(p.iloc[:3, :3, 1].shape, (3, 3)) self.assertEqual(p.iloc[1, 1, :3].shape, (3, )) self.assertEqual(p.iloc[1, :3, 1].shape, (3, )) self.assertEqual(p.iloc[:3, 1, 1].shape, (3, )) def test_panel_getitem(self): # GH4016, date selection returns a frame when a partial string # selection ind = date_range(start="2000", freq="D", periods=1000) df = DataFrame( np.random.randn( len(ind), 5), index=ind, columns=list('ABCDE')) panel = Panel(dict([('frame_' + c, df) for c in list('ABC')])) test2 = panel.ix[:, "2002":"2002-12-31"] test1 = panel.ix[:, "2002"] tm.assert_panel_equal(test1, test2) # GH8710 # multi-element getting with a list panel = tm.makePanel() expected = panel.iloc[[0, 1]] result = panel.loc[['ItemA', 'ItemB']] tm.assert_panel_equal(result, expected) result = panel.loc[['ItemA', 'ItemB'], :, :] tm.assert_panel_equal(result, expected) result = panel[['ItemA', 'ItemB']] tm.assert_panel_equal(result, expected) result = panel.loc['ItemA':'ItemB'] tm.assert_panel_equal(result, expected) result = panel.ix['ItemA':'ItemB'] tm.assert_panel_equal(result, expected) result = panel.ix[['ItemA', 'ItemB']] tm.assert_panel_equal(result, expected) # with an object-like # GH 9140 class TestObject: def __str__(self): return "TestObject" obj = TestObject() p = Panel(np.random.randn(1, 5, 4), items=[obj], major_axis=date_range('1/1/2000', periods=5), minor_axis=['A', 'B', 'C', 'D']) expected = p.iloc[0] result = p[obj] tm.assert_frame_equal(result, expected) def test_panel_setitem(self): # GH 7763 # loc and setitem have setting differences np.random.seed(0) index = range(3) columns = list('abc') panel = Panel({'A': DataFrame(np.random.randn(3, 3), index=index, columns=columns), 'B': DataFrame(np.random.randn(3, 3), index=index, columns=columns), 'C': DataFrame(np.random.randn(3, 3), index=index, columns=columns)}) replace = DataFrame(np.eye(3, 3), index=range(3), columns=columns) expected = Panel({'A': replace, 'B': replace, 'C': replace}) p = panel.copy() for idx in list('ABC'): p[idx] = replace tm.assert_panel_equal(p, expected) p = panel.copy() for idx in list('ABC'): p.loc[idx, :, :] = replace tm.assert_panel_equal(p, expected) def test_panel_setitem_with_multiindex(self): # 10360 # failing with a multi-index arr = np.array([[[1, 2, 3], [0, 0, 0]], [[0, 0, 0], [0, 0, 0]]], dtype=np.float64) # reg index axes = dict(items=['A', 'B'], major_axis=[0, 1], minor_axis=['X', 'Y', 'Z']) p1 = Panel(0., **axes) p1.iloc[0, 0, :] = [1, 2, 3] expected = Panel(arr, **axes) tm.assert_panel_equal(p1, expected) # multi-indexes axes['items'] = pd.MultiIndex.from_tuples([('A', 'a'), ('B', 'b')]) p2 = Panel(0., **axes) p2.iloc[0, 0, :] = [1, 2, 3] expected = Panel(arr, **axes) tm.assert_panel_equal(p2, expected) axes['major_axis'] = pd.MultiIndex.from_tuples([('A', 1), ('A', 2)]) p3 = Panel(0., **axes) p3.iloc[0, 0, :] = [1, 2, 3] expected = Panel(arr, **axes) tm.assert_panel_equal(p3, expected) axes['minor_axis'] = pd.MultiIndex.from_product([['X'], range(3)]) p4 = Panel(0., **axes) p4.iloc[0, 0, :] = [1, 2, 3] expected = Panel(arr, **axes) tm.assert_panel_equal(p4, expected) arr = np.array( [[[1, 0, 0], [2, 0, 0]], [[0, 0, 0], [0, 0, 0]]], dtype=np.float64) p5 = Panel(0., **axes) p5.iloc[0, :, 0] = [1, 2] expected = Panel(arr, **axes) tm.assert_panel_equal(p5, expected) def test_panel_assignment(self): # GH3777 wp = Panel(randn(2, 5, 4), items=['Item1', 'Item2'], major_axis=date_range('1/1/2000', periods=5), minor_axis=['A', 'B', 'C', 'D']) wp2 = Panel(randn(2, 5, 4), items=['Item1', 'Item2'], major_axis=date_range('1/1/2000', periods=5), minor_axis=['A', 'B', 'C', 'D']) # TODO: unused? # expected = wp.loc[['Item1', 'Item2'], :, ['A', 'B']] def f(): wp.loc[['Item1', 'Item2'], :, ['A', 'B']] = wp2.loc[ ['Item1', 'Item2'], :, ['A', 'B']] self.assertRaises(NotImplementedError, f) # to_assign = wp2.loc[['Item1', 'Item2'], :, ['A', 'B']] # wp.loc[['Item1', 'Item2'], :, ['A', 'B']] = to_assign # result = wp.loc[['Item1', 'Item2'], :, ['A', 'B']] # tm.assert_panel_equal(result,expected) def test_multiindex_assignment(self): # GH3777 part 2 # mixed dtype df = DataFrame(np.random.randint(5, 10, size=9).reshape(3, 3), columns=list('abc'), index=[[4, 4, 8], [8, 10, 12]]) df['d'] = np.nan arr = np.array([0., 1.]) df.ix[4, 'd'] = arr tm.assert_series_equal(df.ix[4, 'd'], Series(arr, index=[8, 10], name='d')) # single dtype df = DataFrame(np.random.randint(5, 10, size=9).reshape(3, 3), columns=list('abc'), index=[[4, 4, 8], [8, 10, 12]]) df.ix[4, 'c'] = arr exp = Series(arr, index=[8, 10], name='c', dtype='float64') tm.assert_series_equal(df.ix[4, 'c'], exp) # scalar ok df.ix[4, 'c'] = 10 exp = Series(10, index=[8, 10], name='c', dtype='float64') tm.assert_series_equal(df.ix[4, 'c'], exp) # invalid assignments def f(): df.ix[4, 'c'] = [0, 1, 2, 3] self.assertRaises(ValueError, f) def f(): df.ix[4, 'c'] = [0] self.assertRaises(ValueError, f) # groupby example NUM_ROWS = 100 NUM_COLS = 10 col_names = ['A' + num for num in map(str, np.arange(NUM_COLS).tolist())] index_cols = col_names[:5] df = DataFrame(np.random.randint(5, size=(NUM_ROWS, NUM_COLS)), dtype=np.int64, columns=col_names) df = df.set_index(index_cols).sort_index() grp = df.groupby(level=index_cols[:4]) df['new_col'] = np.nan f_index = np.arange(5) def f(name, df2): return Series(np.arange(df2.shape[0]), name=df2.index.values[0]).reindex(f_index) # TODO(wesm): unused? # new_df = pd.concat([f(name, df2) for name, df2 in grp], axis=1).T # we are actually operating on a copy here # but in this case, that's ok for name, df2 in grp: new_vals = np.arange(df2.shape[0]) df.ix[name, 'new_col'] = new_vals def test_multi_assign(self): df = DataFrame({'FC': ['a', 'b', 'a', 'b', 'a', 'b'], 'PF': [0, 0, 0, 0, 1, 1], 'col1': lrange(6), 'col2': lrange(6, 12)}) df.ix[1, 0] = np.nan df2 = df.copy() mask = ~df2.FC.isnull() cols = ['col1', 'col2'] dft = df2 * 2 dft.ix[3, 3] = np.nan expected = DataFrame({'FC': ['a', np.nan, 'a', 'b', 'a', 'b'], 'PF': [0, 0, 0, 0, 1, 1], 'col1': Series([0, 1, 4, 6, 8, 10]), 'col2': [12, 7, 16, np.nan, 20, 22]}) df2.ix[mask, cols] = dft.ix[mask, cols] tm.assert_frame_equal(df2, expected) df2.ix[mask, cols] = dft.ix[mask, cols] tm.assert_frame_equal(df2, expected) df2 = df.copy() df2.ix[mask, cols] = dft.ix[mask, cols].values tm.assert_frame_equal(df2, expected) df2.ix[mask, cols] = dft.ix[mask, cols].values tm.assert_frame_equal(df2, expected) df = DataFrame(dict(A=[1, 2, 0, 0, 0], B=[0, 0, 0, 10, 11], C=[ 0, 0, 0, 10, 11], D=[3, 4, 5, 6, 7])) expected = df.copy() mask = expected['A'] == 0 for col in ['A', 'B']: expected.loc[mask, col] = df['D'] df.loc[df['A'] == 0, ['A', 'B']] = df['D'] tm.assert_frame_equal(df, expected) def test_ix_assign_column_mixed(self): df = DataFrame(tm.getSeriesData()) df['foo'] = 'bar' orig = df.ix[:, 'B'].copy() df.ix[:, 'B'] = df.ix[:, 'B'] + 1 tm.assert_series_equal(df.B, orig + 1) df = DataFrame({'x': lrange(10), 'y': lrange(10, 20), 'z': 'bar'}) expected = df.copy() for i in range(5): indexer = i * 2 v = 1000 + i * 200 expected.ix[indexer, 'y'] = v self.assertEqual(expected.ix[indexer, 'y'], v) df.ix[df.x % 2 == 0, 'y'] = df.ix[df.x % 2 == 0, 'y'] * 100 tm.assert_frame_equal(df, expected) df = DataFrame({'a': [1, 2, 3], 'b': [0, 1, 2]}) df.ix[[0, 2, ], 'b'] = [100, -100] expected = DataFrame({'a': [1, 2, 3], 'b': [100, 1, -100]}) tm.assert_frame_equal(df, expected) df = pd.DataFrame({'a': lrange(4)}) df['b'] = np.nan df.ix[[1, 3], 'b'] = [100, -100] expected = DataFrame({'a': [0, 1, 2, 3], 'b': [np.nan, 100, np.nan, -100]}) tm.assert_frame_equal(df, expected) with option_context('chained_assignment', None): df = pd.DataFrame({'a': lrange(4)}) df['b'] = np.nan df['b'].ix[[1, 3]] = [100, -100] tm.assert_frame_equal(df, expected) def test_ix_get_set_consistency(self): df = DataFrame(np.arange(16).reshape((4, 4)), columns=['a', 'b', 8, 'c'], index=['e', 7, 'f', 'g']) self.assertEqual(df.ix['e', 8], 2) self.assertEqual(df.loc['e', 8], 2) df.ix['e', 8] = 42 self.assertEqual(df.ix['e', 8], 42) self.assertEqual(df.loc['e', 8], 42) df.loc['e', 8] = 45 self.assertEqual(df.ix['e', 8], 45) self.assertEqual(df.loc['e', 8], 45) def test_setitem_list(self): df = DataFrame(index=[0, 1], columns=[0]) df.ix[1, 0] = [1, 2, 3] df.ix[1, 0] = [1, 2] result = DataFrame(index=[0, 1], columns=[0]) result.ix[1, 0] = [1, 2] tm.assert_frame_equal(result, df) class TO(object): def __init__(self, value): self.value = value def __str__(self): return "[{0}]".format(self.value) __repr__ = __str__ def __eq__(self, other): return self.value == other.value def view(self): return self df = DataFrame(index=[0, 1], columns=[0]) df.ix[1, 0] = TO(1) df.ix[1, 0] = TO(2) result = DataFrame(index=[0, 1], columns=[0]) result.ix[1, 0] = TO(2) tm.assert_frame_equal(result, df) df = DataFrame(index=[0, 1], columns=[0]) df.ix[1, 0] = TO(1) df.ix[1, 0] = np.nan result = DataFrame(index=[0, 1], columns=[0]) tm.assert_frame_equal(result, df) def test_iloc_mask(self): df = DataFrame(lrange(5), list('ABCDE'), columns=['a']) mask = (df.a % 2 == 0) self.assertRaises(ValueError, df.iloc.__getitem__, tuple([mask])) mask.index = lrange(len(mask)) self.assertRaises(NotImplementedError, df.iloc.__getitem__, tuple([mask])) result = df.iloc[np.array([True] * len(mask), dtype=bool)] tm.assert_frame_equal(result, df) locs = np.arange(4) nums = 2 ** locs reps = lmap(bin, nums) df = DataFrame({'locs': locs, 'nums': nums}, reps) expected = { (None, ''): '0b1100', (None, '.loc'): '0b1100', (None, '.iloc'): '0b1100', ('index', ''): '0b11', ('index', '.loc'): '0b11', ('index', '.iloc'): ('iLocation based boolean indexing ' 'cannot use an indexable as a mask'), ('locs', ''): 'Unalignable boolean Series provided as indexer ' '(index of the boolean Series and of the indexed ' 'object do not match', ('locs', '.loc'): 'Unalignable boolean Series provided as indexer ' '(index of the boolean Series and of the ' 'indexed object do not match', ('locs', '.iloc'): ('iLocation based boolean indexing on an ' 'integer type is not available'), } with warnings.catch_warnings(record=True): result = dict() for idx in [None, 'index', 'locs']: mask = (df.nums > 2).values if idx: mask = Series(mask, list(reversed(getattr(df, idx)))) for method in ['', '.loc', '.iloc']: try: if method: accessor = getattr(df, method[1:]) else: accessor = df ans = str(bin(accessor[mask]['nums'].sum())) except Exception as e: ans = str(e) key = tuple([idx, method]) r = expected.get(key) if r != ans: raise AssertionError( "[%s] does not match [%s], received [%s]" % (key, ans, r)) def test_ix_slicing_strings(self): data = {'Classification': ['SA EQUITY CFD', 'bbb', 'SA EQUITY', 'SA SSF', 'aaa'], 'Random': [1, 2, 3, 4, 5], 'X': ['correct', 'wrong', 'correct', 'correct', 'wrong']} df = DataFrame(data) x = df[~df.Classification.isin(['SA EQUITY CFD', 'SA EQUITY', 'SA SSF' ])] df.ix[x.index, 'X'] = df['Classification'] expected = DataFrame({'Classification': {0: 'SA EQUITY CFD', 1: 'bbb', 2: 'SA EQUITY', 3: 'SA SSF', 4: 'aaa'}, 'Random': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}, 'X': {0: 'correct', 1: 'bbb', 2: 'correct', 3: 'correct', 4: 'aaa'}}) tm.assert_frame_equal(df, expected) def test_non_unique_loc(self): taFrame({'A': [1, 2, 3, 4, 5, 6], 'B': [3, 4, 5, 6, 7, 8]}, index=[0, 1, 0, 1, 2, 3]) self.assertRaises(KeyError, df.loc.__getitem__, tuple([slice(1, None)])) self.assertRaises(KeyError, df.loc.__getitem__, tuple([slice(0, None)])) self.assertRaises(KeyError, df.loc.__getitem__, tuple([slice(1, 2)])) df = DataFrame({'A': [1, 2, 3, 4, 5, 6], 'B': [3, 4, 5, 6, 7, 8]}, index=[0, 1, 0, 1, 2, 3]).sort_index(axis=0) result = df.loc[1:] expected = DataFrame({'A': [2, 4, 5, 6], 'B': [4, 6, 7, 8]}, index=[1, 1, 2, 3]) tm.assert_frame_equal(result, expected) result = df.loc[0:] tm.assert_frame_equal(result, df) result = df.loc[1:2] expected = DataFrame({'A': [2, 4, 5], 'B': [4, 6, 7]}, index=[1, 1, 2]) tm.assert_frame_equal(result, expected) def test_loc_name(self): df = DataFrame([[1, 1], [1, 1]]) df.index.name = 'index_name' result = df.iloc[[0, 1]].index.name self.assertEqual(result, 'index_name') result = df.ix[[0, 1]].index.name self.assertEqual(result, 'index_name') result = df.loc[[0, 1]].index.name self.assertEqual(result, 'index_name') def test_iloc_non_unique_indexing(self): df = DataFrame({'A': [0.1] * 3000, 'B': [1] * 3000}) idx = np.array(lrange(30)) * 99 expected = df.iloc[idx] df3 = pd.concat([df, 2 * df, 3 * df]) result = df3.iloc[idx] tm.assert_frame_equal(result, expected) df2 = DataFrame({'A': [0.1] * 1000, 'B': [1] * 1000}) df2 = pd.concat([df2, 2 * df2, 3 * df2]) sidx = df2.index.to_series() expected = df2.iloc[idx[idx <= sidx.max()]] new_list = [] for r, s in expected.iterrows(): new_list.append(s) new_list.append(s * 2) new_list.append(s * 3) expected = DataFrame(new_list) expected = pd.concat([expected, DataFrame(index=idx[idx > sidx.max()]) ]) result = df2.loc[idx] tm.assert_frame_equal(result, expected, check_index_type=False) def test_string_slice(self): df = pd.DataFrame([1], pd.Index([pd.Timestamp('2011-01-01')], dtype=object)) self.assertTrue(df.index.is_all_dates) with tm.assertRaises(KeyError): df['2011'] with tm.assertRaises(KeyError): df.loc['2011', 0] df = pd.DataFrame() self.assertFalse(df.index.is_all_dates) with tm.assertRaises(KeyError): df['2011'] with tm.assertRaises(KeyError): df.loc['2011', 0] def test_mi_access(self): data = """h1 main h3 sub h5 0 a A 1 A1 1 1 b B 2 B1 2 2 c B 3 A1 3 3 d A 4 B2 4 4 e A 5 B2 5 5 f B 6 A2 6 """ df = pd.read_csv(StringIO(data), sep=r'\s+', index_col=0) df2 = df.set_index(['main', 'sub']).T.sort_index(1) index = Index(['h1', 'h3', 'h5']) columns = MultiIndex.from_tuples([('A', 'A1')], names=['main', 'sub']) expected = DataFrame([['a', 1, 1]], index=columns, columns=index).T result = df2.loc[:, ('A', 'A1')] tm.assert_frame_equal(result, expected) result = df2[('A', 'A1')] tm.assert_frame_equal(result, expected) expected = Series(['a', 1, 1], index=['h1', 'h3', 'h5'], name='A1') result = df2['A']['A1'] tm.assert_series_equal(result, expected) expected = DataFrame([['d', 4, 4], ['e', 5, 5]], index=Index(['B2', 'B2'], name='sub'), columns=['h1', 'h3', 'h5'], ).T result = df2['A']['B2'] tm.assert_frame_equal(result, expected) def test_non_unique_loc_memory_error(self): columns = list('ABCDEFG') def gen_test(l, l2): return pd.concat([DataFrame(randn(l, len(columns)), index=lrange(l), columns=columns), DataFrame(np.ones((l2, len(columns))), index=[0] * l2, columns=columns)]) def gen_expected(df, mask): l = len(mask) return pd.concat([df.take([0], convert=False), DataFrame(np.ones((l, len(columns))), index=[0] * l, columns=columns), df.take(mask[1:], convert=False)]) df = gen_test(900, 100) self.assertFalse(df.index.is_unique) mask = np.arange(100) result = df.loc[mask] expected = gen_expected(df, mask) tm.assert_frame_equal(result, expected) df = gen_test(900000, 100000) self.assertFalse(df.index.is_unique) mask = np.arange(100000) result = df.loc[mask] expected = gen_expected(df, mask) tm.assert_frame_equal(result, expected) def test_astype_assignment(self): df_orig = DataFrame([['1', '2', '3', '.4', 5, 6., 'foo']], columns=list('ABCDEFG')) df = df_orig.copy() df.iloc[:, 0:2] = df.iloc[:, 0:2].astype(np.int64) expected = DataFrame([[1, 2, '3', '.4', 5, 6., 'foo']], columns=list('ABCDEFG')) tm.assert_frame_equal(df, expected) df = df_orig.copy() df.iloc[:, 0:2] = df.iloc[:, 0:2]._convert(datetime=True, numeric=True) expected = DataFrame([[1, 2, '3', '.4', 5, 6., 'foo']], columns=list('ABCDEFG')) tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc[:, 'A'] = df.loc[:, 'A'].astype(np.int64) expected = DataFrame([[1, '2', '3', '.4', 5, 6., 'foo']], columns=list('ABCDEFG')) tm.assert_frame_equal(df, expected) df = df_orig.copy() df.loc[:, ['B', 'C']] = df.loc[:, ['B', 'C']].astype(np.int64) expected = DataFrame([['1', 2, 3, '.4', 5, 6., 'foo']], columns=list('ABCDEFG')) tm.assert_frame_equal(df, expected) df = DataFrame({'A': [1., 2., 3., 4.]}) df.iloc[:, 0] = df['A'].astype(np.int64) expected = DataFrame({'A': [1, 2, 3, 4]}) tm.assert_frame_equal(df, expected) df = DataFrame({'A': [1., 2., 3., 4.]}) df.loc[:, 'A'] = df['A'].astype(np.int64) expected = DataFrame({'A': [1, 2, 3, 4]}) tm.assert_frame_equal(df, expected) def test_astype_assignment_with_dups(self): cols = pd.MultiIndex.from_tuples([('A', '1'), ('B', '1'), ('A', '2')]) df = DataFrame(np.arange(3).reshape((1, 3)), columns=cols, dtype=object) index = df.index.copy() df['A'] = df['A'].astype(np.float64) self.assert_index_equal(df.index, index) def test_dups_loc(self): df = DataFrame([[1, 2, 'foo', 'bar', Timestamp('20130101')]], columns=['a', 'a', 'a', 'a', 'a'], index=[1]) expected = Series([1, 2, 'foo', 'bar', Timestamp('20130101')], index=['a', 'a', 'a', 'a', 'a'], name=1) result = df.iloc[0] tm.assert_series_equal(result, expected) result = df.loc[1] tm.assert_series_equal(result, expected) def test_partial_setting(self): s_orig = Series([1, 2, 3]) s = s_orig.copy() s[5] = 5 expected = Series([1, 2, 3, 5], index=[0, 1, 2, 5]) tm.assert_series_equal(s, expected) s = s_orig.copy() s.loc[5] = 5 expected = Series([1, 2, 3, 5], index=[0, 1, 2, 5]) tm.assert_series_equal(s, expected) s = s_orig.copy() s[5] = 5. expected = Series([1, 2, 3, 5.], index=[0, 1, 2, 5]) tm.assert_series_equal(s, expected) s = s_orig.copy() s.loc[5] = 5. expected = Series([1, 2, 3, 5.], index=[0, 1, 2, 5]) tm.assert_series_equal(s, expected) s = s_orig.copy() def f(): s.iloc[3] = 5. self.assertRaises(IndexError, f) def f(): s.iat[3] = 5. self.assertRaises(IndexError, f) Frame( np.arange(6).reshape(3, 2), columns=['A', 'B'], dtype='int64') df = df_orig.copy() def f(): df.iloc[4, 2] = 5. self.assertRaises(IndexError, f) def f(): df.iat[4, 2] = 5. self.assertRaises(IndexError, f) expected = DataFrame(dict({'A': [0, 4, 4], 'B': [1, 5, 5]})) df = df_orig.copy() df.iloc[1] = df.iloc[2] tm.assert_frame_equal(df, expected) expected = DataFrame(dict({'A': [0, 4, 4], 'B': [1, 5, 5]})) df = df_orig.copy() df.loc[1] = df.loc[2] tm.assert_frame_equal(df, expected) expected = DataFrame(dict({'A': [0, 2, 4, 4], 'B': [1, 3, 5, 5]})) df = df_orig.copy() df.loc[3] = df.loc[2] tm.assert_frame_equal(df, expected) expected = DataFrame(dict({'A': [0, 2, 4], 'B': [0, 2, 4]})) df = df_orig.copy() df.ix[:, 'B'] = df.ix[:, 'A'] tm.assert_frame_equal(df, expected) expected = DataFrame(dict({'A': [0, 2, 4], 'B': Series([0, 2, 4])})) df = df_orig.copy() df['B'] = df['B'].astype(np.float64) df.ix[:, 'B'] = df.ix[:, 'A'] tm.assert_frame_equal(df, expected) expected = df_orig.copy() expected['C'] = df['A'] df = df_orig.copy() df.ix[:, 'C'] = df.ix[:, 'A'] tm.assert_frame_equal(df, expected) expected = df_orig.copy() expected['C'] = df['A'] df = df_orig.copy() df.ix[:, 'C'] = df.ix[:, 'A'] tm.assert_frame_equal(df, expected) np.arange(16).reshape(2, 4, 2), items=['Item1', 'Item2'], major_axis=pd.date_range('2001/1/12', periods=4), minor_axis=['A', 'B'], dtype='float64') p_orig = Panel(np.arange(16).reshape(2, 4, 2), items=['Item1', 'Item2'], major_axis=pd.date_range('2001/1/12', periods=4), minor_axis=['A', 'B'], dtype='float64') expected = p_orig.copy() expected['Item3'] = expected['Item1'] p = p_orig.copy() p.loc['Item3'] = p['Item1'] tm.assert_panel_equal(p, expected) expected = p_orig.copy() expected = expected.transpose(2, 1, 0) expected['C'] = DataFrame({'Item1': [30, 30, 30, 30], 'Item2': [32, 32, 32, 32]}, index=p_orig.major_axis) expected = expected.transpose(2, 1, 0) p = p_orig.copy() p.loc[:, :, 'C'] = Series([30, 32], index=p_orig.items) tm.assert_panel_equal(p, expected) dates = date_range('1/1/2000', periods=8) df_orig = DataFrame(np.random.randn(8, 4), index=dates, columns=['A', 'B', 'C', 'D']) expected = pd.concat([df_orig, DataFrame( {'A': 7}, index=[dates[-1] + 1])]) df = df_orig.copy() df.loc[dates[-1] + 1, 'A'] = 7 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.at[dates[-1] + 1, 'A'] = 7 tm.assert_frame_equal(df, expected) exp_other = DataFrame({0: 7}, index=[dates[-1] + 1]) expected = pd.concat([df_orig, exp_other], axis=1) df = df_orig.copy() df.loc[dates[-1] + 1, 0] = 7 tm.assert_frame_equal(df, expected) df = df_orig.copy() df.at[dates[-1] + 1, 0] = 7 tm.assert_frame_equal(df, expected) def test_partial_setting_mixed_dtype(self): df = DataFrame([[True, 1], [False, 2]], columns=["female", "fitness"]) s = df.loc[1].copy() s.name = 2 expected = df.append(s) df.loc[2] = df.loc[1] tm.assert_frame_equal(df, expected) df = DataFrame(columns=['A', 'B']) df.loc[0] = Series(1, index=range(4)) tm.assert_frame_equal(df, DataFrame(columns=['A', 'B'], index=[0])) df = DataFrame(columns=['A', 'B']) df.loc[0] = Series(1, index=['B']) exp = DataFrame([[np.nan, 1]], columns=['A', 'B'], index=[0], dtype='float64') tm.assert_frame_equal(df, exp) df = DataFrame(columns=['A', 'B']) def f(): df.loc[0] = [1, 2, 3] self.assertRaises(ValueError, f) df = DataFrame(columns=['A', 'B']) df.loc[3] = [6, 7] exp = DataFrame([[6, 7]], index=[3], columns=['A', 'B'], dtype='float64') tm.assert_frame_equal(df, exp) def test_partial_setting_with_datetimelike_dtype(self): df = pd.DataFrame(np.arange(6.).reshape(3, 2), columns=list('AB'), index=pd.date_range('1/1/2000', periods=3, freq='1H')) expected = df.copy() expected['C'] = [expected.index[0]] + [pd.NaT, pd.NaT] mask = df.A < 1 df.loc[mask, 'C'] = df.loc[mask].index tm.assert_frame_equal(df, expected) def test_loc_setitem_datetime(self): dt1 = Timestamp('20130101 09:00:00') dt2 = Timestamp('20130101 10:00:00') for conv in [lambda x: x, lambda x: x.to_datetime64(), lambda x: x.to_pydatetime(), lambda x: np.datetime64(x)]: df = pd.DataFrame() df.loc[conv(dt1), 'one'] = 100 df.loc[conv(dt2), 'one'] = 200 expected = DataFrame({'one': [100.0, 200.0]}, index=[dt1, dt2]) tm.assert_frame_equal(df, expected) def test_series_partial_set(self): ser = Series([0.1, 0.2], index=[1, 2]) expected = Series([np.nan, 0.2, np.nan], index=[3, 2, 3]) result = ser.loc[[3, 2, 3]] tm.assert_series_equal(result, expected, check_index_type=True) expected = Series([np.nan, 0.2, np.nan, np.nan], index=[3, 2, 3, 'x']) result = ser.loc[[3, 2, 3, 'x']] tm.assert_series_equal(result, expected, check_index_type=True) expected = Series([0.2, 0.2, 0.1], index=[2, 2, 1]) result = ser.loc[[2, 2, 1]] tm.assert_series_equal(result, expected, check_index_type=True) expected = Series([0.2, 0.2, np.nan, 0.1], index=[2, 2, 'x', 1]) result = ser.loc[[2, 2, 'x', 1]] tm.assert_series_equal(result, expected, check_index_type=True) self.assertRaises(KeyError, lambda: ser.loc[[3, 3, 3]]) expected = Series([0.2, 0.2, np.nan], index=[2, 2, 3]) result = ser.loc[[2, 2, 3]] tm.assert_series_equal(result, expected, check_index_type=True) expected = Series([0.3, np.nan, np.nan], index=[3, 4, 4]) result = Series([0.1, 0.2, 0.3], index=[1, 2, 3]).loc[[3, 4, 4]] tm.assert_series_equal(result, expected, check_index_type=True) expected = Series([np.nan, 0.3, 0.3], index=[5, 3, 3]) result = Series([0.1, 0.2, 0.3, 0.4], index=[1, 2, 3, 4]).loc[[5, 3, 3]] tm.assert_series_equal(result, expected, check_index_type=True) expected = Series([np.nan, 0.4, 0.4], index=[5, 4, 4]) result = Series([0.1, 0.2, 0.3, 0.4], index=[1, 2, 3, 4]).loc[[5, 4, 4]] tm.assert_series_equal(result, expected, check_index_type=True) expected = Series([0.4, np.nan, np.nan], index=[7, 2, 2]) result = Series([0.1, 0.2, 0.3, 0.4], index=[4, 5, 6, 7]).loc[[7, 2, 2]] tm.assert_series_equal(result, expected, check_index_type=True) expected = Series([0.4, np.nan, np.nan], index=[4, 5, 5]) result = Series([0.1, 0.2, 0.3, 0.4], index=[1, 2, 3, 4]).loc[[4, 5, 5]] tm.assert_series_equal(result, expected, check_index_type=True) expected = Series([0.2, 0.2, 0.1, 0.1], index=[2, 2, 1, 1]) result = ser.iloc[[1, 1, 0, 0]] tm.assert_series_equal(result, expected, check_index_type=True) def test_series_partial_set_with_name(self): idx = Index([1, 2], dtype='int64', name='idx') ser = Series([0.1, 0.2], index=idx, name='s') exp_idx = Index([3, 2, 3], dtype='int64', name='idx') expected = Series([np.nan, 0.2, np.nan], index=exp_idx, name='s') result = ser.loc[[3, 2, 3]] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([3, 2, 3, 'x'], dtype='object', name='idx') expected = Series([np.nan, 0.2, np.nan, np.nan], index=exp_idx, name='s') result = ser.loc[[3, 2, 3, 'x']] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([2, 2, 1], dtype='int64', name='idx') expected = Series([0.2, 0.2, 0.1], index=exp_idx, name='s') result = ser.loc[[2, 2, 1]] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([2, 2, 'x', 1], dtype='object', name='idx') expected = Series([0.2, 0.2, np.nan, 0.1], index=exp_idx, name='s') result = ser.loc[[2, 2, 'x', 1]] tm.assert_series_equal(result, expected, check_index_type=True) self.assertRaises(KeyError, lambda: ser.loc[[3, 3, 3]]) exp_idx = Index([2, 2, 3], dtype='int64', name='idx') expected = Series([0.2, 0.2, np.nan], index=exp_idx, name='s') result = ser.loc[[2, 2, 3]] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([3, 4, 4], dtype='int64', name='idx') expected = Series([0.3, np.nan, np.nan], index=exp_idx, name='s') idx = Index([1, 2, 3], dtype='int64', name='idx') result = Series([0.1, 0.2, 0.3], index=idx, name='s').loc[[3, 4, 4]] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([5, 3, 3], dtype='int64', name='idx') expected = Series([np.nan, 0.3, 0.3], index=exp_idx, name='s') idx = Index([1, 2, 3, 4], dtype='int64', name='idx') result = Series([0.1, 0.2, 0.3, 0.4], index=idx, name='s').loc[[5, 3, 3]] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([5, 4, 4], dtype='int64', name='idx') expected = Series([np.nan, 0.4, 0.4], index=exp_idx, name='s') idx = Index([1, 2, 3, 4], dtype='int64', name='idx') result = Series([0.1, 0.2, 0.3, 0.4], index=idx, name='s').loc[[5, 4, 4]] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([7, 2, 2], dtype='int64', name='idx') expected = Series([0.4, np.nan, np.nan], index=exp_idx, name='s') idx = Index([4, 5, 6, 7], dtype='int64', name='idx') result = Series([0.1, 0.2, 0.3, 0.4], index=idx, name='s').loc[[7, 2, 2]] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([4, 5, 5], dtype='int64', name='idx') expected = Series([0.4, np.nan, np.nan], index=exp_idx, name='s') idx = Index([1, 2, 3, 4], dtype='int64', name='idx') result = Series([0.1, 0.2, 0.3, 0.4], index=idx, name='s').loc[[4, 5, 5]] tm.assert_series_equal(result, expected, check_index_type=True) exp_idx = Index([2, 2, 1, 1], dtype='int64', name='idx') expected = Series([0.2, 0.2, 0.1, 0.1], index=exp_idx, name='s') result = ser.iloc[[1, 1, 0, 0]] tm.assert_series_equal(result, expected, check_index_type=True) def test_series_partial_set_datetime(self): idx = date_range('2011-01-01', '2011-01-02', freq='D', name='idx') ser = Series([0.1, 0.2], index=idx, name='s') result = ser.loc[[Timestamp('2011-01-01'), Timestamp('2011-01-02')]] exp = Series([0.1, 0.2], index=idx, name='s') tm.assert_series_equal(result, exp, check_index_type=True) keys = [Timestamp('2011-01-02'), Timestamp('2011-01-02'), Timestamp('2011-01-01')] exp = Series([0.2, 0.2, 0.1], index=pd.DatetimeIndex(keys, name='idx'), name='s') tm.assert_series_equal(ser.loc[keys], exp, check_index_type=True) keys = [Timestamp('2011-01-03'), Timestamp('2011-01-02'), Timestamp('2011-01-03')] exp = Series([np.nan, 0.2, np.nan], index=pd.DatetimeIndex(keys, name='idx'), name='s') tm.assert_series_equal(ser.loc[keys], exp, check_index_type=True) def test_series_partial_set_period(self): idx = pd.period_range('2011-01-01', '2011-01-02', freq='D', name='idx') ser = Series([0.1, 0.2], index=idx, name='s') result = ser.loc[[pd.Period('2011-01-01', freq='D'), pd.Period('2011-01-02', freq='D')]] exp = Series([0.1, 0.2], index=idx, name='s') tm.assert_series_equal(result, exp, check_index_type=True) keys = [pd.Period('2011-01-02', freq='D'), pd.Period('2011-01-02', freq='D'), pd.Period('2011-01-01', freq='D')] exp = Series([0.2, 0.2, 0.1], index=pd.PeriodIndex(keys, name='idx'), name='s') tm.assert_series_equal(ser.loc[keys], exp, check_index_type=True) keys = [pd.Period('2011-01-03', freq='D'), pd.Period('2011-01-02', freq='D'), pd.Period('2011-01-03', freq='D')] exp = Series([np.nan, 0.2, np.nan], index=pd.PeriodIndex(keys, name='idx'), name='s') result = ser.loc[keys] tm.assert_series_equal(result, exp) def test_partial_set_invalid(self): orig = tm.makeTimeDataFrame() df = orig.copy() def f(): df.loc[100.0, :] = df.ix[0] self.assertRaises(TypeError, f) def f(): df.loc[100, :] = df.ix[0] self.assertRaises(TypeError, f) def f(): df.ix[100.0, :] = df.ix[0] self.assertRaises(TypeError, f) def f(): df.ix[100, :] = df.ix[0] self.assertRaises(ValueError, f) # allow object conversion here df = orig.copy() df.loc['a', :] = df.ix[0] exp = orig.append(pd.Series(df.ix[0], name='a')) tm.assert_frame_equal(df, exp) tm.assert_index_equal(df.index, pd.Index(orig.index.tolist() + ['a'])) self.assertEqual(df.index.dtype, 'object') def test_partial_set_empty_series(self): # GH5226 # partially set with an empty object series s = Series() s.loc[1] = 1 tm.assert_series_equal(s, Series([1], index=[1])) s.loc[3] = 3 tm.assert_series_equal(s, Series([1, 3], index=[1, 3])) s = Series() s.loc[1] = 1. tm.assert_series_equal(s, Series([1.], index=[1])) s.loc[3] = 3. tm.assert_series_equal(s, Series([1., 3.], index=[1, 3])) s = Series() s.loc['foo'] = 1 tm.assert_series_equal(s, Series([1], index=['foo'])) s.loc['bar'] = 3 tm.assert_series_equal(s, Series([1, 3], index=['foo', 'bar'])) s.loc[3] = 4 tm.assert_series_equal(s, Series([1, 3, 4], index=['foo', 'bar', 3])) def test_partial_set_empty_frame(self): # partially set with an empty object # frame df = DataFrame() def f(): df.loc[1] = 1 self.assertRaises(ValueError, f) def f(): df.loc[1] = Series([1], index=['foo']) self.assertRaises(ValueError, f) def f(): df.loc[:, 1] = 1 self.assertRaises(ValueError, f) # these work as they don't really change expected = DataFrame(columns=['foo'], index=pd.Index( [], dtype='int64')) def f(): df = DataFrame() df['foo'] = Series([], dtype='object') return df tm.assert_frame_equal(f(), expected) def f(): df = DataFrame() df['foo'] = Series(df.index) return df tm.assert_frame_equal(f(), expected) def f(): df = DataFrame() df['foo'] = df.index return df tm.assert_frame_equal(f(), expected) expected = DataFrame(columns=['foo'], index=pd.Index([], dtype='int64')) expected['foo'] = expected['foo'].astype('float64') def f(): df = DataFrame() df['foo'] = [] return df tm.assert_frame_equal(f(), expected) def f(): df = DataFrame() df['foo'] = Series(range(len(df))) return df tm.assert_frame_equal(f(), expected) def f(): df = DataFrame() tm.assert_index_equal(df.index, pd.Index([], dtype='object')) df['foo'] = range(len(df)) return df expected = DataFrame(columns=['foo'], index=pd.Index([], dtype='int64')) expected['foo'] = expected['foo'].astype('float64') tm.assert_frame_equal(f(), expected) df = DataFrame() tm.assert_index_equal(df.columns, pd.Index([], dtype=object)) df2 = DataFrame() df2[1] = Series([1], index=['foo']) df.loc[:, 1] = Series([1], index=['foo']) tm.assert_frame_equal(df, DataFrame([[1]], index=['foo'], columns=[1])) tm.assert_frame_equal(df, df2) expected = DataFrame({0: Series(1, index=range(4))}, columns=['A', 'B', 0]) df = DataFrame(columns=['A', 'B']) df[0] = Series(1, index=range(4)) df.dtypes str(df) tm.assert_frame_equal(df, expected) df = DataFrame(columns=['A', 'B']) df.loc[:, 0] = Series(1, index=range(4)) df.dtypes str(df) tm.assert_frame_equal(df, expected) def test_partial_set_empty_frame_row(self): expected = DataFrame(columns=['A', 'B', 'New'], index=pd.Index([], dtype='int64')) expected['A'] = expected['A'].astype('int64') expected['B'] = expected['B'].astype('float64') expected['New'] = expected['New'].astype('float64') df = DataFrame({"A": [1, 2, 3], "B": [1.2, 4.2, 5.2]}) y = df[df.A > 5] y['New'] = np.nan tm.assert_frame_equal(y, expected) # tm.assert_frame_equal(y,expected) expected = DataFrame(columns=['a', 'b', 'c c', 'd']) expected['d'] = expected['d'].astype('int64') df = DataFrame(columns=['a', 'b', 'c c']) df['d'] = 3 tm.assert_frame_equal(df, expected) tm.assert_series_equal(df['c c'], Series(name='c c', dtype=object)) # reindex columns is ok df = DataFrame({"A": [1, 2, 3], "B": [1.2, 4.2, 5.2]}) y = df[df.A > 5] result = y.reindex(columns=['A', 'B', 'C']) expected = DataFrame(columns=['A', 'B', 'C'], index=pd.Index([], dtype='int64')) expected['A'] = expected['A'].astype('int64') expected['B'] = expected['B'].astype('float64') expected['C'] = expected['C'].astype('float64') tm.assert_frame_equal(result, expected) def test_partial_set_empty_frame_set_series(self): # GH 5756 # setting with empty Series df = DataFrame(Series()) tm.assert_frame_equal(df, DataFrame({0: Series()})) df = DataFrame(Series(name='foo')) tm.assert_frame_equal(df, DataFrame({'foo': Series()})) def test_partial_set_empty_frame_empty_copy_assignment(self): # GH 5932 # copy on empty with assignment fails df = DataFrame(index=[0]) df = df.copy() df['a'] = 0 expected = DataFrame(0, index=[0], columns=['a']) tm.assert_frame_equal(df, expected) def test_partial_set_empty_frame_empty_consistencies(self): # GH 6171 # consistency on empty frames df = DataFrame(columns=['x', 'y']) df['x'] = [1, 2] expected = DataFrame(dict(x=[1, 2], y=[np.nan, np.nan])) tm.assert_frame_equal(df, expected, check_dtype=False) df = DataFrame(columns=['x', 'y']) df['x'] = ['1', '2'] expected = DataFrame( dict(x=['1', '2'], y=[np.nan, np.nan]), dtype=object) tm.assert_frame_equal(df, expected) df = DataFrame(columns=['x', 'y']) df.loc[0, 'x'] = 1 expected = DataFrame(dict(x=[1], y=[np.nan])) tm.assert_frame_equal(df, expected, check_dtype=False) def test_cache_updating(self): # GH 4939, make sure to update the cache on setitem df = tm.makeDataFrame() df['A'] # cache series df.ix["Hello Friend"] = df.ix[0] self.assertIn("Hello Friend", df['A'].index) self.assertIn("Hello Friend", df['B'].index) panel = tm.makePanel() panel.ix[0] # get first item into cache panel.ix[:, :, 'A+1'] = panel.ix[:, :, 'A'] + 1 self.assertIn("A+1", panel.ix[0].columns) self.assertIn("A+1", panel.ix[1].columns) # 5216 # make sure that we don't try to set a dead cache a = np.random.rand(10, 3) df = DataFrame(a, columns=['x', 'y', 'z']) tuples = [(i, j) for i in range(5) for j in range(2)] index = MultiIndex.from_tuples(tuples) df.index = index df.loc[0]['z'].iloc[0] = 1. result = df.loc[(0, 0), 'z'] self.assertEqual(result, 1) df.loc[(0, 0), 'z'] = 2 result = df.loc[(0, 0), 'z'] self.assertEqual(result, 2) df = DataFrame(np.zeros((5, 5), dtype='int64'), columns=[ 'a', 'b', 'c', 'd', 'e'], index=range(5)) df['f'] = 0 df.f.values[3] = 1 df.f.values[3] = 2 expected = DataFrame(np.zeros((5, 6), dtype='int64'), columns=[ 'a', 'b', 'c', 'd', 'e', 'f'], index=range(5)) expected.at[3, 'f'] = 2 tm.assert_frame_equal(df, expected) expected = Series([0, 0, 0, 2, 0], name='f') tm.assert_series_equal(df.f, expected) def test_slice_consolidate_invalidate_item_cache(self): with option_context('chained_assignment', None): df = DataFrame({"aa": lrange(5), "bb": [2.2] * 5}) df["cc"] = 0.0 df["bb"] repr(df) df['bb'].iloc[0] = 0.17 df._clear_item_cache() self.assertAlmostEqual(df['bb'][0], 0.17) def test_setitem_cache_updating(self): cont = ['one', 'two', 'three', 'four', 'five', 'six', 'seven'] for do_ref in [False, False]: df = DataFrame({'a': cont, "b": cont[3:] + cont[:3], 'c': np.arange(7)}) if do_ref: df.ix[0, "c"] df.ix[7, 'c'] = 1 self.assertEqual(df.ix[0, 'c'], 0.0) self.assertEqual(df.ix[7, 'c'], 1.0) expected = DataFrame({'A': [600, 600, 600]}, index=date_range('5/7/2014', '5/9/2014')) out = DataFrame({'A': [0, 0, 0]}, index=date_range('5/7/2014', '5/9/2014')) df = DataFrame({'C': ['A', 'A', 'A'], 'D': [100, 200, 300]}) six = Timestamp('5/7/2014') eix = Timestamp('5/9/2014') for ix, row in df.iterrows(): out.loc[six:eix, row['C']] = out.loc[six:eix, row['C']] + row['D'] tm.assert_frame_equal(out, expected) tm.assert_series_equal(out['A'], expected['A']) out = DataFrame({'A': [0, 0, 0]}, index=date_range('5/7/2014', '5/9/2014')) for ix, row in df.iterrows(): v = out[row['C']][six:eix] + row['D'] out[row['C']][six:eix] = v tm.assert_frame_equal(out, expected) tm.assert_series_equal(out['A'], expected['A']) out = DataFrame({'A': [0, 0, 0]}, index=date_range('5/7/2014', '5/9/2014')) for ix, row in df.iterrows(): out.loc[six:eix, row['C']] += row['D'] tm.assert_frame_equal(out, expected) tm.assert_series_equal(out['A'], expected['A']) def test_setitem_chained_setfault(self): data = ['right', 'left', 'left', 'left', 'right', 'left', 'timeout'] mdata = ['right', 'left', 'left', 'left', 'right', 'left', 'none'] df = DataFrame({'response': np.array(data)}) mask = df.response == 'timeout' df.response[mask] = 'none' tm.assert_frame_equal(df, DataFrame({'response': mdata})) recarray = np.rec.fromarrays([data], names=['response']) df = DataFrame(recarray) mask = df.response == 'timeout' df.response[mask] = 'none' tm.assert_frame_equal(df, DataFrame({'response': mdata})) df = DataFrame({'response': data, 'response1': data}) mask = df.response == 'timeout' df.response[mask] = 'none' tm.assert_frame_equal(df, DataFrame({'response': mdata, 'response1': data})) expected = DataFrame(dict(A=[np.nan, 'bar', 'bah', 'foo', 'bar'])) df = DataFrame(dict(A=np.array(['foo', 'bar', 'bah', 'foo', 'bar']))) df['A'].iloc[0] = np.nan result = df.head() tm.assert_frame_equal(result, expected) df = DataFrame(dict(A=np.array(['foo', 'bar', 'bah', 'foo', 'bar']))) df.A.iloc[0] = np.nan result = df.head() tm.assert_frame_equal(result, expected) def test_detect_chained_assignment(self): pd.set_option('chained_assignment', 'raise') expected = DataFrame([[-5, 1], [-6, 3]], columns=list('AB')) df = DataFrame(np.arange(4).reshape(2, 2), columns=list('AB'), dtype='int64') self.assertIsNone(df.is_copy) df['A'][0] = -5 df['A'][1] = -6 tm.assert_frame_equal(df, expected) df = DataFrame({'A': Series(range(2), dtype='int64'), 'B': np.array(np.arange(2, 4), dtype=np.float64)}) self.assertIsNone(df.is_copy) def f(): df['A'][0] = -5 self.assertRaises(com.SettingWithCopyError, f) def f(): df['A'][1] = np.nan self.assertRaises(com.SettingWithCopyError, f) self.assertIsNone(df['A'].is_copy) df = DataFrame({'A': Series(range(2), dtype='int64'), 'B': np.array(np.arange(2, 4), dtype=np.float64)}) def f(): df.loc[0]['A'] = -5 self.assertRaises(com.SettingWithCopyError, f) df = DataFrame({'a': ['one', 'one', 'two', 'three', 'two', 'one', 'six'], 'c': Series(range(7), dtype='int64')}) self.assertIsNone(df.is_copy) expected = DataFrame({'a': ['one', 'one', 'two', 'three', 'two', 'one', 'six'], 'c': [42, 42, 2, 3, 4, 42, 6]}) def f(): indexer = df.a.str.startswith('o') df[indexer]['c'] = 42 self.assertRaises(com.SettingWithCopyError, f) expected = DataFrame({'A': [111, 'bbb', 'ccc'], 'B': [1, 2, 3]}) df = DataFrame({'A': ['aaa', 'bbb', 'ccc'], 'B': [1, 2, 3]}) def f(): df['A'][0] = 111 self.assertRaises(com.SettingWithCopyError, f) def f(): df.loc[0]['A'] = 111 self.assertRaises(com.SettingWithCopyError, f) df.loc[0, 'A'] = 111 tm.assert_frame_equal(df, expected) df = DataFrame({"A": [1, 2]}) self.assertIsNone(df.is_copy) with tm.ensure_clean('__tmp__pickle') as path: df.to_pickle(path) df2 = pd.read_pickle(path) df2["B"] = df2["A"] df2["B"] = df2["A"] from string import ascii_letters as letters def random_text(nobs=100): df = [] for i in range(nobs): idx = np.random.randint(len(letters), size=2) idx.sort() df.append([letters[idx[0]:idx[1]]]) return DataFrame(df, columns=['letters']) df = random_text(100000) x = df.iloc[[0, 1, 2]] self.assertIsNotNone(x.is_copy) x = df.iloc[[0, 1, 2, 4]] self.assertIsNotNone(x.is_copy) indexer = df.letters.apply(lambda x: len(x) > 10) df = df.ix[indexer].copy() self.assertIsNone(df.is_copy) df['letters'] = df['letters'].apply(str.lower) df = random_text(100000) indexer = df.letters.apply(lambda x: len(x) > 10) df = df.ix[indexer] self.assertIsNotNone(df.is_copy) df['letters'] = df['letters'].apply(str.lower) df = random_text(100000) indexer = df.letters.apply(lambda x: len(x) > 10) df = df.ix[indexer] self.assertIsNotNone(df.is_copy) df.loc[:, 'letters'] = df['letters'].apply(str.lower) self.assertIsNone(df.is_copy) df['letters'] = df['letters'].apply(str.lower) self.assertIsNone(df.is_copy) df = random_text(100000) indexer = df.letters.apply(lambda x: len(x) > 10) df.ix[indexer, 'letters'] = df.ix[indexer, 'letters'].apply(str.lower) # an identical take, so no copy df = DataFrame({'a': [1]}).dropna() self.assertIsNone(df.is_copy) df['a'] += 1 # inplace ops # original from: # http://stackoverflow.com/questions/20508968/series-fillna-in-a-multiindex-dataframe-does-not-fill-is-this-a-bug a = [12, 23] b = [123, None] c = [1234, 2345] d = [12345, 23456] tuples = [('eyes', 'left'), ('eyes', 'right'), ('ears', 'left'), ('ears', 'right')] events = {('eyes', 'left'): a, ('eyes', 'right'): b, ('ears', 'left'): c, ('ears', 'right'): d} multiind = MultiIndex.from_tuples(tuples, names=['part', 'side']) zed = DataFrame(events, index=['a', 'b'], columns=multiind) def f(): zed['eyes']['right'].fillna(value=555, inplace=True) self.assertRaises(com.SettingWithCopyError, f) df = DataFrame(np.random.randn(10, 4)) s = df.iloc[:, 0].sort_values() tm.assert_series_equal(s, df.iloc[:, 0].sort_values()) tm.assert_series_equal(s, df[0].sort_values()) # false positives GH6025 df = DataFrame({'column1': ['a', 'a', 'a'], 'column2': [4, 8, 9]}) str(df) df['column1'] = df['column1'] + 'b' str(df) df = df[df['column2'] != 8] str(df) df['column1'] = df['column1'] + 'c' str(df) # from SO: # http://stackoverflow.com/questions/24054495/potential-bug-setting-value-for-undefined-column-using-iloc df = DataFrame(np.arange(0, 9), columns=['count']) df['group'] = 'b' def f(): df.iloc[0:5]['group'] = 'a' self.assertRaises(com.SettingWithCopyError, f) # mixed type setting # same dtype & changing dtype df = DataFrame(dict(A=date_range('20130101', periods=5), B=np.random.randn(5), C=np.arange(5, dtype='int64'), D=list('abcde'))) def f(): df.ix[2]['D'] = 'foo' self.assertRaises(com.SettingWithCopyError, f) def f(): df.ix[2]['C'] = 'foo' self.assertRaises(com.SettingWithCopyError, f) def f(): df['C'][2] = 'foo' self.assertRaises(com.SettingWithCopyError, f) def test_setting_with_copy_bug(self): # operating on a copy df = pd.DataFrame({'a': list(range(4)), 'b': list('ab..'), 'c': ['a', 'b', np.nan, 'd']}) mask = pd.isnull(df.c) def f(): df[['c']][mask] = df[['b']][mask] self.assertRaises(com.SettingWithCopyError, f) # invalid warning as we are returning a new object # GH 8730 df1 = DataFrame({'x': Series(['a', 'b', 'c']), 'y': Series(['d', 'e', 'f'])}) df2 = df1[['x']] # this should not raise df2['y'] = ['g', 'h', 'i'] def test_detect_chained_assignment_warnings(self): # warnings with option_context('chained_assignment', 'warn'): df = DataFrame({'A': ['aaa', 'bbb', 'ccc'], 'B': [1, 2, 3]}) with tm.assert_produces_warning( expected_warning=com.SettingWithCopyWarning): df.loc[0]['A'] = 111 def test_float64index_slicing_bug(self): # GH 5557, related to slicing a float index ser = {256: 2321.0, 1: 78.0, 2: 2716.0, 3: 0.0, 4: 369.0, 5: 0.0, 6: 269.0, 7: 0.0, 8: 0.0, 9: 0.0, 10: 3536.0, 11: 0.0, 12: 24.0, 13: 0.0, 14: 931.0, 15: 0.0, 16: 101.0, 17: 78.0, 18: 9643.0, 19: 0.0, 20: 0.0, 21: 0.0, 22: 63761.0, 23: 0.0, 24: 446.0, 25: 0.0, 26: 34773.0, 27: 0.0, 28: 729.0, 29: 78.0, 30: 0.0, 31: 0.0, 32: 3374.0, 33: 0.0, 34: 1391.0, 35: 0.0, 36: 361.0, 37: 0.0, 38: 61808.0, 39: 0.0, 40: 0.0, 41: 0.0, 42: 6677.0, 43: 0.0, 44: 802.0, 45: 0.0, 46: 2691.0, 47: 0.0, 48: 3582.0, 49: 0.0, 50: 734.0, 51: 0.0, 52: 627.0, 53: 70.0, 54: 2584.0, 55: 0.0, 56: 324.0, 57: 0.0, 58: 605.0, 59: 0.0, 60: 0.0, 61: 0.0, 62: 3989.0, 63: 10.0, 64: 42.0, 65: 0.0, 66: 904.0, 67: 0.0, 68: 88.0, 69: 70.0, 70: 8172.0, 71: 0.0, 72: 0.0, 73: 0.0, 74: 64902.0, 75: 0.0, 76: 347.0, 77: 0.0, 78: 36605.0, 79: 0.0, 80: 379.0, 81: 70.0, 82: 0.0, 83: 0.0, 84: 3001.0, 85: 0.0, 86: 1630.0, 87: 7.0, 88: 364.0, 89: 0.0, 90: 67404.0, 91: 9.0, 92: 0.0, 93: 0.0, 94: 7685.0, 95: 0.0, 96: 1017.0, 97: 0.0, 98: 2831.0, 99: 0.0, 100: 2963.0, 101: 0.0, 102: 854.0, 103: 0.0, 104: 0.0, 105: 0.0, 106: 0.0, 107: 0.0, 108: 0.0, 109: 0.0, 110: 0.0, 111: 0.0, 112: 0.0, 113: 0.0, 114: 0.0, 115: 0.0, 116: 0.0, 117: 0.0, 118: 0.0, 119: 0.0, 120: 0.0, 121: 0.0, 122: 0.0, 123: 0.0, 124: 0.0, 125: 0.0, 126: 67744.0, 127: 22.0, 128: 264.0, 129: 0.0, 260: 197.0, 268: 0.0, 265: 0.0, 269: 0.0, 261: 0.0, 266: 1198.0, 267: 0.0, 262: 2629.0, 258: 775.0, 257: 0.0, 263: 0.0, 259: 0.0, 264: 163.0, 250: 10326.0, 251: 0.0, 252: 1228.0, 253: 0.0, 254: 2769.0, 255: 0.0} # smoke test for the repr s = Series(ser) result = s.value_counts() str(result) def test_set_ix_out_of_bounds_axis_0(self): df = pd.DataFrame( randn(2, 5), index=["row%s" % i for i in range(2)], columns=["col%s" % i for i in range(5)]) self.assertRaises(ValueError, df.ix.__setitem__, (2, 0), 100) def test_set_ix_out_of_bounds_axis_1(self): df = pd.DataFrame( randn(5, 2), index=["row%s" % i for i in range(5)], columns=["col%s" % i for i in range(2)]) self.assertRaises(ValueError, df.ix.__setitem__, (0, 2), 100) def test_iloc_empty_list_indexer_is_ok(self): from pandas.util.testing import makeCustomDataframe as mkdf df = mkdf(5, 2) # vertical empty tm.assert_frame_equal(df.iloc[:, []], df.iloc[:, :0], check_index_type=True, check_column_type=True) # horizontal empty tm.assert_frame_equal(df.iloc[[], :], df.iloc[:0, :], check_index_type=True, check_column_type=True) # horizontal empty tm.assert_frame_equal(df.iloc[[]], df.iloc[:0, :], check_index_type=True, check_column_type=True) def test_loc_empty_list_indexer_is_ok(self): from pandas.util.testing import makeCustomDataframe as mkdf df = mkdf(5, 2) # vertical empty tm.assert_frame_equal(df.loc[:, []], df.iloc[:, :0], check_index_type=True, check_column_type=True) # horizontal empty tm.assert_frame_equal(df.loc[[], :], df.iloc[:0, :], check_index_type=True, check_column_type=True) # horizontal empty tm.assert_frame_equal(df.loc[[]], df.iloc[:0, :], check_index_type=True, check_column_type=True) def test_ix_empty_list_indexer_is_ok(self): from pandas.util.testing import makeCustomDataframe as mkdf df = mkdf(5, 2) # vertical empty tm.assert_frame_equal(df.ix[:, []], df.iloc[:, :0], check_index_type=True, check_column_type=True) # horizontal empty tm.assert_frame_equal(df.ix[[], :], df.iloc[:0, :], check_index_type=True, check_column_type=True) # horizontal empty tm.assert_frame_equal(df.ix[[]], df.iloc[:0, :], check_index_type=True, check_column_type=True) def test_index_type_coercion(self): # GH 11836 # if we have an index type and set it with something that looks # to numpy like the same, but is actually, not # (e.g. setting with a float or string '0') # then we need to coerce to object # integer indexes for s in [Series(range(5)), Series(range(5), index=range(1, 6))]: self.assertTrue(s.index.is_integer()) for indexer in [lambda x: x.ix, lambda x: x.loc, lambda x: x]: s2 = s.copy() indexer(s2)[0.1] = 0 self.assertTrue(s2.index.is_floating()) self.assertTrue(indexer(s2)[0.1] == 0) s2 = s.copy() indexer(s2)[0.0] = 0 exp = s.index if 0 not in s: exp = Index(s.index.tolist() + [0]) tm.assert_index_equal(s2.index, exp) s2 = s.copy() indexer(s2)['0'] = 0 self.assertTrue(s2.index.is_object()) for s in [Series(range(5), index=np.arange(5.))]: self.assertTrue(s.index.is_floating()) for idxr in [lambda x: x.ix, lambda x: x.loc, lambda x: x]: s2 = s.copy() idxr(s2)[0.1] = 0 self.assertTrue(s2.index.is_floating()) self.assertTrue(idxr(s2)[0.1] == 0) s2 = s.copy() idxr(s2)[0.0] = 0 tm.assert_index_equal(s2.index, s.index) s2 = s.copy() idxr(s2)['0'] = 0 self.assertTrue(s2.index.is_object()) def test_float_index_to_mixed(self): df = DataFrame({0.0: np.random.rand(10), 1.0: np.random.rand(10)}) df['a'] = 10 tm.assert_frame_equal(DataFrame({0.0: df[0.0], 1.0: df[1.0], 'a': [10] * 10}), df) def test_duplicate_ix_returns_series(self): df = DataFrame(np.random.randn(3, 3), index=[0.1, 0.2, 0.2], columns=list('abc')) r = df.ix[0.2, 'a'] e = df.loc[0.2, 'a'] tm.assert_series_equal(r, e) def test_float_index_non_scalar_assignment(self): df = DataFrame({'a': [1, 2, 3], 'b': [3, 4, 5]}, index=[1., 2., 3.]) df.loc[df.index[:2]] = 1 expected = DataFrame({'a': [1, 1, 3], 'b': [1, 1, 5]}, index=df.index) tm.assert_frame_equal(expected, df) df = DataFrame({'a': [1, 2, 3], 'b': [3, 4, 5]}, index=[1., 2., 3.]) df2 = df.copy() df.loc[df.index] = df.loc[df.index] tm.assert_frame_equal(df, df2) def test_float_index_at_iat(self): s = pd.Series([1, 2, 3], index=[0.1, 0.2, 0.3]) for el, item in s.iteritems(): self.assertEqual(s.at[el], item) for i in range(len(s)): self.assertEqual(s.iat[i], i + 1) def test_rhs_alignment(self): # GH8258, tests that both rows & columns are aligned to what is # assigned to. covers both uniform data-type & multi-type cases def run_tests(df, rhs, right): # label, index, slice r, i, s = list('bcd'), [1, 2, 3], slice(1, 4) c, j, l = ['joe', 'jolie'], [1, 2], slice(1, 3) left = df.copy() left.loc[r, c] = rhs tm.assert_frame_equal(left, right) left = df.copy() left.iloc[i, j] = rhs tm.assert_frame_equal(left, right) left = df.copy() left.ix[s, l] = rhs tm.assert_frame_equal(left, right) left = df.copy() left.ix[i, j] = rhs tm.assert_frame_equal(left, right) left = df.copy() left.ix[r, c] = rhs tm.assert_frame_equal(left, right) xs = np.arange(20).reshape(5, 4) cols = ['jim', 'joe', 'jolie', 'joline'] df = pd.DataFrame(xs, columns=cols, index=list('abcde')) # right hand side; permute the indices and multiplpy by -2 rhs = -2 * df.iloc[3:0:-1, 2:0:-1] # expected `right` result; just multiply by -2 right = df.copy() right.iloc[1:4, 1:3] *= -2 # run tests with uniform dtypes run_tests(df, rhs, right) # make frames multi-type & re-run tests for frame in [df, rhs, right]: frame['joe'] = frame['joe'].astype('float64') frame['jolie'] = frame['jolie'].map('@{0}'.format) run_tests(df, rhs, right) def test_str_label_slicing_with_negative_step(self): SLC = pd.IndexSlice def assert_slices_equivalent(l_slc, i_slc): tm.assert_series_equal(s.loc[l_slc], s.iloc[i_slc]) if not idx.is_integer: # For integer indices, ix and plain getitem are position-based. tm.assert_series_equal(s[l_slc], s.iloc[i_slc]) tm.assert_series_equal(s.ix[l_slc], s.iloc[i_slc]) for idx in [_mklbl('A', 20), np.arange(20) + 100, np.linspace(100, 150, 20)]: idx = Index(idx) s = Series(np.arange(20), index=idx) assert_slices_equivalent(SLC[idx[9]::-1], SLC[9::-1]) assert_slices_equivalent(SLC[:idx[9]:-1], SLC[:8:-1]) assert_slices_equivalent(SLC[idx[13]:idx[9]:-1], SLC[13:8:-1]) assert_slices_equivalent(SLC[idx[9]:idx[13]:-1], SLC[:0]) def test_multiindex_label_slicing_with_negative_step(self): s = Series(np.arange(20), MultiIndex.from_product([list('abcde'), np.arange(4)])) SLC = pd.IndexSlice def assert_slices_equivalent(l_slc, i_slc): tm.assert_series_equal(s.loc[l_slc], s.iloc[i_slc]) tm.assert_series_equal(s[l_slc], s.iloc[i_slc]) tm.assert_series_equal(s.ix[l_slc], s.iloc[i_slc]) assert_slices_equivalent(SLC[::-1], SLC[::-1]) assert_slices_equivalent(SLC['d'::-1], SLC[15::-1]) assert_slices_equivalent(SLC[('d', )::-1], SLC[15::-1]) assert_slices_equivalent(SLC[:'d':-1], SLC[:11:-1]) assert_slices_equivalent(SLC[:('d', ):-1], SLC[:11:-1]) assert_slices_equivalent(SLC['d':'b':-1], SLC[15:3:-1]) assert_slices_equivalent(SLC[('d', ):'b':-1], SLC[15:3:-1]) assert_slices_equivalent(SLC['d':('b', ):-1], SLC[15:3:-1]) assert_slices_equivalent(SLC[('d', ):('b', ):-1], SLC[15:3:-1]) assert_slices_equivalent(SLC['b':'d':-1], SLC[:0]) assert_slices_equivalent(SLC[('c', 2)::-1], SLC[10::-1]) assert_slices_equivalent(SLC[:('c', 2):-1], SLC[:9:-1]) assert_slices_equivalent(SLC[('e', 0):('c', 2):-1], SLC[16:9:-1]) def test_slice_with_zero_step_raises(self): s = Series(np.arange(20), index=_mklbl('A', 20)) self.assertRaisesRegexp(ValueError, 'slice step cannot be zero', lambda: s[::0]) self.assertRaisesRegexp(ValueError, 'slice step cannot be zero', lambda: s.loc[::0]) self.assertRaisesRegexp(ValueError, 'slice step cannot be zero', lambda: s.ix[::0]) def test_indexing_assignment_dict_already_exists(self): df = pd.DataFrame({'x': [1, 2, 6], 'y': [2, 2, 8], 'z': [-5, 0, 5]}).set_index('z') expected = df.copy() rhs = dict(x=9, y=99) df.loc[5] = rhs expected.loc[5] = [9, 99] tm.assert_frame_equal(df, expected) def test_indexing_dtypes_on_empty(self): # Check that .iloc and .ix return correct dtypes GH9983 df = DataFrame({'a': [1, 2, 3], 'b': ['b', 'b2', 'b3']}) df2 = df.ix[[], :] self.assertEqual(df2.loc[:, 'a'].dtype, np.int64) tm.assert_series_equal(df2.loc[:, 'a'], df2.iloc[:, 0]) tm.assert_series_equal(df2.loc[:, 'a'], df2.ix[:, 0]) def test_range_in_series_indexing(self): # range can cause an indexing error # GH 11652 for x in [5, 999999, 1000000]: s = pd.Series(index=range(x)) s.loc[range(1)] = 42 tm.assert_series_equal(s.loc[range(1)], Series(42.0, index=[0])) s.loc[range(2)] = 43 tm.assert_series_equal(s.loc[range(2)], Series(43.0, index=[0, 1])) def test_non_reducing_slice(self): df = pd.DataFrame([[0, 1], [2, 3]]) slices = [ # pd.IndexSlice[:, :], pd.IndexSlice[:, 1], pd.IndexSlice[1, :], pd.IndexSlice[[1], [1]], pd.IndexSlice[1, [1]], pd.IndexSlice[[1], 1], pd.IndexSlice[1], pd.IndexSlice[1, 1], slice(None, None, None), [0, 1], np.array([0, 1]), pd.Series([0, 1]) ] for slice_ in slices: tslice_ = _non_reducing_slice(slice_) self.assertTrue(isinstance(df.loc[tslice_], DataFrame)) def test_list_slice(self): # like dataframe getitem slices = [['A'], pd.Series(['A']), np.array(['A'])] df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}, index=['A', 'B']) expected = pd.IndexSlice[:, ['A']] for subset in slices: result = _non_reducing_slice(subset) tm.assert_frame_equal(df.loc[result], df.loc[expected]) def test_maybe_numeric_slice(self): df = pd.DataFrame({'A': [1, 2], 'B': ['c', 'd'], 'C': [True, False]}) result = _maybe_numeric_slice(df, slice_=None) expected = pd.IndexSlice[:, ['A']] self.assertEqual(result, expected) result = _maybe_numeric_slice(df, None, include_bool=True) expected = pd.IndexSlice[:, ['A', 'C']] result = _maybe_numeric_slice(df, [1]) expected = [1] self.assertEqual(result, expected) def test_multiindex_slice_first_level(self): # GH 12697 freq = ['a', 'b', 'c', 'd'] idx = pd.MultiIndex.from_product([freq, np.arange(500)]) df = pd.DataFrame(list(range(2000)), index=idx, columns=['Test']) df_slice = df.loc[pd.IndexSlice[:, 30:70], :] result = df_slice.loc['a'] expected = pd.DataFrame(list(range(30, 71)), columns=['Test'], index=range(30, 71)) tm.assert_frame_equal(result, expected) result = df_slice.loc['d'] expected = pd.DataFrame(list(range(1530, 1571)), columns=['Test'], index=range(30, 71)) tm.assert_frame_equal(result, expected) class TestSeriesNoneCoercion(tm.TestCase): EXPECTED_RESULTS = [ # For numeric series, we should coerce to NaN. ([1, 2, 3], [np.nan, 2, 3]), ([1.0, 2.0, 3.0], [np.nan, 2.0, 3.0]), # For datetime series, we should coerce to NaT. ([datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)], [NaT, datetime(2000, 1, 2), datetime(2000, 1, 3)]), # For objects, we should preserve the None value. (["foo", "bar", "baz"], [None, "bar", "baz"]), ] def test_coercion_with_setitem(self): for start_data, expected_result in self.EXPECTED_RESULTS: start_series = Series(start_data) start_series[0] = None expected_series = Series(expected_result) tm.assert_series_equal(start_series, expected_series) def test_coercion_with_loc_setitem(self): for start_data, expected_result in self.EXPECTED_RESULTS: start_series = Series(start_data) start_series.loc[0] = None expected_series = Series(expected_result) tm.assert_series_equal(start_series, expected_series) def test_coercion_with_setitem_and_series(self): for start_data, expected_result in self.EXPECTED_RESULTS: start_series = Series(start_data) start_series[start_series == start_series[0]] = None expected_series = Series(expected_result) tm.assert_series_equal(start_series, expected_series) def test_coercion_with_loc_and_series(self): for start_data, expected_result in self.EXPECTED_RESULTS: start_series = Series(start_data) start_series.loc[start_series == start_series[0]] = None expected_series = Series(expected_result) tm.assert_series_equal(start_series, expected_series) class TestDataframeNoneCoercion(tm.TestCase): EXPECTED_SINGLE_ROW_RESULTS = [ # For numeric series, we should coerce to NaN. ([1, 2, 3], [np.nan, 2, 3]), ([1.0, 2.0, 3.0], [np.nan, 2.0, 3.0]), # For datetime series, we should coerce to NaT. ([datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)], [NaT, datetime(2000, 1, 2), datetime(2000, 1, 3)]), # For objects, we should preserve the None value. (["foo", "bar", "baz"], [None, "bar", "baz"]), ] def test_coercion_with_loc(self): for start_data, expected_result, in self.EXPECTED_SINGLE_ROW_RESULTS: start_dataframe = DataFrame({'foo': start_data}) start_dataframe.loc[0, ['foo']] = None expected_dataframe = DataFrame({'foo': expected_result}) tm.assert_frame_equal(start_dataframe, expected_dataframe) def test_coercion_with_setitem_and_dataframe(self): for start_data, expected_result, in self.EXPECTED_SINGLE_ROW_RESULTS: start_dataframe = DataFrame({'foo': start_data}) start_dataframe[start_dataframe['foo'] == start_dataframe['foo'][ 0]] = None expected_dataframe = DataFrame({'foo': expected_result}) tm.assert_frame_equal(start_dataframe, expected_dataframe) def test_none_coercion_loc_and_dataframe(self): for start_data, expected_result, in self.EXPECTED_SINGLE_ROW_RESULTS: start_dataframe = DataFrame({'foo': start_data}) start_dataframe.loc[start_dataframe['foo'] == start_dataframe[ 'foo'][0]] = None expected_dataframe = DataFrame({'foo': expected_result}) tm.assert_frame_equal(start_dataframe, expected_dataframe) def test_none_coercion_mixed_dtypes(self): start_dataframe = DataFrame({ 'a': [1, 2, 3], 'b': [1.0, 2.0, 3.0], 'c': [datetime(2000, 1, 1), datetime(2000, 1, 2), datetime(2000, 1, 3)], 'd': ['a', 'b', 'c'] }) start_dataframe.iloc[0] = None exp = DataFrame({'a': [np.nan, 2, 3], 'b': [np.nan, 2.0, 3.0], 'c': [NaT, datetime(2000, 1, 2), datetime(2000, 1, 3)], 'd': [None, 'b', 'c']}) tm.assert_frame_equal(start_dataframe, exp) class TestTimedeltaIndexing(tm.TestCase): def test_boolean_indexing(self): # GH 14946 df = pd.DataFrame({'x': range(10)}) df.index = pd.to_timedelta(range(10), unit='s') conditions = [df['x'] > 3, df['x'] == 3, df['x'] < 3] expected_data = [[0, 1, 2, 3, 10, 10, 10, 10, 10, 10], [0, 1, 2, 10, 4, 5, 6, 7, 8, 9], [10, 10, 10, 3, 4, 5, 6, 7, 8, 9]] for cond, data in zip(conditions, expected_data): result = df.copy() result.loc[cond, 'x'] = 10 expected = pd.DataFrame(data, index=pd.to_timedelta(range(10), unit='s'), columns=['x']) tm.assert_frame_equal(expected, result) if __name__ == '__main__': nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], exit=False)
true
true
f7fa079767483c87e199239d28ae6fa12eb8c6c4
3,186
py
Python
src/tools/python/build_carrier_curl_requests.py
Justintime50/easypost-tools
b5118eec331cd9ec5502e617c73ead61fc322c94
[ "MIT" ]
1
2022-02-17T21:04:05.000Z
2022-02-17T21:04:05.000Z
src/tools/python/build_carrier_curl_requests.py
Justintime50/easypost-tools
b5118eec331cd9ec5502e617c73ead61fc322c94
[ "MIT" ]
null
null
null
src/tools/python/build_carrier_curl_requests.py
Justintime50/easypost-tools
b5118eec331cd9ec5502e617c73ead61fc322c94
[ "MIT" ]
null
null
null
import os import easypost # Builds a file containing every cURL request to add a Carrier Account via EasyPost # USAGE: API_KEY=123... venv/bin/python build_carrier_curl_requests.py > carrier_curl_requests.sh URL = os.getenv('URL', 'https://api.easypost.com/v2') API_KEY = os.getenv('API_KEY') def main(): carrier_types = get_carrier_types() # TODO: this may have a side effect of ordering the items inside each object too for carrier in sorted(carrier_types, key=lambda x: x['type']): curl_request = build_carrier_curl_request(carrier) print(curl_request) def get_carrier_types(): """Get the carrier_types from the EasyPost API.""" easypost.api_key = API_KEY easypost.api_base = URL carrier_accounts = easypost.CarrierAccount.types() return carrier_accounts def build_carrier_curl_request(carrier): """Builds a cURL request for a carrier via EasyPost.""" fedex_custom_workflow_carriers = ['FedexAccount', 'FedexSmartpostAccount'] ups_custom_workflow_carriers = ['UpsAccount', 'UpsDapAccount'] canadapost_custom_workflow_carriers = ['CanadaPostAccount'] # noqa # Add carrier account title comment carrier_output = f'# {carrier.get("type")}\n' # Add curl command and registration url if carrier.get('type') in (fedex_custom_workflow_carriers or ups_custom_workflow_carriers): carrier_output += 'curl -X POST https://api.easypost.com/v2/carrier_accounts/register \\\n' else: carrier_output += 'curl -X POST https://api.easypost.com/v2/carrier_accounts \\\n' # Add authentication, carrier account type and description carrier_output += "-u 'API_KEY': \\\n" carrier_output += f"-d 'carrier_account[type]={carrier.get('type')}' \\\n" carrier_output += f"-d 'carrier_account[description]={carrier.get('type')}' \\\n" # Iterate over the carrier fields and print the credential structure carrier_fields = carrier.get('fields').to_dict() if carrier.get('type') in fedex_custom_workflow_carriers: for category in carrier_fields['creation_fields']: for item in carrier_fields['creation_fields'][category]: carrier_output += f"-d 'carrier_account[registration_data][{item}]=VALUE' \\\n" carrier_output += '| json_pp\n' elif carrier.get('type') in (ups_custom_workflow_carriers or canadapost_custom_workflow_carriers): # TODO: Fix UPS carrier account # TODO: Fix CanadaPost carrier account pass else: end = '| json_pp\n' for top_level in carrier_fields: # If there is a custom_workflow such as 3rd party auth or a similar flow # we should warn about that here. The credential structure will differ from # a normal carrier account and is currently not automated if top_level == 'custom_workflow': end += '## REQUIRES CUSTOM WORKFLOW ##\n' else: for item in carrier_fields[top_level]: carrier_output += f"-d 'carrier_account[{top_level}][{item}]=VALUE' \\\n" carrier_output += end return carrier_output if __name__ == '__main__': main()
41.376623
102
0.685813
import os import easypost URL = os.getenv('URL', 'https://api.easypost.com/v2') API_KEY = os.getenv('API_KEY') def main(): carrier_types = get_carrier_types() for carrier in sorted(carrier_types, key=lambda x: x['type']): curl_request = build_carrier_curl_request(carrier) print(curl_request) def get_carrier_types(): easypost.api_key = API_KEY easypost.api_base = URL carrier_accounts = easypost.CarrierAccount.types() return carrier_accounts def build_carrier_curl_request(carrier): fedex_custom_workflow_carriers = ['FedexAccount', 'FedexSmartpostAccount'] ups_custom_workflow_carriers = ['UpsAccount', 'UpsDapAccount'] canadapost_custom_workflow_carriers = ['CanadaPostAccount'] carrier_output = f'# {carrier.get("type")}\n' if carrier.get('type') in (fedex_custom_workflow_carriers or ups_custom_workflow_carriers): carrier_output += 'curl -X POST https://api.easypost.com/v2/carrier_accounts/register \\\n' else: carrier_output += 'curl -X POST https://api.easypost.com/v2/carrier_accounts \\\n' carrier_output += "-u 'API_KEY': \\\n" carrier_output += f"-d 'carrier_account[type]={carrier.get('type')}' \\\n" carrier_output += f"-d 'carrier_account[description]={carrier.get('type')}' \\\n" carrier_fields = carrier.get('fields').to_dict() if carrier.get('type') in fedex_custom_workflow_carriers: for category in carrier_fields['creation_fields']: for item in carrier_fields['creation_fields'][category]: carrier_output += f"-d 'carrier_account[registration_data][{item}]=VALUE' \\\n" carrier_output += '| json_pp\n' elif carrier.get('type') in (ups_custom_workflow_carriers or canadapost_custom_workflow_carriers): pass else: end = '| json_pp\n' for top_level in carrier_fields: if top_level == 'custom_workflow': end += '## REQUIRES CUSTOM WORKFLOW ##\n' else: for item in carrier_fields[top_level]: carrier_output += f"-d 'carrier_account[{top_level}][{item}]=VALUE' \\\n" carrier_output += end return carrier_output if __name__ == '__main__': main()
true
true
f7fa0869c737f04e9b456939753316fffbe853cf
655
py
Python
github/API_V3/commit_guru/ingester/commitFile_new.py
ai-se/Data_Miner
69a363703c91f95f9f296170bf23b0a01f344088
[ "MIT" ]
1
2022-03-18T02:33:49.000Z
2022-03-18T02:33:49.000Z
github/API_V3/commit_guru/ingester/commitFile_new.py
ai-se/Data_Miner
69a363703c91f95f9f296170bf23b0a01f344088
[ "MIT" ]
1
2019-12-09T16:36:44.000Z
2020-01-23T16:56:47.000Z
github/API_V3/commit_guru/ingester/commitFile_new.py
ai-se/Data_Miner
69a363703c91f95f9f296170bf23b0a01f344088
[ "MIT" ]
null
null
null
""" Representing a single file in a commit @name name of file @loc lines of code in file @authors all authors of the file @nuc number of unique changes made to the file """ class CommitFile: def __init__(self, name, loc, authors, lastchanged, owner,co_commited_files,adev): self.name = name # File name self.loc = loc # LOC in file self.authors = authors # Array of authors self.lastchanged = lastchanged # unix time stamp of when last changed self.nuc = 1 self.owner = owner self.co_commited_files = co_commited_files self.adev = adev # number of unique changes to the file
32.75
83
0.670229
class CommitFile: def __init__(self, name, loc, authors, lastchanged, owner,co_commited_files,adev): self.name = name self.loc = loc self.authors = authors self.lastchanged = lastchanged self.nuc = 1 self.owner = owner self.co_commited_files = co_commited_files self.adev = adev
true
true
f7fa08737254df1652733ad531a1c08f599b0d84
9,746
py
Python
awx/main/tests/functional/api/test_job.py
bhyunki/awx
ce588a6af5a5c7f71a5b176ffe53eda5ebc3492c
[ "Apache-2.0" ]
11,396
2017-09-07T04:56:02.000Z
2022-03-31T13:56:17.000Z
awx/main/tests/functional/api/test_job.py
bhyunki/awx
ce588a6af5a5c7f71a5b176ffe53eda5ebc3492c
[ "Apache-2.0" ]
11,046
2017-09-07T09:30:46.000Z
2022-03-31T20:28:01.000Z
awx/main/tests/functional/api/test_job.py
TinLe/awx
73d8c12e3bf5b193305ed1202549331ea00088c1
[ "Apache-2.0" ]
3,592
2017-09-07T04:14:31.000Z
2022-03-31T23:53:09.000Z
# Python import pytest from unittest import mock from dateutil.parser import parse from dateutil.relativedelta import relativedelta from crum import impersonate import datetime # Django rest framework from rest_framework.exceptions import PermissionDenied from django.utils import timezone # AWX from awx.api.versioning import reverse from awx.api.views import RelatedJobsPreventDeleteMixin, UnifiedJobDeletionMixin from awx.main.models import ( JobTemplate, User, Job, AdHocCommand, ProjectUpdate, ) @pytest.mark.django_db def test_job_relaunch_permission_denied_response(post, get, inventory, project, credential, net_credential, machine_credential): jt = JobTemplate.objects.create(name='testjt', inventory=inventory, project=project, ask_credential_on_launch=True) jt.credentials.add(machine_credential) jt_user = User.objects.create(username='jobtemplateuser') jt.execute_role.members.add(jt_user) with impersonate(jt_user): job = jt.create_unified_job() # User capability is shown for this r = get(job.get_absolute_url(), jt_user, expect=200) assert r.data['summary_fields']['user_capabilities']['start'] # Job has prompted credential, launch denied w/ message job.launch_config.credentials.add(net_credential) r = post(reverse('api:job_relaunch', kwargs={'pk': job.pk}), {}, jt_user, expect=403) assert 'launched with prompted fields you do not have access to' in r.data['detail'] @pytest.mark.django_db def test_job_relaunch_prompts_not_accepted_response(post, get, inventory, project, credential, net_credential, machine_credential): jt = JobTemplate.objects.create(name='testjt', inventory=inventory, project=project) jt.credentials.add(machine_credential) jt_user = User.objects.create(username='jobtemplateuser') jt.execute_role.members.add(jt_user) with impersonate(jt_user): job = jt.create_unified_job() # User capability is shown for this r = get(job.get_absolute_url(), jt_user, expect=200) assert r.data['summary_fields']['user_capabilities']['start'] # Job has prompted credential, launch denied w/ message job.launch_config.credentials.add(net_credential) r = post(reverse('api:job_relaunch', kwargs={'pk': job.pk}), {}, jt_user, expect=403) @pytest.mark.django_db def test_job_relaunch_permission_denied_response_other_user(get, post, inventory, project, alice, bob, survey_spec_factory): """ Asserts custom permission denied message corresponding to awx/main/tests/functional/test_rbac_job.py::TestJobRelaunchAccess::test_other_user_prompts """ jt = JobTemplate.objects.create( name='testjt', inventory=inventory, project=project, ask_credential_on_launch=True, ask_variables_on_launch=True, survey_spec=survey_spec_factory([{'variable': 'secret_key', 'default': '6kQngg3h8lgiSTvIEb21', 'type': 'password'}]), survey_enabled=True, ) jt.execute_role.members.add(alice, bob) with impersonate(bob): job = jt.create_unified_job(extra_vars={'job_var': 'foo2', 'secret_key': 'sk4t3Rb01'}) # User capability is shown for this r = get(job.get_absolute_url(), alice, expect=200) assert r.data['summary_fields']['user_capabilities']['start'] # Job has prompted data, launch denied w/ message r = post(url=reverse('api:job_relaunch', kwargs={'pk': job.pk}), data={}, user=alice, expect=403) assert 'Job was launched with secret prompts provided by another user' in r.data['detail'] @pytest.mark.django_db def test_job_relaunch_without_creds(post, inventory, project, admin_user): jt = JobTemplate.objects.create(name='testjt', inventory=inventory, project=project) job = jt.create_unified_job() post(url=reverse('api:job_relaunch', kwargs={'pk': job.pk}), data={}, user=admin_user, expect=201) @pytest.mark.django_db @pytest.mark.parametrize( "status,hosts", [ ('all', 'host1,host2,host3'), ('failed', 'host3'), ], ) def test_job_relaunch_on_failed_hosts(post, inventory, project, machine_credential, admin_user, status, hosts): h1 = inventory.hosts.create(name='host1') # no-op h2 = inventory.hosts.create(name='host2') # changed host h3 = inventory.hosts.create(name='host3') # failed host jt = JobTemplate.objects.create(name='testjt', inventory=inventory, project=project) jt.credentials.add(machine_credential) job = jt.create_unified_job(_eager_fields={'status': 'failed'}, limit='host1,host2,host3') job.job_events.create(event='playbook_on_stats') job.job_host_summaries.create(host=h1, failed=False, ok=1, changed=0, failures=0, host_name=h1.name) job.job_host_summaries.create(host=h2, failed=False, ok=0, changed=1, failures=0, host_name=h2.name) job.job_host_summaries.create(host=h3, failed=False, ok=0, changed=0, failures=1, host_name=h3.name) r = post(url=reverse('api:job_relaunch', kwargs={'pk': job.pk}), data={'hosts': status}, user=admin_user, expect=201) assert r.data.get('limit') == hosts @pytest.mark.django_db def test_summary_fields_recent_jobs(job_template, admin_user, get): jobs = [] for i in range(13): jobs.append( Job.objects.create( job_template=job_template, status='failed', created=timezone.make_aware(datetime.datetime(2017, 3, 21, 9, i)), finished=timezone.make_aware(datetime.datetime(2017, 3, 21, 10, i)), ) ) r = get(url=job_template.get_absolute_url(), user=admin_user, exepect=200) recent_jobs = r.data['summary_fields']['recent_jobs'] assert len(recent_jobs) == 10 assert recent_jobs == [{'id': job.id, 'status': 'failed', 'finished': job.finished, 'canceled_on': None, 'type': 'job'} for job in jobs[-10:][::-1]] @pytest.mark.django_db def test_slice_jt_recent_jobs(slice_job_factory, admin_user, get): workflow_job = slice_job_factory(3, spawn=True) slice_jt = workflow_job.job_template r = get(url=slice_jt.get_absolute_url(), user=admin_user, expect=200) job_ids = [entry['id'] for entry in r.data['summary_fields']['recent_jobs']] # decision is that workflow job should be shown in the related jobs # joblets of the workflow job should NOT be shown assert job_ids == [workflow_job.pk] @pytest.mark.django_db def test_block_unprocessed_events(delete, admin_user, mocker): time_of_finish = parse("Thu Feb 28 09:10:20 2013 -0500") job = Job.objects.create(emitted_events=1, status='finished', finished=time_of_finish) request = mock.MagicMock() class MockView(UnifiedJobDeletionMixin): model = Job def get_object(self): return job view = MockView() time_of_request = time_of_finish + relativedelta(seconds=2) with mock.patch('awx.api.views.mixin.now', lambda: time_of_request): r = view.destroy(request) assert r.status_code == 400 @pytest.mark.django_db def test_block_related_unprocessed_events(mocker, organization, project, delete, admin_user): job_template = JobTemplate.objects.create(project=project, playbook='helloworld.yml') time_of_finish = parse("Thu Feb 23 14:17:24 2012 -0500") Job.objects.create( emitted_events=1, status='finished', finished=time_of_finish, job_template=job_template, project=project, organization=project.organization ) view = RelatedJobsPreventDeleteMixin() time_of_request = time_of_finish + relativedelta(seconds=2) with mock.patch('awx.api.views.mixin.now', lambda: time_of_request): with pytest.raises(PermissionDenied): view.perform_destroy(organization) @pytest.mark.django_db def test_disallowed_http_update_methods(put, patch, post, inventory, project, admin_user): jt = JobTemplate.objects.create(name='test_disallowed_methods', inventory=inventory, project=project) job = jt.create_unified_job() post(url=reverse('api:job_detail', kwargs={'pk': job.pk}), data={}, user=admin_user, expect=405) put(url=reverse('api:job_detail', kwargs={'pk': job.pk}), data={}, user=admin_user, expect=405) patch(url=reverse('api:job_detail', kwargs={'pk': job.pk}), data={}, user=admin_user, expect=405) class TestControllerNode: @pytest.fixture def project_update(self, project): return ProjectUpdate.objects.create(project=project) @pytest.fixture def job(self): return JobTemplate.objects.create().create_unified_job() @pytest.fixture def adhoc(self, inventory): return AdHocCommand.objects.create(inventory=inventory) @pytest.mark.django_db def test_field_controller_node_exists(self, sqlite_copy_expert, admin_user, job, project_update, inventory_update, adhoc, get, system_job_factory): system_job = system_job_factory() r = get(reverse('api:unified_job_list') + '?id={}'.format(job.id), admin_user, expect=200) assert 'controller_node' in r.data['results'][0] r = get(job.get_absolute_url(), admin_user, expect=200) assert 'controller_node' in r.data r = get(reverse('api:ad_hoc_command_detail', kwargs={'pk': adhoc.pk}), admin_user, expect=200) assert 'controller_node' in r.data r = get(reverse('api:project_update_detail', kwargs={'pk': project_update.pk}), admin_user, expect=200) assert 'controller_node' not in r.data r = get(reverse('api:inventory_update_detail', kwargs={'pk': inventory_update.pk}), admin_user, expect=200) assert 'controller_node' not in r.data r = get(reverse('api:system_job_detail', kwargs={'pk': system_job.pk}), admin_user, expect=200) assert 'controller_node' not in r.data
42.933921
152
0.716089
import pytest from unittest import mock from dateutil.parser import parse from dateutil.relativedelta import relativedelta from crum import impersonate import datetime from rest_framework.exceptions import PermissionDenied from django.utils import timezone from awx.api.versioning import reverse from awx.api.views import RelatedJobsPreventDeleteMixin, UnifiedJobDeletionMixin from awx.main.models import ( JobTemplate, User, Job, AdHocCommand, ProjectUpdate, ) @pytest.mark.django_db def test_job_relaunch_permission_denied_response(post, get, inventory, project, credential, net_credential, machine_credential): jt = JobTemplate.objects.create(name='testjt', inventory=inventory, project=project, ask_credential_on_launch=True) jt.credentials.add(machine_credential) jt_user = User.objects.create(username='jobtemplateuser') jt.execute_role.members.add(jt_user) with impersonate(jt_user): job = jt.create_unified_job() r = get(job.get_absolute_url(), jt_user, expect=200) assert r.data['summary_fields']['user_capabilities']['start'] job.launch_config.credentials.add(net_credential) r = post(reverse('api:job_relaunch', kwargs={'pk': job.pk}), {}, jt_user, expect=403) assert 'launched with prompted fields you do not have access to' in r.data['detail'] @pytest.mark.django_db def test_job_relaunch_prompts_not_accepted_response(post, get, inventory, project, credential, net_credential, machine_credential): jt = JobTemplate.objects.create(name='testjt', inventory=inventory, project=project) jt.credentials.add(machine_credential) jt_user = User.objects.create(username='jobtemplateuser') jt.execute_role.members.add(jt_user) with impersonate(jt_user): job = jt.create_unified_job() r = get(job.get_absolute_url(), jt_user, expect=200) assert r.data['summary_fields']['user_capabilities']['start'] job.launch_config.credentials.add(net_credential) r = post(reverse('api:job_relaunch', kwargs={'pk': job.pk}), {}, jt_user, expect=403) @pytest.mark.django_db def test_job_relaunch_permission_denied_response_other_user(get, post, inventory, project, alice, bob, survey_spec_factory): jt = JobTemplate.objects.create( name='testjt', inventory=inventory, project=project, ask_credential_on_launch=True, ask_variables_on_launch=True, survey_spec=survey_spec_factory([{'variable': 'secret_key', 'default': '6kQngg3h8lgiSTvIEb21', 'type': 'password'}]), survey_enabled=True, ) jt.execute_role.members.add(alice, bob) with impersonate(bob): job = jt.create_unified_job(extra_vars={'job_var': 'foo2', 'secret_key': 'sk4t3Rb01'}) r = get(job.get_absolute_url(), alice, expect=200) assert r.data['summary_fields']['user_capabilities']['start'] r = post(url=reverse('api:job_relaunch', kwargs={'pk': job.pk}), data={}, user=alice, expect=403) assert 'Job was launched with secret prompts provided by another user' in r.data['detail'] @pytest.mark.django_db def test_job_relaunch_without_creds(post, inventory, project, admin_user): jt = JobTemplate.objects.create(name='testjt', inventory=inventory, project=project) job = jt.create_unified_job() post(url=reverse('api:job_relaunch', kwargs={'pk': job.pk}), data={}, user=admin_user, expect=201) @pytest.mark.django_db @pytest.mark.parametrize( "status,hosts", [ ('all', 'host1,host2,host3'), ('failed', 'host3'), ], ) def test_job_relaunch_on_failed_hosts(post, inventory, project, machine_credential, admin_user, status, hosts): h1 = inventory.hosts.create(name='host1') h2 = inventory.hosts.create(name='host2') h3 = inventory.hosts.create(name='host3') jt = JobTemplate.objects.create(name='testjt', inventory=inventory, project=project) jt.credentials.add(machine_credential) job = jt.create_unified_job(_eager_fields={'status': 'failed'}, limit='host1,host2,host3') job.job_events.create(event='playbook_on_stats') job.job_host_summaries.create(host=h1, failed=False, ok=1, changed=0, failures=0, host_name=h1.name) job.job_host_summaries.create(host=h2, failed=False, ok=0, changed=1, failures=0, host_name=h2.name) job.job_host_summaries.create(host=h3, failed=False, ok=0, changed=0, failures=1, host_name=h3.name) r = post(url=reverse('api:job_relaunch', kwargs={'pk': job.pk}), data={'hosts': status}, user=admin_user, expect=201) assert r.data.get('limit') == hosts @pytest.mark.django_db def test_summary_fields_recent_jobs(job_template, admin_user, get): jobs = [] for i in range(13): jobs.append( Job.objects.create( job_template=job_template, status='failed', created=timezone.make_aware(datetime.datetime(2017, 3, 21, 9, i)), finished=timezone.make_aware(datetime.datetime(2017, 3, 21, 10, i)), ) ) r = get(url=job_template.get_absolute_url(), user=admin_user, exepect=200) recent_jobs = r.data['summary_fields']['recent_jobs'] assert len(recent_jobs) == 10 assert recent_jobs == [{'id': job.id, 'status': 'failed', 'finished': job.finished, 'canceled_on': None, 'type': 'job'} for job in jobs[-10:][::-1]] @pytest.mark.django_db def test_slice_jt_recent_jobs(slice_job_factory, admin_user, get): workflow_job = slice_job_factory(3, spawn=True) slice_jt = workflow_job.job_template r = get(url=slice_jt.get_absolute_url(), user=admin_user, expect=200) job_ids = [entry['id'] for entry in r.data['summary_fields']['recent_jobs']] assert job_ids == [workflow_job.pk] @pytest.mark.django_db def test_block_unprocessed_events(delete, admin_user, mocker): time_of_finish = parse("Thu Feb 28 09:10:20 2013 -0500") job = Job.objects.create(emitted_events=1, status='finished', finished=time_of_finish) request = mock.MagicMock() class MockView(UnifiedJobDeletionMixin): model = Job def get_object(self): return job view = MockView() time_of_request = time_of_finish + relativedelta(seconds=2) with mock.patch('awx.api.views.mixin.now', lambda: time_of_request): r = view.destroy(request) assert r.status_code == 400 @pytest.mark.django_db def test_block_related_unprocessed_events(mocker, organization, project, delete, admin_user): job_template = JobTemplate.objects.create(project=project, playbook='helloworld.yml') time_of_finish = parse("Thu Feb 23 14:17:24 2012 -0500") Job.objects.create( emitted_events=1, status='finished', finished=time_of_finish, job_template=job_template, project=project, organization=project.organization ) view = RelatedJobsPreventDeleteMixin() time_of_request = time_of_finish + relativedelta(seconds=2) with mock.patch('awx.api.views.mixin.now', lambda: time_of_request): with pytest.raises(PermissionDenied): view.perform_destroy(organization) @pytest.mark.django_db def test_disallowed_http_update_methods(put, patch, post, inventory, project, admin_user): jt = JobTemplate.objects.create(name='test_disallowed_methods', inventory=inventory, project=project) job = jt.create_unified_job() post(url=reverse('api:job_detail', kwargs={'pk': job.pk}), data={}, user=admin_user, expect=405) put(url=reverse('api:job_detail', kwargs={'pk': job.pk}), data={}, user=admin_user, expect=405) patch(url=reverse('api:job_detail', kwargs={'pk': job.pk}), data={}, user=admin_user, expect=405) class TestControllerNode: @pytest.fixture def project_update(self, project): return ProjectUpdate.objects.create(project=project) @pytest.fixture def job(self): return JobTemplate.objects.create().create_unified_job() @pytest.fixture def adhoc(self, inventory): return AdHocCommand.objects.create(inventory=inventory) @pytest.mark.django_db def test_field_controller_node_exists(self, sqlite_copy_expert, admin_user, job, project_update, inventory_update, adhoc, get, system_job_factory): system_job = system_job_factory() r = get(reverse('api:unified_job_list') + '?id={}'.format(job.id), admin_user, expect=200) assert 'controller_node' in r.data['results'][0] r = get(job.get_absolute_url(), admin_user, expect=200) assert 'controller_node' in r.data r = get(reverse('api:ad_hoc_command_detail', kwargs={'pk': adhoc.pk}), admin_user, expect=200) assert 'controller_node' in r.data r = get(reverse('api:project_update_detail', kwargs={'pk': project_update.pk}), admin_user, expect=200) assert 'controller_node' not in r.data r = get(reverse('api:inventory_update_detail', kwargs={'pk': inventory_update.pk}), admin_user, expect=200) assert 'controller_node' not in r.data r = get(reverse('api:system_job_detail', kwargs={'pk': system_job.pk}), admin_user, expect=200) assert 'controller_node' not in r.data
true
true
f7fa08f90aeb905f4d5c027c717666e9656b0fb2
8,381
py
Python
keras_/kerascv/models/seresnext.py
oliviaweng/imgclsmob
80fffbb46f986614b162c725b21f3d208597ac77
[ "MIT" ]
2
2020-11-14T08:40:41.000Z
2021-11-08T09:30:41.000Z
keras_/kerascv/models/seresnext.py
ibrahim85/Sandbox-for-training-convolutional-networks-for-computer-vision
a1f1f52eecbb841fa878bff4d3c311b79864835d
[ "MIT" ]
null
null
null
keras_/kerascv/models/seresnext.py
ibrahim85/Sandbox-for-training-convolutional-networks-for-computer-vision
a1f1f52eecbb841fa878bff4d3c311b79864835d
[ "MIT" ]
2
2020-09-01T12:22:50.000Z
2020-10-24T22:02:35.000Z
""" SE-ResNeXt for ImageNet-1K, implemented in Keras. Original paper: 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. """ __all__ = ['seresnext', 'seresnext50_32x4d', 'seresnext101_32x4d', 'seresnext101_64x4d'] import os from keras import layers as nn from keras.models import Model from .common import conv1x1_block, se_block, is_channels_first, flatten from .resnet import res_init_block from .resnext import resnext_bottleneck def seresnext_unit(x, in_channels, out_channels, strides, cardinality, bottleneck_width, name="seresnext_unit"): """ SE-ResNeXt unit. Parameters: ---------- x : keras.backend tensor/variable/symbol Input tensor/variable/symbol. in_channels : int Number of input channels. out_channels : int Number of output channels. strides : int or tuple/list of 2 int Strides of the convolution. cardinality: int Number of groups. bottleneck_width: int Width of bottleneck block. name : str, default 'seresnext_unit' Unit name. Returns ------- keras.backend tensor/variable/symbol Resulted tensor/variable/symbol. """ resize_identity = (in_channels != out_channels) or (strides != 1) if resize_identity: identity = conv1x1_block( x=x, in_channels=in_channels, out_channels=out_channels, strides=strides, activation=None, name=name + "/identity_conv") else: identity = x x = resnext_bottleneck( x=x, in_channels=in_channels, out_channels=out_channels, strides=strides, cardinality=cardinality, bottleneck_width=bottleneck_width, name=name + "/body") x = se_block( x=x, channels=out_channels, name=name + "/se") x = nn.add([x, identity], name=name + "/add") activ = nn.Activation("relu", name=name + "/activ") x = activ(x) return x def seresnext(channels, init_block_channels, cardinality, bottleneck_width, in_channels=3, in_size=(224, 224), classes=1000): """ SE-ResNeXt model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- channels : list of list of int Number of output channels for each unit. init_block_channels : int Number of output channels for the initial unit. cardinality: int Number of groups. bottleneck_width: int Width of bottleneck block. in_channels : int, default 3 Number of input channels. in_size : tuple of two ints, default (224, 224) Spatial size of the expected input image. classes : int, default 1000 Number of classification classes. """ input_shape = (in_channels, in_size[0], in_size[1]) if is_channels_first() else\ (in_size[0], in_size[1], in_channels) input = nn.Input(shape=input_shape) x = res_init_block( x=input, in_channels=in_channels, out_channels=init_block_channels, name="features/init_block") in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): for j, out_channels in enumerate(channels_per_stage): strides = 2 if (j == 0) and (i != 0) else 1 x = seresnext_unit( x=x, in_channels=in_channels, out_channels=out_channels, strides=strides, cardinality=cardinality, bottleneck_width=bottleneck_width, name="features/stage{}/unit{}".format(i + 1, j + 1)) in_channels = out_channels x = nn.AvgPool2D( pool_size=7, strides=1, name="features/final_pool")(x) # x = nn.Flatten()(x) x = flatten(x) x = nn.Dense( units=classes, input_dim=in_channels, name="output")(x) model = Model(inputs=input, outputs=x) model.in_size = in_size model.classes = classes return model def get_seresnext(blocks, cardinality, bottleneck_width, model_name=None, pretrained=False, root=os.path.join("~", ".keras", "models"), **kwargs): """ Create SE-ResNeXt model with specific parameters. Parameters: ---------- blocks : int Number of blocks. cardinality: int Number of groups. bottleneck_width: int Width of bottleneck block. model_name : str or None, default None Model name for loading pretrained model. pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.keras/models' Location for keeping the model parameters. """ if blocks == 50: layers = [3, 4, 6, 3] elif blocks == 101: layers = [3, 4, 23, 3] else: raise ValueError("Unsupported SE-ResNeXt with number of blocks: {}".format(blocks)) init_block_channels = 64 channels_per_layers = [256, 512, 1024, 2048] channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)] net = seresnext( channels=channels, init_block_channels=init_block_channels, cardinality=cardinality, bottleneck_width=bottleneck_width, **kwargs) if pretrained: if (model_name is None) or (not model_name): raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.") from .model_store import download_model download_model( net=net, model_name=model_name, local_model_store_dir_path=root) return net def seresnext50_32x4d(**kwargs): """ SE-ResNeXt-50 (32x4d) model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.keras/models' Location for keeping the model parameters. """ return get_seresnext(blocks=50, cardinality=32, bottleneck_width=4, model_name="seresnext50_32x4d", **kwargs) def seresnext101_32x4d(**kwargs): """ SE-ResNeXt-101 (32x4d) model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.keras/models' Location for keeping the model parameters. """ return get_seresnext(blocks=101, cardinality=32, bottleneck_width=4, model_name="seresnext101_32x4d", **kwargs) def seresnext101_64x4d(**kwargs): """ SE-ResNeXt-101 (64x4d) model from 'Squeeze-and-Excitation Networks,' https://arxiv.org/abs/1709.01507. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.keras/models' Location for keeping the model parameters. """ return get_seresnext(blocks=101, cardinality=64, bottleneck_width=4, model_name="seresnext101_64x4d", **kwargs) def _test(): import numpy as np import keras pretrained = False models = [ seresnext50_32x4d, seresnext101_32x4d, seresnext101_64x4d, ] for model in models: net = model(pretrained=pretrained) # net.summary() weight_count = keras.utils.layer_utils.count_params(net.trainable_weights) print("m={}, {}".format(model.__name__, weight_count)) assert (model != seresnext50_32x4d or weight_count == 27559896) assert (model != seresnext101_32x4d or weight_count == 48955416) assert (model != seresnext101_64x4d or weight_count == 88232984) if is_channels_first(): x = np.zeros((1, 3, 224, 224), np.float32) else: x = np.zeros((1, 224, 224, 3), np.float32) y = net.predict(x) assert (y.shape == (1, 1000)) if __name__ == "__main__": _test()
30.039427
115
0.612099
__all__ = ['seresnext', 'seresnext50_32x4d', 'seresnext101_32x4d', 'seresnext101_64x4d'] import os from keras import layers as nn from keras.models import Model from .common import conv1x1_block, se_block, is_channels_first, flatten from .resnet import res_init_block from .resnext import resnext_bottleneck def seresnext_unit(x, in_channels, out_channels, strides, cardinality, bottleneck_width, name="seresnext_unit"): resize_identity = (in_channels != out_channels) or (strides != 1) if resize_identity: identity = conv1x1_block( x=x, in_channels=in_channels, out_channels=out_channels, strides=strides, activation=None, name=name + "/identity_conv") else: identity = x x = resnext_bottleneck( x=x, in_channels=in_channels, out_channels=out_channels, strides=strides, cardinality=cardinality, bottleneck_width=bottleneck_width, name=name + "/body") x = se_block( x=x, channels=out_channels, name=name + "/se") x = nn.add([x, identity], name=name + "/add") activ = nn.Activation("relu", name=name + "/activ") x = activ(x) return x def seresnext(channels, init_block_channels, cardinality, bottleneck_width, in_channels=3, in_size=(224, 224), classes=1000): input_shape = (in_channels, in_size[0], in_size[1]) if is_channels_first() else\ (in_size[0], in_size[1], in_channels) input = nn.Input(shape=input_shape) x = res_init_block( x=input, in_channels=in_channels, out_channels=init_block_channels, name="features/init_block") in_channels = init_block_channels for i, channels_per_stage in enumerate(channels): for j, out_channels in enumerate(channels_per_stage): strides = 2 if (j == 0) and (i != 0) else 1 x = seresnext_unit( x=x, in_channels=in_channels, out_channels=out_channels, strides=strides, cardinality=cardinality, bottleneck_width=bottleneck_width, name="features/stage{}/unit{}".format(i + 1, j + 1)) in_channels = out_channels x = nn.AvgPool2D( pool_size=7, strides=1, name="features/final_pool")(x) x = flatten(x) x = nn.Dense( units=classes, input_dim=in_channels, name="output")(x) model = Model(inputs=input, outputs=x) model.in_size = in_size model.classes = classes return model def get_seresnext(blocks, cardinality, bottleneck_width, model_name=None, pretrained=False, root=os.path.join("~", ".keras", "models"), **kwargs): if blocks == 50: layers = [3, 4, 6, 3] elif blocks == 101: layers = [3, 4, 23, 3] else: raise ValueError("Unsupported SE-ResNeXt with number of blocks: {}".format(blocks)) init_block_channels = 64 channels_per_layers = [256, 512, 1024, 2048] channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)] net = seresnext( channels=channels, init_block_channels=init_block_channels, cardinality=cardinality, bottleneck_width=bottleneck_width, **kwargs) if pretrained: if (model_name is None) or (not model_name): raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.") from .model_store import download_model download_model( net=net, model_name=model_name, local_model_store_dir_path=root) return net def seresnext50_32x4d(**kwargs): return get_seresnext(blocks=50, cardinality=32, bottleneck_width=4, model_name="seresnext50_32x4d", **kwargs) def seresnext101_32x4d(**kwargs): return get_seresnext(blocks=101, cardinality=32, bottleneck_width=4, model_name="seresnext101_32x4d", **kwargs) def seresnext101_64x4d(**kwargs): return get_seresnext(blocks=101, cardinality=64, bottleneck_width=4, model_name="seresnext101_64x4d", **kwargs) def _test(): import numpy as np import keras pretrained = False models = [ seresnext50_32x4d, seresnext101_32x4d, seresnext101_64x4d, ] for model in models: net = model(pretrained=pretrained) weight_count = keras.utils.layer_utils.count_params(net.trainable_weights) print("m={}, {}".format(model.__name__, weight_count)) assert (model != seresnext50_32x4d or weight_count == 27559896) assert (model != seresnext101_32x4d or weight_count == 48955416) assert (model != seresnext101_64x4d or weight_count == 88232984) if is_channels_first(): x = np.zeros((1, 3, 224, 224), np.float32) else: x = np.zeros((1, 224, 224, 3), np.float32) y = net.predict(x) assert (y.shape == (1, 1000)) if __name__ == "__main__": _test()
true
true
f7fa091dacfbf5dab51985e0f517f9cbc271d7e7
876
py
Python
scripts/a1_trim_PSF.py
bhishanpdl/DMstack_obsfile_example
6987cc0bc418de209dc660a447f023ca278a7553
[ "MIT" ]
null
null
null
scripts/a1_trim_PSF.py
bhishanpdl/DMstack_obsfile_example
6987cc0bc418de209dc660a447f023ca278a7553
[ "MIT" ]
4
2018-02-17T16:53:46.000Z
2018-02-28T20:37:04.000Z
scripts/a1_trim_PSF.py
bhishanpdl/DMstack_obsfile_example
6987cc0bc418de209dc660a447f023ca278a7553
[ "MIT" ]
null
null
null
#!python # -*- coding: utf-8 -*-# """ Trim the psf to a given size. @author: Bhishan Poudel @date: Feb 19, 2018 @email: bhishanpdl@gmail.com """ # Imports import numpy as np from astropy.io import fits import sys def trim_psf(psf,x,y,r,scale_up): data = fits.getdata(psf) data_trim = data[y-r:y+r,x-r:x+r] * scale_up ofile = 'trimmed_' + psf print('Creating: ', ofile) fits.writeto(ofile,data_trim,overwrite=True) def main(): """Run main function.""" # psf = 'psf/psfb.fits' psf = sys.argv[1] x = 2035 # opening psf in ds9, center was 2035,2015 y = 2015 r = 20 scale_up = sys.argv[2] # prints print('Input psf: ', psf) print('Center of psf: ', x, ' ', y) print('Radius of psf: ', r) print('Scale up: ', scale_up) trim_psf(psf,x,y,r,scale_up) if __name__ == "__main__": main()
19.466667
55
0.593607
import numpy as np from astropy.io import fits import sys def trim_psf(psf,x,y,r,scale_up): data = fits.getdata(psf) data_trim = data[y-r:y+r,x-r:x+r] * scale_up ofile = 'trimmed_' + psf print('Creating: ', ofile) fits.writeto(ofile,data_trim,overwrite=True) def main(): psf = sys.argv[1] x = 2035 y = 2015 r = 20 scale_up = sys.argv[2] print('Input psf: ', psf) print('Center of psf: ', x, ' ', y) print('Radius of psf: ', r) print('Scale up: ', scale_up) trim_psf(psf,x,y,r,scale_up) if __name__ == "__main__": main()
true
true
f7fa0977ad39d139fecd35b5571051debf8b7010
1,517
py
Python
cst/waveform.py
gely/coseis
8b608a5f7a5eab570bbd17a6d6caf278e787ada0
[ "BSD-2-Clause" ]
7
2015-11-22T16:16:45.000Z
2019-08-21T09:19:27.000Z
cst/waveform.py
gely/coseis
8b608a5f7a5eab570bbd17a6d6caf278e787ada0
[ "BSD-2-Clause" ]
null
null
null
cst/waveform.py
gely/coseis
8b608a5f7a5eab570bbd17a6d6caf278e787ada0
[ "BSD-2-Clause" ]
5
2016-06-09T22:34:27.000Z
2020-04-12T01:31:11.000Z
""" Waveform data tools. """ import numpy def csmip_vol2(filename, max_year=2050): """ Read strong motion record in CSMIP Volume 2 format. California Strong Motion Instrumentation Program: http://www.strongmotioncenter.org """ # read file ss = open(filename).readlines() j = 0 # text header t = ss[j+4][59:69] m = int(ss[j+4][49:51]) d = int(ss[j+4][52:54]) y = int(ss[j+4][55:57]) + 2000 if y > max_year: y -= 100 time = '%04d/%02d/%02dT%s' % (y, m, d, t) lon = ss[j+5][29:36] lat = ss[j+5][20:26] data = {'time': time, 'lon': lon, 'lat': lat} # loop over channels while j < len(ss): # integer-value header j += 25 ihdr = [] n = 5 while len(ihdr) < 100: ihdr += [int(ss[j][i:i+n]) for i in range(0, len(ss[j]) - 2, n)] j += 1 orient = ihdr[26] # real-value header rhdr = [] n = 10 while len(rhdr) < 100: rhdr += [float(ss[j][i:i+n]) for i in range(0, len(ss[j]) - 2, n)] j += 1 data['dt'] = rhdr[52] # data n = 10 for w in 'avd': m = int(ss[j][:6]) v = [] j += 1 while len(v) < m: v += [float(ss[j][i:i+n]) for i in range(0, len(ss[j]) - 2, n)] j += 1 k = '%s%03d' % (w, orient) data[k] = numpy.array(v) # trailer j += 1 return data
22.641791
79
0.439684
import numpy def csmip_vol2(filename, max_year=2050): ss = open(filename).readlines() j = 0 t = ss[j+4][59:69] m = int(ss[j+4][49:51]) d = int(ss[j+4][52:54]) y = int(ss[j+4][55:57]) + 2000 if y > max_year: y -= 100 time = '%04d/%02d/%02dT%s' % (y, m, d, t) lon = ss[j+5][29:36] lat = ss[j+5][20:26] data = {'time': time, 'lon': lon, 'lat': lat} while j < len(ss): j += 25 ihdr = [] n = 5 while len(ihdr) < 100: ihdr += [int(ss[j][i:i+n]) for i in range(0, len(ss[j]) - 2, n)] j += 1 orient = ihdr[26] rhdr = [] n = 10 while len(rhdr) < 100: rhdr += [float(ss[j][i:i+n]) for i in range(0, len(ss[j]) - 2, n)] j += 1 data['dt'] = rhdr[52] n = 10 for w in 'avd': m = int(ss[j][:6]) v = [] j += 1 while len(v) < m: v += [float(ss[j][i:i+n]) for i in range(0, len(ss[j]) - 2, n)] j += 1 k = '%s%03d' % (w, orient) data[k] = numpy.array(v) j += 1 return data
true
true
f7fa098a599b244315df0e1199b06087e0ccebd4
3,175
py
Python
_downloads/youtube_dl/extractor/noovo.py
andrew4699/Audis
bcf905cc0c04ab92efdeb116c630745149a3076b
[ "Apache-2.0" ]
12
2017-11-01T12:35:47.000Z
2020-02-26T19:41:30.000Z
_downloads/youtube_dl/extractor/noovo.py
andrew4699/Audis
bcf905cc0c04ab92efdeb116c630745149a3076b
[ "Apache-2.0" ]
8
2017-12-05T23:45:54.000Z
2022-02-09T23:28:51.000Z
_downloads/youtube_dl/extractor/noovo.py
andrew4699/Audis
bcf905cc0c04ab92efdeb116c630745149a3076b
[ "Apache-2.0" ]
6
2017-07-15T07:17:29.000Z
2018-03-13T07:31:18.000Z
# coding: utf-8 from __future__ import unicode_literals from .brightcove import BrightcoveNewIE from .common import InfoExtractor from ..compat import compat_str from ..utils import ( int_or_none, smuggle_url, try_get, ) class NoovoIE(InfoExtractor): _VALID_URL = r'https?://(?:[^/]+\.)?noovo\.ca/videos/(?P<id>[^/]+/[^/?#&]+)' _TESTS = [{ # clip 'url': 'http://noovo.ca/videos/rpm-plus/chrysler-imperial', 'info_dict': { 'id': '5386045029001', 'ext': 'mp4', 'title': 'Chrysler Imperial', 'description': 'md5:de3c898d1eb810f3e6243e08c8b4a056', 'timestamp': 1491399228, 'upload_date': '20170405', 'uploader_id': '618566855001', 'creator': 'vtele', 'view_count': int, 'series': 'RPM+', }, 'params': { 'skip_download': True, }, }, { # episode 'url': 'http://noovo.ca/videos/l-amour-est-dans-le-pre/episode-13-8', 'info_dict': { 'id': '5395865725001', 'title': 'Épisode 13 : Les retrouvailles', 'description': 'md5:336d5ebc5436534e61d16e63ddfca327', 'ext': 'mp4', 'timestamp': 1492019320, 'upload_date': '20170412', 'uploader_id': '618566855001', 'creator': 'vtele', 'view_count': int, 'series': "L'amour est dans le pré", 'season_number': 5, 'episode': 'Épisode 13', 'episode_number': 13, }, 'params': { 'skip_download': True, }, }] BRIGHTCOVE_URL_TEMPLATE = 'http://players.brightcove.net/618566855001/default_default/index.html?videoId=%s' def _real_extract(self, url): video_id = self._match_id(url) data = self._download_json( 'http://api.noovo.ca/api/v1/pages/single-episode/%s' % video_id, video_id)['data'] content = try_get(data, lambda x: x['contents'][0]) brightcove_id = data.get('brightcoveId') or content['brightcoveId'] series = try_get( data, ( lambda x: x['show']['title'], lambda x: x['season']['show']['title']), compat_str) episode = None og = data.get('og') if isinstance(og, dict) and og.get('type') == 'video.episode': episode = og.get('title') video = content or data return { '_type': 'url_transparent', 'ie_key': BrightcoveNewIE.ie_key(), 'url': smuggle_url( self.BRIGHTCOVE_URL_TEMPLATE % brightcove_id, {'geo_countries': ['CA']}), 'id': brightcove_id, 'title': video.get('title'), 'creator': video.get('source'), 'view_count': int_or_none(video.get('viewsCount')), 'series': series, 'season_number': int_or_none(try_get( data, lambda x: x['season']['seasonNumber'])), 'episode': episode, 'episode_number': int_or_none(data.get('episodeNumber')), }
32.397959
112
0.524094
from __future__ import unicode_literals from .brightcove import BrightcoveNewIE from .common import InfoExtractor from ..compat import compat_str from ..utils import ( int_or_none, smuggle_url, try_get, ) class NoovoIE(InfoExtractor): _VALID_URL = r'https?://(?:[^/]+\.)?noovo\.ca/videos/(?P<id>[^/]+/[^/?#&]+)' _TESTS = [{ 'url': 'http://noovo.ca/videos/rpm-plus/chrysler-imperial', 'info_dict': { 'id': '5386045029001', 'ext': 'mp4', 'title': 'Chrysler Imperial', 'description': 'md5:de3c898d1eb810f3e6243e08c8b4a056', 'timestamp': 1491399228, 'upload_date': '20170405', 'uploader_id': '618566855001', 'creator': 'vtele', 'view_count': int, 'series': 'RPM+', }, 'params': { 'skip_download': True, }, }, { 'url': 'http://noovo.ca/videos/l-amour-est-dans-le-pre/episode-13-8', 'info_dict': { 'id': '5395865725001', 'title': 'Épisode 13 : Les retrouvailles', 'description': 'md5:336d5ebc5436534e61d16e63ddfca327', 'ext': 'mp4', 'timestamp': 1492019320, 'upload_date': '20170412', 'uploader_id': '618566855001', 'creator': 'vtele', 'view_count': int, 'series': "L'amour est dans le pré", 'season_number': 5, 'episode': 'Épisode 13', 'episode_number': 13, }, 'params': { 'skip_download': True, }, }] BRIGHTCOVE_URL_TEMPLATE = 'http://players.brightcove.net/618566855001/default_default/index.html?videoId=%s' def _real_extract(self, url): video_id = self._match_id(url) data = self._download_json( 'http://api.noovo.ca/api/v1/pages/single-episode/%s' % video_id, video_id)['data'] content = try_get(data, lambda x: x['contents'][0]) brightcove_id = data.get('brightcoveId') or content['brightcoveId'] series = try_get( data, ( lambda x: x['show']['title'], lambda x: x['season']['show']['title']), compat_str) episode = None og = data.get('og') if isinstance(og, dict) and og.get('type') == 'video.episode': episode = og.get('title') video = content or data return { '_type': 'url_transparent', 'ie_key': BrightcoveNewIE.ie_key(), 'url': smuggle_url( self.BRIGHTCOVE_URL_TEMPLATE % brightcove_id, {'geo_countries': ['CA']}), 'id': brightcove_id, 'title': video.get('title'), 'creator': video.get('source'), 'view_count': int_or_none(video.get('viewsCount')), 'series': series, 'season_number': int_or_none(try_get( data, lambda x: x['season']['seasonNumber'])), 'episode': episode, 'episode_number': int_or_none(data.get('episodeNumber')), }
true
true
f7fa0c329a34f4051e5a1cd9abb20db3705486b7
12,783
py
Python
authors/apps/articles/views.py
andela/ah-backend-stark
c38810e221f95567262034b860ee0512cf15f102
[ "BSD-3-Clause" ]
null
null
null
authors/apps/articles/views.py
andela/ah-backend-stark
c38810e221f95567262034b860ee0512cf15f102
[ "BSD-3-Clause" ]
29
2018-09-25T13:53:06.000Z
2021-06-10T20:51:58.000Z
authors/apps/articles/views.py
andela/ah-backend-stark
c38810e221f95567262034b860ee0512cf15f102
[ "BSD-3-Clause" ]
2
2019-08-02T12:23:24.000Z
2019-11-05T12:22:23.000Z
from django.shortcuts import get_object_or_404 from rest_framework import status, serializers, exceptions from rest_framework.pagination import LimitOffsetPagination from rest_framework.permissions import (IsAuthenticatedOrReadOnly, IsAuthenticated, AllowAny) from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.generics import (UpdateAPIView, CreateAPIView, RetrieveAPIView, ListAPIView) from .renderers import ArticleJSONRenderer, LikesJSONRenderer from .serializers import (ArticlesSerializer, CommentSerializer, CommentDetailSerializer, LikeSerializer, ArticlesReadSerializer) from .models import Article, Comment, Likes, ArticlesRead from authors.apps.profiles.serializers import ProfileSerializer from authors.apps.profiles.models import Profile from authors.apps.authentication.backends import JWTAuthentication from .mixins import AhPaginationMixin class ArticleCreationAPIView(APIView, AhPaginationMixin): permission_classes = (IsAuthenticatedOrReadOnly, ) serializer_class = ArticlesSerializer pagination_class = LimitOffsetPagination profile_serializer_class = ProfileSerializer def get(self, request): article = Article.objects.all().order_by('-id') page = self.paginate_queryset(article) if page is not None: serializer = self.serializer_class(page, many=True) res_data = Article.format_data_for_display(serializer.data) new_data = self.get_paginated_response(res_data) return new_data def post(self, request): article = request.data.get('article') user = get_user_from_auth(request) article['author'] = user.id if Article.title_exists(user.id, article['title']): raise serializers.ValidationError( 'You already have an article with the same title', 409) article = ArticlesSerializer.convert_tagList_to_str(article) serializer = self.serializer_class(data=article) serializer.is_valid(raise_exception=True) serializer.save() action = "increment" Profile.update_write_stats(request, self.profile_serializer_class, action) res_data = Article.format_data_for_display(serializer.data) return Response(res_data, status=status.HTTP_201_CREATED) class GetSingleArticleAPIView(APIView): permission_classes = (IsAuthenticatedOrReadOnly, ) renderer_classes = (ArticleJSONRenderer, ) serializer_class = ArticlesSerializer articles_read_serializer_class = ArticlesReadSerializer profile_serializer_class = ProfileSerializer def check_authenticated(self, request, user, slug, author): if user: if ArticlesRead.already_read(user, slug) or user == author: pass else: self.update_read_stats(user, request, slug) def update_read_stats(self, user, request, slug): """ This method increments the articles_read field when a user reads an article """ serializer_data = {"user": user, "slug": slug} read_serializer = self.articles_read_serializer_class( data=serializer_data) read_serializer.is_valid(raise_exception=True) read_serializer.save() field_str = "articles_read" user_id = request.user.id instance = Profile.objects.filter(user_id=user_id) username = instance.first() profile = Profile.objects.select_related('user').get( user__username=username) action = "increment" Profile.update_profile_stats(request, self.profile_serializer_class, profile.articles_read, field_str, action) def get(self, request, slug): article = Article.get_article(slug) if not article: raise exceptions.NotFound('The selected article was not found.') serializer = self.serializer_class(article) res_data = Article.format_data_for_display(serializer.data) user = request.user.id author = Article.get_single_article(slug)[0].author_id self.check_authenticated(request, user, slug, author) return Response({"article": res_data}, status.HTTP_200_OK) def put(self, request, slug): user = get_user_from_auth(request) new_article = request.data.get('article') status = Article.update_article(user.id, slug, new_article) if status[1] == 202: serializer = self.serializer_class(status[0]) res_data = Article.format_data_for_display(serializer.data) return Response(res_data, 202) return Response({'message': status[0]}, status[1]) def delete(self, request, slug): user = get_user_from_auth(request) status = Article.delete_article(user.id, slug) action = "decrement" Profile.update_write_stats(request, self.profile_serializer_class, action) return Response({'message': status[0]}, status[1]) class RateArticleAPIView(APIView): """ This class contains the views regarding the article rating feature """ permission_classes = (IsAuthenticated, ) serializer_class = ArticlesSerializer def get_values(self, queryset): """ This method takes in the article queryset and returns a dictionary of the article's data """ return queryset.values()[0] def validate_rating(self, rating): if rating not in list(range(1, 6)): raise exceptions.ParseError( "Sorry, only a rating in the 1-5 range can be given.") def put(self, request, slug): """ This method rates an article and saves the updated rating and ratingsCount in the database """ queryset = Article.objects.filter(slug=slug) article = self.get_values(queryset) if not queryset: raise exceptions.NotFound('The selected article was not found.') elif article.get("author_id") == get_user_from_auth(request).id: raise exceptions.ParseError( "Sorry, you cannot rate your own article.") serializer_instance = queryset.first() serializer_data = request.data.get('article', {}) self.validate_rating(serializer_data.get("rating")) current_rating = article['rating'] current_rating_count = article['ratingsCount'] user_rating = serializer_data.get('rating') new_rating = Article.calculate_rating( current_rating, current_rating_count, user_rating) serializer_data["rating"] = new_rating["rating"] serializer_data["ratingsCount"] = new_rating["ratingsCount"] serializer = self.serializer_class( serializer_instance, data=serializer_data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response({ "article": serializer.data }, status=status.HTTP_202_ACCEPTED) def get_user_from_auth(request): """ This helper function returns an instance of the authenticated user and their token from the authentication class """ auth = JWTAuthentication() user = auth.authenticate(request)[0] return user class LikeView(CreateAPIView, UpdateAPIView): """like view class""" permission_classes = (IsAuthenticated, ) renderer_classes = (LikesJSONRenderer, ) serializer_class = LikeSerializer def create(self, request, *args, **kwargs): article = self.kwargs["slug"] self.article1 = get_object_or_404(Article, slug=article) if Likes.objects.filter( action_by=request.user, article=self.article1).exists(): raise serializers.ValidationError( 'you can only like or dislike an article once', 400) else: action = request.data.get('like', {}) serializer = self.serializer_class(data=action) serializer.is_valid(raise_exception=True) serializer.save(action_by=self.request.user, article=self.article1) return Response(serializer.data, status=status.HTTP_201_CREATED) def update(self, request, *args, **kwargs): article1 = self.kwargs["slug"] article = get_object_or_404(Article, slug=article1) try: instance = Likes.objects.get( action_by=request.user.id, article=article.id) action = request.data.get('like', {}) serializer = self.serializer_class( instance, data=action, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) except Exception: raise serializers.ValidationError( 'cannot update' 'like or dislike article', 400) class PostCommentApiView(APIView): permission_classes = (IsAuthenticatedOrReadOnly, ) serializer_class = CommentSerializer def get(self, request, slug): instance = get_object_or_404(Article, slug=slug) article = instance.id comment = Comment.objects.all().filter(article_id=article) serializer = self.serializer_class(comment, many=True) return Response({"comments": serializer.data}, status.HTTP_200_OK) def post(self, request, slug): comment = request.data.get("comment") instance = get_object_or_404(Article, slug=slug) user = get_user_from_auth(request) comment["user"] = user.id comment["article"] = instance.id serializer = self.serializer_class(data=comment) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) class CommentDetailApiView(APIView): permission_classes = (IsAuthenticatedOrReadOnly, ) serializer_class = CommentDetailSerializer def get(self, request, slug, id): comment = Comment.objects.all().filter(id=id) serializer = self.serializer_class(comment, many=True) new_data = serializer.data for item in new_data: new_comment = self.format_dictionary(item) return Response({"comment": new_comment}, status.HTTP_200_OK) def format_dictionary(self, item): new_comment = dict( id=item["id"], body=item["body"], user=item["user"], timestamp=item["timestamp"], reply=item["replies"]) return new_comment def post(self, request, slug, id): comment = request.data.get("reply") instance = get_object_or_404(Article, slug=slug) user = get_user_from_auth(request) comment["user"] = user.id comment["article"] = instance.id comment["parent_comment"] = id serializer = self.serializer_class(data=comment) serializer.is_valid(raise_exception=True) serializer.save() new_data = serializer.data new_comment = self.format_dictionary(new_data) return Response(new_comment, status=status.HTTP_201_CREATED) @staticmethod def delete(request, slug, id): comment = Comment.objects.get(pk=id) comment.delete() return Response(status=status.HTTP_204_NO_CONTENT) class SearchArticleView(ListAPIView): permission_classes = (AllowAny, ) serializer_class = ArticlesSerializer def get(self, request): search_params = request.query_params query_set = Article.objects.all() author = search_params.get('author', None) title = search_params.get('title', None) tag = search_params.get('tag', None) keywords = search_params.get('keywords', None) if author: query_set = query_set.filter(author__username=author) if title: query_set = query_set.filter(title__icontains=title) if tag: query_set = query_set.filter(tagList__icontains=tag) if keywords: words = str(keywords).split(',') final_queryset = '' for word in words: final_queryset = query_set.filter(title__icontains=word) query_set = final_queryset serializer = self.serializer_class(query_set, many=True) res_data = serializer.data if res_data: res_data = Article.format_data_for_display(res_data) return Response({"search results": res_data}, status.HTTP_200_OK)
39.82243
79
0.660252
from django.shortcuts import get_object_or_404 from rest_framework import status, serializers, exceptions from rest_framework.pagination import LimitOffsetPagination from rest_framework.permissions import (IsAuthenticatedOrReadOnly, IsAuthenticated, AllowAny) from rest_framework.response import Response from rest_framework.views import APIView from rest_framework.generics import (UpdateAPIView, CreateAPIView, RetrieveAPIView, ListAPIView) from .renderers import ArticleJSONRenderer, LikesJSONRenderer from .serializers import (ArticlesSerializer, CommentSerializer, CommentDetailSerializer, LikeSerializer, ArticlesReadSerializer) from .models import Article, Comment, Likes, ArticlesRead from authors.apps.profiles.serializers import ProfileSerializer from authors.apps.profiles.models import Profile from authors.apps.authentication.backends import JWTAuthentication from .mixins import AhPaginationMixin class ArticleCreationAPIView(APIView, AhPaginationMixin): permission_classes = (IsAuthenticatedOrReadOnly, ) serializer_class = ArticlesSerializer pagination_class = LimitOffsetPagination profile_serializer_class = ProfileSerializer def get(self, request): article = Article.objects.all().order_by('-id') page = self.paginate_queryset(article) if page is not None: serializer = self.serializer_class(page, many=True) res_data = Article.format_data_for_display(serializer.data) new_data = self.get_paginated_response(res_data) return new_data def post(self, request): article = request.data.get('article') user = get_user_from_auth(request) article['author'] = user.id if Article.title_exists(user.id, article['title']): raise serializers.ValidationError( 'You already have an article with the same title', 409) article = ArticlesSerializer.convert_tagList_to_str(article) serializer = self.serializer_class(data=article) serializer.is_valid(raise_exception=True) serializer.save() action = "increment" Profile.update_write_stats(request, self.profile_serializer_class, action) res_data = Article.format_data_for_display(serializer.data) return Response(res_data, status=status.HTTP_201_CREATED) class GetSingleArticleAPIView(APIView): permission_classes = (IsAuthenticatedOrReadOnly, ) renderer_classes = (ArticleJSONRenderer, ) serializer_class = ArticlesSerializer articles_read_serializer_class = ArticlesReadSerializer profile_serializer_class = ProfileSerializer def check_authenticated(self, request, user, slug, author): if user: if ArticlesRead.already_read(user, slug) or user == author: pass else: self.update_read_stats(user, request, slug) def update_read_stats(self, user, request, slug): serializer_data = {"user": user, "slug": slug} read_serializer = self.articles_read_serializer_class( data=serializer_data) read_serializer.is_valid(raise_exception=True) read_serializer.save() field_str = "articles_read" user_id = request.user.id instance = Profile.objects.filter(user_id=user_id) username = instance.first() profile = Profile.objects.select_related('user').get( user__username=username) action = "increment" Profile.update_profile_stats(request, self.profile_serializer_class, profile.articles_read, field_str, action) def get(self, request, slug): article = Article.get_article(slug) if not article: raise exceptions.NotFound('The selected article was not found.') serializer = self.serializer_class(article) res_data = Article.format_data_for_display(serializer.data) user = request.user.id author = Article.get_single_article(slug)[0].author_id self.check_authenticated(request, user, slug, author) return Response({"article": res_data}, status.HTTP_200_OK) def put(self, request, slug): user = get_user_from_auth(request) new_article = request.data.get('article') status = Article.update_article(user.id, slug, new_article) if status[1] == 202: serializer = self.serializer_class(status[0]) res_data = Article.format_data_for_display(serializer.data) return Response(res_data, 202) return Response({'message': status[0]}, status[1]) def delete(self, request, slug): user = get_user_from_auth(request) status = Article.delete_article(user.id, slug) action = "decrement" Profile.update_write_stats(request, self.profile_serializer_class, action) return Response({'message': status[0]}, status[1]) class RateArticleAPIView(APIView): permission_classes = (IsAuthenticated, ) serializer_class = ArticlesSerializer def get_values(self, queryset): return queryset.values()[0] def validate_rating(self, rating): if rating not in list(range(1, 6)): raise exceptions.ParseError( "Sorry, only a rating in the 1-5 range can be given.") def put(self, request, slug): queryset = Article.objects.filter(slug=slug) article = self.get_values(queryset) if not queryset: raise exceptions.NotFound('The selected article was not found.') elif article.get("author_id") == get_user_from_auth(request).id: raise exceptions.ParseError( "Sorry, you cannot rate your own article.") serializer_instance = queryset.first() serializer_data = request.data.get('article', {}) self.validate_rating(serializer_data.get("rating")) current_rating = article['rating'] current_rating_count = article['ratingsCount'] user_rating = serializer_data.get('rating') new_rating = Article.calculate_rating( current_rating, current_rating_count, user_rating) serializer_data["rating"] = new_rating["rating"] serializer_data["ratingsCount"] = new_rating["ratingsCount"] serializer = self.serializer_class( serializer_instance, data=serializer_data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response({ "article": serializer.data }, status=status.HTTP_202_ACCEPTED) def get_user_from_auth(request): auth = JWTAuthentication() user = auth.authenticate(request)[0] return user class LikeView(CreateAPIView, UpdateAPIView): permission_classes = (IsAuthenticated, ) renderer_classes = (LikesJSONRenderer, ) serializer_class = LikeSerializer def create(self, request, *args, **kwargs): article = self.kwargs["slug"] self.article1 = get_object_or_404(Article, slug=article) if Likes.objects.filter( action_by=request.user, article=self.article1).exists(): raise serializers.ValidationError( 'you can only like or dislike an article once', 400) else: action = request.data.get('like', {}) serializer = self.serializer_class(data=action) serializer.is_valid(raise_exception=True) serializer.save(action_by=self.request.user, article=self.article1) return Response(serializer.data, status=status.HTTP_201_CREATED) def update(self, request, *args, **kwargs): article1 = self.kwargs["slug"] article = get_object_or_404(Article, slug=article1) try: instance = Likes.objects.get( action_by=request.user.id, article=article.id) action = request.data.get('like', {}) serializer = self.serializer_class( instance, data=action, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) except Exception: raise serializers.ValidationError( 'cannot update' 'like or dislike article', 400) class PostCommentApiView(APIView): permission_classes = (IsAuthenticatedOrReadOnly, ) serializer_class = CommentSerializer def get(self, request, slug): instance = get_object_or_404(Article, slug=slug) article = instance.id comment = Comment.objects.all().filter(article_id=article) serializer = self.serializer_class(comment, many=True) return Response({"comments": serializer.data}, status.HTTP_200_OK) def post(self, request, slug): comment = request.data.get("comment") instance = get_object_or_404(Article, slug=slug) user = get_user_from_auth(request) comment["user"] = user.id comment["article"] = instance.id serializer = self.serializer_class(data=comment) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) class CommentDetailApiView(APIView): permission_classes = (IsAuthenticatedOrReadOnly, ) serializer_class = CommentDetailSerializer def get(self, request, slug, id): comment = Comment.objects.all().filter(id=id) serializer = self.serializer_class(comment, many=True) new_data = serializer.data for item in new_data: new_comment = self.format_dictionary(item) return Response({"comment": new_comment}, status.HTTP_200_OK) def format_dictionary(self, item): new_comment = dict( id=item["id"], body=item["body"], user=item["user"], timestamp=item["timestamp"], reply=item["replies"]) return new_comment def post(self, request, slug, id): comment = request.data.get("reply") instance = get_object_or_404(Article, slug=slug) user = get_user_from_auth(request) comment["user"] = user.id comment["article"] = instance.id comment["parent_comment"] = id serializer = self.serializer_class(data=comment) serializer.is_valid(raise_exception=True) serializer.save() new_data = serializer.data new_comment = self.format_dictionary(new_data) return Response(new_comment, status=status.HTTP_201_CREATED) @staticmethod def delete(request, slug, id): comment = Comment.objects.get(pk=id) comment.delete() return Response(status=status.HTTP_204_NO_CONTENT) class SearchArticleView(ListAPIView): permission_classes = (AllowAny, ) serializer_class = ArticlesSerializer def get(self, request): search_params = request.query_params query_set = Article.objects.all() author = search_params.get('author', None) title = search_params.get('title', None) tag = search_params.get('tag', None) keywords = search_params.get('keywords', None) if author: query_set = query_set.filter(author__username=author) if title: query_set = query_set.filter(title__icontains=title) if tag: query_set = query_set.filter(tagList__icontains=tag) if keywords: words = str(keywords).split(',') final_queryset = '' for word in words: final_queryset = query_set.filter(title__icontains=word) query_set = final_queryset serializer = self.serializer_class(query_set, many=True) res_data = serializer.data if res_data: res_data = Article.format_data_for_display(res_data) return Response({"search results": res_data}, status.HTTP_200_OK)
true
true
f7fa0c74cacb6871720920abe3c7178246af416a
8,491
py
Python
open_spiel/python/tests/pyspiel_test.py
JialianLee/open_spiel
7d3d7921591aeaf993e94fd9ff7567af66f071c7
[ "Apache-2.0" ]
null
null
null
open_spiel/python/tests/pyspiel_test.py
JialianLee/open_spiel
7d3d7921591aeaf993e94fd9ff7567af66f071c7
[ "Apache-2.0" ]
null
null
null
open_spiel/python/tests/pyspiel_test.py
JialianLee/open_spiel
7d3d7921591aeaf993e94fd9ff7567af66f071c7
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 DeepMind Technologies Ltd. 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 open_spiel.python.pybind11.pyspiel.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl.testing import absltest import six from open_spiel.python import policy import pyspiel class PyspielTest(absltest.TestCase): def test_registered_names(self): game_names = pyspiel.registered_names() # Specify game names in alphabetical order, to make the test easier to read. expected = set([ "backgammon", "blotto", "breakthrough", "bridge", "bridge_uncontested_bidding", "catch", "chess", "cliff_walking", "coin_game", "connect_four", "coop_box_pushing", "coop_to_1p", "cursor_go", "deep_sea", "efg_game", "first_sealed_auction", "gin_rummy", "go", "goofspiel", "havannah", "hex", "kuhn_poker", "laser_tag", "leduc_poker", "liars_dice", "markov_soccer", "matching_pennies_3p", "matrix_cd", "matrix_coordination", "matrix_mp", "matrix_pd", "matrix_rps", "matrix_rpsw", "matrix_sh", "matrix_shapleys_game", "misere", "negotiation", "normal_form_extensive_game", "oshi_zumo", "oware", "pentago", "phantom_ttt", "pig", "quoridor", "skat", "tic_tac_toe", "tiny_bridge_2p", "tiny_bridge_4p", "tiny_hanabi", "turn_based_simultaneous_game", "y", ]) if os.environ.get("BUILD_WITH_HANABI", "OFF") == "ON": expected.add("hanabi") if os.environ.get("BUILD_WITH_ACPC", "OFF") == "ON": expected.add("universal_poker") expected = sorted(list(expected)) self.assertCountEqual(game_names, expected) def test_no_mandatory_parameters(self): # Games with mandatory parameters will be skipped by several standard # tests. Mandatory parameters should therefore be avoided if at all # possible. We make a list of such games here in order to make implementors # think twice about adding mandatory parameters. def has_mandatory_params(game): return any(param.is_mandatory() for param in game.parameter_specification.values()) games_with_mandatory_parameters = [ game.short_name for game in pyspiel.registered_games() if has_mandatory_params(game) ] expected = [ # Mandatory parameters prevent various sorts of automated testing. # Only add games here if there is no sensible default for a parameter. "misere", "turn_based_simultaneous_game", "normal_form_extensive_game", ] self.assertCountEqual(games_with_mandatory_parameters, expected) def test_registered_game_attributes(self): games = {game.short_name: game for game in pyspiel.registered_games()} self.assertEqual(games["kuhn_poker"].dynamics, pyspiel.GameType.Dynamics.SEQUENTIAL) self.assertEqual(games["kuhn_poker"].chance_mode, pyspiel.GameType.ChanceMode.EXPLICIT_STOCHASTIC) self.assertEqual(games["kuhn_poker"].information, pyspiel.GameType.Information.IMPERFECT_INFORMATION) self.assertEqual(games["kuhn_poker"].utility, pyspiel.GameType.Utility.ZERO_SUM) self.assertEqual(games["kuhn_poker"].min_num_players, 2) def test_create_game(self): game = pyspiel.load_game("kuhn_poker") game_info = game.get_type() self.assertEqual(game_info.information, pyspiel.GameType.Information.IMPERFECT_INFORMATION) self.assertEqual(game.num_players(), 2) def test_play_kuhn_poker(self): game = pyspiel.load_game("kuhn_poker") state = game.new_initial_state() self.assertEqual(state.is_chance_node(), True) self.assertEqual(state.chance_outcomes(), [(0, 1 / 3), (1, 1 / 3), (2, 1 / 3)]) state.apply_action(1) self.assertEqual(state.is_chance_node(), True) self.assertEqual(state.chance_outcomes(), [(0, 0.5), (2, 0.5)]) state.apply_action(2) self.assertEqual(state.is_chance_node(), False) self.assertEqual(state.legal_actions(), [0, 1]) sampler = pyspiel.UniformProbabilitySampler(0., 1.) clone = state.resample_from_infostate(1, sampler) self.assertEqual( clone.information_state_string(1), state.information_state_string(1)) def test_tic_tac_toe(self): game = pyspiel.load_game("tic_tac_toe") state = game.new_initial_state() self.assertFalse(state.is_chance_node()) self.assertFalse(state.is_terminal()) self.assertEqual(state.legal_actions(), [0, 1, 2, 3, 4, 5, 6, 7, 8]) def test_game_parameter_representation(self): param = pyspiel.GameParameter(True) self.assertEqual(repr(param), "GameParameter(bool_value=True)") param = pyspiel.GameParameter(False) self.assertEqual(repr(param), "GameParameter(bool_value=False)") param = pyspiel.GameParameter("one") self.assertEqual(repr(param), "GameParameter(string_value='one')") param = pyspiel.GameParameter(1) self.assertEqual(repr(param), "GameParameter(int_value=1)") param = pyspiel.GameParameter(1.0) self.assertEqual(repr(param), "GameParameter(double_value=1)") param = pyspiel.GameParameter(1.2) self.assertEqual(repr(param), "GameParameter(double_value=1.2)") def test_game_parameter_equality(self): param1 = pyspiel.GameParameter("one") param1_again = pyspiel.GameParameter("one") param2 = pyspiel.GameParameter("two") self.assertEqual(param1, param1_again) self.assertNotEqual(param1, param2) def test_game_type(self): game_type = pyspiel.GameType( "matrix_mp", "Matching Pennies", pyspiel.GameType.Dynamics.SIMULTANEOUS, pyspiel.GameType.ChanceMode.DETERMINISTIC, pyspiel.GameType.Information.PERFECT_INFORMATION, pyspiel.GameType.Utility.ZERO_SUM, pyspiel.GameType.RewardModel.TERMINAL, 2, 2, True, True, False, False, dict()) self.assertEqual(game_type.chance_mode, pyspiel.GameType.ChanceMode.DETERMINISTIC) def test_error_handling(self): with six.assertRaisesRegex(self, RuntimeError, "Unknown game 'invalid_game_name'"): unused_game = pyspiel.load_game("invalid_game_name") def test_can_create_cpp_tabular_policy(self): for game_name in ["kuhn_poker", "leduc_poker", "liars_dice"]: game = pyspiel.load_game(game_name) # We just test that we can create a tabular policy. policy.python_policy_to_pyspiel_policy(policy.TabularPolicy(game)) def test_simultaneous_game_history(self): game = pyspiel.load_game("coop_box_pushing") state = game.new_initial_state() state.apply_action(0) state2 = game.new_initial_state() state2.apply_actions([0] * game.num_players()) self.assertEqual(state.history(), state2.history()) def test_record_batched_trajectories(self): for game_name in ["kuhn_poker", "leduc_poker", "liars_dice"]: game = pyspiel.load_game(game_name) python_policy = policy.TabularPolicy(game) tabular_policy = policy.python_policy_to_pyspiel_policy(python_policy) policies = [tabular_policy] * 2 # We test that we can create a batch of trajectories. seed = 0 batch_size = 128 include_full_observations = False pyspiel.record_batched_trajectories(game, policies, python_policy.state_lookup, batch_size, include_full_observations, seed, -1) if __name__ == "__main__": absltest.main()
36.44206
80
0.66965
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl.testing import absltest import six from open_spiel.python import policy import pyspiel class PyspielTest(absltest.TestCase): def test_registered_names(self): game_names = pyspiel.registered_names() expected = set([ "backgammon", "blotto", "breakthrough", "bridge", "bridge_uncontested_bidding", "catch", "chess", "cliff_walking", "coin_game", "connect_four", "coop_box_pushing", "coop_to_1p", "cursor_go", "deep_sea", "efg_game", "first_sealed_auction", "gin_rummy", "go", "goofspiel", "havannah", "hex", "kuhn_poker", "laser_tag", "leduc_poker", "liars_dice", "markov_soccer", "matching_pennies_3p", "matrix_cd", "matrix_coordination", "matrix_mp", "matrix_pd", "matrix_rps", "matrix_rpsw", "matrix_sh", "matrix_shapleys_game", "misere", "negotiation", "normal_form_extensive_game", "oshi_zumo", "oware", "pentago", "phantom_ttt", "pig", "quoridor", "skat", "tic_tac_toe", "tiny_bridge_2p", "tiny_bridge_4p", "tiny_hanabi", "turn_based_simultaneous_game", "y", ]) if os.environ.get("BUILD_WITH_HANABI", "OFF") == "ON": expected.add("hanabi") if os.environ.get("BUILD_WITH_ACPC", "OFF") == "ON": expected.add("universal_poker") expected = sorted(list(expected)) self.assertCountEqual(game_names, expected) def test_no_mandatory_parameters(self): def has_mandatory_params(game): return any(param.is_mandatory() for param in game.parameter_specification.values()) games_with_mandatory_parameters = [ game.short_name for game in pyspiel.registered_games() if has_mandatory_params(game) ] expected = [ "misere", "turn_based_simultaneous_game", "normal_form_extensive_game", ] self.assertCountEqual(games_with_mandatory_parameters, expected) def test_registered_game_attributes(self): games = {game.short_name: game for game in pyspiel.registered_games()} self.assertEqual(games["kuhn_poker"].dynamics, pyspiel.GameType.Dynamics.SEQUENTIAL) self.assertEqual(games["kuhn_poker"].chance_mode, pyspiel.GameType.ChanceMode.EXPLICIT_STOCHASTIC) self.assertEqual(games["kuhn_poker"].information, pyspiel.GameType.Information.IMPERFECT_INFORMATION) self.assertEqual(games["kuhn_poker"].utility, pyspiel.GameType.Utility.ZERO_SUM) self.assertEqual(games["kuhn_poker"].min_num_players, 2) def test_create_game(self): game = pyspiel.load_game("kuhn_poker") game_info = game.get_type() self.assertEqual(game_info.information, pyspiel.GameType.Information.IMPERFECT_INFORMATION) self.assertEqual(game.num_players(), 2) def test_play_kuhn_poker(self): game = pyspiel.load_game("kuhn_poker") state = game.new_initial_state() self.assertEqual(state.is_chance_node(), True) self.assertEqual(state.chance_outcomes(), [(0, 1 / 3), (1, 1 / 3), (2, 1 / 3)]) state.apply_action(1) self.assertEqual(state.is_chance_node(), True) self.assertEqual(state.chance_outcomes(), [(0, 0.5), (2, 0.5)]) state.apply_action(2) self.assertEqual(state.is_chance_node(), False) self.assertEqual(state.legal_actions(), [0, 1]) sampler = pyspiel.UniformProbabilitySampler(0., 1.) clone = state.resample_from_infostate(1, sampler) self.assertEqual( clone.information_state_string(1), state.information_state_string(1)) def test_tic_tac_toe(self): game = pyspiel.load_game("tic_tac_toe") state = game.new_initial_state() self.assertFalse(state.is_chance_node()) self.assertFalse(state.is_terminal()) self.assertEqual(state.legal_actions(), [0, 1, 2, 3, 4, 5, 6, 7, 8]) def test_game_parameter_representation(self): param = pyspiel.GameParameter(True) self.assertEqual(repr(param), "GameParameter(bool_value=True)") param = pyspiel.GameParameter(False) self.assertEqual(repr(param), "GameParameter(bool_value=False)") param = pyspiel.GameParameter("one") self.assertEqual(repr(param), "GameParameter(string_value='one')") param = pyspiel.GameParameter(1) self.assertEqual(repr(param), "GameParameter(int_value=1)") param = pyspiel.GameParameter(1.0) self.assertEqual(repr(param), "GameParameter(double_value=1)") param = pyspiel.GameParameter(1.2) self.assertEqual(repr(param), "GameParameter(double_value=1.2)") def test_game_parameter_equality(self): param1 = pyspiel.GameParameter("one") param1_again = pyspiel.GameParameter("one") param2 = pyspiel.GameParameter("two") self.assertEqual(param1, param1_again) self.assertNotEqual(param1, param2) def test_game_type(self): game_type = pyspiel.GameType( "matrix_mp", "Matching Pennies", pyspiel.GameType.Dynamics.SIMULTANEOUS, pyspiel.GameType.ChanceMode.DETERMINISTIC, pyspiel.GameType.Information.PERFECT_INFORMATION, pyspiel.GameType.Utility.ZERO_SUM, pyspiel.GameType.RewardModel.TERMINAL, 2, 2, True, True, False, False, dict()) self.assertEqual(game_type.chance_mode, pyspiel.GameType.ChanceMode.DETERMINISTIC) def test_error_handling(self): with six.assertRaisesRegex(self, RuntimeError, "Unknown game 'invalid_game_name'"): unused_game = pyspiel.load_game("invalid_game_name") def test_can_create_cpp_tabular_policy(self): for game_name in ["kuhn_poker", "leduc_poker", "liars_dice"]: game = pyspiel.load_game(game_name) policy.python_policy_to_pyspiel_policy(policy.TabularPolicy(game)) def test_simultaneous_game_history(self): game = pyspiel.load_game("coop_box_pushing") state = game.new_initial_state() state.apply_action(0) state2 = game.new_initial_state() state2.apply_actions([0] * game.num_players()) self.assertEqual(state.history(), state2.history()) def test_record_batched_trajectories(self): for game_name in ["kuhn_poker", "leduc_poker", "liars_dice"]: game = pyspiel.load_game(game_name) python_policy = policy.TabularPolicy(game) tabular_policy = policy.python_policy_to_pyspiel_policy(python_policy) policies = [tabular_policy] * 2 seed = 0 batch_size = 128 include_full_observations = False pyspiel.record_batched_trajectories(game, policies, python_policy.state_lookup, batch_size, include_full_observations, seed, -1) if __name__ == "__main__": absltest.main()
true
true
f7fa0cc05200dacf46fdd4caea191e834cfcb5b6
220
py
Python
intro/part05-23_create_tuple/src/create_tuple.py
Hannah-Abi/python-pro-21
2ce32c4bf118054329d19afdf83c50561be1ada8
[ "MIT" ]
null
null
null
intro/part05-23_create_tuple/src/create_tuple.py
Hannah-Abi/python-pro-21
2ce32c4bf118054329d19afdf83c50561be1ada8
[ "MIT" ]
null
null
null
intro/part05-23_create_tuple/src/create_tuple.py
Hannah-Abi/python-pro-21
2ce32c4bf118054329d19afdf83c50561be1ada8
[ "MIT" ]
null
null
null
# Write your solution here def create_tuple(x: int, y: int, z: int): list = [x,y,z] new_tuple = (min(list), max(list), sum(list)) return new_tuple if __name__ == "__main__": print(create_tuple(5, 3, -1))
27.5
49
0.627273
def create_tuple(x: int, y: int, z: int): list = [x,y,z] new_tuple = (min(list), max(list), sum(list)) return new_tuple if __name__ == "__main__": print(create_tuple(5, 3, -1))
true
true
f7fa0debfbbfa411f06c165664cbc224799aaf7b
15,336
py
Python
acq4/devices/Sensapex.py
acq4/acq4
c77636a76d68ffa1bc7dbd41edc522e523b909b8
[ "MIT" ]
47
2015-01-05T16:18:10.000Z
2022-03-16T13:09:30.000Z
acq4/devices/Sensapex.py
acq4/acq4
c77636a76d68ffa1bc7dbd41edc522e523b909b8
[ "MIT" ]
48
2015-04-19T16:51:41.000Z
2022-03-31T14:48:16.000Z
acq4/devices/Sensapex.py
acq4/acq4
c77636a76d68ffa1bc7dbd41edc522e523b909b8
[ "MIT" ]
32
2015-01-15T14:11:49.000Z
2021-07-15T13:44:52.000Z
# -*- coding: utf-8 -*- from __future__ import print_function import numpy as np import pyqtgraph as pg from pyqtgraph import ptime, Transform3D, solve3DTransform from acq4.util import Qt from acq4.drivers.sensapex import UMP from .Stage import Stage, MoveFuture, ManipulatorAxesCalibrationWindow, StageAxesCalibrationWindow class Sensapex(Stage): """ A Sensapex manipulator. """ _sigRestartUpdateTimer = Qt.Signal(object) # timeout duration devices = {} def __init__(self, man, config: dict, name): self.devid = config.get("deviceId") config.setdefault("isManipulator", self.devid < 20) self.scale = config.pop("scale", (1e-6, 1e-6, 1e-6)) self.xPitch = config.pop("xPitch", 0) # angle of x-axis. 0=parallel to xy plane, 90=pointing downward self.maxMoveError = config.pop("maxError", 1e-6) self._force_linear_movement = config.get("forceLinearMovement", False) address = config.pop("address", None) address = None if address is None else address.encode() group = config.pop("group", None) ump = UMP.get_ump(address=address, group=group) # create handle to this manipulator self.dev = ump.get_device(self.devid) Stage.__init__(self, man, config, name) # Read position updates on a timer to rate-limit self._updateTimer = Qt.QTimer() self._updateTimer.timeout.connect(self._getPosition) self._lastUpdate = 0 self._sigRestartUpdateTimer.connect(self._restartUpdateTimer) # note: n_axes is used in cases where the device is not capable of answering this on its own if "nAxes" in config: self.dev.set_n_axes(config["nAxes"]) if "maxAcceleration" in config: self.dev.set_max_acceleration(config["maxAcceleration"]) self.dev.add_callback(self._positionChanged) # force cache update for this device. # This should also verify that we have a valid device ID self.dev.get_pos() self._lastMove = None man.sigAbortAll.connect(self.stop) # clear cached position for this device and re-read to generate an initial position update self._lastPos = None self.getPosition(refresh=True) # TODO: set any extra parameters specified in the config Sensapex.devices[self.devid] = self def axes(self): return "x", "y", "z" def capabilities(self): """Return a structure describing the capabilities of this device""" if "capabilities" in self.config: return self.config["capabilities"] else: return { "getPos": (True, True, True), "setPos": (True, True, True), "limits": (False, False, False), } def axisTransform(self): if self._axisTransform is None: # sensapex manipulators do not have orthogonal axes, so we set up a 3D transform to compensate: a = self.xPitch * np.pi / 180.0 s = self.scale pts1 = np.array([ # unit vector in sensapex space [0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], ]) pts2 = np.array([ # corresponding vector in global space [0, 0, 0], [s[0] * np.cos(a), 0, -s[0] * np.sin(a)], [0, s[1], 0], [0, 0, s[2]], ]) tr = solve3DTransform(pts1, pts2) tr[3, 3] = 1 self._axisTransform = Transform3D(tr) self._inverseAxisTransform = None return self._axisTransform def stop(self): """Stop the manipulator immediately. """ with self.lock: self.dev.stop() self._lastMove = None def _getPosition(self): # Called by superclass when user requests position refresh with self.lock: # using timeout=0 forces read from cache (the monitor thread ensures # these values are up to date) pos = self.dev.get_pos(timeout=0)[:3] self._lastUpdate = ptime.time() if self._lastPos is not None: dif = np.linalg.norm(np.array(pos, dtype=float) - np.array(self._lastPos, dtype=float)) # do not report changes < 100 nm if self._lastPos is None or dif > 0.1: self._lastPos = pos emit = True else: emit = False if emit: # don't emit signal while locked self.posChanged(pos) return pos def _positionChanged(self, dev, newPos, oldPos): # called by driver poller when position has changed now = ptime.time() # rate limit updates to 10 Hz wait = 100e-3 - (now - self._lastUpdate) if wait > 0: self._sigRestartUpdateTimer.emit(wait) else: self._getPosition() def _restartUpdateTimer(self, wait): self._updateTimer.start(int(wait * 1000)) def targetPosition(self): with self.lock: if self._lastMove is None or self._lastMove.isDone(): return self.getPosition() else: return self._lastMove.targetPos def quit(self): Sensapex.devices.pop(self.devid, None) if len(Sensapex.devices) == 0: UMP.get_ump().poller.stop() Stage.quit(self) def _move(self, pos, speed, linear): with self.lock: speed = self._interpretSpeed(speed) self._lastMove = SensapexMoveFuture(self, pos, speed, self._force_linear_movement or linear) return self._lastMove def deviceInterface(self, win): return SensapexInterface(self, win) class SensapexMoveFuture(MoveFuture): """Provides access to a move-in-progress on a Sensapex manipulator. """ def __init__(self, dev, pos, speed, linear): MoveFuture.__init__(self, dev, pos, speed) self._linear = linear self._interrupted = False self._errorMsg = None self._finished = False self._moveReq = self.dev.dev.goto_pos(pos, speed * 1e6, simultaneous=linear, linear=linear) self._checked = False def wasInterrupted(self): """Return True if the move was interrupted before completing. """ return self._moveReq.interrupted def isDone(self): """Return True if the move is complete. """ return self._moveReq.finished def _checkError(self): if self._checked or not self.isDone(): return # interrupted? if self._moveReq.interrupted: self._errorMsg = self._moveReq.interrupt_reason else: # did we reach target? pos = self._moveReq.last_pos dif = np.linalg.norm(np.array(pos) - np.array(self.targetPos)) if dif > self.dev.maxMoveError * 1e9: # require 1um accuracy # missed self._errorMsg = "{} stopped before reaching target (start={}, target={}, position={}, dif={}, speed={}).".format( self.dev.name(), self.startPos, self.targetPos, pos, dif, self.speed ) self._checked = True def wait(self, timeout=None, updates=False): """Block until the move has completed, has been interrupted, or the specified timeout has elapsed. If *updates* is True, process Qt events while waiting. If the move did not complete, raise an exception. """ if updates is False: # if we don't need gui updates, then block on the finished_event for better performance if not self._moveReq.finished_event.wait(timeout=timeout): raise self.Timeout("Timed out waiting for %s move to complete." % self.dev.name()) self._raiseError() else: return MoveFuture.wait(self, timeout=timeout, updates=updates) def errorMessage(self): self._checkError() return self._errorMsg # class SensapexGUI(StageInterface): # def __init__(self, dev, win): # StageInterface.__init__(self, dev, win) # # # Insert Sensapex-specific controls into GUI # self.zeroBtn = Qt.QPushButton('Zero position') # self.layout.addWidget(self.zeroBtn, self.nextRow, 0, 1, 2) # self.nextRow += 1 # # self.psGroup = Qt.QGroupBox('Rotary Controller') # self.layout.addWidget(self.psGroup, self.nextRow, 0, 1, 2) # self.nextRow += 1 # # self.psLayout = Qt.QGridLayout() # self.psGroup.setLayout(self.psLayout) # self.speedLabel = Qt.QLabel('Speed') # self.speedSpin = SpinBox(value=self.dev.userSpeed, suffix='m/turn', siPrefix=True, dec=True, limits=[1e-6, 10e-3]) # self.psLayout.addWidget(self.speedLabel, 0, 0) # self.psLayout.addWidget(self.speedSpin, 0, 1) # # self.zeroBtn.clicked.connect(self.dev.dev.zeroPosition) # # UNSAFE lambdas with self prevent GC # # self.speedSpin.valueChanged.connect(lambda v: self.dev.setDefaultSpeed(v)) class SensapexInterface(Qt.QWidget): def __init__(self, dev, win): Qt.QWidget.__init__(self) self.win = win self.dev = dev self.layout = Qt.QGridLayout() self.setLayout(self.layout) self.axCtrls = {} self.posLabels = {} self.positionLabelWidget = Qt.QWidget() self.layout.addWidget(self.positionLabelWidget, 0, 0) self.positionLabelLayout = Qt.QGridLayout() self.positionLabelWidget.setLayout(self.positionLabelLayout) self.positionLabelLayout.setContentsMargins(0, 0, 0, 0) self.globalLabel = Qt.QLabel("global") self.positionLabelLayout.addWidget(self.globalLabel, 0, 1) self.stageLabel = Qt.QLabel("stage") self.positionLabelLayout.addWidget(self.stageLabel, 0, 2) self.btnContainer = Qt.QWidget() self.btnLayout = Qt.QGridLayout() self.btnContainer.setLayout(self.btnLayout) self.layout.addWidget(self.btnContainer, self.layout.rowCount(), 0) self.btnLayout.setContentsMargins(0, 0, 0, 0) self.goHomeBtn = Qt.QPushButton("Home") self.btnLayout.addWidget(self.goHomeBtn, 0, 0) self.goHomeBtn.clicked.connect(self.goHomeClicked) self.setHomeBtn = Qt.QPushButton("Set Home") self.btnLayout.addWidget(self.setHomeBtn, 0, 1) self.setHomeBtn.clicked.connect(self.setHomeClicked) self.calibrateBtn = Qt.QPushButton("Calibrate") self.btnLayout.addWidget(self.calibrateBtn, 0, 2) self.calibrateBtn.clicked.connect(self.calibrateClicked) self.stopBtn = Qt.QPushButton("Stop!") self.btnLayout.addWidget(self.stopBtn, 1, 0) self.stopBtn.clicked.connect(self.stopClicked) self.stopBtn.setStyleSheet("QPushButton {background-color:red; color:white}") self.calibrateZeroBtn = Qt.QPushButton("Run Zero Calibration") self.btnLayout.addWidget(self.calibrateZeroBtn, 1, 1) self.calibrateZeroBtn.clicked.connect(self.calibrateZeroClicked) self.calibrateLoadBtn = Qt.QPushButton("Run Load Calibration") self.btnLayout.addWidget(self.calibrateLoadBtn, 1, 2) self.calibrateLoadBtn.clicked.connect(self.calibrateLoadClicked) self.softStartValue = Qt.QLineEdit() self.btnLayout.addWidget(self.softStartValue, 2, 1) self.softStartValue.editingFinished.connect(self.softstartChanged) self.getSoftStartValue() self.softStartBtn = Qt.QPushButton("Soft Start Enabled") self.softStartBtn.setCheckable(True) self.softStartBtn.setStyleSheet("QPushButton:checked{background-color:lightgreen; color:black}") self.btnLayout.addWidget(self.softStartBtn, 2, 0) self.softStartBtn.clicked.connect(self.softstartClicked) self.getSoftStartState() self.calibrateWindow = None cap = dev.capabilities() for axis, axisName in enumerate(self.dev.axes()): if cap["getPos"][axis]: axLabel = Qt.QLabel(axisName) axLabel.setMaximumWidth(15) globalPosLabel = Qt.QLabel("0") stagePosLabel = Qt.QLabel("0") self.posLabels[axis] = (globalPosLabel, stagePosLabel) widgets = [axLabel, globalPosLabel, stagePosLabel] if cap["limits"][axis]: minCheck = Qt.QCheckBox("Min:") minCheck.tag = (axis, 0) maxCheck = Qt.QCheckBox("Max:") maxCheck.tag = (axis, 1) self.limitChecks[axis] = (minCheck, maxCheck) widgets.extend([minCheck, maxCheck]) for check in (minCheck, maxCheck): check.clicked.connect(self.limitCheckClicked) nextRow = self.positionLabelLayout.rowCount() for i, w in enumerate(widgets): self.positionLabelLayout.addWidget(w, nextRow, i) self.axCtrls[axis] = widgets self.dev.sigPositionChanged.connect(self.update) self.update() def update(self): globalPos = self.dev.globalPosition() stagePos = self.dev.getPosition() for i in self.posLabels: text = pg.siFormat(globalPos[i], suffix="m", precision=5) self.posLabels[i][0].setText(text) self.posLabels[i][1].setText(str(stagePos[i])) def goHomeClicked(self): self.dev.goHome() def setHomeClicked(self): self.dev.setHomePosition() def calibrateClicked(self): if self.calibrateWindow is None: if self.dev.isManipulator: self.calibrateWindow = ManipulatorAxesCalibrationWindow(self.dev) else: self.calibrateWindow = StageAxesCalibrationWindow(self.dev) self.calibrateWindow.show() self.calibrateWindow.raise_() def calibrateZeroClicked(self): self.dev.dev.calibrate_zero_position() def calibrateLoadClicked(self): self.dev.dev.calibrate_load() def stopClicked(self): self.dev.dev.stop() def getSoftStartState(self): state = self.dev.dev.get_soft_start_state() if state == 1: self.softStartBtn.setChecked(True) self.softStartBtn.setText("Soft Start Enabled") self.softStartValue.setVisible(True) self.getSoftStartValue() return True self.softStartBtn.setChecked(False) self.softStartBtn.setText("Soft Start Disabled") self.softStartValue.setVisible(False) return False def softstartClicked(self): checked = self.getSoftStartState() if checked: self.dev.dev.set_soft_start_state(0) else: self.dev.dev.set_soft_start_state(1) self.getSoftStartState() def softstartChanged(self): value = int(self.softStartValue.text()) self.dev.dev.set_soft_start_value(value) def getSoftStartValue(self): value = self.dev.dev.get_soft_start_value() self.softStartValue.setText(str(value))
36.865385
130
0.614567
from __future__ import print_function import numpy as np import pyqtgraph as pg from pyqtgraph import ptime, Transform3D, solve3DTransform from acq4.util import Qt from acq4.drivers.sensapex import UMP from .Stage import Stage, MoveFuture, ManipulatorAxesCalibrationWindow, StageAxesCalibrationWindow class Sensapex(Stage): _sigRestartUpdateTimer = Qt.Signal(object) devices = {} def __init__(self, man, config: dict, name): self.devid = config.get("deviceId") config.setdefault("isManipulator", self.devid < 20) self.scale = config.pop("scale", (1e-6, 1e-6, 1e-6)) self.xPitch = config.pop("xPitch", 0) self.maxMoveError = config.pop("maxError", 1e-6) self._force_linear_movement = config.get("forceLinearMovement", False) address = config.pop("address", None) address = None if address is None else address.encode() group = config.pop("group", None) ump = UMP.get_ump(address=address, group=group) self.dev = ump.get_device(self.devid) Stage.__init__(self, man, config, name) self._updateTimer = Qt.QTimer() self._updateTimer.timeout.connect(self._getPosition) self._lastUpdate = 0 self._sigRestartUpdateTimer.connect(self._restartUpdateTimer) if "nAxes" in config: self.dev.set_n_axes(config["nAxes"]) if "maxAcceleration" in config: self.dev.set_max_acceleration(config["maxAcceleration"]) self.dev.add_callback(self._positionChanged) self.dev.get_pos() self._lastMove = None man.sigAbortAll.connect(self.stop) self._lastPos = None self.getPosition(refresh=True) Sensapex.devices[self.devid] = self def axes(self): return "x", "y", "z" def capabilities(self): if "capabilities" in self.config: return self.config["capabilities"] else: return { "getPos": (True, True, True), "setPos": (True, True, True), "limits": (False, False, False), } def axisTransform(self): if self._axisTransform is None: a = self.xPitch * np.pi / 180.0 s = self.scale pts1 = np.array([ [0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], ]) pts2 = np.array([ [0, 0, 0], [s[0] * np.cos(a), 0, -s[0] * np.sin(a)], [0, s[1], 0], [0, 0, s[2]], ]) tr = solve3DTransform(pts1, pts2) tr[3, 3] = 1 self._axisTransform = Transform3D(tr) self._inverseAxisTransform = None return self._axisTransform def stop(self): with self.lock: self.dev.stop() self._lastMove = None def _getPosition(self): with self.lock: pos = self.dev.get_pos(timeout=0)[:3] self._lastUpdate = ptime.time() if self._lastPos is not None: dif = np.linalg.norm(np.array(pos, dtype=float) - np.array(self._lastPos, dtype=float)) if self._lastPos is None or dif > 0.1: self._lastPos = pos emit = True else: emit = False if emit: self.posChanged(pos) return pos def _positionChanged(self, dev, newPos, oldPos): # called by driver poller when position has changed now = ptime.time() # rate limit updates to 10 Hz wait = 100e-3 - (now - self._lastUpdate) if wait > 0: self._sigRestartUpdateTimer.emit(wait) else: self._getPosition() def _restartUpdateTimer(self, wait): self._updateTimer.start(int(wait * 1000)) def targetPosition(self): with self.lock: if self._lastMove is None or self._lastMove.isDone(): return self.getPosition() else: return self._lastMove.targetPos def quit(self): Sensapex.devices.pop(self.devid, None) if len(Sensapex.devices) == 0: UMP.get_ump().poller.stop() Stage.quit(self) def _move(self, pos, speed, linear): with self.lock: speed = self._interpretSpeed(speed) self._lastMove = SensapexMoveFuture(self, pos, speed, self._force_linear_movement or linear) return self._lastMove def deviceInterface(self, win): return SensapexInterface(self, win) class SensapexMoveFuture(MoveFuture): def __init__(self, dev, pos, speed, linear): MoveFuture.__init__(self, dev, pos, speed) self._linear = linear self._interrupted = False self._errorMsg = None self._finished = False self._moveReq = self.dev.dev.goto_pos(pos, speed * 1e6, simultaneous=linear, linear=linear) self._checked = False def wasInterrupted(self): return self._moveReq.interrupted def isDone(self): return self._moveReq.finished def _checkError(self): if self._checked or not self.isDone(): return # interrupted? if self._moveReq.interrupted: self._errorMsg = self._moveReq.interrupt_reason else: # did we reach target? pos = self._moveReq.last_pos dif = np.linalg.norm(np.array(pos) - np.array(self.targetPos)) if dif > self.dev.maxMoveError * 1e9: # require 1um accuracy # missed self._errorMsg = "{} stopped before reaching target (start={}, target={}, position={}, dif={}, speed={}).".format( self.dev.name(), self.startPos, self.targetPos, pos, dif, self.speed ) self._checked = True def wait(self, timeout=None, updates=False): if updates is False: # if we don't need gui updates, then block on the finished_event for better performance if not self._moveReq.finished_event.wait(timeout=timeout): raise self.Timeout("Timed out waiting for %s move to complete." % self.dev.name()) self._raiseError() else: return MoveFuture.wait(self, timeout=timeout, updates=updates) def errorMessage(self): self._checkError() return self._errorMsg self.dev = dev self.layout = Qt.QGridLayout() self.setLayout(self.layout) self.axCtrls = {} self.posLabels = {} self.positionLabelWidget = Qt.QWidget() self.layout.addWidget(self.positionLabelWidget, 0, 0) self.positionLabelLayout = Qt.QGridLayout() self.positionLabelWidget.setLayout(self.positionLabelLayout) self.positionLabelLayout.setContentsMargins(0, 0, 0, 0) self.globalLabel = Qt.QLabel("global") self.positionLabelLayout.addWidget(self.globalLabel, 0, 1) self.stageLabel = Qt.QLabel("stage") self.positionLabelLayout.addWidget(self.stageLabel, 0, 2) self.btnContainer = Qt.QWidget() self.btnLayout = Qt.QGridLayout() self.btnContainer.setLayout(self.btnLayout) self.layout.addWidget(self.btnContainer, self.layout.rowCount(), 0) self.btnLayout.setContentsMargins(0, 0, 0, 0) self.goHomeBtn = Qt.QPushButton("Home") self.btnLayout.addWidget(self.goHomeBtn, 0, 0) self.goHomeBtn.clicked.connect(self.goHomeClicked) self.setHomeBtn = Qt.QPushButton("Set Home") self.btnLayout.addWidget(self.setHomeBtn, 0, 1) self.setHomeBtn.clicked.connect(self.setHomeClicked) self.calibrateBtn = Qt.QPushButton("Calibrate") self.btnLayout.addWidget(self.calibrateBtn, 0, 2) self.calibrateBtn.clicked.connect(self.calibrateClicked) self.stopBtn = Qt.QPushButton("Stop!") self.btnLayout.addWidget(self.stopBtn, 1, 0) self.stopBtn.clicked.connect(self.stopClicked) self.stopBtn.setStyleSheet("QPushButton {background-color:red; color:white}") self.calibrateZeroBtn = Qt.QPushButton("Run Zero Calibration") self.btnLayout.addWidget(self.calibrateZeroBtn, 1, 1) self.calibrateZeroBtn.clicked.connect(self.calibrateZeroClicked) self.calibrateLoadBtn = Qt.QPushButton("Run Load Calibration") self.btnLayout.addWidget(self.calibrateLoadBtn, 1, 2) self.calibrateLoadBtn.clicked.connect(self.calibrateLoadClicked) self.softStartValue = Qt.QLineEdit() self.btnLayout.addWidget(self.softStartValue, 2, 1) self.softStartValue.editingFinished.connect(self.softstartChanged) self.getSoftStartValue() self.softStartBtn = Qt.QPushButton("Soft Start Enabled") self.softStartBtn.setCheckable(True) self.softStartBtn.setStyleSheet("QPushButton:checked{background-color:lightgreen; color:black}") self.btnLayout.addWidget(self.softStartBtn, 2, 0) self.softStartBtn.clicked.connect(self.softstartClicked) self.getSoftStartState() self.calibrateWindow = None cap = dev.capabilities() for axis, axisName in enumerate(self.dev.axes()): if cap["getPos"][axis]: axLabel = Qt.QLabel(axisName) axLabel.setMaximumWidth(15) globalPosLabel = Qt.QLabel("0") stagePosLabel = Qt.QLabel("0") self.posLabels[axis] = (globalPosLabel, stagePosLabel) widgets = [axLabel, globalPosLabel, stagePosLabel] if cap["limits"][axis]: minCheck = Qt.QCheckBox("Min:") minCheck.tag = (axis, 0) maxCheck = Qt.QCheckBox("Max:") maxCheck.tag = (axis, 1) self.limitChecks[axis] = (minCheck, maxCheck) widgets.extend([minCheck, maxCheck]) for check in (minCheck, maxCheck): check.clicked.connect(self.limitCheckClicked) nextRow = self.positionLabelLayout.rowCount() for i, w in enumerate(widgets): self.positionLabelLayout.addWidget(w, nextRow, i) self.axCtrls[axis] = widgets self.dev.sigPositionChanged.connect(self.update) self.update() def update(self): globalPos = self.dev.globalPosition() stagePos = self.dev.getPosition() for i in self.posLabels: text = pg.siFormat(globalPos[i], suffix="m", precision=5) self.posLabels[i][0].setText(text) self.posLabels[i][1].setText(str(stagePos[i])) def goHomeClicked(self): self.dev.goHome() def setHomeClicked(self): self.dev.setHomePosition() def calibrateClicked(self): if self.calibrateWindow is None: if self.dev.isManipulator: self.calibrateWindow = ManipulatorAxesCalibrationWindow(self.dev) else: self.calibrateWindow = StageAxesCalibrationWindow(self.dev) self.calibrateWindow.show() self.calibrateWindow.raise_() def calibrateZeroClicked(self): self.dev.dev.calibrate_zero_position() def calibrateLoadClicked(self): self.dev.dev.calibrate_load() def stopClicked(self): self.dev.dev.stop() def getSoftStartState(self): state = self.dev.dev.get_soft_start_state() if state == 1: self.softStartBtn.setChecked(True) self.softStartBtn.setText("Soft Start Enabled") self.softStartValue.setVisible(True) self.getSoftStartValue() return True self.softStartBtn.setChecked(False) self.softStartBtn.setText("Soft Start Disabled") self.softStartValue.setVisible(False) return False def softstartClicked(self): checked = self.getSoftStartState() if checked: self.dev.dev.set_soft_start_state(0) else: self.dev.dev.set_soft_start_state(1) self.getSoftStartState() def softstartChanged(self): value = int(self.softStartValue.text()) self.dev.dev.set_soft_start_value(value) def getSoftStartValue(self): value = self.dev.dev.get_soft_start_value() self.softStartValue.setText(str(value))
true
true
f7fa0e337555e305019fdc6f33de37712a47c92f
1,049
py
Python
src/synthesis/evaluation/experiment.py
bcebere/synthetic_data_generation
84d34d00a5859d3db5d160ef8798b865a0c59fe7
[ "MIT" ]
null
null
null
src/synthesis/evaluation/experiment.py
bcebere/synthetic_data_generation
84d34d00a5859d3db5d160ef8798b865a0c59fe7
[ "MIT" ]
null
null
null
src/synthesis/evaluation/experiment.py
bcebere/synthetic_data_generation
84d34d00a5859d3db5d160ef8798b865a0c59fe7
[ "MIT" ]
null
null
null
"""Functions to help perform an experimental run of synthesis""" from itertools import product from pathlib import Path from synthesis.synthesizers.privbayes import PrivBayes from synthesis.synthesizers.marginal import MarginalSynthesizer def synthesis_experiment( X, X_name, synthesizers=None, epsilon=None, n_records_synth=None, path=None, verbose=2, ): if synthesizers is None: synthesizers = [MarginalSynthesizer, PrivBayes] if not isinstance(path, Path): path = Path(path) model_path = path / "output_model" data_path = path / "output_data" if epsilon is None: epsilon = [0.01, 0.1, 1] for sts, e in product(synthesizers, epsilon): synthesizer = sts(epsilon=e, verbose=verbose) if isinstance(synthesizer, MarginalSynthesizer): synthesizer.verbose = 0 synthesizer.fit(X) # Xs = synthesizer.sample() # synthesizer.save(model_path) print("Synthesis complete for: {}".format(sts)) return synthesizer
26.225
64
0.677788
from itertools import product from pathlib import Path from synthesis.synthesizers.privbayes import PrivBayes from synthesis.synthesizers.marginal import MarginalSynthesizer def synthesis_experiment( X, X_name, synthesizers=None, epsilon=None, n_records_synth=None, path=None, verbose=2, ): if synthesizers is None: synthesizers = [MarginalSynthesizer, PrivBayes] if not isinstance(path, Path): path = Path(path) model_path = path / "output_model" data_path = path / "output_data" if epsilon is None: epsilon = [0.01, 0.1, 1] for sts, e in product(synthesizers, epsilon): synthesizer = sts(epsilon=e, verbose=verbose) if isinstance(synthesizer, MarginalSynthesizer): synthesizer.verbose = 0 synthesizer.fit(X) print("Synthesis complete for: {}".format(sts)) return synthesizer
true
true
f7fa0e503591c1d339c85a9f1de6d7cffc4f9320
22,784
py
Python
src/main/java/com/google/autoesc/JS.java.py
teddykis/html-contextual-autoescaper-java
4963d700146a06776fe4870d03b53a35cb0908bd
[ "Apache-2.0" ]
5
2015-06-19T17:34:20.000Z
2020-04-03T17:54:03.000Z
src/main/java/com/google/autoesc/JS.java.py
teddykis/html-contextual-autoescaper-java
4963d700146a06776fe4870d03b53a35cb0908bd
[ "Apache-2.0" ]
null
null
null
src/main/java/com/google/autoesc/JS.java.py
teddykis/html-contextual-autoescaper-java
4963d700146a06776fe4870d03b53a35cb0908bd
[ "Apache-2.0" ]
1
2020-10-02T07:58:16.000Z
2020-10-02T07:58:16.000Z
#!python # This generates a java source file by taking each method that has a # parameters (String s, int off, int end) and generating a copy that # takes (char[] s, int off, int end). src = r"""// Copyright (C) 2011 Google Inc. // // 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. package com.google.autoesc; import java.io.IOException; import java.io.Writer; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Nullable; /** JS contains utilities for dealing with JavaScript contexts. */ class JS { /** * nextJSCtx returns the context that determines whether a slash after the * given run of tokens tokens starts a regular expression instead of a * division operator: / or /=. * <p> * This assumes that the token run does not include any string tokens, comment * tokens, regular expression literal tokens, or division operators. * <p> * This fails on some valid but nonsensical JavaScript programs like * "x = ++/foo/i" which is quite different than "x++/foo/i", but is not known * to fail on any known useful programs. It is based on the draft * JavaScript 2.0 lexical grammar and requires one token of lookbehind: * http://www.mozilla.org/js/language/js20-2000-07/rationale/syntax.html * * @param precJSCtx one of the {@clink Context.JSCtx} values which is used * when there are no tokens on the end of s. */ static int nextJSCtx(String s, int off, int end, int precJSCtx) { int e = end; while (e > off) { char ch = s.charAt(e - 1); switch (ch) { case '\t': case '\n': case '\r': case ' ': case '\u2028': case '\u2029': --e; continue; } break; } if (off == e) { return precJSCtx; } // All cases below are in the single-byte UTF-8 group. char c = s.charAt(e - 1); switch (c) { case '+': case '-': // ++ and -- are not regexp preceders, but + and - are whether // they are used as infix or prefix operators. int start = e - 1; // Count the number of adjacent dashes or pluses. while (start > off && s.charAt(start-1) == c) { start--; } if (((e - start) & 1) == 1) { // Reached for trailing minus signs since "---" is the // same as "-- -". return Context.JSCtx.Regexp; } return Context.JSCtx.DivOp; case '.': // Handle "42." if (e-off >= 2 && '0' <= s.charAt(e-2) && s.charAt(e-2) <= '9') { return Context.JSCtx.DivOp; } return Context.JSCtx.Regexp; // Suffixes for all punctuators from section 7.7 of the language spec // that only end binary operators not handled above. case ',': case '<': case '>': case '=': case '*': case '%': case '&': case '|': case '^': case '?': return Context.JSCtx.Regexp; // Suffixes for all punctuators from section 7.7 of the language spec // that are prefix operators not handled above. case '!': case '~': return Context.JSCtx.Regexp; // Matches all the punctuators from section 7.7 of the language spec // that are open brackets not handled above. case '(': case '[': return Context.JSCtx.Regexp; // Matches all the punctuators from section 7.7 of the language spec // that precede expression starts. case ':': case ';': case '{': return Context.JSCtx.Regexp; // CAVEAT: the close punctuators ('}', ']', ')') precede div ops and // are handled in the default except for '}' which can precede a // division op as in // ({ valueOf: function () { return 42 } } / 2 // which is valid, but, in practice, developers don't divide object // literals, so our heuristic works well for code like // function () { ... } /foo/.test(x) && sideEffect(); // The ')' punctuator can precede a regular expression as in // if (b) /foo/.test(x) && ... // but this is much less likely than // (a + b) / c case '}': return Context.JSCtx.Regexp; default: // Look for an IdentifierName and see if it is a keyword that // can precede a regular expression. int j = e; while (j > off && isJSIdentPart(s.charAt(j - 1))) { j--; } if (isRegexpPrecederKeyword(s, j, e)) { return Context.JSCtx.Regexp; } // Otherwise is a punctuator not listed above, or // a string which precedes a div op, or an identifier // which precedes a div op. return Context.JSCtx.DivOp; } } static boolean isRegexpPrecederKeyword(String s, int off, int end) { // Below is a set of reserved JS keywords that can // precede a regular expression in JS source. switch (end - off) { case 2: return CharsUtil.startsWith(s, off, end, "do") || CharsUtil.startsWith(s, off, end, "in"); case 3: return CharsUtil.startsWith(s, off, end, "try"); case 4: return CharsUtil.startsWith(s, off, end, "case") || CharsUtil.startsWith(s, off, end, "else") || CharsUtil.startsWith(s, off, end, "void"); case 5: return CharsUtil.startsWith(s, off, end, "break") || CharsUtil.startsWith(s, off, end, "throw"); case 6: return CharsUtil.startsWith(s, off, end, "delete") || CharsUtil.startsWith(s, off, end, "return") || CharsUtil.startsWith(s, off, end, "typeof"); case 7: return CharsUtil.startsWith(s, off, end, "finally"); case 8: return CharsUtil.startsWith(s, off, end, "continue"); case 10: return CharsUtil.startsWith(s, off, end, "instanceof"); } return false; } /** * isJSIdentPart returns whether the given rune is a JS identifier part. * It does not handle all the non-Latin letters, joiners, and combining marks, * but it does handle every codepoint that can occur in a numeric literal or * a keyword. */ static boolean isJSIdentPart(char c) { return c == '$' || c == '_' || ('0' <= c && c <= '9') || ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'); } static final ReplacementTable STR_REPLACEMENT_TABLE = new ReplacementTable() .add((char) 0, "\\0") // Encode HTML specials as hex so the output can be embedded // in HTML attributes without further encoding. .add('`', "\\x60") .add('"', "\\x22") .add('&', "\\x26") .add('\'', "\\x27") // JS strings cannot contain embedded newlines. Escape all space chars. // U+2028 and U+2029 handled below. .add('\t', "\\t") .add('\n', "\\n") .add('\u000b', "\\x0b") // "\v" == "v" on IE 6. .add('\f', "\\f") .add('\r', "\\r") // Prevent function calls even if they escape, and handle capturing // groups when inherited by regex below. .add('(', "\\(") .add(')', "\\)") // UTF-7 attack vector .add('+', "\\x2b") // Prevent embedded "</script" .add('/', "\\/") // Prevent embedded <!-- and --> .add('<', "\\x3c") .add('>', "\\x3e") // Correctness. .add('\\', "\\\\") // JavaScript specific newline chars. .replaceNonAscii(new int[] { 0x2028, 0x2029 }, new String[] { "\\u2028", "\\u2029" }); /** * STR_NORM_REPLACEMENT_TABLE is like STR_REPLACEMENT_TABLE but does not * overencode existing escapes since this table has no entry for "\\". */ static final ReplacementTable STR_NORM_REPLACEMENT_TABLE = new ReplacementTable(STR_REPLACEMENT_TABLE) .add('\\', null); private static final ReplacementTable REGEX_REPLACEMENT_TABLE = new ReplacementTable(STR_REPLACEMENT_TABLE) { /** * Ensures that {@code /$x/} does not become a line comment when x is * empty. */ @Override protected void writeEmpty(Writer out) throws IOException { out.write("(?:)"); } } .add('{', "\\{") .add('|', "\\|") .add('}', "\\}") .add('$', "\\$") .add('*', "\\*") .add('-', "\\-") .add('.', "\\.") .add('?', "\\?") .add('[', "\\[") .add(']', "\\]") .add('^', "\\^"); static void escapeStrOnto(@Nullable Object o, Writer out) throws IOException { String safe = ContentType.JSStr.derefSafeContent(o); if (safe != null) { STR_NORM_REPLACEMENT_TABLE.escapeOnto(safe, out); return; } STR_REPLACEMENT_TABLE.escapeOnto(o, out); } static void escapeStrOnto(String s, int off, int end, Writer out) throws IOException { STR_REPLACEMENT_TABLE.escapeOnto(s, off, end, out); } static void escapeRegexpOnto(@Nullable Object o, Writer out) throws IOException { REGEX_REPLACEMENT_TABLE.escapeOnto(o, out); } static void escapeRegexpOnto(String s, int off, int end, Writer out) throws IOException { REGEX_REPLACEMENT_TABLE.escapeOnto(s, off, end, out); } static void escapeValueOnto(@Nullable Object o, Writer out) throws IOException { new JSValueEscaper(out).escape(o, true); } static void escapeValueOnto(String s, int off, int end, Writer out) throws IOException { out.write('\''); STR_REPLACEMENT_TABLE.escapeOnto(s, off, end, out); out.write('\''); } } class JSValueEscaper { private final Writer out; private IdentityHashMap<Object, ?> seen; JSValueEscaper(Writer out) { this.out = out; } /** A sequence of one or more valid JSON tokens as defined in RFC 4627. */ private static final Pattern JSON_TOKENS = Pattern.compile( // Ignore leading whitespace. "[\t\n\r ]*" + "(?:(?:[\\[\\]{}:,]|" // A keyword. + "(?:false|null|true|" // A number + "-?(?:0|[1-9][0-9]*)(?:[.][0-9]+)?(?:[eE][+-]?[0-9]+)?" // Keywords and numbers cannot be followed by identifier chars. + "(?![a-zA-Z0-9_$])" + ")|" // A string + "\"(?:[^\\\\\"\\u0000-\\u001f]|\\\\(?:[\"\\\\/bfnrt]|u[0-9a-fA-F]{4}))*\"" + ")" // Any token can be followed by trailing whitespace. + "[\t\n\r ]*)+"); /** * Sanity check JSON to make sure it preserves string boundaries and does * not contain free variables. */ static String sanityCheckJSON(String json) { // This does not match brackets. // TODO: match brackets to exclude all invalid JSON. if (JSON_TOKENS.matcher(json).matches()) { // Fixup U+2028 and U+2029 which are allowed in JSON string literals // unencoded but not in JS. return json.replace("\u2028", "\\u2028").replace("\u2029", "\\u2029"); } // Report an error message as a comment. Matcher m = JSON_TOKENS.matcher(json); String problemText; if (m.find()) { if (m.start() != 0) { // Invalid content at the front. problemText = json.substring(0, m.start()); } else { problemText = json.substring(m.end()); } } else { // Not a single valid JSON token in the entire string. problemText = json; } if (problemText.length() > 40) { problemText = problemText.substring(0, 37) + "..."; } // Space before comment prevents it from combining with a div op to form // a line comment. return " /* json: " + problemText.replace("*", "* ") + " */ null "; } void escape(@Nullable Object obj, boolean protectBoundaries) throws IOException { // Escape maps and collections to java object and array constructors. Object o = obj; if (o == null || (seen != null && seen.containsKey(o))) { // We surround keyword and numeric values with spaces so they do not // merge into other tokens. // Surrounding with parentheses might introduce call operators. out.write(protectBoundaries ? " null " : "null"); return; } if (o instanceof SafeContent) { SafeContent ct = (SafeContent) o; ContentType t = ct.getContentType(); switch (t) { case JS: if (protectBoundaries) { out.write(' '); } out.write(ct.toString()); if (protectBoundaries) { out.write(' '); } return; case JSStr: String s = ct.toString(); int trailingSlashes = 0; for (int i = s.length(); --i >= 0; ++trailingSlashes) { if (s.charAt(i) != '\\') { break; } } out.write('\''); JS.STR_NORM_REPLACEMENT_TABLE.escapeOnto(s, out); if ((trailingSlashes & 1) != 0) { out.write('\\'); } // If s ends with an incomplete escape sequence, complete it. out.write('\''); return; default: // Fall through to cases below. o = ct.toString(); } } if (o instanceof JSONMarshaler) { String json = sanityCheckJSON(((JSONMarshaler) o).toJSON()); char ch0 = json.charAt(0); // sanityCheckJSON does not allow empty. if (protectBoundaries && JS.isJSIdentPart(ch0)) { out.write(' '); } out.write(json); char chn = json.charAt(json.length() - 1); if (protectBoundaries && JS.isJSIdentPart(chn)) { out.write(' '); } } else if (o instanceof Number || o instanceof Boolean) { // This might result in free variables NaN and Infinity being read. if (protectBoundaries) { out.write(' '); } out.write(o.toString()); if (protectBoundaries) { out.write(' '); } } else if (o instanceof Iterable<?>) { markSeen(o); char pre = '['; for (Object el : (Iterable<?>) o) { out.write(pre); pre = ','; escape(el, false); } if (pre == '[') { out.write("[]"); } else { out.write(']'); } } else if (o instanceof Map<?, ?>) { markSeen(o); char pre = '{'; for (Map.Entry<?, ?> e : ((Map<?, ?>) o).entrySet()) { out.write(pre); pre = ','; Object k = e.getKey(); Object v = e.getValue(); out.write('\''); JS.STR_REPLACEMENT_TABLE.escapeOnto(k, out); out.write("\':"); escape(v, false); } if (pre == '{') { out.write("{}"); } else { out.write('}'); } } else if (o.getClass().isArray() && !(o instanceof char[])) { markSeen(o); int len = Array.getLength(o); if (len == 0) { out.write("[]"); } else { char pre = '['; for (int i = 0; i < len; ++i) { out.write(pre); pre = ','; escape(Array.get(o, i), false); } out.write(']'); } } else if (!beanToJS(o)) { out.write('\''); JS.STR_REPLACEMENT_TABLE.escapeOnto(o, out); out.write('\''); } } private void markSeen(Object o) { if (seen == null) { seen = new IdentityHashMap<>(); } seen.put(o, null); } /** * Converts a Java bean object into a JS object constructor by reflectively * examining its public fields and getter methods. */ private boolean beanToJS(Object o) throws IOException { // CharSequences should be treated as strings, and enum values should // not have fields serialized since they are better identified by name // or ordinal. if (o instanceof CharSequence || o instanceof Enum) { return false; } Class<?> c = o.getClass(); ClassSchema schema = ClassSchema.forClass(c); if (schema == null) { return false; } markSeen(o); char pre = '{'; for (Field f : schema.fields) { String name = f.getName(); Object v; try { v = f.get(o); } catch (IllegalAccessException e) { // Should not occur since we checked public-ness. // TODO: does the declaring class and any containing class also have // to be public? throw (AssertionError) new AssertionError(name + " of " + o.getClass()).initCause(e); } out.write(pre); pre = ','; out.write('\''); out.write(name); // Name is a valid JavaScript identifier. out.write("\':"); escape(v, false); } for (int i = 0, n = schema.getters.length; i < n; ++i) { Method m = schema.getters[i]; String name = schema.getterFieldNames[i]; Object v = null; try { v = m.invoke(o); } catch (IllegalAccessException e) { // TODO: same caveats to check as above. throw (AssertionError) new AssertionError(name + " of " + o.getClass()).initCause(e); } catch (@SuppressWarnings("unused") InvocationTargetException e) { // Getter failed. Treat as a non-existant property. continue; } out.write(pre); pre = ','; out.write('\''); out.write(name); out.write("\':"); escape(v, false); } if (pre == '{') { out.write("{}"); } else { out.write('}'); } return true; } } /** * Collects reflective information about the properties of a class that can * be used to turn it into a JS representation. */ class ClassSchema { final String className; final Field[] fields; final Method[] getters; final String[] getterFieldNames; private static final ClassSchema NOT_A_BEAN = new ClassSchema(); private static final Map<Class<?>, ClassSchema> CLASS_TO_SCHEMA = Collections.synchronizedMap( new IdentityHashMap<Class<?>, ClassSchema>()); static { CLASS_TO_SCHEMA.put(Class.class, NOT_A_BEAN); try { CLASS_TO_SCHEMA.put( GregorianCalendar.class, new ClassSchema(GregorianCalendar.class, new String[0], new String[] { "getClass", "getTimeInMillis" })); CLASS_TO_SCHEMA.put( Date.class, new ClassSchema(Date.class, new String[0], new String[] { "getClass", "getTime" })); CLASS_TO_SCHEMA.put( java.sql.Date.class, new ClassSchema(Date.class, new String[0], new String[] { "getClass", "getTime" })); } catch (NoSuchFieldException e) { throw new AssertionError(e); } catch (NoSuchMethodException e) { throw new AssertionError(e); } } static ClassSchema forClass(Class<?> c) { ClassSchema s = CLASS_TO_SCHEMA.get(c); if (s == null) { s = new ClassSchema(c); if (s.fields.length == 0 && s.getters.length == 1 /* getClass */) { s = NOT_A_BEAN; } CLASS_TO_SCHEMA.put(c, s); } return s == NOT_A_BEAN ? null : s; } private ClassSchema() { this.className = null; this.fields = null; this.getters = null; this.getterFieldNames = null; } private ClassSchema(Class<?> c, String[] fieldNames, String[] methodNames) throws NoSuchFieldException, NoSuchMethodException { this.className = c.getName(); this.fields = new Field[fieldNames.length]; for (int i = 0; i < fieldNames.length; ++i) { fields[i] = c.getField(fieldNames[i]); } this.getterFieldNames = new String[methodNames.length]; this.getters = new Method[methodNames.length]; Class<?>[] none = new Class<?>[0]; for (int i = 0; i < methodNames.length; ++i) { String name = methodNames[i]; if (name.startsWith("get")) { getterFieldNames[i] = Character.toLowerCase(name.charAt(3)) + name.substring(4); } else { getterFieldNames[i] = name; } getters[i] = c.getMethod(name, none); } } private ClassSchema(Class<?> c) { this.className = c.getName(); List<Field> fieldList = new ArrayList<>(); List<Method> getterList = new ArrayList<>(); Set<String> names = new HashSet<>(); for (Field f : c.getFields()) { int mods = f.getModifiers(); if (Modifier.isPublic(mods) && !Modifier.isStatic(mods) && !Modifier.isVolatile(mods) && names.add(f.getName())) { fieldList.add(f); } } for (Method m : c.getMethods()) { if (Void.TYPE.equals(m.getReturnType())) { continue; } String name = m.getName(); if (!(name.startsWith("get") && m.getParameterTypes().length == 0)) { continue; } int mods = m.getModifiers(); if (!(Modifier.isPublic(mods) && !Modifier.isStatic(mods))) { continue; } if (names.add(methodNameToFieldName(name))) { getterList.add(m); } } this.fields = fieldList.toArray(new Field[fieldList.size()]); // TODO: Create one comparator for members and make it singleton. // TODO: Find a JSR305 annotation or something similar to exempt fields // from serialization. Maybe JPA @javax.persistence.Transient. Arrays.sort(this.fields, new Comparator<Field>() { @Override public int compare(Field a, Field b) { return a.getName().compareTo(b.getName()); } }); this.getters = getterList.toArray(new Method[getterList.size()]); Arrays.sort(this.getters, new Comparator<Method>() { @Override public int compare(Method a, Method b) { return a.getName().compareTo(b.getName()); } }); this.getterFieldNames = new String[this.getters.length]; for (int i = 0; i < this.getters.length; ++i) { this.getterFieldNames[i] = methodNameToFieldName( this.getters[i].getName()); } } static String methodNameToFieldName(String name) { if (name.startsWith("get")) { // getFoo -> foo return Character.toLowerCase(name.charAt(3)) + name.substring(4); } return name; } } """ # Fix emacs syntax highlighting " import dupe_methods print dupe_methods.dupe(src)
34.261654
81
0.577642
src = r"""// Copyright (C) 2011 Google Inc. // // 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. package com.google.autoesc; import java.io.IOException; import java.io.Writer; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Nullable; /** JS contains utilities for dealing with JavaScript contexts. */ class JS { /** * nextJSCtx returns the context that determines whether a slash after the * given run of tokens tokens starts a regular expression instead of a * division operator: / or /=. * <p> * This assumes that the token run does not include any string tokens, comment * tokens, regular expression literal tokens, or division operators. * <p> * This fails on some valid but nonsensical JavaScript programs like * "x = ++/foo/i" which is quite different than "x++/foo/i", but is not known * to fail on any known useful programs. It is based on the draft * JavaScript 2.0 lexical grammar and requires one token of lookbehind: * http://www.mozilla.org/js/language/js20-2000-07/rationale/syntax.html * * @param precJSCtx one of the {@clink Context.JSCtx} values which is used * when there are no tokens on the end of s. */ static int nextJSCtx(String s, int off, int end, int precJSCtx) { int e = end; while (e > off) { char ch = s.charAt(e - 1); switch (ch) { case '\t': case '\n': case '\r': case ' ': case '\u2028': case '\u2029': --e; continue; } break; } if (off == e) { return precJSCtx; } // All cases below are in the single-byte UTF-8 group. char c = s.charAt(e - 1); switch (c) { case '+': case '-': // ++ and -- are not regexp preceders, but + and - are whether // they are used as infix or prefix operators. int start = e - 1; // Count the number of adjacent dashes or pluses. while (start > off && s.charAt(start-1) == c) { start--; } if (((e - start) & 1) == 1) { // Reached for trailing minus signs since "---" is the // same as "-- -". return Context.JSCtx.Regexp; } return Context.JSCtx.DivOp; case '.': // Handle "42." if (e-off >= 2 && '0' <= s.charAt(e-2) && s.charAt(e-2) <= '9') { return Context.JSCtx.DivOp; } return Context.JSCtx.Regexp; // Suffixes for all punctuators from section 7.7 of the language spec // that only end binary operators not handled above. case ',': case '<': case '>': case '=': case '*': case '%': case '&': case '|': case '^': case '?': return Context.JSCtx.Regexp; // Suffixes for all punctuators from section 7.7 of the language spec // that are prefix operators not handled above. case '!': case '~': return Context.JSCtx.Regexp; // Matches all the punctuators from section 7.7 of the language spec // that are open brackets not handled above. case '(': case '[': return Context.JSCtx.Regexp; // Matches all the punctuators from section 7.7 of the language spec // that precede expression starts. case ':': case ';': case '{': return Context.JSCtx.Regexp; // CAVEAT: the close punctuators ('}', ']', ')') precede div ops and // are handled in the default except for '}' which can precede a // division op as in // ({ valueOf: function () { return 42 } } / 2 // which is valid, but, in practice, developers don't divide object // literals, so our heuristic works well for code like // function () { ... } /foo/.test(x) && sideEffect(); // The ')' punctuator can precede a regular expression as in // if (b) /foo/.test(x) && ... // but this is much less likely than // (a + b) / c case '}': return Context.JSCtx.Regexp; default: // Look for an IdentifierName and see if it is a keyword that // can precede a regular expression. int j = e; while (j > off && isJSIdentPart(s.charAt(j - 1))) { j--; } if (isRegexpPrecederKeyword(s, j, e)) { return Context.JSCtx.Regexp; } // Otherwise is a punctuator not listed above, or // a string which precedes a div op, or an identifier // which precedes a div op. return Context.JSCtx.DivOp; } } static boolean isRegexpPrecederKeyword(String s, int off, int end) { // Below is a set of reserved JS keywords that can // precede a regular expression in JS source. switch (end - off) { case 2: return CharsUtil.startsWith(s, off, end, "do") || CharsUtil.startsWith(s, off, end, "in"); case 3: return CharsUtil.startsWith(s, off, end, "try"); case 4: return CharsUtil.startsWith(s, off, end, "case") || CharsUtil.startsWith(s, off, end, "else") || CharsUtil.startsWith(s, off, end, "void"); case 5: return CharsUtil.startsWith(s, off, end, "break") || CharsUtil.startsWith(s, off, end, "throw"); case 6: return CharsUtil.startsWith(s, off, end, "delete") || CharsUtil.startsWith(s, off, end, "return") || CharsUtil.startsWith(s, off, end, "typeof"); case 7: return CharsUtil.startsWith(s, off, end, "finally"); case 8: return CharsUtil.startsWith(s, off, end, "continue"); case 10: return CharsUtil.startsWith(s, off, end, "instanceof"); } return false; } /** * isJSIdentPart returns whether the given rune is a JS identifier part. * It does not handle all the non-Latin letters, joiners, and combining marks, * but it does handle every codepoint that can occur in a numeric literal or * a keyword. */ static boolean isJSIdentPart(char c) { return c == '$' || c == '_' || ('0' <= c && c <= '9') || ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'); } static final ReplacementTable STR_REPLACEMENT_TABLE = new ReplacementTable() .add((char) 0, "\\0") // Encode HTML specials as hex so the output can be embedded // in HTML attributes without further encoding. .add('`', "\\x60") .add('"', "\\x22") .add('&', "\\x26") .add('\'', "\\x27") // JS strings cannot contain embedded newlines. Escape all space chars. // U+2028 and U+2029 handled below. .add('\t', "\\t") .add('\n', "\\n") .add('\u000b', "\\x0b") // "\v" == "v" on IE 6. .add('\f', "\\f") .add('\r', "\\r") // Prevent function calls even if they escape, and handle capturing // groups when inherited by regex below. .add('(', "\\(") .add(')', "\\)") // UTF-7 attack vector .add('+', "\\x2b") // Prevent embedded "</script" .add('/', "\\/") // Prevent embedded <!-- and --> .add('<', "\\x3c") .add('>', "\\x3e") // Correctness. .add('\\', "\\\\") // JavaScript specific newline chars. .replaceNonAscii(new int[] { 0x2028, 0x2029 }, new String[] { "\\u2028", "\\u2029" }); /** * STR_NORM_REPLACEMENT_TABLE is like STR_REPLACEMENT_TABLE but does not * overencode existing escapes since this table has no entry for "\\". */ static final ReplacementTable STR_NORM_REPLACEMENT_TABLE = new ReplacementTable(STR_REPLACEMENT_TABLE) .add('\\', null); private static final ReplacementTable REGEX_REPLACEMENT_TABLE = new ReplacementTable(STR_REPLACEMENT_TABLE) { /** * Ensures that {@code /$x/} does not become a line comment when x is * empty. */ @Override protected void writeEmpty(Writer out) throws IOException { out.write("(?:)"); } } .add('{', "\\{") .add('|', "\\|") .add('}', "\\}") .add('$', "\\$") .add('*', "\\*") .add('-', "\\-") .add('.', "\\.") .add('?', "\\?") .add('[', "\\[") .add(']', "\\]") .add('^', "\\^"); static void escapeStrOnto(@Nullable Object o, Writer out) throws IOException { String safe = ContentType.JSStr.derefSafeContent(o); if (safe != null) { STR_NORM_REPLACEMENT_TABLE.escapeOnto(safe, out); return; } STR_REPLACEMENT_TABLE.escapeOnto(o, out); } static void escapeStrOnto(String s, int off, int end, Writer out) throws IOException { STR_REPLACEMENT_TABLE.escapeOnto(s, off, end, out); } static void escapeRegexpOnto(@Nullable Object o, Writer out) throws IOException { REGEX_REPLACEMENT_TABLE.escapeOnto(o, out); } static void escapeRegexpOnto(String s, int off, int end, Writer out) throws IOException { REGEX_REPLACEMENT_TABLE.escapeOnto(s, off, end, out); } static void escapeValueOnto(@Nullable Object o, Writer out) throws IOException { new JSValueEscaper(out).escape(o, true); } static void escapeValueOnto(String s, int off, int end, Writer out) throws IOException { out.write('\''); STR_REPLACEMENT_TABLE.escapeOnto(s, off, end, out); out.write('\''); } } class JSValueEscaper { private final Writer out; private IdentityHashMap<Object, ?> seen; JSValueEscaper(Writer out) { this.out = out; } /** A sequence of one or more valid JSON tokens as defined in RFC 4627. */ private static final Pattern JSON_TOKENS = Pattern.compile( // Ignore leading whitespace. "[\t\n\r ]*" + "(?:(?:[\\[\\]{}:,]|" // A keyword. + "(?:false|null|true|" // A number + "-?(?:0|[1-9][0-9]*)(?:[.][0-9]+)?(?:[eE][+-]?[0-9]+)?" // Keywords and numbers cannot be followed by identifier chars. + "(?![a-zA-Z0-9_$])" + ")|" // A string + "\"(?:[^\\\\\"\\u0000-\\u001f]|\\\\(?:[\"\\\\/bfnrt]|u[0-9a-fA-F]{4}))*\"" + ")" // Any token can be followed by trailing whitespace. + "[\t\n\r ]*)+"); /** * Sanity check JSON to make sure it preserves string boundaries and does * not contain free variables. */ static String sanityCheckJSON(String json) { // This does not match brackets. // TODO: match brackets to exclude all invalid JSON. if (JSON_TOKENS.matcher(json).matches()) { // Fixup U+2028 and U+2029 which are allowed in JSON string literals // unencoded but not in JS. return json.replace("\u2028", "\\u2028").replace("\u2029", "\\u2029"); } // Report an error message as a comment. Matcher m = JSON_TOKENS.matcher(json); String problemText; if (m.find()) { if (m.start() != 0) { // Invalid content at the front. problemText = json.substring(0, m.start()); } else { problemText = json.substring(m.end()); } } else { // Not a single valid JSON token in the entire string. problemText = json; } if (problemText.length() > 40) { problemText = problemText.substring(0, 37) + "..."; } // Space before comment prevents it from combining with a div op to form // a line comment. return " /* json: " + problemText.replace("*", "* ") + " */ null "; } void escape(@Nullable Object obj, boolean protectBoundaries) throws IOException { // Escape maps and collections to java object and array constructors. Object o = obj; if (o == null || (seen != null && seen.containsKey(o))) { // We surround keyword and numeric values with spaces so they do not // merge into other tokens. // Surrounding with parentheses might introduce call operators. out.write(protectBoundaries ? " null " : "null"); return; } if (o instanceof SafeContent) { SafeContent ct = (SafeContent) o; ContentType t = ct.getContentType(); switch (t) { case JS: if (protectBoundaries) { out.write(' '); } out.write(ct.toString()); if (protectBoundaries) { out.write(' '); } return; case JSStr: String s = ct.toString(); int trailingSlashes = 0; for (int i = s.length(); --i >= 0; ++trailingSlashes) { if (s.charAt(i) != '\\') { break; } } out.write('\''); JS.STR_NORM_REPLACEMENT_TABLE.escapeOnto(s, out); if ((trailingSlashes & 1) != 0) { out.write('\\'); } // If s ends with an incomplete escape sequence, complete it. out.write('\''); return; default: // Fall through to cases below. o = ct.toString(); } } if (o instanceof JSONMarshaler) { String json = sanityCheckJSON(((JSONMarshaler) o).toJSON()); char ch0 = json.charAt(0); // sanityCheckJSON does not allow empty. if (protectBoundaries && JS.isJSIdentPart(ch0)) { out.write(' '); } out.write(json); char chn = json.charAt(json.length() - 1); if (protectBoundaries && JS.isJSIdentPart(chn)) { out.write(' '); } } else if (o instanceof Number || o instanceof Boolean) { // This might result in free variables NaN and Infinity being read. if (protectBoundaries) { out.write(' '); } out.write(o.toString()); if (protectBoundaries) { out.write(' '); } } else if (o instanceof Iterable<?>) { markSeen(o); char pre = '['; for (Object el : (Iterable<?>) o) { out.write(pre); pre = ','; escape(el, false); } if (pre == '[') { out.write("[]"); } else { out.write(']'); } } else if (o instanceof Map<?, ?>) { markSeen(o); char pre = '{'; for (Map.Entry<?, ?> e : ((Map<?, ?>) o).entrySet()) { out.write(pre); pre = ','; Object k = e.getKey(); Object v = e.getValue(); out.write('\''); JS.STR_REPLACEMENT_TABLE.escapeOnto(k, out); out.write("\':"); escape(v, false); } if (pre == '{') { out.write("{}"); } else { out.write('}'); } } else if (o.getClass().isArray() && !(o instanceof char[])) { markSeen(o); int len = Array.getLength(o); if (len == 0) { out.write("[]"); } else { char pre = '['; for (int i = 0; i < len; ++i) { out.write(pre); pre = ','; escape(Array.get(o, i), false); } out.write(']'); } } else if (!beanToJS(o)) { out.write('\''); JS.STR_REPLACEMENT_TABLE.escapeOnto(o, out); out.write('\''); } } private void markSeen(Object o) { if (seen == null) { seen = new IdentityHashMap<>(); } seen.put(o, null); } /** * Converts a Java bean object into a JS object constructor by reflectively * examining its public fields and getter methods. */ private boolean beanToJS(Object o) throws IOException { // CharSequences should be treated as strings, and enum values should // not have fields serialized since they are better identified by name // or ordinal. if (o instanceof CharSequence || o instanceof Enum) { return false; } Class<?> c = o.getClass(); ClassSchema schema = ClassSchema.forClass(c); if (schema == null) { return false; } markSeen(o); char pre = '{'; for (Field f : schema.fields) { String name = f.getName(); Object v; try { v = f.get(o); } catch (IllegalAccessException e) { // Should not occur since we checked public-ness. // TODO: does the declaring class and any containing class also have // to be public? throw (AssertionError) new AssertionError(name + " of " + o.getClass()).initCause(e); } out.write(pre); pre = ','; out.write('\''); out.write(name); // Name is a valid JavaScript identifier. out.write("\':"); escape(v, false); } for (int i = 0, n = schema.getters.length; i < n; ++i) { Method m = schema.getters[i]; String name = schema.getterFieldNames[i]; Object v = null; try { v = m.invoke(o); } catch (IllegalAccessException e) { // TODO: same caveats to check as above. throw (AssertionError) new AssertionError(name + " of " + o.getClass()).initCause(e); } catch (@SuppressWarnings("unused") InvocationTargetException e) { // Getter failed. Treat as a non-existant property. continue; } out.write(pre); pre = ','; out.write('\''); out.write(name); out.write("\':"); escape(v, false); } if (pre == '{') { out.write("{}"); } else { out.write('}'); } return true; } } /** * Collects reflective information about the properties of a class that can * be used to turn it into a JS representation. */ class ClassSchema { final String className; final Field[] fields; final Method[] getters; final String[] getterFieldNames; private static final ClassSchema NOT_A_BEAN = new ClassSchema(); private static final Map<Class<?>, ClassSchema> CLASS_TO_SCHEMA = Collections.synchronizedMap( new IdentityHashMap<Class<?>, ClassSchema>()); static { CLASS_TO_SCHEMA.put(Class.class, NOT_A_BEAN); try { CLASS_TO_SCHEMA.put( GregorianCalendar.class, new ClassSchema(GregorianCalendar.class, new String[0], new String[] { "getClass", "getTimeInMillis" })); CLASS_TO_SCHEMA.put( Date.class, new ClassSchema(Date.class, new String[0], new String[] { "getClass", "getTime" })); CLASS_TO_SCHEMA.put( java.sql.Date.class, new ClassSchema(Date.class, new String[0], new String[] { "getClass", "getTime" })); } catch (NoSuchFieldException e) { throw new AssertionError(e); } catch (NoSuchMethodException e) { throw new AssertionError(e); } } static ClassSchema forClass(Class<?> c) { ClassSchema s = CLASS_TO_SCHEMA.get(c); if (s == null) { s = new ClassSchema(c); if (s.fields.length == 0 && s.getters.length == 1 /* getClass */) { s = NOT_A_BEAN; } CLASS_TO_SCHEMA.put(c, s); } return s == NOT_A_BEAN ? null : s; } private ClassSchema() { this.className = null; this.fields = null; this.getters = null; this.getterFieldNames = null; } private ClassSchema(Class<?> c, String[] fieldNames, String[] methodNames) throws NoSuchFieldException, NoSuchMethodException { this.className = c.getName(); this.fields = new Field[fieldNames.length]; for (int i = 0; i < fieldNames.length; ++i) { fields[i] = c.getField(fieldNames[i]); } this.getterFieldNames = new String[methodNames.length]; this.getters = new Method[methodNames.length]; Class<?>[] none = new Class<?>[0]; for (int i = 0; i < methodNames.length; ++i) { String name = methodNames[i]; if (name.startsWith("get")) { getterFieldNames[i] = Character.toLowerCase(name.charAt(3)) + name.substring(4); } else { getterFieldNames[i] = name; } getters[i] = c.getMethod(name, none); } } private ClassSchema(Class<?> c) { this.className = c.getName(); List<Field> fieldList = new ArrayList<>(); List<Method> getterList = new ArrayList<>(); Set<String> names = new HashSet<>(); for (Field f : c.getFields()) { int mods = f.getModifiers(); if (Modifier.isPublic(mods) && !Modifier.isStatic(mods) && !Modifier.isVolatile(mods) && names.add(f.getName())) { fieldList.add(f); } } for (Method m : c.getMethods()) { if (Void.TYPE.equals(m.getReturnType())) { continue; } String name = m.getName(); if (!(name.startsWith("get") && m.getParameterTypes().length == 0)) { continue; } int mods = m.getModifiers(); if (!(Modifier.isPublic(mods) && !Modifier.isStatic(mods))) { continue; } if (names.add(methodNameToFieldName(name))) { getterList.add(m); } } this.fields = fieldList.toArray(new Field[fieldList.size()]); // TODO: Create one comparator for members and make it singleton. // TODO: Find a JSR305 annotation or something similar to exempt fields // from serialization. Maybe JPA @javax.persistence.Transient. Arrays.sort(this.fields, new Comparator<Field>() { @Override public int compare(Field a, Field b) { return a.getName().compareTo(b.getName()); } }); this.getters = getterList.toArray(new Method[getterList.size()]); Arrays.sort(this.getters, new Comparator<Method>() { @Override public int compare(Method a, Method b) { return a.getName().compareTo(b.getName()); } }); this.getterFieldNames = new String[this.getters.length]; for (int i = 0; i < this.getters.length; ++i) { this.getterFieldNames[i] = methodNameToFieldName( this.getters[i].getName()); } } static String methodNameToFieldName(String name) { if (name.startsWith("get")) { // getFoo -> foo return Character.toLowerCase(name.charAt(3)) + name.substring(4); } return name; } } """ # Fix emacs syntax highlighting " import dupe_methods print dupe_methods.dupe(src)
false
true
f7fa0edd6b8252cdfbaeb28433619ed38c01a7f4
394
py
Python
infinitd_server/handler/user.py
rhofour/InfiniTDBackend
8763d64a82d02e4282abff5419e1ab256af41d7e
[ "MIT" ]
null
null
null
infinitd_server/handler/user.py
rhofour/InfiniTDBackend
8763d64a82d02e4282abff5419e1ab256af41d7e
[ "MIT" ]
null
null
null
infinitd_server/handler/user.py
rhofour/InfiniTDBackend
8763d64a82d02e4282abff5419e1ab256af41d7e
[ "MIT" ]
null
null
null
import attr from infinitd_server.game import Game from infinitd_server.handler.base import BaseHandler class UserHandler(BaseHandler): game: Game # See https://github.com/google/pytype/issues/652 def get(self, username): user = self.game.getUserSummaryByName(username) if user: self.write(attr.asdict(user)) else: self.set_status(404)
26.266667
64
0.687817
import attr from infinitd_server.game import Game from infinitd_server.handler.base import BaseHandler class UserHandler(BaseHandler): game: Game def get(self, username): user = self.game.getUserSummaryByName(username) if user: self.write(attr.asdict(user)) else: self.set_status(404)
true
true
f7fa0fac001e8aa7a1f040dafbf5dc57c7be8d5b
1,167
py
Python
model/formfiller.py
talareq/python_training_mantis
3662a8e984ba32f8f309803ecf430b6f4f938886
[ "Apache-2.0" ]
null
null
null
model/formfiller.py
talareq/python_training_mantis
3662a8e984ba32f8f309803ecf430b6f4f938886
[ "Apache-2.0" ]
null
null
null
model/formfiller.py
talareq/python_training_mantis
3662a8e984ba32f8f309803ecf430b6f4f938886
[ "Apache-2.0" ]
null
null
null
from sys import maxsize class Project: def __init__(self, name=None, description=None, id=None): self.name = name self.description = description self.id = id def __repr__(self): return "%s:%s:%s" % (self.id, self.name, self.description) def __eq__(self, other): #return self.id == other.id and self.name == other.name return (self.id is None or other.id is None or self.id== other.id) and self.name == other.name def id_or_max(self): if self.id: return int(self.id) else: return maxsize class SoapProject(object): def __init__(self, data): self.name = data.name self.description = data.description self.id = data.id def __repr__(self): return "%s:%s:%s" % (self.id, self.name, self.description) def __eq__(self, other): #return self.id == other.id and self.name == other.name return (self.id is None or other.id is None or self.id== other.id) and self.name == other.name def id_or_max(self): if self.id: return int(self.id) else: return maxsize
25.369565
102
0.590403
from sys import maxsize class Project: def __init__(self, name=None, description=None, id=None): self.name = name self.description = description self.id = id def __repr__(self): return "%s:%s:%s" % (self.id, self.name, self.description) def __eq__(self, other): return (self.id is None or other.id is None or self.id== other.id) and self.name == other.name def id_or_max(self): if self.id: return int(self.id) else: return maxsize class SoapProject(object): def __init__(self, data): self.name = data.name self.description = data.description self.id = data.id def __repr__(self): return "%s:%s:%s" % (self.id, self.name, self.description) def __eq__(self, other): return (self.id is None or other.id is None or self.id== other.id) and self.name == other.name def id_or_max(self): if self.id: return int(self.id) else: return maxsize
true
true
f7fa10cf551a4e3ff4357b120ed04b8f5a2553bc
7,560
py
Python
Lib/test/libregrtest/runtest_mp.py
native-api/cpython
63799136e6c0491bb5d6f4a234d5a775db3458db
[ "PSF-2.0" ]
2
2019-03-20T13:10:46.000Z
2019-05-15T20:00:31.000Z
engine/2.80/python/lib/test/libregrtest/runtest_mp.py
byteinc/Phasor
f7d23a489c2b4bcc3c1961ac955926484ff8b8d9
[ "Unlicense" ]
null
null
null
engine/2.80/python/lib/test/libregrtest/runtest_mp.py
byteinc/Phasor
f7d23a489c2b4bcc3c1961ac955926484ff8b8d9
[ "Unlicense" ]
1
2018-10-16T15:14:17.000Z
2018-10-16T15:14:17.000Z
import faulthandler import json import os import queue import sys import threading import time import traceback import types from test import support from test.libregrtest.runtest import ( runtest, INTERRUPTED, CHILD_ERROR, PROGRESS_MIN_TIME, format_test_result) from test.libregrtest.setup import setup_tests from test.libregrtest.utils import format_duration # Display the running tests if nothing happened last N seconds PROGRESS_UPDATE = 30.0 # seconds # If interrupted, display the wait progress every N seconds WAIT_PROGRESS = 2.0 # seconds def run_test_in_subprocess(testname, ns): """Run the given test in a subprocess with --slaveargs. ns is the option Namespace parsed from command-line arguments. regrtest is invoked in a subprocess with the --slaveargs argument; when the subprocess exits, its return code, stdout and stderr are returned as a 3-tuple. """ from subprocess import Popen, PIPE ns_dict = vars(ns) slaveargs = (ns_dict, testname) slaveargs = json.dumps(slaveargs) cmd = [sys.executable, *support.args_from_interpreter_flags(), '-u', # Unbuffered stdout and stderr '-m', 'test.regrtest', '--slaveargs', slaveargs] if ns.pgo: cmd += ['--pgo'] # Running the child from the same working directory as regrtest's original # invocation ensures that TEMPDIR for the child is the same when # sysconfig.is_python_build() is true. See issue 15300. popen = Popen(cmd, stdout=PIPE, stderr=PIPE, universal_newlines=True, close_fds=(os.name != 'nt'), cwd=support.SAVEDCWD) with popen: stdout, stderr = popen.communicate() retcode = popen.wait() return retcode, stdout, stderr def run_tests_slave(slaveargs): ns_dict, testname = json.loads(slaveargs) ns = types.SimpleNamespace(**ns_dict) setup_tests(ns) try: result = runtest(ns, testname) except KeyboardInterrupt: result = INTERRUPTED, '' except BaseException as e: traceback.print_exc() result = CHILD_ERROR, str(e) print() # Force a newline (just in case) print(json.dumps(result), flush=True) sys.exit(0) # We do not use a generator so multiple threads can call next(). class MultiprocessIterator: """A thread-safe iterator over tests for multiprocess mode.""" def __init__(self, tests): self.interrupted = False self.lock = threading.Lock() self.tests = tests def __iter__(self): return self def __next__(self): with self.lock: if self.interrupted: raise StopIteration('tests interrupted') return next(self.tests) class MultiprocessThread(threading.Thread): def __init__(self, pending, output, ns): super().__init__() self.pending = pending self.output = output self.ns = ns self.current_test = None self.start_time = None def _runtest(self): try: test = next(self.pending) except StopIteration: self.output.put((None, None, None, None)) return True try: self.start_time = time.monotonic() self.current_test = test retcode, stdout, stderr = run_test_in_subprocess(test, self.ns) finally: self.current_test = None if retcode != 0: result = (CHILD_ERROR, "Exit code %s" % retcode) self.output.put((test, stdout.rstrip(), stderr.rstrip(), result)) return False stdout, _, result = stdout.strip().rpartition("\n") if not result: self.output.put((None, None, None, None)) return True result = json.loads(result) self.output.put((test, stdout.rstrip(), stderr.rstrip(), result)) return False def run(self): try: stop = False while not stop: stop = self._runtest() except BaseException: self.output.put((None, None, None, None)) raise def run_tests_multiprocess(regrtest): output = queue.Queue() pending = MultiprocessIterator(regrtest.tests) test_timeout = regrtest.ns.timeout use_timeout = (test_timeout is not None) workers = [MultiprocessThread(pending, output, regrtest.ns) for i in range(regrtest.ns.use_mp)] print("Run tests in parallel using %s child processes" % len(workers)) for worker in workers: worker.start() def get_running(workers): running = [] for worker in workers: current_test = worker.current_test if not current_test: continue dt = time.monotonic() - worker.start_time if dt >= PROGRESS_MIN_TIME: text = '%s (%s)' % (current_test, format_duration(dt)) running.append(text) return running finished = 0 test_index = 1 get_timeout = max(PROGRESS_UPDATE, PROGRESS_MIN_TIME) try: while finished < regrtest.ns.use_mp: if use_timeout: faulthandler.dump_traceback_later(test_timeout, exit=True) try: item = output.get(timeout=get_timeout) except queue.Empty: running = get_running(workers) if running and not regrtest.ns.pgo: print('running: %s' % ', '.join(running), flush=True) continue test, stdout, stderr, result = item if test is None: finished += 1 continue regrtest.accumulate_result(test, result) # Display progress ok, test_time = result text = format_test_result(test, ok) if (ok not in (CHILD_ERROR, INTERRUPTED) and test_time >= PROGRESS_MIN_TIME and not regrtest.ns.pgo): text += ' (%.0f sec)' % test_time elif ok == CHILD_ERROR: text = '%s (%s)' % (text, test_time) running = get_running(workers) if running and not regrtest.ns.pgo: text += ' -- running: %s' % ', '.join(running) regrtest.display_progress(test_index, text) # Copy stdout and stderr from the child process if stdout: print(stdout, flush=True) if stderr and not regrtest.ns.pgo: print(stderr, file=sys.stderr, flush=True) if result[0] == INTERRUPTED: raise KeyboardInterrupt test_index += 1 except KeyboardInterrupt: regrtest.interrupted = True pending.interrupted = True print() finally: if use_timeout: faulthandler.cancel_dump_traceback_later() # If tests are interrupted, wait until tests complete wait_start = time.monotonic() while True: running = [worker.current_test for worker in workers] running = list(filter(bool, running)) if not running: break dt = time.monotonic() - wait_start line = "Waiting for %s (%s tests)" % (', '.join(running), len(running)) if dt >= WAIT_PROGRESS: line = "%s since %.0f sec" % (line, dt) print(line, flush=True) for worker in workers: worker.join(WAIT_PROGRESS)
31.111111
79
0.591931
import faulthandler import json import os import queue import sys import threading import time import traceback import types from test import support from test.libregrtest.runtest import ( runtest, INTERRUPTED, CHILD_ERROR, PROGRESS_MIN_TIME, format_test_result) from test.libregrtest.setup import setup_tests from test.libregrtest.utils import format_duration PROGRESS_UPDATE = 30.0 WAIT_PROGRESS = 2.0 def run_test_in_subprocess(testname, ns): from subprocess import Popen, PIPE ns_dict = vars(ns) slaveargs = (ns_dict, testname) slaveargs = json.dumps(slaveargs) cmd = [sys.executable, *support.args_from_interpreter_flags(), '-u', '-m', 'test.regrtest', '--slaveargs', slaveargs] if ns.pgo: cmd += ['--pgo'] # invocation ensures that TEMPDIR for the child is the same when # sysconfig.is_python_build() is true. See issue 15300. popen = Popen(cmd, stdout=PIPE, stderr=PIPE, universal_newlines=True, close_fds=(os.name != 'nt'), cwd=support.SAVEDCWD) with popen: stdout, stderr = popen.communicate() retcode = popen.wait() return retcode, stdout, stderr def run_tests_slave(slaveargs): ns_dict, testname = json.loads(slaveargs) ns = types.SimpleNamespace(**ns_dict) setup_tests(ns) try: result = runtest(ns, testname) except KeyboardInterrupt: result = INTERRUPTED, '' except BaseException as e: traceback.print_exc() result = CHILD_ERROR, str(e) print() # Force a newline (just in case) print(json.dumps(result), flush=True) sys.exit(0) # We do not use a generator so multiple threads can call next(). class MultiprocessIterator: def __init__(self, tests): self.interrupted = False self.lock = threading.Lock() self.tests = tests def __iter__(self): return self def __next__(self): with self.lock: if self.interrupted: raise StopIteration('tests interrupted') return next(self.tests) class MultiprocessThread(threading.Thread): def __init__(self, pending, output, ns): super().__init__() self.pending = pending self.output = output self.ns = ns self.current_test = None self.start_time = None def _runtest(self): try: test = next(self.pending) except StopIteration: self.output.put((None, None, None, None)) return True try: self.start_time = time.monotonic() self.current_test = test retcode, stdout, stderr = run_test_in_subprocess(test, self.ns) finally: self.current_test = None if retcode != 0: result = (CHILD_ERROR, "Exit code %s" % retcode) self.output.put((test, stdout.rstrip(), stderr.rstrip(), result)) return False stdout, _, result = stdout.strip().rpartition("\n") if not result: self.output.put((None, None, None, None)) return True result = json.loads(result) self.output.put((test, stdout.rstrip(), stderr.rstrip(), result)) return False def run(self): try: stop = False while not stop: stop = self._runtest() except BaseException: self.output.put((None, None, None, None)) raise def run_tests_multiprocess(regrtest): output = queue.Queue() pending = MultiprocessIterator(regrtest.tests) test_timeout = regrtest.ns.timeout use_timeout = (test_timeout is not None) workers = [MultiprocessThread(pending, output, regrtest.ns) for i in range(regrtest.ns.use_mp)] print("Run tests in parallel using %s child processes" % len(workers)) for worker in workers: worker.start() def get_running(workers): running = [] for worker in workers: current_test = worker.current_test if not current_test: continue dt = time.monotonic() - worker.start_time if dt >= PROGRESS_MIN_TIME: text = '%s (%s)' % (current_test, format_duration(dt)) running.append(text) return running finished = 0 test_index = 1 get_timeout = max(PROGRESS_UPDATE, PROGRESS_MIN_TIME) try: while finished < regrtest.ns.use_mp: if use_timeout: faulthandler.dump_traceback_later(test_timeout, exit=True) try: item = output.get(timeout=get_timeout) except queue.Empty: running = get_running(workers) if running and not regrtest.ns.pgo: print('running: %s' % ', '.join(running), flush=True) continue test, stdout, stderr, result = item if test is None: finished += 1 continue regrtest.accumulate_result(test, result) # Display progress ok, test_time = result text = format_test_result(test, ok) if (ok not in (CHILD_ERROR, INTERRUPTED) and test_time >= PROGRESS_MIN_TIME and not regrtest.ns.pgo): text += ' (%.0f sec)' % test_time elif ok == CHILD_ERROR: text = '%s (%s)' % (text, test_time) running = get_running(workers) if running and not regrtest.ns.pgo: text += ' -- running: %s' % ', '.join(running) regrtest.display_progress(test_index, text) # Copy stdout and stderr from the child process if stdout: print(stdout, flush=True) if stderr and not regrtest.ns.pgo: print(stderr, file=sys.stderr, flush=True) if result[0] == INTERRUPTED: raise KeyboardInterrupt test_index += 1 except KeyboardInterrupt: regrtest.interrupted = True pending.interrupted = True print() finally: if use_timeout: faulthandler.cancel_dump_traceback_later() # If tests are interrupted, wait until tests complete wait_start = time.monotonic() while True: running = [worker.current_test for worker in workers] running = list(filter(bool, running)) if not running: break dt = time.monotonic() - wait_start line = "Waiting for %s (%s tests)" % (', '.join(running), len(running)) if dt >= WAIT_PROGRESS: line = "%s since %.0f sec" % (line, dt) print(line, flush=True) for worker in workers: worker.join(WAIT_PROGRESS)
true
true
f7fa11575942ae25beb39eaf06862fe73d89fb5a
4,060
py
Python
heat/tests/test_scaling_template.py
pshchelo/heat
6cf94a3ece89d77b839f61292e5f023c3f192c82
[ "Apache-2.0" ]
null
null
null
heat/tests/test_scaling_template.py
pshchelo/heat
6cf94a3ece89d77b839f61292e5f023c3f192c82
[ "Apache-2.0" ]
null
null
null
heat/tests/test_scaling_template.py
pshchelo/heat
6cf94a3ece89d77b839f61292e5f023c3f192c82
[ "Apache-2.0" ]
null
null
null
# # 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 functools import itertools from heat.common import short_id from heat.scaling import template from heat.tests import common class ResourceTemplatesTest(common.HeatTestCase): def setUp(self): super(ResourceTemplatesTest, self).setUp() ids = ('stubbed-id-%s' % (i,) for i in itertools.count()) self.patchobject( short_id, 'generate_id').side_effect = functools.partial(next, ids) def test_create_template(self): """ When creating a template from scratch, an empty list is accepted as the "old" resources and new resources are created up to num_resource. """ templates = template.resource_templates([], {'type': 'Foo'}, 2, 0) expected = [ ('stubbed-id-0', {'type': 'Foo'}), ('stubbed-id-1', {'type': 'Foo'})] self.assertEqual(expected, list(templates)) def test_replace_template(self): """ If num_replace is the number of old resources, then all of the resources will be replaced. """ old_resources = [ ('old-id-0', {'type': 'Foo'}), ('old-id-1', {'type': 'Foo'})] templates = template.resource_templates(old_resources, {'type': 'Bar'}, 1, 2) expected = [('old-id-1', {'type': 'Bar'})] self.assertEqual(expected, list(templates)) def test_replace_some_units(self): """ If the resource definition changes, only the number of replacements specified will be made; beyond that, the original templates are used. """ old_resources = [ ('old-id-0', {'type': 'Foo'}), ('old-id-1', {'type': 'Foo'})] new_spec = {'type': 'Bar'} templates = template.resource_templates(old_resources, new_spec, 2, 1) expected = [ ('old-id-0', {'type': 'Bar'}), ('old-id-1', {'type': 'Foo'})] self.assertEqual(expected, list(templates)) def test_growth_counts_as_replacement(self): """ If we grow the template and replace some elements at the same time, the number of replacements to perform is reduced by the number of new resources to be created. """ spec = {'type': 'Foo'} old_resources = [ ('old-id-0', spec), ('old-id-1', spec)] new_spec = {'type': 'Bar'} templates = template.resource_templates(old_resources, new_spec, 4, 2) expected = [ ('old-id-0', spec), ('old-id-1', spec), ('stubbed-id-0', new_spec), ('stubbed-id-1', new_spec)] self.assertEqual(expected, list(templates)) def test_replace_units_some_already_up_to_date(self): """ If some of the old resources already have the new resource definition, then they won't be considered for replacement, and the next resource that is out-of-date will be replaced. """ old_resources = [ ('old-id-0', {'type': 'Bar'}), ('old-id-1', {'type': 'Foo'})] new_spec = {'type': 'Bar'} templates = template.resource_templates(old_resources, new_spec, 2, 1) second_batch_expected = [ ('old-id-0', {'type': 'Bar'}), ('old-id-1', {'type': 'Bar'})] self.assertEqual(second_batch_expected, list(templates))
39.038462
79
0.578325
import functools import itertools from heat.common import short_id from heat.scaling import template from heat.tests import common class ResourceTemplatesTest(common.HeatTestCase): def setUp(self): super(ResourceTemplatesTest, self).setUp() ids = ('stubbed-id-%s' % (i,) for i in itertools.count()) self.patchobject( short_id, 'generate_id').side_effect = functools.partial(next, ids) def test_create_template(self): templates = template.resource_templates([], {'type': 'Foo'}, 2, 0) expected = [ ('stubbed-id-0', {'type': 'Foo'}), ('stubbed-id-1', {'type': 'Foo'})] self.assertEqual(expected, list(templates)) def test_replace_template(self): old_resources = [ ('old-id-0', {'type': 'Foo'}), ('old-id-1', {'type': 'Foo'})] templates = template.resource_templates(old_resources, {'type': 'Bar'}, 1, 2) expected = [('old-id-1', {'type': 'Bar'})] self.assertEqual(expected, list(templates)) def test_replace_some_units(self): old_resources = [ ('old-id-0', {'type': 'Foo'}), ('old-id-1', {'type': 'Foo'})] new_spec = {'type': 'Bar'} templates = template.resource_templates(old_resources, new_spec, 2, 1) expected = [ ('old-id-0', {'type': 'Bar'}), ('old-id-1', {'type': 'Foo'})] self.assertEqual(expected, list(templates)) def test_growth_counts_as_replacement(self): spec = {'type': 'Foo'} old_resources = [ ('old-id-0', spec), ('old-id-1', spec)] new_spec = {'type': 'Bar'} templates = template.resource_templates(old_resources, new_spec, 4, 2) expected = [ ('old-id-0', spec), ('old-id-1', spec), ('stubbed-id-0', new_spec), ('stubbed-id-1', new_spec)] self.assertEqual(expected, list(templates)) def test_replace_units_some_already_up_to_date(self): old_resources = [ ('old-id-0', {'type': 'Bar'}), ('old-id-1', {'type': 'Foo'})] new_spec = {'type': 'Bar'} templates = template.resource_templates(old_resources, new_spec, 2, 1) second_batch_expected = [ ('old-id-0', {'type': 'Bar'}), ('old-id-1', {'type': 'Bar'})] self.assertEqual(second_batch_expected, list(templates))
true
true
f7fa116ead852c6bca5653c974a862226ff65ca8
5,845
py
Python
tests/testflows/window_functions/regression.py
chalice19/ClickHouse
2f38e7bc5c2113935ab86260439bb543a1737291
[ "Apache-2.0" ]
1
2022-02-27T15:21:20.000Z
2022-02-27T15:21:20.000Z
tests/testflows/window_functions/regression.py
chalice19/ClickHouse
2f38e7bc5c2113935ab86260439bb543a1737291
[ "Apache-2.0" ]
16
2022-02-14T15:53:29.000Z
2022-03-25T18:39:16.000Z
tests/testflows/window_functions/regression.py
chalice19/ClickHouse
2f38e7bc5c2113935ab86260439bb543a1737291
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 import os import sys from testflows.core import * append_path(sys.path, "..") from helpers.cluster import Cluster from helpers.argparser import argparser from window_functions.requirements import ( SRS019_ClickHouse_Window_Functions, RQ_SRS_019_ClickHouse_WindowFunctions, ) xfails = { "tests/:/frame clause/range frame/between expr following and expr following without order by error": [ (Fail, "invalid error message") ], "tests/:/frame clause/range frame/between expr following and expr preceding without order by error": [ (Fail, "invalid error message") ], "tests/:/frame clause/range frame/between expr following and current row without order by error": [ (Fail, "invalid error message") ], "tests/:/frame clause/range frame/between expr following and current row zero special case": [ (Fail, "known bug") ], "tests/:/frame clause/range frame/between expr following and expr preceding with order by zero special case": [ (Fail, "known bug") ], "tests/:/funcs/lag/anyOrNull with column value as offset": [ (Fail, "column values are not supported as offset") ], "tests/:/funcs/lead/subquery as offset": [ (Fail, "subquery is not supported as offset") ], "tests/:/frame clause/range frame/between current row and unbounded following modifying named window": [ (Fail, "range with named window is not supported") ], "tests/:/frame clause/range overflow/negative overflow with Int16": [ (Fail, "exception on conversion") ], "tests/:/frame clause/range overflow/positive overflow with Int16": [ (Fail, "exception on conversion") ], "tests/:/misc/subquery expr preceding": [ (Fail, "subquery is not supported as offset") ], "tests/:/frame clause/range errors/error negative preceding offset": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/22442") ], "tests/:/frame clause/range errors/error negative following offset": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/22442") ], "tests/:/misc/window functions in select expression": [ (Fail, "not supported, https://github.com/ClickHouse/ClickHouse/issues/19857") ], "tests/:/misc/window functions in subquery": [ (Fail, "not supported, https://github.com/ClickHouse/ClickHouse/issues/19857") ], "tests/:/misc/in view": [ (Fail, "bug, https://github.com/ClickHouse/ClickHouse/issues/26001") ], "tests/:/frame clause/range frame/order by decimal": [ ( Fail, "Exception: The RANGE OFFSET frame for 'DB::ColumnDecimal<DB::Decimal<long> >' ORDER BY column is not implemented", ) ], "tests/:/frame clause/range frame/with nulls": [ ( Fail, "DB::Exception: The RANGE OFFSET frame for 'DB::ColumnNullable' ORDER BY column is not implemented", ) ], "tests/:/aggregate funcs/aggregate funcs over rows frame/func='mannWhitneyUTest(salary, 1)'": [ (Fail, "need to investigate") ], "tests/:/aggregate funcs/aggregate funcs over rows frame/func='rankCorr(salary, 0.5)'": [ (Fail, "need to investigate") ], "tests/distributed/misc/query with order by and one window": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/23902") ], "tests/distributed/over clause/empty named window": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/23902") ], "tests/distributed/over clause/empty": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/23902") ], "tests/distributed/over clause/adhoc window": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/23902") ], "tests/distributed/frame clause/range datetime/:": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/23902") ], "tests/distributed/frame clause/range frame/between expr preceding and expr following with partition by same column twice": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/23902") ], "tests/:/funcs/leadInFrame/explicit default value": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/25057") ], "tests/:/funcs/leadInFrame/with nulls": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/25057") ], "tests/:/funcs/leadInFrame/default offset": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/23902") ], "tests/:/funcs/lagInFrame/explicit default value": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/25057") ], "tests/:/funcs/lagInFrame/with nulls": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/25057") ], "tests/:/funcs/lagInFrame/default offset": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/23902") ], } xflags = {} @TestModule @ArgumentParser(argparser) @XFails(xfails) @XFlags(xflags) @Name("window functions") @Specifications(SRS019_ClickHouse_Window_Functions) @Requirements(RQ_SRS_019_ClickHouse_WindowFunctions("1.0")) def regression( self, local, clickhouse_binary_path, clickhouse_version=None, stress=None ): """Window functions regression.""" nodes = {"clickhouse": ("clickhouse1", "clickhouse2", "clickhouse3")} if stress is not None: self.context.stress = stress self.context.clickhouse_version = clickhouse_version with Cluster( local, clickhouse_binary_path, nodes=nodes, docker_compose_project_dir=os.path.join(current_dir(), "window_functions_env"), ) as cluster: self.context.cluster = cluster Feature(run=load("window_functions.tests.feature", "feature"), flags=TE) if main(): regression()
37.954545
129
0.663644
import os import sys from testflows.core import * append_path(sys.path, "..") from helpers.cluster import Cluster from helpers.argparser import argparser from window_functions.requirements import ( SRS019_ClickHouse_Window_Functions, RQ_SRS_019_ClickHouse_WindowFunctions, ) xfails = { "tests/:/frame clause/range frame/between expr following and expr following without order by error": [ (Fail, "invalid error message") ], "tests/:/frame clause/range frame/between expr following and expr preceding without order by error": [ (Fail, "invalid error message") ], "tests/:/frame clause/range frame/between expr following and current row without order by error": [ (Fail, "invalid error message") ], "tests/:/frame clause/range frame/between expr following and current row zero special case": [ (Fail, "known bug") ], "tests/:/frame clause/range frame/between expr following and expr preceding with order by zero special case": [ (Fail, "known bug") ], "tests/:/funcs/lag/anyOrNull with column value as offset": [ (Fail, "column values are not supported as offset") ], "tests/:/funcs/lead/subquery as offset": [ (Fail, "subquery is not supported as offset") ], "tests/:/frame clause/range frame/between current row and unbounded following modifying named window": [ (Fail, "range with named window is not supported") ], "tests/:/frame clause/range overflow/negative overflow with Int16": [ (Fail, "exception on conversion") ], "tests/:/frame clause/range overflow/positive overflow with Int16": [ (Fail, "exception on conversion") ], "tests/:/misc/subquery expr preceding": [ (Fail, "subquery is not supported as offset") ], "tests/:/frame clause/range errors/error negative preceding offset": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/22442") ], "tests/:/frame clause/range errors/error negative following offset": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/22442") ], "tests/:/misc/window functions in select expression": [ (Fail, "not supported, https://github.com/ClickHouse/ClickHouse/issues/19857") ], "tests/:/misc/window functions in subquery": [ (Fail, "not supported, https://github.com/ClickHouse/ClickHouse/issues/19857") ], "tests/:/misc/in view": [ (Fail, "bug, https://github.com/ClickHouse/ClickHouse/issues/26001") ], "tests/:/frame clause/range frame/order by decimal": [ ( Fail, "Exception: The RANGE OFFSET frame for 'DB::ColumnDecimal<DB::Decimal<long> >' ORDER BY column is not implemented", ) ], "tests/:/frame clause/range frame/with nulls": [ ( Fail, "DB::Exception: The RANGE OFFSET frame for 'DB::ColumnNullable' ORDER BY column is not implemented", ) ], "tests/:/aggregate funcs/aggregate funcs over rows frame/func='mannWhitneyUTest(salary, 1)'": [ (Fail, "need to investigate") ], "tests/:/aggregate funcs/aggregate funcs over rows frame/func='rankCorr(salary, 0.5)'": [ (Fail, "need to investigate") ], "tests/distributed/misc/query with order by and one window": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/23902") ], "tests/distributed/over clause/empty named window": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/23902") ], "tests/distributed/over clause/empty": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/23902") ], "tests/distributed/over clause/adhoc window": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/23902") ], "tests/distributed/frame clause/range datetime/:": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/23902") ], "tests/distributed/frame clause/range frame/between expr preceding and expr following with partition by same column twice": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/23902") ], "tests/:/funcs/leadInFrame/explicit default value": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/25057") ], "tests/:/funcs/leadInFrame/with nulls": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/25057") ], "tests/:/funcs/leadInFrame/default offset": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/23902") ], "tests/:/funcs/lagInFrame/explicit default value": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/25057") ], "tests/:/funcs/lagInFrame/with nulls": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/25057") ], "tests/:/funcs/lagInFrame/default offset": [ (Fail, "https://github.com/ClickHouse/ClickHouse/issues/23902") ], } xflags = {} @TestModule @ArgumentParser(argparser) @XFails(xfails) @XFlags(xflags) @Name("window functions") @Specifications(SRS019_ClickHouse_Window_Functions) @Requirements(RQ_SRS_019_ClickHouse_WindowFunctions("1.0")) def regression( self, local, clickhouse_binary_path, clickhouse_version=None, stress=None ): nodes = {"clickhouse": ("clickhouse1", "clickhouse2", "clickhouse3")} if stress is not None: self.context.stress = stress self.context.clickhouse_version = clickhouse_version with Cluster( local, clickhouse_binary_path, nodes=nodes, docker_compose_project_dir=os.path.join(current_dir(), "window_functions_env"), ) as cluster: self.context.cluster = cluster Feature(run=load("window_functions.tests.feature", "feature"), flags=TE) if main(): regression()
true
true
f7fa12e13a54bdde0476908db3f9321654c8d572
2,862
py
Python
pixloc/utils/eval.py
jmorlana/pixloc
90f7e968398252e8557b284803ee774cb8d80cd0
[ "Apache-2.0" ]
457
2021-03-17T00:39:33.000Z
2022-03-30T02:38:19.000Z
pixloc/utils/eval.py
jmorlana/pixloc
90f7e968398252e8557b284803ee774cb8d80cd0
[ "Apache-2.0" ]
31
2021-03-17T07:35:34.000Z
2022-03-31T07:07:56.000Z
pixloc/utils/eval.py
jmorlana/pixloc
90f7e968398252e8557b284803ee774cb8d80cd0
[ "Apache-2.0" ]
56
2021-03-17T05:55:09.000Z
2022-03-15T01:38:35.000Z
import logging from pathlib import Path from typing import Union, Dict, Tuple, Optional import numpy as np from .io import parse_image_list from .colmap import qvec2rotmat, read_images_binary, read_images_text logger = logging.getLogger(__name__) def evaluate(gt_sfm_model: Path, predictions: Union[Dict, Path], test_file_list: Optional[Path] = None, only_localized: bool = False): """Compute the evaluation metrics for 7Scenes and Cambridge Landmarks. The other datasets are evaluated on visuallocalization.net """ if not isinstance(predictions, dict): predictions = parse_image_list(predictions, with_poses=True) predictions = {n: (im.qvec, im.tvec) for n, im in predictions} # ground truth poses from the sfm model images_bin = gt_sfm_model / 'images.bin' images_txt = gt_sfm_model / 'images.txt' if images_bin.exists(): images = read_images_binary(images_bin) elif images_txt.exists(): images = read_images_text(images_txt) else: raise ValueError(gt_sfm_model) name2id = {image.name: i for i, image in images.items()} if test_file_list is None: test_names = list(name2id) else: with open(test_file_list, 'r') as f: test_names = f.read().rstrip().split('\n') # translation and rotation errors errors_t = [] errors_R = [] for name in test_names: if name not in predictions: if only_localized: continue e_t = np.inf e_R = 180. else: image = images[name2id[name]] R_gt, t_gt = image.qvec2rotmat(), image.tvec qvec, t = predictions[name] R = qvec2rotmat(qvec) e_t = np.linalg.norm(-R_gt.T @ t_gt + R.T @ t, axis=0) cos = np.clip((np.trace(np.dot(R_gt.T, R)) - 1) / 2, -1., 1.) e_R = np.rad2deg(np.abs(np.arccos(cos))) errors_t.append(e_t) errors_R.append(e_R) errors_t = np.array(errors_t) errors_R = np.array(errors_R) med_t = np.median(errors_t) med_R = np.median(errors_R) out = f'\nMedian errors: {med_t:.3f}m, {med_R:.3f}deg' out += '\nPercentage of test images localized within:' threshs_t = [0.01, 0.02, 0.03, 0.05, 0.25, 0.5, 5.0] threshs_R = [1.0, 2.0, 3.0, 5.0, 2.0, 5.0, 10.0] for th_t, th_R in zip(threshs_t, threshs_R): ratio = np.mean((errors_t < th_t) & (errors_R < th_R)) out += f'\n\t{th_t*100:.0f}cm, {th_R:.0f}deg : {ratio*100:.2f}%' logger.info(out) def cumulative_recall(errors: np.ndarray) -> Tuple[np.ndarray]: sort_idx = np.argsort(errors) errors = np.array(errors.copy())[sort_idx] recall = (np.arange(len(errors)) + 1) / len(errors) errors = np.r_[0., errors] recall = np.r_[0., recall] return errors, recall*100
35.333333
74
0.621593
import logging from pathlib import Path from typing import Union, Dict, Tuple, Optional import numpy as np from .io import parse_image_list from .colmap import qvec2rotmat, read_images_binary, read_images_text logger = logging.getLogger(__name__) def evaluate(gt_sfm_model: Path, predictions: Union[Dict, Path], test_file_list: Optional[Path] = None, only_localized: bool = False): if not isinstance(predictions, dict): predictions = parse_image_list(predictions, with_poses=True) predictions = {n: (im.qvec, im.tvec) for n, im in predictions} images_bin = gt_sfm_model / 'images.bin' images_txt = gt_sfm_model / 'images.txt' if images_bin.exists(): images = read_images_binary(images_bin) elif images_txt.exists(): images = read_images_text(images_txt) else: raise ValueError(gt_sfm_model) name2id = {image.name: i for i, image in images.items()} if test_file_list is None: test_names = list(name2id) else: with open(test_file_list, 'r') as f: test_names = f.read().rstrip().split('\n') errors_t = [] errors_R = [] for name in test_names: if name not in predictions: if only_localized: continue e_t = np.inf e_R = 180. else: image = images[name2id[name]] R_gt, t_gt = image.qvec2rotmat(), image.tvec qvec, t = predictions[name] R = qvec2rotmat(qvec) e_t = np.linalg.norm(-R_gt.T @ t_gt + R.T @ t, axis=0) cos = np.clip((np.trace(np.dot(R_gt.T, R)) - 1) / 2, -1., 1.) e_R = np.rad2deg(np.abs(np.arccos(cos))) errors_t.append(e_t) errors_R.append(e_R) errors_t = np.array(errors_t) errors_R = np.array(errors_R) med_t = np.median(errors_t) med_R = np.median(errors_R) out = f'\nMedian errors: {med_t:.3f}m, {med_R:.3f}deg' out += '\nPercentage of test images localized within:' threshs_t = [0.01, 0.02, 0.03, 0.05, 0.25, 0.5, 5.0] threshs_R = [1.0, 2.0, 3.0, 5.0, 2.0, 5.0, 10.0] for th_t, th_R in zip(threshs_t, threshs_R): ratio = np.mean((errors_t < th_t) & (errors_R < th_R)) out += f'\n\t{th_t*100:.0f}cm, {th_R:.0f}deg : {ratio*100:.2f}%' logger.info(out) def cumulative_recall(errors: np.ndarray) -> Tuple[np.ndarray]: sort_idx = np.argsort(errors) errors = np.array(errors.copy())[sort_idx] recall = (np.arange(len(errors)) + 1) / len(errors) errors = np.r_[0., errors] recall = np.r_[0., recall] return errors, recall*100
true
true
f7fa133bac2446b8b36aa258c6b5da3eef61e92c
1,771
py
Python
qakgc/linker/linker.py
pbmstrk/odqa
b5917237d5162eae208382e5d25b0c8c47018681
[ "BSD-3-Clause" ]
4
2020-09-04T16:58:52.000Z
2021-06-23T03:37:18.000Z
qakgc/linker/linker.py
pbmstrk/QAKGC
b5917237d5162eae208382e5d25b0c8c47018681
[ "BSD-3-Clause" ]
3
2020-07-07T23:45:21.000Z
2020-07-09T11:49:23.000Z
qakgc/linker/linker.py
pbmstrk/odqa
b5917237d5162eae208382e5d25b0c8c47018681
[ "BSD-3-Clause" ]
null
null
null
import logging import argparse import blink.main_dense as main_dense logger = logging.getLogger(__name__) class EntityLinker: def __init__(self, model_path, logger=None): self.logger = logger self.models_path = model_path self.config = { "test_entities": None, "test_mentions": None, "interactive": False, "biencoder_model": self.models_path+"biencoder_wiki_large.bin", "biencoder_config": self.models_path+"biencoder_wiki_large.json", "entity_catalogue": self.models_path+"entity.jsonl", "entity_encoding": self.models_path+"all_entities_large.t7", "crossencoder_model": self.models_path+"crossencoder_wiki_large.bin", "crossencoder_config": self.models_path+"crossencoder_wiki_large.json", "fast": True, # set this to be true if speed is a concern "output_path": "logs/", # logging directory "faiss_index": "flat", "index_path": self.models_path+"index.pkl", "top_k": 30 } self.args = argparse.Namespace(**self.config) self.models = main_dense.load_models(self.args, logger=self.logger) def __call__(self, data_to_link): _, _, _, _, _, predictions, scores, = main_dense.run(self.args, logger=self.logger, biencoder=self.models[0], biencoder_params=self.models[1], crossencoder=self.models[2], crossencoder_params=self.models[3], candidate_encoding=self.models[4], title2id=self.models[5], id2title=self.models[6], id2text=self.models[7], wikipedia_id2local_id=self.models[8], faiss_indexer=self.models[9], test_data=data_to_link) return predictions
36.142857
100
0.645963
import logging import argparse import blink.main_dense as main_dense logger = logging.getLogger(__name__) class EntityLinker: def __init__(self, model_path, logger=None): self.logger = logger self.models_path = model_path self.config = { "test_entities": None, "test_mentions": None, "interactive": False, "biencoder_model": self.models_path+"biencoder_wiki_large.bin", "biencoder_config": self.models_path+"biencoder_wiki_large.json", "entity_catalogue": self.models_path+"entity.jsonl", "entity_encoding": self.models_path+"all_entities_large.t7", "crossencoder_model": self.models_path+"crossencoder_wiki_large.bin", "crossencoder_config": self.models_path+"crossencoder_wiki_large.json", "fast": True, "output_path": "logs/", "faiss_index": "flat", "index_path": self.models_path+"index.pkl", "top_k": 30 } self.args = argparse.Namespace(**self.config) self.models = main_dense.load_models(self.args, logger=self.logger) def __call__(self, data_to_link): _, _, _, _, _, predictions, scores, = main_dense.run(self.args, logger=self.logger, biencoder=self.models[0], biencoder_params=self.models[1], crossencoder=self.models[2], crossencoder_params=self.models[3], candidate_encoding=self.models[4], title2id=self.models[5], id2title=self.models[6], id2text=self.models[7], wikipedia_id2local_id=self.models[8], faiss_indexer=self.models[9], test_data=data_to_link) return predictions
true
true
f7fa1373844f3e5b04ea253d13ca7c3d705f60e3
2,114
py
Python
backtoshops/events/urls.py
RaphaelPrevost/Back2Shops
5f2d369e82fe2a7b9b3a6c55782319b23d142dfd
[ "CECILL-B" ]
null
null
null
backtoshops/events/urls.py
RaphaelPrevost/Back2Shops
5f2d369e82fe2a7b9b3a6c55782319b23d142dfd
[ "CECILL-B" ]
6
2021-03-31T19:21:50.000Z
2022-01-13T01:46:09.000Z
backtoshops/events/urls.py
RaphaelPrevost/Back2Shops
5f2d369e82fe2a7b9b3a6c55782319b23d142dfd
[ "CECILL-B" ]
null
null
null
# -*- coding: utf-8 -*- ############################################################################# # # Copyright © Dragon Dollar Limited # contact: contact@dragondollar.com # # This software is a collection of webservices designed to provide a secure # and scalable framework to build e-commerce websites. # # This software is governed by the CeCILL-B license under French law and # abiding by the rules of distribution of free software. You can use, # modify and/ or redistribute the software under the terms of the CeCILL-B # license as circulated by CEA, CNRS and INRIA at the following URL # " http://www.cecill.info". # # As a counterpart to the access to the source code and rights to copy, # modify and redistribute granted by the license, users are provided only # with a limited warranty and the software's author, the holder of the # economic rights, and the successive licensors have only limited # liability. # # In this respect, the user's attention is drawn to the risks associated # with loading, using, modifying and/or developing or reproducing the # software by the user in light of its specific status of free software, # that may mean that it is complicated to manipulate, and that also # therefore means that it is reserved for developers and experienced # professionals having in-depth computer knowledge. Users are therefore # encouraged to load and test the software's suitability as regards their # requirements in conditions enabling the security of their systems and/or # data to be ensured and, more generally, to use and operate it in the # same conditions as regards security. # # The fact that you are presently reading this means that you have had # knowledge of the CeCILL-B license and that you accept its terms. # ############################################################################# import settings from django.conf.urls import patterns, url from fouillis.views import admin_required from events.views import * urlpatterns = patterns(settings.get_site_prefix() + 'events', url(r'/(?P<pk>\d+)$', admin_required(EventView.as_view()), name="get_event"), )
43.142857
77
0.712867
true
true
f7fa1485c1ce165fe1fb8ae31a98f4def312e691
9,830
py
Python
2018/main.py
yingshaoxo/TGAsk
8def7d1fa25974322860f1ea3fe7078fde7edbee
[ "MIT" ]
3
2020-06-11T12:59:13.000Z
2021-12-15T04:55:37.000Z
2018/main.py
yingshaoxo/TGAsk
8def7d1fa25974322860f1ea3fe7078fde7edbee
[ "MIT" ]
null
null
null
2018/main.py
yingshaoxo/TGAsk
8def7d1fa25974322860f1ea3fe7078fde7edbee
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging import threading import maya from auto_everything.base import IO from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, MessageHandler, Filters from telegram import InlineKeyboardButton, InlineKeyboardMarkup import os import time """ export master_user_id= export telegram_bot_token= """ master_user_id = int(os.getenv("master_user_id", "131513300")) TOKEN = os.getenv("telegram_bot_token", "") print(master_user_id) print(TOKEN) io = IO() lock = threading.RLock() ROOT_DIR = "." logging.basicConfig(filename=os.path.join(ROOT_DIR, "__main.log"), level=logging.DEBUG, filemode='w', format='%(levelname)s - %(message)s') data = { "question": "1+1=? (不回答会被踢出群)", "answer": [ "2", "3", ], "right_answer_index": 1 } data = io.read_settings("data", data) waitting_for_master = False people = { # chat_id 324253: "maya timestring" } people = io.read_settings("people", people) historical_message = { "id_list": [] } historical_message = io.read_settings( "historical_message", historical_message) def handle_useless_msg(bot, update, new_msg_id_list): global historical_message chat_type = update.message.chat.type if "group" in chat_type: logging.debug(f"new_msg_id_list: {new_msg_id_list}") logging.debug(f"historical_message: {historical_message['id_list']}") lock.acquire() historical_message.update( {"id_list": historical_message["id_list"] + new_msg_id_list} ) io.write_settings("historical_message", historical_message) lock.release() logging.debug( f"new_historical_message: {historical_message['id_list']}") def clearn(bot, update): chat_type = update.message.chat.type if "group" in chat_type: if len(historical_message["id_list"]) > 0: lock.acquire() for msg_id in historical_message["id_list"]: try: bot.delete_message(update.message.chat_id, msg_id) except Exception as e: print(e) historical_message["id_list"] = [] io.write_settings("historical_message", historical_message) lock.release() bot.delete_message(update.message.chat_id, update.message.message_id) def set(bot, update): global waitting_for_master if update.message.from_user.id != master_user_id: Message = update.message.reply_text( f"You are not admin!\nAdmin is @yingshaoxo ({master_user_id})\n\nYour user_id is:\n{str(update.message.from_user.id)}") handle_useless_msg( bot, update, [update.message.message_id, Message.message_id]) else: Message1 = update.message.reply_text( f"What's your question? \n\nExample:") Message2 = update.message.reply_text( f"you + me = ?\nNone\nWe\n2") handle_useless_msg( bot, update, [update.message.message_id, Message1.message_id, Message2.message_id]) if waitting_for_master == False: waitting_for_master = True else: pass def handle_text_msg(bot, update): global waitting_for_master global io chat_type = update.message.chat.type logging.debug(f"chat_type is {chat_type}") if update.message.from_user.id != master_user_id: if "group" in chat_type: kick_them_out_if_possible(bot, update) else: if "group" in chat_type: kick_them_out_if_possible(bot, update) if waitting_for_master == True: try: text = update.message.text text = text.strip() lines = text.split("\n") lines = [line.strip() for line in lines if line.strip() != ""] question = lines[0] answer = lines[1:-1] index = int(lines[-1]) if index > len(answer): Message = update.message.reply_text( f"The last line should less than or equal to {len(answer)}") handle_useless_msg( bot, update, [update.message.message_id, Message.message_id]) raise Exception lock.acquire() new_data = { "question": question + " (不回答会被踢出群)", "answer": answer, "right_answer_index": index } data.update(new_data) io.write_settings("data", data) lock.release() waitting_for_master = False Message = update.message.reply_text( f"OK, I got it!\n\nQuestion: {question}\nAnswer: {answer[index-1]}") handle_useless_msg( bot, update, [update.message.message_id, Message.message_id]) except Exception as e: Message1 = update.message.reply_text( f"I got this error: {e} \n Can you try again?\n\nExample:") handle_useless_msg(bot, update, [Message.message_id]) Message2 = update.message.reply_text( f"you + me = ?\nNone\nWe\n2") handle_useless_msg( bot, update, [Message1.message_id, Message2.message_id]) def handle_all_msg(bot, update): new_members = update.message.new_chat_members if new_members: lock.acquire() for user in new_members: people.update({ user.id: str(maya.now()) }) print(f"{user.id} came to this group") io.write_settings("people", people) ask(bot, update) lock.release() #left_member = update.message.left_chat_member kick_them_out_if_possible(bot, update) handle_useless_msg(bot, update, [update.message.message_id]) def kick_them_out_if_possible(bot, update): if people != {}: lock.acquire() kicked_people = [] for user_id in people: past = maya.parse(people[user_id]) now = maya.now() time_passed = (now - past).seconds logging.debug( f"how long {user_id} haven't send a message: {str(time_passed)}") if (time_passed > 60 * 3): # I will give you 3 minutes to answer my question print(f"{user_id} has to be kicked out") result = bot.kick_chat_member(update.message.chat_id, user_id) if result == True: kicked_people.append(user_id) else: bot.leave_chat(update.message.chat_id) for user_id in kicked_people: del people[user_id] io.write_settings("people", people) lock.release() def ask(bot, update): chat_type = update.message.chat.type if "group" in chat_type: keyboard = [] for text in data["answer"]: keyboard.append( [InlineKeyboardButton(text, callback_data=text)] ) reply_markup = InlineKeyboardMarkup(keyboard) Message = update.message.reply_text( data["question"], reply_markup=reply_markup) bot.pin_chat_message(update.message.chat_id, Message.message_id, disable_notification=True) handle_useless_msg( bot, update, [update.message.message_id, Message.message_id]) else: Message = update.message.reply_text( f"You are not admin!\nAdmin is @yingshaoxo ({master_user_id})\n\nYour user_id is:\n{str(update.message.from_user.id)}") def button(bot, update): query = update.callback_query right_answer = data['answer'][data["right_answer_index"]-1] if query.data == right_answer: user_id = query.from_user.id if user_id in people: lock.acquire() del people[user_id] io.write_settings("people", people) lock.release() Message = bot.send_message( chat_id=query.message.chat_id, text="You're right.\n\nWelcome!") time.sleep(3) Message.delete() else: try: if query.from_user.id in people.keys(): kicked_people = [] result = bot.kick_chat_member( query.message.chat_id, query.from_user.id) if result == True: lock.acquire() kicked_people.append(query.from_user.id) for user_id in kicked_people: del people[user_id] io.write_settings("people", people) lock.release() else: bot.leave_chat(query.message.chat_id) except Exception as e: print(e) def error(bot, update, error): """Log Errors caused by Updates.""" print(f"{error}") def main(): # Create the Updater and pass it your bot's token. updater = Updater(TOKEN) updater.dispatcher.add_handler(CommandHandler('set', set)) updater.dispatcher.add_handler(CommandHandler('ask', ask)) updater.dispatcher.add_handler(CommandHandler('clearn', clearn)) updater.dispatcher.add_handler(CallbackQueryHandler(button)) updater.dispatcher.add_handler( MessageHandler(Filters.text, handle_text_msg)) updater.dispatcher.add_handler( MessageHandler(Filters.all, handle_all_msg)) updater.dispatcher.add_error_handler(error) # Start the Bot updater.start_polling() # Run the bot until the user presses Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT updater.idle() if __name__ == '__main__': main()
32.019544
131
0.595524
import logging import threading import maya from auto_everything.base import IO from telegram.ext import Updater, CommandHandler, CallbackQueryHandler, MessageHandler, Filters from telegram import InlineKeyboardButton, InlineKeyboardMarkup import os import time master_user_id = int(os.getenv("master_user_id", "131513300")) TOKEN = os.getenv("telegram_bot_token", "") print(master_user_id) print(TOKEN) io = IO() lock = threading.RLock() ROOT_DIR = "." logging.basicConfig(filename=os.path.join(ROOT_DIR, "__main.log"), level=logging.DEBUG, filemode='w', format='%(levelname)s - %(message)s') data = { "question": "1+1=? (不回答会被踢出群)", "answer": [ "2", "3", ], "right_answer_index": 1 } data = io.read_settings("data", data) waitting_for_master = False people = { } people = io.read_settings("people", people) historical_message = { "id_list": [] } historical_message = io.read_settings( "historical_message", historical_message) def handle_useless_msg(bot, update, new_msg_id_list): global historical_message chat_type = update.message.chat.type if "group" in chat_type: logging.debug(f"new_msg_id_list: {new_msg_id_list}") logging.debug(f"historical_message: {historical_message['id_list']}") lock.acquire() historical_message.update( {"id_list": historical_message["id_list"] + new_msg_id_list} ) io.write_settings("historical_message", historical_message) lock.release() logging.debug( f"new_historical_message: {historical_message['id_list']}") def clearn(bot, update): chat_type = update.message.chat.type if "group" in chat_type: if len(historical_message["id_list"]) > 0: lock.acquire() for msg_id in historical_message["id_list"]: try: bot.delete_message(update.message.chat_id, msg_id) except Exception as e: print(e) historical_message["id_list"] = [] io.write_settings("historical_message", historical_message) lock.release() bot.delete_message(update.message.chat_id, update.message.message_id) def set(bot, update): global waitting_for_master if update.message.from_user.id != master_user_id: Message = update.message.reply_text( f"You are not admin!\nAdmin is @yingshaoxo ({master_user_id})\n\nYour user_id is:\n{str(update.message.from_user.id)}") handle_useless_msg( bot, update, [update.message.message_id, Message.message_id]) else: Message1 = update.message.reply_text( f"What's your question? \n\nExample:") Message2 = update.message.reply_text( f"you + me = ?\nNone\nWe\n2") handle_useless_msg( bot, update, [update.message.message_id, Message1.message_id, Message2.message_id]) if waitting_for_master == False: waitting_for_master = True else: pass def handle_text_msg(bot, update): global waitting_for_master global io chat_type = update.message.chat.type logging.debug(f"chat_type is {chat_type}") if update.message.from_user.id != master_user_id: if "group" in chat_type: kick_them_out_if_possible(bot, update) else: if "group" in chat_type: kick_them_out_if_possible(bot, update) if waitting_for_master == True: try: text = update.message.text text = text.strip() lines = text.split("\n") lines = [line.strip() for line in lines if line.strip() != ""] question = lines[0] answer = lines[1:-1] index = int(lines[-1]) if index > len(answer): Message = update.message.reply_text( f"The last line should less than or equal to {len(answer)}") handle_useless_msg( bot, update, [update.message.message_id, Message.message_id]) raise Exception lock.acquire() new_data = { "question": question + " (不回答会被踢出群)", "answer": answer, "right_answer_index": index } data.update(new_data) io.write_settings("data", data) lock.release() waitting_for_master = False Message = update.message.reply_text( f"OK, I got it!\n\nQuestion: {question}\nAnswer: {answer[index-1]}") handle_useless_msg( bot, update, [update.message.message_id, Message.message_id]) except Exception as e: Message1 = update.message.reply_text( f"I got this error: {e} \n Can you try again?\n\nExample:") handle_useless_msg(bot, update, [Message.message_id]) Message2 = update.message.reply_text( f"you + me = ?\nNone\nWe\n2") handle_useless_msg( bot, update, [Message1.message_id, Message2.message_id]) def handle_all_msg(bot, update): new_members = update.message.new_chat_members if new_members: lock.acquire() for user in new_members: people.update({ user.id: str(maya.now()) }) print(f"{user.id} came to this group") io.write_settings("people", people) ask(bot, update) lock.release() #left_member = update.message.left_chat_member kick_them_out_if_possible(bot, update) handle_useless_msg(bot, update, [update.message.message_id]) def kick_them_out_if_possible(bot, update): if people != {}: lock.acquire() kicked_people = [] for user_id in people: past = maya.parse(people[user_id]) now = maya.now() time_passed = (now - past).seconds logging.debug( f"how long {user_id} haven't send a message: {str(time_passed)}") if (time_passed > 60 * 3): print(f"{user_id} has to be kicked out") result = bot.kick_chat_member(update.message.chat_id, user_id) if result == True: kicked_people.append(user_id) else: bot.leave_chat(update.message.chat_id) for user_id in kicked_people: del people[user_id] io.write_settings("people", people) lock.release() def ask(bot, update): chat_type = update.message.chat.type if "group" in chat_type: keyboard = [] for text in data["answer"]: keyboard.append( [InlineKeyboardButton(text, callback_data=text)] ) reply_markup = InlineKeyboardMarkup(keyboard) Message = update.message.reply_text( data["question"], reply_markup=reply_markup) bot.pin_chat_message(update.message.chat_id, Message.message_id, disable_notification=True) handle_useless_msg( bot, update, [update.message.message_id, Message.message_id]) else: Message = update.message.reply_text( f"You are not admin!\nAdmin is @yingshaoxo ({master_user_id})\n\nYour user_id is:\n{str(update.message.from_user.id)}") def button(bot, update): query = update.callback_query right_answer = data['answer'][data["right_answer_index"]-1] if query.data == right_answer: user_id = query.from_user.id if user_id in people: lock.acquire() del people[user_id] io.write_settings("people", people) lock.release() Message = bot.send_message( chat_id=query.message.chat_id, text="You're right.\n\nWelcome!") time.sleep(3) Message.delete() else: try: if query.from_user.id in people.keys(): kicked_people = [] result = bot.kick_chat_member( query.message.chat_id, query.from_user.id) if result == True: lock.acquire() kicked_people.append(query.from_user.id) for user_id in kicked_people: del people[user_id] io.write_settings("people", people) lock.release() else: bot.leave_chat(query.message.chat_id) except Exception as e: print(e) def error(bot, update, error): print(f"{error}") def main(): # Create the Updater and pass it your bot's token. updater = Updater(TOKEN) updater.dispatcher.add_handler(CommandHandler('set', set)) updater.dispatcher.add_handler(CommandHandler('ask', ask)) updater.dispatcher.add_handler(CommandHandler('clearn', clearn)) updater.dispatcher.add_handler(CallbackQueryHandler(button)) updater.dispatcher.add_handler( MessageHandler(Filters.text, handle_text_msg)) updater.dispatcher.add_handler( MessageHandler(Filters.all, handle_all_msg)) updater.dispatcher.add_error_handler(error) updater.start_polling() updater.idle() if __name__ == '__main__': main()
true
true
f7fa17b9f735cdbfcb40ebd59a4a0a1582b61f53
779
py
Python
darkchess/tests/test_normalgame/test_normalgame.py
vishalsubbiah/darkchess
c626de547c3e58a77f25fddb86de9b07bc47ae86
[ "Apache-2.0" ]
null
null
null
darkchess/tests/test_normalgame/test_normalgame.py
vishalsubbiah/darkchess
c626de547c3e58a77f25fddb86de9b07bc47ae86
[ "Apache-2.0" ]
null
null
null
darkchess/tests/test_normalgame/test_normalgame.py
vishalsubbiah/darkchess
c626de547c3e58a77f25fddb86de9b07bc47ae86
[ "Apache-2.0" ]
null
null
null
import pytest import numpy as np from darkchess.src.board import Board from darkchess.src.gamengine import GameEngine from mock import patch def test_normal_game(): """ Plays 100 games with random moves to test the mechanics """ num_games = 100 num_moves = 300 for i in range(num_games): print("game", i+1) board = Board() game = GameEngine(board, player1="computer", player2="computer") for _ in range(num_moves): moves = game.all_moves() if len(moves) == 0: break rand_int = np.random.randint(len(moves)) with patch('sys.exit') as exit_mock: game.choose_move(moves[rand_int]) if exit_mock.called: break
28.851852
72
0.590501
import pytest import numpy as np from darkchess.src.board import Board from darkchess.src.gamengine import GameEngine from mock import patch def test_normal_game(): num_games = 100 num_moves = 300 for i in range(num_games): print("game", i+1) board = Board() game = GameEngine(board, player1="computer", player2="computer") for _ in range(num_moves): moves = game.all_moves() if len(moves) == 0: break rand_int = np.random.randint(len(moves)) with patch('sys.exit') as exit_mock: game.choose_move(moves[rand_int]) if exit_mock.called: break
true
true
f7fa184eba534135c8de9fdf6f7eebf36d1427f5
4,647
py
Python
4-Informer/chainInformer/data/merge_2018_2020_data.py
wang-yuhao/On-the-topological-propertyof-dynamic-transaction-graph
8dc8c3870befb82581099e3a6edc9f9734c23f31
[ "MIT" ]
1
2021-01-13T20:54:18.000Z
2021-01-13T20:54:18.000Z
4-Informer/chainInformer/data/merge_2018_2020_data.py
wang-yuhao/On-the-topological-propertyof-dynamic-transaction-graph
8dc8c3870befb82581099e3a6edc9f9734c23f31
[ "MIT" ]
null
null
null
4-Informer/chainInformer/data/merge_2018_2020_data.py
wang-yuhao/On-the-topological-propertyof-dynamic-transaction-graph
8dc8c3870befb82581099e3a6edc9f9734c23f31
[ "MIT" ]
1
2020-12-03T10:30:53.000Z
2020-12-03T10:30:53.000Z
# Merge 2018-2020 data for Informer # This process will generate merged base, betti, betti_deri, and fl files in PRICESSED_DIR. import pandas as pd import os from sklearn.decomposition import PCA import datetime import math import pandas as pd import numpy as np import torch BETTI_NUMBER_DIR = "/content/drive/MyDrive/aliyun/betti_number/" AMOMAT_DIR = "/content/drive/MyDrive/aliyun/amoMat/" OCCMAT_DIR = "/content/drive/MyDrive/aliyun/occMat/" PRICE_PATH = "/content/drive/MyDrive/aliyun/bitcoin_2018_2020.csv" PROCESSED_DIR = "/content/drive/MyDrive/aliyun/processed_data/2018_2020/" TOTALTX_DIR = "/content/drive/MyDrive/aliyun/bitcoin_totaltx_2018_2020.csv" PERIOD = [2018, 2019, 2020] def getBetweenDay(begin_date, end_date): date_list = [] date_arr = [] date_unix_list = [] begin_date = datetime.datetime.strptime(begin_date, "%Y-%m-%d") print("begin_date:",begin_date) # end_date = datetime.datetime.strptime(time.strftime('%Y-%m-%d', time.localtime(time.time())), "%Y-%m-%d") end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d") print("end_date:",end_date) while begin_date <= end_date: date_unix = math.trunc(begin_date.replace(tzinfo=datetime.timezone.utc).timestamp()*1000) date_unix_list.append(date_unix) date_str = begin_date.strftime("%Y-%m-%d") date_list.append(date_str) date_arr.append([date_str, date_unix]) begin_date += datetime.timedelta(days=1) return np.asarray(date_arr) def combine_features_with_data(dataset_model): data_price = pd.read_csv(PRICE_PATH) btc_price_2018_2020 = data_price.Open.str.replace(",","") total_tx = pd.read_csv(TOTALTX_DIR, index_col=0) date_arr = pd.DataFrame(getBetweenDay("2018-01-01", "2020-12-31"))[0] btc_2018_2020 = pd.concat([total_tx, btc_price_2018_2020, date_arr], axis = 1) btc_2018_2020.columns = ["totaltx", "price", "date"] print("btc_2018_2020:",btc_2018_2020) data_feature = pd.DataFrame([]) if dataset_model == "betti": for YEAR in PERIOD: #for file_name in os.listdir(BETTI_NUMBER_DIR): feature_betti_0 = pd.read_csv(BETTI_NUMBER_DIR + str(YEAR) + "_betti_0.csv", index_col=0).loc[:, "0":"49"] feature_betti_1 = pd.read_csv(BETTI_NUMBER_DIR + str(YEAR) + "_betti_1.csv", index_col=0).loc[:, "0":"49"] feature_betti_number = pd.concat([feature_betti_0,feature_betti_1], axis = 1) data_feature = pd.concat([data_feature,feature_betti_number]).reset_index(drop=True) data_feature.to_csv("data_feature.csv") print("data_feature:",data_feature) elif dataset_model == "betti_der": for YEAR in PERIOD: feature_betti_0 = pd.read_csv(BETTI_NUMBER_DIR + str(YEAR) + "_betti_0.csv", index_col=0).loc[:, "0":"49"] feature_betti_1 = pd.read_csv(BETTI_NUMBER_DIR + str(YEAR) + "_betti_1.csv", index_col=0).loc[:, "0":"49"] feature_betti_0_der = pd.read_csv(BETTI_NUMBER_DIR + str(YEAR) + "_betti_0.csv", index_col=0).diff(axis=1) feature_betti_1_der = pd.read_csv(BETTI_NUMBER_DIR + str(YEAR) + "_betti_1.csv", index_col=0).diff(axis=1) feature_betti_0_der_50 = feature_betti_0_der.loc[:, "1":"50"] feature_betti_1_der_50 = feature_betti_1_der.loc[:, "1":"50"] feature_betti_total = pd.concat([feature_betti_0, feature_betti_1, feature_betti_0_der_50, feature_betti_1_der_50], axis=1) data_feature = pd.concat([data_feature,feature_betti_total]).reset_index(drop=True) elif dataset_model == "fl": for year in PERIOD: for day in getBetweenDay(str(year) + "-01-01", str(year) + "-12-31"): feature = pd.read_csv(OCCMAT_DIR + str(year) + "/occ" + day[0] + '.csv', index_col=0).to_numpy() feature = pd.DataFrame(feature.flatten()).T data_feature = pd.concat([data_feature,feature], axis = 0) data_feature.to_csv(PROCESSED_DIR + dataset_model+"_orig.csv") print("data_feature:",data_feature) if len(data_feature) > 0: pca = PCA(n_components = 20) pca.fit(data_feature) data_feature = pd.DataFrame(pca.transform(data_feature)) print("pca data_feature:",data_feature) data_combined = pd.concat([btc_2018_2020,data_feature], axis=1) cols = data_combined.columns.tolist() cols = cols[2:] + cols[:2] data_combined = data_combined[cols] data_combined.to_csv(PROCESSED_DIR + dataset_model+".csv", index=False) print(data_combined) for dataset_model in ["base", "betti","betti_der", "fl"]: combine_features_with_data(dataset_model)
49.43617
135
0.688832
import pandas as pd import os from sklearn.decomposition import PCA import datetime import math import pandas as pd import numpy as np import torch BETTI_NUMBER_DIR = "/content/drive/MyDrive/aliyun/betti_number/" AMOMAT_DIR = "/content/drive/MyDrive/aliyun/amoMat/" OCCMAT_DIR = "/content/drive/MyDrive/aliyun/occMat/" PRICE_PATH = "/content/drive/MyDrive/aliyun/bitcoin_2018_2020.csv" PROCESSED_DIR = "/content/drive/MyDrive/aliyun/processed_data/2018_2020/" TOTALTX_DIR = "/content/drive/MyDrive/aliyun/bitcoin_totaltx_2018_2020.csv" PERIOD = [2018, 2019, 2020] def getBetweenDay(begin_date, end_date): date_list = [] date_arr = [] date_unix_list = [] begin_date = datetime.datetime.strptime(begin_date, "%Y-%m-%d") print("begin_date:",begin_date) end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d") print("end_date:",end_date) while begin_date <= end_date: date_unix = math.trunc(begin_date.replace(tzinfo=datetime.timezone.utc).timestamp()*1000) date_unix_list.append(date_unix) date_str = begin_date.strftime("%Y-%m-%d") date_list.append(date_str) date_arr.append([date_str, date_unix]) begin_date += datetime.timedelta(days=1) return np.asarray(date_arr) def combine_features_with_data(dataset_model): data_price = pd.read_csv(PRICE_PATH) btc_price_2018_2020 = data_price.Open.str.replace(",","") total_tx = pd.read_csv(TOTALTX_DIR, index_col=0) date_arr = pd.DataFrame(getBetweenDay("2018-01-01", "2020-12-31"))[0] btc_2018_2020 = pd.concat([total_tx, btc_price_2018_2020, date_arr], axis = 1) btc_2018_2020.columns = ["totaltx", "price", "date"] print("btc_2018_2020:",btc_2018_2020) data_feature = pd.DataFrame([]) if dataset_model == "betti": for YEAR in PERIOD: feature_betti_0 = pd.read_csv(BETTI_NUMBER_DIR + str(YEAR) + "_betti_0.csv", index_col=0).loc[:, "0":"49"] feature_betti_1 = pd.read_csv(BETTI_NUMBER_DIR + str(YEAR) + "_betti_1.csv", index_col=0).loc[:, "0":"49"] feature_betti_number = pd.concat([feature_betti_0,feature_betti_1], axis = 1) data_feature = pd.concat([data_feature,feature_betti_number]).reset_index(drop=True) data_feature.to_csv("data_feature.csv") print("data_feature:",data_feature) elif dataset_model == "betti_der": for YEAR in PERIOD: feature_betti_0 = pd.read_csv(BETTI_NUMBER_DIR + str(YEAR) + "_betti_0.csv", index_col=0).loc[:, "0":"49"] feature_betti_1 = pd.read_csv(BETTI_NUMBER_DIR + str(YEAR) + "_betti_1.csv", index_col=0).loc[:, "0":"49"] feature_betti_0_der = pd.read_csv(BETTI_NUMBER_DIR + str(YEAR) + "_betti_0.csv", index_col=0).diff(axis=1) feature_betti_1_der = pd.read_csv(BETTI_NUMBER_DIR + str(YEAR) + "_betti_1.csv", index_col=0).diff(axis=1) feature_betti_0_der_50 = feature_betti_0_der.loc[:, "1":"50"] feature_betti_1_der_50 = feature_betti_1_der.loc[:, "1":"50"] feature_betti_total = pd.concat([feature_betti_0, feature_betti_1, feature_betti_0_der_50, feature_betti_1_der_50], axis=1) data_feature = pd.concat([data_feature,feature_betti_total]).reset_index(drop=True) elif dataset_model == "fl": for year in PERIOD: for day in getBetweenDay(str(year) + "-01-01", str(year) + "-12-31"): feature = pd.read_csv(OCCMAT_DIR + str(year) + "/occ" + day[0] + '.csv', index_col=0).to_numpy() feature = pd.DataFrame(feature.flatten()).T data_feature = pd.concat([data_feature,feature], axis = 0) data_feature.to_csv(PROCESSED_DIR + dataset_model+"_orig.csv") print("data_feature:",data_feature) if len(data_feature) > 0: pca = PCA(n_components = 20) pca.fit(data_feature) data_feature = pd.DataFrame(pca.transform(data_feature)) print("pca data_feature:",data_feature) data_combined = pd.concat([btc_2018_2020,data_feature], axis=1) cols = data_combined.columns.tolist() cols = cols[2:] + cols[:2] data_combined = data_combined[cols] data_combined.to_csv(PROCESSED_DIR + dataset_model+".csv", index=False) print(data_combined) for dataset_model in ["base", "betti","betti_der", "fl"]: combine_features_with_data(dataset_model)
true
true
f7fa18721db026e7b14c1241ab312e2fffe0a037
10,420
py
Python
adafruit_featherwing/rtc_featherwing.py
FoamyGuy/Adafruit_CircuitPython_FeatherWing
bdddd820ede356026be18319b045a414e450002d
[ "MIT" ]
null
null
null
adafruit_featherwing/rtc_featherwing.py
FoamyGuy/Adafruit_CircuitPython_FeatherWing
bdddd820ede356026be18319b045a414e450002d
[ "MIT" ]
null
null
null
adafruit_featherwing/rtc_featherwing.py
FoamyGuy/Adafruit_CircuitPython_FeatherWing
bdddd820ede356026be18319b045a414e450002d
[ "MIT" ]
null
null
null
# The MIT License (MIT) # # Copyright (c) 2019 Melissa LeBlanc-Williams for Adafruit Industries LLC # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. """ `adafruit_featherwing.rtc_featherwing` ==================================================== Helper for using the `DS3231 Precision RTC FeatherWing <https://www.adafruit.com/product/3028>`_. * Author(s): Melissa LeBlanc-Williams """ __version__ = "0.0.0-auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_FeatherWing.git" import time from collections import namedtuple import board import adafruit_ds3231 class RTCFeatherWing: """Class representing an `DS3231 Precision RTC FeatherWing <https://www.adafruit.com/product/3028>`_. Automatically uses the feather's I2C bus.""" def __init__(self, i2c=None): if i2c is None: i2c = board.I2C() self._rtc = adafruit_ds3231.DS3231(i2c) def __setitem__(self, index, value): """ Allow updates using setitem if that makes it easier """ self._set_time_value(index, value) def __getitem__(self, index): """ Allow retrievals using getitem if that makes it easier """ return self._get_time_value(index) def _set_time_value(self, unit, value): """ Set just the specific unit of time """ now = self._get_now() if unit in now: now[unit] = value else: raise ValueError("The specified unit of time is invalid") self._rtc.datetime = self._encode(now) def _get_time_value(self, unit): """ Get just the specific unit of time """ now = self._get_now() if unit in now: return now[unit] raise ValueError("The specified unit of time is invalid") def _get_now(self): """ Return the current date and time in a nice updatable dictionary """ now = self._rtc.datetime return { "second": now.tm_sec, "minute": now.tm_min, "hour": now.tm_hour, "day": now.tm_mday, "month": now.tm_mon, "year": now.tm_year, "weekday": now.tm_wday, } def _encode(self, date): """ Encode the updatable dictionary back into a time struct """ now = self._rtc.datetime return time.struct_time( ( date["year"], date["month"], date["day"], date["hour"], date["minute"], date["second"], date["weekday"], now.tm_yday, now.tm_isdst, ) ) def is_leap_year(self, year=None): """ Check if the year is a leap year :param int year: (Optional) The year to check. If none is provided, current year is used. """ if year is None: year = self._get_time_value("year") return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) def get_month_days(self, month=None, year=None): """ Return the number of days for the month of the given year :param int month: (Optional) The month to use. If none is provided, current month is used. :param int year: (Optional) The year to check. If none is provided, current year is used. """ if month is None: month = self._get_time_value("month") leap_year = self.is_leap_year(year) max_days = (31, 29 if leap_year else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) return max_days[month - 1] def set_time(self, hour, minute, second=0): """ Set the time only :param int hour: The hour we want to set the time to :param int minute: The minute we want to set the time to :param int second: (Optional) The second we want to set the time to (default=0) """ if not isinstance(second, int) or not 0 <= second < 60: raise ValueError("The second must be an integer in the range of 0-59") if not isinstance(minute, int) or not 0 <= minute < 60: raise ValueError("The minute must be an integer in the range of 0-59") if not isinstance(hour, int) or not 0 <= hour < 24: raise ValueError("The hour must be an integer in the range of 0-23") now = self._get_now() now["hour"] = hour now["minute"] = minute now["second"] = second self._rtc.datetime = self._encode(now) def set_date(self, day, month, year): """ Set the date only :param int day: The day we want to set the date to :param int month: The month we want to set the date to :param int year: The year we want to set the date to """ if not isinstance(year, int): raise ValueError("The year must be an integer") if not isinstance(month, int) or not 1 <= month <= 12: raise ValueError("The month must be an integer in the range of 1-12") month_days = self.get_month_days(month, year) if not isinstance(day, int) or not 1 <= day <= month_days: raise ValueError( "The day must be an integer in the range of 1-{}".format(month_days) ) now = self._get_now() now["day"] = day now["month"] = month now["year"] = year self._rtc.datetime = self._encode(now) @property def datetime(self): """ Passthru property to the ds3231 library for compatibility """ return self._rtc.datetime @datetime.setter def datetime(self, datetime): self._rtc.datetime = datetime @property def year(self): """ The Current Year """ return self._get_time_value("year") @year.setter def year(self, year): if isinstance(year, int): self._set_time_value("year", year) else: raise ValueError("The year must be an integer") @property def month(self): """ The Current Month """ return self._get_time_value("month") @month.setter def month(self, month): if isinstance(month, int) and 1 <= month <= 12: self._set_time_value("month", month) else: raise ValueError("The month must be an integer in the range of 1-12") @property def day(self): """ The Current Day """ return self._get_time_value("day") @day.setter def day(self, day): month_days = self.get_month_days() if isinstance(day, int) and 1 <= day <= month_days: self._set_time_value("day", day) else: raise ValueError( "The day must be an integer in the range of 1-{}".format(month_days) ) @property def hour(self): """ The Current Hour """ return self._get_time_value("hour") @hour.setter def hour(self, hour): if isinstance(hour, int) and 0 <= hour < 24: self._set_time_value("hour", hour) else: raise ValueError("The hour must be an integer in the range of 0-23") @property def minute(self): """ The Current Minute """ return self._get_time_value("minute") @minute.setter def minute(self, minute): if isinstance(minute, int) and 0 <= minute < 60: self._set_time_value("minute", minute) else: raise ValueError("The minute must be an integer in the range of 0-59") @property def second(self): """ The Current Second """ return self._get_time_value("second") @second.setter def second(self, second): if isinstance(second, int) and 0 <= second < 60: self._set_time_value("second", second) else: raise ValueError("The second must be an integer in the range of 0-59") @property def weekday(self): """ The Current Day of the Week Value (0-6) where Sunday is 0 """ return self._get_time_value("weekday") @weekday.setter def weekday(self, weekday): if isinstance(weekday, int) and 0 <= weekday < 7: self._set_time_value("weekday", weekday) else: raise ValueError("The weekday must be an integer in the range of 0-6") @property def now(self): """ The Current Date and Time in Named Tuple Style (Read Only) """ date_time = namedtuple("DateTime", "second minute hour day month year weekday") return date_time(**self._get_now()) @property def unixtime(self): """ The Current Date and Time in Unix Time """ try: return time.mktime(self._rtc.datetime) except (AttributeError, RuntimeError) as error: print("Error attempting to run time.mktime() on this board\n", error) @unixtime.setter def unixtime(self, unixtime): if isinstance(unixtime, int): try: self._rtc.datetime = time.localtime(unixtime) except (AttributeError, RuntimeError) as error: print("Error attempting to run time.localtime() on this board\n", error)
31.768293
98
0.588292
__version__ = "0.0.0-auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_FeatherWing.git" import time from collections import namedtuple import board import adafruit_ds3231 class RTCFeatherWing: def __init__(self, i2c=None): if i2c is None: i2c = board.I2C() self._rtc = adafruit_ds3231.DS3231(i2c) def __setitem__(self, index, value): self._set_time_value(index, value) def __getitem__(self, index): return self._get_time_value(index) def _set_time_value(self, unit, value): now = self._get_now() if unit in now: now[unit] = value else: raise ValueError("The specified unit of time is invalid") self._rtc.datetime = self._encode(now) def _get_time_value(self, unit): now = self._get_now() if unit in now: return now[unit] raise ValueError("The specified unit of time is invalid") def _get_now(self): now = self._rtc.datetime return { "second": now.tm_sec, "minute": now.tm_min, "hour": now.tm_hour, "day": now.tm_mday, "month": now.tm_mon, "year": now.tm_year, "weekday": now.tm_wday, } def _encode(self, date): now = self._rtc.datetime return time.struct_time( ( date["year"], date["month"], date["day"], date["hour"], date["minute"], date["second"], date["weekday"], now.tm_yday, now.tm_isdst, ) ) def is_leap_year(self, year=None): if year is None: year = self._get_time_value("year") return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) def get_month_days(self, month=None, year=None): if month is None: month = self._get_time_value("month") leap_year = self.is_leap_year(year) max_days = (31, 29 if leap_year else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) return max_days[month - 1] def set_time(self, hour, minute, second=0): if not isinstance(second, int) or not 0 <= second < 60: raise ValueError("The second must be an integer in the range of 0-59") if not isinstance(minute, int) or not 0 <= minute < 60: raise ValueError("The minute must be an integer in the range of 0-59") if not isinstance(hour, int) or not 0 <= hour < 24: raise ValueError("The hour must be an integer in the range of 0-23") now = self._get_now() now["hour"] = hour now["minute"] = minute now["second"] = second self._rtc.datetime = self._encode(now) def set_date(self, day, month, year): if not isinstance(year, int): raise ValueError("The year must be an integer") if not isinstance(month, int) or not 1 <= month <= 12: raise ValueError("The month must be an integer in the range of 1-12") month_days = self.get_month_days(month, year) if not isinstance(day, int) or not 1 <= day <= month_days: raise ValueError( "The day must be an integer in the range of 1-{}".format(month_days) ) now = self._get_now() now["day"] = day now["month"] = month now["year"] = year self._rtc.datetime = self._encode(now) @property def datetime(self): return self._rtc.datetime @datetime.setter def datetime(self, datetime): self._rtc.datetime = datetime @property def year(self): return self._get_time_value("year") @year.setter def year(self, year): if isinstance(year, int): self._set_time_value("year", year) else: raise ValueError("The year must be an integer") @property def month(self): return self._get_time_value("month") @month.setter def month(self, month): if isinstance(month, int) and 1 <= month <= 12: self._set_time_value("month", month) else: raise ValueError("The month must be an integer in the range of 1-12") @property def day(self): return self._get_time_value("day") @day.setter def day(self, day): month_days = self.get_month_days() if isinstance(day, int) and 1 <= day <= month_days: self._set_time_value("day", day) else: raise ValueError( "The day must be an integer in the range of 1-{}".format(month_days) ) @property def hour(self): return self._get_time_value("hour") @hour.setter def hour(self, hour): if isinstance(hour, int) and 0 <= hour < 24: self._set_time_value("hour", hour) else: raise ValueError("The hour must be an integer in the range of 0-23") @property def minute(self): return self._get_time_value("minute") @minute.setter def minute(self, minute): if isinstance(minute, int) and 0 <= minute < 60: self._set_time_value("minute", minute) else: raise ValueError("The minute must be an integer in the range of 0-59") @property def second(self): return self._get_time_value("second") @second.setter def second(self, second): if isinstance(second, int) and 0 <= second < 60: self._set_time_value("second", second) else: raise ValueError("The second must be an integer in the range of 0-59") @property def weekday(self): return self._get_time_value("weekday") @weekday.setter def weekday(self, weekday): if isinstance(weekday, int) and 0 <= weekday < 7: self._set_time_value("weekday", weekday) else: raise ValueError("The weekday must be an integer in the range of 0-6") @property def now(self): date_time = namedtuple("DateTime", "second minute hour day month year weekday") return date_time(**self._get_now()) @property def unixtime(self): try: return time.mktime(self._rtc.datetime) except (AttributeError, RuntimeError) as error: print("Error attempting to run time.mktime() on this board\n", error) @unixtime.setter def unixtime(self, unixtime): if isinstance(unixtime, int): try: self._rtc.datetime = time.localtime(unixtime) except (AttributeError, RuntimeError) as error: print("Error attempting to run time.localtime() on this board\n", error)
true
true
f7fa18da7f648c7aa0b0c2361e2e592e2b9c2cb3
794
py
Python
mysite/main/models.py
Anjani100/mysite-tuts
bf145118f2bbde97d389acfe827fbed444522c04
[ "MIT" ]
null
null
null
mysite/main/models.py
Anjani100/mysite-tuts
bf145118f2bbde97d389acfe827fbed444522c04
[ "MIT" ]
null
null
null
mysite/main/models.py
Anjani100/mysite-tuts
bf145118f2bbde97d389acfe827fbed444522c04
[ "MIT" ]
null
null
null
from django.db import models from datetime import datetime from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Tutorial(models.Model): tutorial_title = models.CharField(max_length = 200) tutorial_published = models.DateTimeField("date published", default = datetime.now()) tutorial_content = models.TextField() def __str__(self): return self.tutorial_title class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save()
31.76
86
0.799748
from django.db import models from datetime import datetime from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Tutorial(models.Model): tutorial_title = models.CharField(max_length = 200) tutorial_published = models.DateTimeField("date published", default = datetime.now()) tutorial_content = models.TextField() def __str__(self): return self.tutorial_title class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) email_confirmed = models.BooleanField(default=False) @receiver(post_save, sender=User) def update_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save()
true
true